1 | n/a | """idlelib.config -- Manage IDLE configuration information. |
---|
2 | n/a | |
---|
3 | n/a | The comments at the beginning of config-main.def describe the |
---|
4 | n/a | configuration files and the design implemented to update user |
---|
5 | n/a | configuration information. In particular, user configuration choices |
---|
6 | n/a | which duplicate the defaults will be removed from the user's |
---|
7 | n/a | configuration files, and if a user file becomes empty, it will be |
---|
8 | n/a | deleted. |
---|
9 | n/a | |
---|
10 | n/a | The configuration database maps options to values. Comceptually, the |
---|
11 | n/a | database keys are tuples (config-type, section, item). As implemented, |
---|
12 | n/a | there are separate dicts for default and user values. Each has |
---|
13 | n/a | config-type keys 'main', 'extensions', 'highlight', and 'keys'. The |
---|
14 | n/a | value for each key is a ConfigParser instance that maps section and item |
---|
15 | n/a | to values. For 'main' and 'extenstons', user values override |
---|
16 | n/a | default values. For 'highlight' and 'keys', user sections augment the |
---|
17 | n/a | default sections (and must, therefore, have distinct names). |
---|
18 | n/a | |
---|
19 | n/a | Throughout this module there is an emphasis on returning useable defaults |
---|
20 | n/a | when a problem occurs in returning a requested configuration value back to |
---|
21 | n/a | idle. This is to allow IDLE to continue to function in spite of errors in |
---|
22 | n/a | the retrieval of config information. When a default is returned instead of |
---|
23 | n/a | a requested config value, a message is printed to stderr to aid in |
---|
24 | n/a | configuration problem notification and resolution. |
---|
25 | n/a | """ |
---|
26 | n/a | # TODOs added Oct 2014, tjr |
---|
27 | n/a | |
---|
28 | n/a | from configparser import ConfigParser |
---|
29 | n/a | import os |
---|
30 | n/a | import sys |
---|
31 | n/a | |
---|
32 | n/a | from tkinter.font import Font, nametofont |
---|
33 | n/a | |
---|
34 | n/a | class InvalidConfigType(Exception): pass |
---|
35 | n/a | class InvalidConfigSet(Exception): pass |
---|
36 | n/a | class InvalidFgBg(Exception): pass |
---|
37 | n/a | class InvalidTheme(Exception): pass |
---|
38 | n/a | |
---|
39 | n/a | class IdleConfParser(ConfigParser): |
---|
40 | n/a | """ |
---|
41 | n/a | A ConfigParser specialised for idle configuration file handling |
---|
42 | n/a | """ |
---|
43 | n/a | def __init__(self, cfgFile, cfgDefaults=None): |
---|
44 | n/a | """ |
---|
45 | n/a | cfgFile - string, fully specified configuration file name |
---|
46 | n/a | """ |
---|
47 | n/a | self.file = cfgFile |
---|
48 | n/a | ConfigParser.__init__(self, defaults=cfgDefaults, strict=False) |
---|
49 | n/a | |
---|
50 | n/a | def Get(self, section, option, type=None, default=None, raw=False): |
---|
51 | n/a | """ |
---|
52 | n/a | Get an option value for given section/option or return default. |
---|
53 | n/a | If type is specified, return as type. |
---|
54 | n/a | """ |
---|
55 | n/a | # TODO Use default as fallback, at least if not None |
---|
56 | n/a | # Should also print Warning(file, section, option). |
---|
57 | n/a | # Currently may raise ValueError |
---|
58 | n/a | if not self.has_option(section, option): |
---|
59 | n/a | return default |
---|
60 | n/a | if type == 'bool': |
---|
61 | n/a | return self.getboolean(section, option) |
---|
62 | n/a | elif type == 'int': |
---|
63 | n/a | return self.getint(section, option) |
---|
64 | n/a | else: |
---|
65 | n/a | return self.get(section, option, raw=raw) |
---|
66 | n/a | |
---|
67 | n/a | def GetOptionList(self, section): |
---|
68 | n/a | "Return a list of options for given section, else []." |
---|
69 | n/a | if self.has_section(section): |
---|
70 | n/a | return self.options(section) |
---|
71 | n/a | else: #return a default value |
---|
72 | n/a | return [] |
---|
73 | n/a | |
---|
74 | n/a | def Load(self): |
---|
75 | n/a | "Load the configuration file from disk." |
---|
76 | n/a | self.read(self.file) |
---|
77 | n/a | |
---|
78 | n/a | class IdleUserConfParser(IdleConfParser): |
---|
79 | n/a | """ |
---|
80 | n/a | IdleConfigParser specialised for user configuration handling. |
---|
81 | n/a | """ |
---|
82 | n/a | |
---|
83 | n/a | def AddSection(self, section): |
---|
84 | n/a | "If section doesn't exist, add it." |
---|
85 | n/a | if not self.has_section(section): |
---|
86 | n/a | self.add_section(section) |
---|
87 | n/a | |
---|
88 | n/a | def RemoveEmptySections(self): |
---|
89 | n/a | "Remove any sections that have no options." |
---|
90 | n/a | for section in self.sections(): |
---|
91 | n/a | if not self.GetOptionList(section): |
---|
92 | n/a | self.remove_section(section) |
---|
93 | n/a | |
---|
94 | n/a | def IsEmpty(self): |
---|
95 | n/a | "Return True if no sections after removing empty sections." |
---|
96 | n/a | self.RemoveEmptySections() |
---|
97 | n/a | return not self.sections() |
---|
98 | n/a | |
---|
99 | n/a | def RemoveOption(self, section, option): |
---|
100 | n/a | """Return True if option is removed from section, else False. |
---|
101 | n/a | |
---|
102 | n/a | False if either section does not exist or did not have option. |
---|
103 | n/a | """ |
---|
104 | n/a | if self.has_section(section): |
---|
105 | n/a | return self.remove_option(section, option) |
---|
106 | n/a | return False |
---|
107 | n/a | |
---|
108 | n/a | def SetOption(self, section, option, value): |
---|
109 | n/a | """Return True if option is added or changed to value, else False. |
---|
110 | n/a | |
---|
111 | n/a | Add section if required. False means option already had value. |
---|
112 | n/a | """ |
---|
113 | n/a | if self.has_option(section, option): |
---|
114 | n/a | if self.get(section, option) == value: |
---|
115 | n/a | return False |
---|
116 | n/a | else: |
---|
117 | n/a | self.set(section, option, value) |
---|
118 | n/a | return True |
---|
119 | n/a | else: |
---|
120 | n/a | if not self.has_section(section): |
---|
121 | n/a | self.add_section(section) |
---|
122 | n/a | self.set(section, option, value) |
---|
123 | n/a | return True |
---|
124 | n/a | |
---|
125 | n/a | def RemoveFile(self): |
---|
126 | n/a | "Remove user config file self.file from disk if it exists." |
---|
127 | n/a | if os.path.exists(self.file): |
---|
128 | n/a | os.remove(self.file) |
---|
129 | n/a | |
---|
130 | n/a | def Save(self): |
---|
131 | n/a | """Update user configuration file. |
---|
132 | n/a | |
---|
133 | n/a | Remove empty sections. If resulting config isn't empty, write the file |
---|
134 | n/a | to disk. If config is empty, remove the file from disk if it exists. |
---|
135 | n/a | |
---|
136 | n/a | """ |
---|
137 | n/a | if not self.IsEmpty(): |
---|
138 | n/a | fname = self.file |
---|
139 | n/a | try: |
---|
140 | n/a | cfgFile = open(fname, 'w') |
---|
141 | n/a | except OSError: |
---|
142 | n/a | os.unlink(fname) |
---|
143 | n/a | cfgFile = open(fname, 'w') |
---|
144 | n/a | with cfgFile: |
---|
145 | n/a | self.write(cfgFile) |
---|
146 | n/a | else: |
---|
147 | n/a | self.RemoveFile() |
---|
148 | n/a | |
---|
149 | n/a | class IdleConf: |
---|
150 | n/a | """Hold config parsers for all idle config files in singleton instance. |
---|
151 | n/a | |
---|
152 | n/a | Default config files, self.defaultCfg -- |
---|
153 | n/a | for config_type in self.config_types: |
---|
154 | n/a | (idle install dir)/config-{config-type}.def |
---|
155 | n/a | |
---|
156 | n/a | User config files, self.userCfg -- |
---|
157 | n/a | for config_type in self.config_types: |
---|
158 | n/a | (user home dir)/.idlerc/config-{config-type}.cfg |
---|
159 | n/a | """ |
---|
160 | n/a | def __init__(self): |
---|
161 | n/a | self.config_types = ('main', 'extensions', 'highlight', 'keys') |
---|
162 | n/a | self.defaultCfg = {} |
---|
163 | n/a | self.userCfg = {} |
---|
164 | n/a | self.cfg = {} # TODO use to select userCfg vs defaultCfg |
---|
165 | n/a | self.CreateConfigHandlers() |
---|
166 | n/a | self.LoadCfgFiles() |
---|
167 | n/a | |
---|
168 | n/a | |
---|
169 | n/a | def CreateConfigHandlers(self): |
---|
170 | n/a | "Populate default and user config parser dictionaries." |
---|
171 | n/a | #build idle install path |
---|
172 | n/a | if __name__ != '__main__': # we were imported |
---|
173 | n/a | idleDir=os.path.dirname(__file__) |
---|
174 | n/a | else: # we were exec'ed (for testing only) |
---|
175 | n/a | idleDir=os.path.abspath(sys.path[0]) |
---|
176 | n/a | userDir=self.GetUserCfgDir() |
---|
177 | n/a | |
---|
178 | n/a | defCfgFiles = {} |
---|
179 | n/a | usrCfgFiles = {} |
---|
180 | n/a | # TODO eliminate these temporaries by combining loops |
---|
181 | n/a | for cfgType in self.config_types: #build config file names |
---|
182 | n/a | defCfgFiles[cfgType] = os.path.join( |
---|
183 | n/a | idleDir, 'config-' + cfgType + '.def') |
---|
184 | n/a | usrCfgFiles[cfgType] = os.path.join( |
---|
185 | n/a | userDir, 'config-' + cfgType + '.cfg') |
---|
186 | n/a | for cfgType in self.config_types: #create config parsers |
---|
187 | n/a | self.defaultCfg[cfgType] = IdleConfParser(defCfgFiles[cfgType]) |
---|
188 | n/a | self.userCfg[cfgType] = IdleUserConfParser(usrCfgFiles[cfgType]) |
---|
189 | n/a | |
---|
190 | n/a | def GetUserCfgDir(self): |
---|
191 | n/a | """Return a filesystem directory for storing user config files. |
---|
192 | n/a | |
---|
193 | n/a | Creates it if required. |
---|
194 | n/a | """ |
---|
195 | n/a | cfgDir = '.idlerc' |
---|
196 | n/a | userDir = os.path.expanduser('~') |
---|
197 | n/a | if userDir != '~': # expanduser() found user home dir |
---|
198 | n/a | if not os.path.exists(userDir): |
---|
199 | n/a | warn = ('\n Warning: os.path.expanduser("~") points to\n ' + |
---|
200 | n/a | userDir + ',\n but the path does not exist.') |
---|
201 | n/a | try: |
---|
202 | n/a | print(warn, file=sys.stderr) |
---|
203 | n/a | except OSError: |
---|
204 | n/a | pass |
---|
205 | n/a | userDir = '~' |
---|
206 | n/a | if userDir == "~": # still no path to home! |
---|
207 | n/a | # traditionally IDLE has defaulted to os.getcwd(), is this adequate? |
---|
208 | n/a | userDir = os.getcwd() |
---|
209 | n/a | userDir = os.path.join(userDir, cfgDir) |
---|
210 | n/a | if not os.path.exists(userDir): |
---|
211 | n/a | try: |
---|
212 | n/a | os.mkdir(userDir) |
---|
213 | n/a | except OSError: |
---|
214 | n/a | warn = ('\n Warning: unable to create user config directory\n' + |
---|
215 | n/a | userDir + '\n Check path and permissions.\n Exiting!\n') |
---|
216 | n/a | print(warn, file=sys.stderr) |
---|
217 | n/a | raise SystemExit |
---|
218 | n/a | # TODO continue without userDIr instead of exit |
---|
219 | n/a | return userDir |
---|
220 | n/a | |
---|
221 | n/a | def GetOption(self, configType, section, option, default=None, type=None, |
---|
222 | n/a | warn_on_default=True, raw=False): |
---|
223 | n/a | """Return a value for configType section option, or default. |
---|
224 | n/a | |
---|
225 | n/a | If type is not None, return a value of that type. Also pass raw |
---|
226 | n/a | to the config parser. First try to return a valid value |
---|
227 | n/a | (including type) from a user configuration. If that fails, try |
---|
228 | n/a | the default configuration. If that fails, return default, with a |
---|
229 | n/a | default of None. |
---|
230 | n/a | |
---|
231 | n/a | Warn if either user or default configurations have an invalid value. |
---|
232 | n/a | Warn if default is returned and warn_on_default is True. |
---|
233 | n/a | """ |
---|
234 | n/a | try: |
---|
235 | n/a | if self.userCfg[configType].has_option(section, option): |
---|
236 | n/a | return self.userCfg[configType].Get(section, option, |
---|
237 | n/a | type=type, raw=raw) |
---|
238 | n/a | except ValueError: |
---|
239 | n/a | warning = ('\n Warning: config.py - IdleConf.GetOption -\n' |
---|
240 | n/a | ' invalid %r value for configuration option %r\n' |
---|
241 | n/a | ' from section %r: %r' % |
---|
242 | n/a | (type, option, section, |
---|
243 | n/a | self.userCfg[configType].Get(section, option, raw=raw))) |
---|
244 | n/a | _warn(warning, configType, section, option) |
---|
245 | n/a | try: |
---|
246 | n/a | if self.defaultCfg[configType].has_option(section,option): |
---|
247 | n/a | return self.defaultCfg[configType].Get( |
---|
248 | n/a | section, option, type=type, raw=raw) |
---|
249 | n/a | except ValueError: |
---|
250 | n/a | pass |
---|
251 | n/a | #returning default, print warning |
---|
252 | n/a | if warn_on_default: |
---|
253 | n/a | warning = ('\n Warning: config.py - IdleConf.GetOption -\n' |
---|
254 | n/a | ' problem retrieving configuration option %r\n' |
---|
255 | n/a | ' from section %r.\n' |
---|
256 | n/a | ' returning default value: %r' % |
---|
257 | n/a | (option, section, default)) |
---|
258 | n/a | _warn(warning, configType, section, option) |
---|
259 | n/a | return default |
---|
260 | n/a | |
---|
261 | n/a | def SetOption(self, configType, section, option, value): |
---|
262 | n/a | """Set section option to value in user config file.""" |
---|
263 | n/a | self.userCfg[configType].SetOption(section, option, value) |
---|
264 | n/a | |
---|
265 | n/a | def GetSectionList(self, configSet, configType): |
---|
266 | n/a | """Return sections for configSet configType configuration. |
---|
267 | n/a | |
---|
268 | n/a | configSet must be either 'user' or 'default' |
---|
269 | n/a | configType must be in self.config_types. |
---|
270 | n/a | """ |
---|
271 | n/a | if not (configType in self.config_types): |
---|
272 | n/a | raise InvalidConfigType('Invalid configType specified') |
---|
273 | n/a | if configSet == 'user': |
---|
274 | n/a | cfgParser = self.userCfg[configType] |
---|
275 | n/a | elif configSet == 'default': |
---|
276 | n/a | cfgParser=self.defaultCfg[configType] |
---|
277 | n/a | else: |
---|
278 | n/a | raise InvalidConfigSet('Invalid configSet specified') |
---|
279 | n/a | return cfgParser.sections() |
---|
280 | n/a | |
---|
281 | n/a | def GetHighlight(self, theme, element, fgBg=None): |
---|
282 | n/a | """Return individual theme element highlight color(s). |
---|
283 | n/a | |
---|
284 | n/a | fgBg - string ('fg' or 'bg') or None. |
---|
285 | n/a | If None, return a dictionary containing fg and bg colors with |
---|
286 | n/a | keys 'foreground' and 'background'. Otherwise, only return |
---|
287 | n/a | fg or bg color, as specified. Colors are intended to be |
---|
288 | n/a | appropriate for passing to Tkinter in, e.g., a tag_config call). |
---|
289 | n/a | """ |
---|
290 | n/a | if self.defaultCfg['highlight'].has_section(theme): |
---|
291 | n/a | themeDict = self.GetThemeDict('default', theme) |
---|
292 | n/a | else: |
---|
293 | n/a | themeDict = self.GetThemeDict('user', theme) |
---|
294 | n/a | fore = themeDict[element + '-foreground'] |
---|
295 | n/a | if element == 'cursor': # There is no config value for cursor bg |
---|
296 | n/a | back = themeDict['normal-background'] |
---|
297 | n/a | else: |
---|
298 | n/a | back = themeDict[element + '-background'] |
---|
299 | n/a | highlight = {"foreground": fore, "background": back} |
---|
300 | n/a | if not fgBg: # Return dict of both colors |
---|
301 | n/a | return highlight |
---|
302 | n/a | else: # Return specified color only |
---|
303 | n/a | if fgBg == 'fg': |
---|
304 | n/a | return highlight["foreground"] |
---|
305 | n/a | if fgBg == 'bg': |
---|
306 | n/a | return highlight["background"] |
---|
307 | n/a | else: |
---|
308 | n/a | raise InvalidFgBg('Invalid fgBg specified') |
---|
309 | n/a | |
---|
310 | n/a | def GetThemeDict(self, type, themeName): |
---|
311 | n/a | """Return {option:value} dict for elements in themeName. |
---|
312 | n/a | |
---|
313 | n/a | type - string, 'default' or 'user' theme type |
---|
314 | n/a | themeName - string, theme name |
---|
315 | n/a | Values are loaded over ultimate fallback defaults to guarantee |
---|
316 | n/a | that all theme elements are present in a newly created theme. |
---|
317 | n/a | """ |
---|
318 | n/a | if type == 'user': |
---|
319 | n/a | cfgParser = self.userCfg['highlight'] |
---|
320 | n/a | elif type == 'default': |
---|
321 | n/a | cfgParser = self.defaultCfg['highlight'] |
---|
322 | n/a | else: |
---|
323 | n/a | raise InvalidTheme('Invalid theme type specified') |
---|
324 | n/a | # Provide foreground and background colors for each theme |
---|
325 | n/a | # element (other than cursor) even though some values are not |
---|
326 | n/a | # yet used by idle, to allow for their use in the future. |
---|
327 | n/a | # Default values are generally black and white. |
---|
328 | n/a | # TODO copy theme from a class attribute. |
---|
329 | n/a | theme ={'normal-foreground':'#000000', |
---|
330 | n/a | 'normal-background':'#ffffff', |
---|
331 | n/a | 'keyword-foreground':'#000000', |
---|
332 | n/a | 'keyword-background':'#ffffff', |
---|
333 | n/a | 'builtin-foreground':'#000000', |
---|
334 | n/a | 'builtin-background':'#ffffff', |
---|
335 | n/a | 'comment-foreground':'#000000', |
---|
336 | n/a | 'comment-background':'#ffffff', |
---|
337 | n/a | 'string-foreground':'#000000', |
---|
338 | n/a | 'string-background':'#ffffff', |
---|
339 | n/a | 'definition-foreground':'#000000', |
---|
340 | n/a | 'definition-background':'#ffffff', |
---|
341 | n/a | 'hilite-foreground':'#000000', |
---|
342 | n/a | 'hilite-background':'gray', |
---|
343 | n/a | 'break-foreground':'#ffffff', |
---|
344 | n/a | 'break-background':'#000000', |
---|
345 | n/a | 'hit-foreground':'#ffffff', |
---|
346 | n/a | 'hit-background':'#000000', |
---|
347 | n/a | 'error-foreground':'#ffffff', |
---|
348 | n/a | 'error-background':'#000000', |
---|
349 | n/a | #cursor (only foreground can be set) |
---|
350 | n/a | 'cursor-foreground':'#000000', |
---|
351 | n/a | #shell window |
---|
352 | n/a | 'stdout-foreground':'#000000', |
---|
353 | n/a | 'stdout-background':'#ffffff', |
---|
354 | n/a | 'stderr-foreground':'#000000', |
---|
355 | n/a | 'stderr-background':'#ffffff', |
---|
356 | n/a | 'console-foreground':'#000000', |
---|
357 | n/a | 'console-background':'#ffffff' } |
---|
358 | n/a | for element in theme: |
---|
359 | n/a | if not cfgParser.has_option(themeName, element): |
---|
360 | n/a | # Print warning that will return a default color |
---|
361 | n/a | warning = ('\n Warning: config.IdleConf.GetThemeDict' |
---|
362 | n/a | ' -\n problem retrieving theme element %r' |
---|
363 | n/a | '\n from theme %r.\n' |
---|
364 | n/a | ' returning default color: %r' % |
---|
365 | n/a | (element, themeName, theme[element])) |
---|
366 | n/a | _warn(warning, 'highlight', themeName, element) |
---|
367 | n/a | theme[element] = cfgParser.Get( |
---|
368 | n/a | themeName, element, default=theme[element]) |
---|
369 | n/a | return theme |
---|
370 | n/a | |
---|
371 | n/a | def CurrentTheme(self): |
---|
372 | n/a | "Return the name of the currently active text color theme." |
---|
373 | n/a | return self.current_colors_and_keys('Theme') |
---|
374 | n/a | |
---|
375 | n/a | def CurrentKeys(self): |
---|
376 | n/a | """Return the name of the currently active key set.""" |
---|
377 | n/a | return self.current_colors_and_keys('Keys') |
---|
378 | n/a | |
---|
379 | n/a | def current_colors_and_keys(self, section): |
---|
380 | n/a | """Return the currently active name for Theme or Keys section. |
---|
381 | n/a | |
---|
382 | n/a | idlelib.config-main.def ('default') includes these sections |
---|
383 | n/a | |
---|
384 | n/a | [Theme] |
---|
385 | n/a | default= 1 |
---|
386 | n/a | name= IDLE Classic |
---|
387 | n/a | name2= |
---|
388 | n/a | |
---|
389 | n/a | [Keys] |
---|
390 | n/a | default= 1 |
---|
391 | n/a | name= |
---|
392 | n/a | name2= |
---|
393 | n/a | |
---|
394 | n/a | Item 'name2', is used for built-in ('default') themes and keys |
---|
395 | n/a | added after 2015 Oct 1 and 2016 July 1. This kludge is needed |
---|
396 | n/a | because setting 'name' to a builtin not defined in older IDLEs |
---|
397 | n/a | to display multiple error messages or quit. |
---|
398 | n/a | See https://bugs.python.org/issue25313. |
---|
399 | n/a | When default = True, 'name2' takes precedence over 'name', |
---|
400 | n/a | while older IDLEs will just use name. When default = False, |
---|
401 | n/a | 'name2' may still be set, but it is ignored. |
---|
402 | n/a | """ |
---|
403 | n/a | cfgname = 'highlight' if section == 'Theme' else 'keys' |
---|
404 | n/a | default = self.GetOption('main', section, 'default', |
---|
405 | n/a | type='bool', default=True) |
---|
406 | n/a | name = '' |
---|
407 | n/a | if default: |
---|
408 | n/a | name = self.GetOption('main', section, 'name2', default='') |
---|
409 | n/a | if not name: |
---|
410 | n/a | name = self.GetOption('main', section, 'name', default='') |
---|
411 | n/a | if name: |
---|
412 | n/a | source = self.defaultCfg if default else self.userCfg |
---|
413 | n/a | if source[cfgname].has_section(name): |
---|
414 | n/a | return name |
---|
415 | n/a | return "IDLE Classic" if section == 'Theme' else self.default_keys() |
---|
416 | n/a | |
---|
417 | n/a | @staticmethod |
---|
418 | n/a | def default_keys(): |
---|
419 | n/a | if sys.platform[:3] == 'win': |
---|
420 | n/a | return 'IDLE Classic Windows' |
---|
421 | n/a | elif sys.platform == 'darwin': |
---|
422 | n/a | return 'IDLE Classic OSX' |
---|
423 | n/a | else: |
---|
424 | n/a | return 'IDLE Modern Unix' |
---|
425 | n/a | |
---|
426 | n/a | def GetExtensions(self, active_only=True, |
---|
427 | n/a | editor_only=False, shell_only=False): |
---|
428 | n/a | """Return extensions in default and user config-extensions files. |
---|
429 | n/a | |
---|
430 | n/a | If active_only True, only return active (enabled) extensions |
---|
431 | n/a | and optionally only editor or shell extensions. |
---|
432 | n/a | If active_only False, return all extensions. |
---|
433 | n/a | """ |
---|
434 | n/a | extns = self.RemoveKeyBindNames( |
---|
435 | n/a | self.GetSectionList('default', 'extensions')) |
---|
436 | n/a | userExtns = self.RemoveKeyBindNames( |
---|
437 | n/a | self.GetSectionList('user', 'extensions')) |
---|
438 | n/a | for extn in userExtns: |
---|
439 | n/a | if extn not in extns: #user has added own extension |
---|
440 | n/a | extns.append(extn) |
---|
441 | n/a | if active_only: |
---|
442 | n/a | activeExtns = [] |
---|
443 | n/a | for extn in extns: |
---|
444 | n/a | if self.GetOption('extensions', extn, 'enable', default=True, |
---|
445 | n/a | type='bool'): |
---|
446 | n/a | #the extension is enabled |
---|
447 | n/a | if editor_only or shell_only: # TODO both True contradict |
---|
448 | n/a | if editor_only: |
---|
449 | n/a | option = "enable_editor" |
---|
450 | n/a | else: |
---|
451 | n/a | option = "enable_shell" |
---|
452 | n/a | if self.GetOption('extensions', extn,option, |
---|
453 | n/a | default=True, type='bool', |
---|
454 | n/a | warn_on_default=False): |
---|
455 | n/a | activeExtns.append(extn) |
---|
456 | n/a | else: |
---|
457 | n/a | activeExtns.append(extn) |
---|
458 | n/a | return activeExtns |
---|
459 | n/a | else: |
---|
460 | n/a | return extns |
---|
461 | n/a | |
---|
462 | n/a | def RemoveKeyBindNames(self, extnNameList): |
---|
463 | n/a | "Return extnNameList with keybinding section names removed." |
---|
464 | n/a | # TODO Easier to return filtered copy with list comp |
---|
465 | n/a | names = extnNameList |
---|
466 | n/a | kbNameIndicies = [] |
---|
467 | n/a | for name in names: |
---|
468 | n/a | if name.endswith(('_bindings', '_cfgBindings')): |
---|
469 | n/a | kbNameIndicies.append(names.index(name)) |
---|
470 | n/a | kbNameIndicies.sort(reverse=True) |
---|
471 | n/a | for index in kbNameIndicies: #delete each keybinding section name |
---|
472 | n/a | del(names[index]) |
---|
473 | n/a | return names |
---|
474 | n/a | |
---|
475 | n/a | def GetExtnNameForEvent(self, virtualEvent): |
---|
476 | n/a | """Return the name of the extension binding virtualEvent, or None. |
---|
477 | n/a | |
---|
478 | n/a | virtualEvent - string, name of the virtual event to test for, |
---|
479 | n/a | without the enclosing '<< >>' |
---|
480 | n/a | """ |
---|
481 | n/a | extName = None |
---|
482 | n/a | vEvent = '<<' + virtualEvent + '>>' |
---|
483 | n/a | for extn in self.GetExtensions(active_only=0): |
---|
484 | n/a | for event in self.GetExtensionKeys(extn): |
---|
485 | n/a | if event == vEvent: |
---|
486 | n/a | extName = extn # TODO return here? |
---|
487 | n/a | return extName |
---|
488 | n/a | |
---|
489 | n/a | def GetExtensionKeys(self, extensionName): |
---|
490 | n/a | """Return dict: {configurable extensionName event : active keybinding}. |
---|
491 | n/a | |
---|
492 | n/a | Events come from default config extension_cfgBindings section. |
---|
493 | n/a | Keybindings come from GetCurrentKeySet() active key dict, |
---|
494 | n/a | where previously used bindings are disabled. |
---|
495 | n/a | """ |
---|
496 | n/a | keysName = extensionName + '_cfgBindings' |
---|
497 | n/a | activeKeys = self.GetCurrentKeySet() |
---|
498 | n/a | extKeys = {} |
---|
499 | n/a | if self.defaultCfg['extensions'].has_section(keysName): |
---|
500 | n/a | eventNames = self.defaultCfg['extensions'].GetOptionList(keysName) |
---|
501 | n/a | for eventName in eventNames: |
---|
502 | n/a | event = '<<' + eventName + '>>' |
---|
503 | n/a | binding = activeKeys[event] |
---|
504 | n/a | extKeys[event] = binding |
---|
505 | n/a | return extKeys |
---|
506 | n/a | |
---|
507 | n/a | def __GetRawExtensionKeys(self,extensionName): |
---|
508 | n/a | """Return dict {configurable extensionName event : keybinding list}. |
---|
509 | n/a | |
---|
510 | n/a | Events come from default config extension_cfgBindings section. |
---|
511 | n/a | Keybindings list come from the splitting of GetOption, which |
---|
512 | n/a | tries user config before default config. |
---|
513 | n/a | """ |
---|
514 | n/a | keysName = extensionName+'_cfgBindings' |
---|
515 | n/a | extKeys = {} |
---|
516 | n/a | if self.defaultCfg['extensions'].has_section(keysName): |
---|
517 | n/a | eventNames = self.defaultCfg['extensions'].GetOptionList(keysName) |
---|
518 | n/a | for eventName in eventNames: |
---|
519 | n/a | binding = self.GetOption( |
---|
520 | n/a | 'extensions', keysName, eventName, default='').split() |
---|
521 | n/a | event = '<<' + eventName + '>>' |
---|
522 | n/a | extKeys[event] = binding |
---|
523 | n/a | return extKeys |
---|
524 | n/a | |
---|
525 | n/a | def GetExtensionBindings(self, extensionName): |
---|
526 | n/a | """Return dict {extensionName event : active or defined keybinding}. |
---|
527 | n/a | |
---|
528 | n/a | Augment self.GetExtensionKeys(extensionName) with mapping of non- |
---|
529 | n/a | configurable events (from default config) to GetOption splits, |
---|
530 | n/a | as in self.__GetRawExtensionKeys. |
---|
531 | n/a | """ |
---|
532 | n/a | bindsName = extensionName + '_bindings' |
---|
533 | n/a | extBinds = self.GetExtensionKeys(extensionName) |
---|
534 | n/a | #add the non-configurable bindings |
---|
535 | n/a | if self.defaultCfg['extensions'].has_section(bindsName): |
---|
536 | n/a | eventNames = self.defaultCfg['extensions'].GetOptionList(bindsName) |
---|
537 | n/a | for eventName in eventNames: |
---|
538 | n/a | binding = self.GetOption( |
---|
539 | n/a | 'extensions', bindsName, eventName, default='').split() |
---|
540 | n/a | event = '<<' + eventName + '>>' |
---|
541 | n/a | extBinds[event] = binding |
---|
542 | n/a | |
---|
543 | n/a | return extBinds |
---|
544 | n/a | |
---|
545 | n/a | def GetKeyBinding(self, keySetName, eventStr): |
---|
546 | n/a | """Return the keybinding list for keySetName eventStr. |
---|
547 | n/a | |
---|
548 | n/a | keySetName - name of key binding set (config-keys section). |
---|
549 | n/a | eventStr - virtual event, including brackets, as in '<<event>>'. |
---|
550 | n/a | """ |
---|
551 | n/a | eventName = eventStr[2:-2] #trim off the angle brackets |
---|
552 | n/a | binding = self.GetOption('keys', keySetName, eventName, default='', |
---|
553 | n/a | warn_on_default=False).split() |
---|
554 | n/a | return binding |
---|
555 | n/a | |
---|
556 | n/a | def GetCurrentKeySet(self): |
---|
557 | n/a | "Return CurrentKeys with 'darwin' modifications." |
---|
558 | n/a | result = self.GetKeySet(self.CurrentKeys()) |
---|
559 | n/a | |
---|
560 | n/a | if sys.platform == "darwin": |
---|
561 | n/a | # OS X Tk variants do not support the "Alt" keyboard modifier. |
---|
562 | n/a | # So replace all keybingings that use "Alt" with ones that |
---|
563 | n/a | # use the "Option" keyboard modifier. |
---|
564 | n/a | # TODO (Ned?): the "Option" modifier does not work properly for |
---|
565 | n/a | # Cocoa Tk and XQuartz Tk so we should not use it |
---|
566 | n/a | # in default OS X KeySets. |
---|
567 | n/a | for k, v in result.items(): |
---|
568 | n/a | v2 = [ x.replace('<Alt-', '<Option-') for x in v ] |
---|
569 | n/a | if v != v2: |
---|
570 | n/a | result[k] = v2 |
---|
571 | n/a | |
---|
572 | n/a | return result |
---|
573 | n/a | |
---|
574 | n/a | def GetKeySet(self, keySetName): |
---|
575 | n/a | """Return event-key dict for keySetName core plus active extensions. |
---|
576 | n/a | |
---|
577 | n/a | If a binding defined in an extension is already in use, the |
---|
578 | n/a | extension binding is disabled by being set to '' |
---|
579 | n/a | """ |
---|
580 | n/a | keySet = self.GetCoreKeys(keySetName) |
---|
581 | n/a | activeExtns = self.GetExtensions(active_only=1) |
---|
582 | n/a | for extn in activeExtns: |
---|
583 | n/a | extKeys = self.__GetRawExtensionKeys(extn) |
---|
584 | n/a | if extKeys: #the extension defines keybindings |
---|
585 | n/a | for event in extKeys: |
---|
586 | n/a | if extKeys[event] in keySet.values(): |
---|
587 | n/a | #the binding is already in use |
---|
588 | n/a | extKeys[event] = '' #disable this binding |
---|
589 | n/a | keySet[event] = extKeys[event] #add binding |
---|
590 | n/a | return keySet |
---|
591 | n/a | |
---|
592 | n/a | def IsCoreBinding(self, virtualEvent): |
---|
593 | n/a | """Return True if the virtual event is one of the core idle key events. |
---|
594 | n/a | |
---|
595 | n/a | virtualEvent - string, name of the virtual event to test for, |
---|
596 | n/a | without the enclosing '<< >>' |
---|
597 | n/a | """ |
---|
598 | n/a | return ('<<'+virtualEvent+'>>') in self.GetCoreKeys() |
---|
599 | n/a | |
---|
600 | n/a | # TODO make keyBindins a file or class attribute used for test above |
---|
601 | n/a | # and copied in function below |
---|
602 | n/a | |
---|
603 | n/a | def GetCoreKeys(self, keySetName=None): |
---|
604 | n/a | """Return dict of core virtual-key keybindings for keySetName. |
---|
605 | n/a | |
---|
606 | n/a | The default keySetName None corresponds to the keyBindings base |
---|
607 | n/a | dict. If keySetName is not None, bindings from the config |
---|
608 | n/a | file(s) are loaded _over_ these defaults, so if there is a |
---|
609 | n/a | problem getting any core binding there will be an 'ultimate last |
---|
610 | n/a | resort fallback' to the CUA-ish bindings defined here. |
---|
611 | n/a | """ |
---|
612 | n/a | keyBindings={ |
---|
613 | n/a | '<<copy>>': ['<Control-c>', '<Control-C>'], |
---|
614 | n/a | '<<cut>>': ['<Control-x>', '<Control-X>'], |
---|
615 | n/a | '<<paste>>': ['<Control-v>', '<Control-V>'], |
---|
616 | n/a | '<<beginning-of-line>>': ['<Control-a>', '<Home>'], |
---|
617 | n/a | '<<center-insert>>': ['<Control-l>'], |
---|
618 | n/a | '<<close-all-windows>>': ['<Control-q>'], |
---|
619 | n/a | '<<close-window>>': ['<Alt-F4>'], |
---|
620 | n/a | '<<do-nothing>>': ['<Control-x>'], |
---|
621 | n/a | '<<end-of-file>>': ['<Control-d>'], |
---|
622 | n/a | '<<python-docs>>': ['<F1>'], |
---|
623 | n/a | '<<python-context-help>>': ['<Shift-F1>'], |
---|
624 | n/a | '<<history-next>>': ['<Alt-n>'], |
---|
625 | n/a | '<<history-previous>>': ['<Alt-p>'], |
---|
626 | n/a | '<<interrupt-execution>>': ['<Control-c>'], |
---|
627 | n/a | '<<view-restart>>': ['<F6>'], |
---|
628 | n/a | '<<restart-shell>>': ['<Control-F6>'], |
---|
629 | n/a | '<<open-class-browser>>': ['<Alt-c>'], |
---|
630 | n/a | '<<open-module>>': ['<Alt-m>'], |
---|
631 | n/a | '<<open-new-window>>': ['<Control-n>'], |
---|
632 | n/a | '<<open-window-from-file>>': ['<Control-o>'], |
---|
633 | n/a | '<<plain-newline-and-indent>>': ['<Control-j>'], |
---|
634 | n/a | '<<print-window>>': ['<Control-p>'], |
---|
635 | n/a | '<<redo>>': ['<Control-y>'], |
---|
636 | n/a | '<<remove-selection>>': ['<Escape>'], |
---|
637 | n/a | '<<save-copy-of-window-as-file>>': ['<Alt-Shift-S>'], |
---|
638 | n/a | '<<save-window-as-file>>': ['<Alt-s>'], |
---|
639 | n/a | '<<save-window>>': ['<Control-s>'], |
---|
640 | n/a | '<<select-all>>': ['<Alt-a>'], |
---|
641 | n/a | '<<toggle-auto-coloring>>': ['<Control-slash>'], |
---|
642 | n/a | '<<undo>>': ['<Control-z>'], |
---|
643 | n/a | '<<find-again>>': ['<Control-g>', '<F3>'], |
---|
644 | n/a | '<<find-in-files>>': ['<Alt-F3>'], |
---|
645 | n/a | '<<find-selection>>': ['<Control-F3>'], |
---|
646 | n/a | '<<find>>': ['<Control-f>'], |
---|
647 | n/a | '<<replace>>': ['<Control-h>'], |
---|
648 | n/a | '<<goto-line>>': ['<Alt-g>'], |
---|
649 | n/a | '<<smart-backspace>>': ['<Key-BackSpace>'], |
---|
650 | n/a | '<<newline-and-indent>>': ['<Key-Return>', '<Key-KP_Enter>'], |
---|
651 | n/a | '<<smart-indent>>': ['<Key-Tab>'], |
---|
652 | n/a | '<<indent-region>>': ['<Control-Key-bracketright>'], |
---|
653 | n/a | '<<dedent-region>>': ['<Control-Key-bracketleft>'], |
---|
654 | n/a | '<<comment-region>>': ['<Alt-Key-3>'], |
---|
655 | n/a | '<<uncomment-region>>': ['<Alt-Key-4>'], |
---|
656 | n/a | '<<tabify-region>>': ['<Alt-Key-5>'], |
---|
657 | n/a | '<<untabify-region>>': ['<Alt-Key-6>'], |
---|
658 | n/a | '<<toggle-tabs>>': ['<Alt-Key-t>'], |
---|
659 | n/a | '<<change-indentwidth>>': ['<Alt-Key-u>'], |
---|
660 | n/a | '<<del-word-left>>': ['<Control-Key-BackSpace>'], |
---|
661 | n/a | '<<del-word-right>>': ['<Control-Key-Delete>'] |
---|
662 | n/a | } |
---|
663 | n/a | if keySetName: |
---|
664 | n/a | if not (self.userCfg['keys'].has_section(keySetName) or |
---|
665 | n/a | self.defaultCfg['keys'].has_section(keySetName)): |
---|
666 | n/a | warning = ( |
---|
667 | n/a | '\n Warning: config.py - IdleConf.GetCoreKeys -\n' |
---|
668 | n/a | ' key set %r is not defined, using default bindings.' % |
---|
669 | n/a | (keySetName,) |
---|
670 | n/a | ) |
---|
671 | n/a | _warn(warning, 'keys', keySetName) |
---|
672 | n/a | else: |
---|
673 | n/a | for event in keyBindings: |
---|
674 | n/a | binding = self.GetKeyBinding(keySetName, event) |
---|
675 | n/a | if binding: |
---|
676 | n/a | keyBindings[event] = binding |
---|
677 | n/a | else: #we are going to return a default, print warning |
---|
678 | n/a | warning = ( |
---|
679 | n/a | '\n Warning: config.py - IdleConf.GetCoreKeys -\n' |
---|
680 | n/a | ' problem retrieving key binding for event %r\n' |
---|
681 | n/a | ' from key set %r.\n' |
---|
682 | n/a | ' returning default value: %r' % |
---|
683 | n/a | (event, keySetName, keyBindings[event]) |
---|
684 | n/a | ) |
---|
685 | n/a | _warn(warning, 'keys', keySetName, event) |
---|
686 | n/a | return keyBindings |
---|
687 | n/a | |
---|
688 | n/a | def GetExtraHelpSourceList(self, configSet): |
---|
689 | n/a | """Return list of extra help sources from a given configSet. |
---|
690 | n/a | |
---|
691 | n/a | Valid configSets are 'user' or 'default'. Return a list of tuples of |
---|
692 | n/a | the form (menu_item , path_to_help_file , option), or return the empty |
---|
693 | n/a | list. 'option' is the sequence number of the help resource. 'option' |
---|
694 | n/a | values determine the position of the menu items on the Help menu, |
---|
695 | n/a | therefore the returned list must be sorted by 'option'. |
---|
696 | n/a | |
---|
697 | n/a | """ |
---|
698 | n/a | helpSources = [] |
---|
699 | n/a | if configSet == 'user': |
---|
700 | n/a | cfgParser = self.userCfg['main'] |
---|
701 | n/a | elif configSet == 'default': |
---|
702 | n/a | cfgParser = self.defaultCfg['main'] |
---|
703 | n/a | else: |
---|
704 | n/a | raise InvalidConfigSet('Invalid configSet specified') |
---|
705 | n/a | options=cfgParser.GetOptionList('HelpFiles') |
---|
706 | n/a | for option in options: |
---|
707 | n/a | value=cfgParser.Get('HelpFiles', option, default=';') |
---|
708 | n/a | if value.find(';') == -1: #malformed config entry with no ';' |
---|
709 | n/a | menuItem = '' #make these empty |
---|
710 | n/a | helpPath = '' #so value won't be added to list |
---|
711 | n/a | else: #config entry contains ';' as expected |
---|
712 | n/a | value=value.split(';') |
---|
713 | n/a | menuItem=value[0].strip() |
---|
714 | n/a | helpPath=value[1].strip() |
---|
715 | n/a | if menuItem and helpPath: #neither are empty strings |
---|
716 | n/a | helpSources.append( (menuItem,helpPath,option) ) |
---|
717 | n/a | helpSources.sort(key=lambda x: x[2]) |
---|
718 | n/a | return helpSources |
---|
719 | n/a | |
---|
720 | n/a | def GetAllExtraHelpSourcesList(self): |
---|
721 | n/a | """Return a list of the details of all additional help sources. |
---|
722 | n/a | |
---|
723 | n/a | Tuples in the list are those of GetExtraHelpSourceList. |
---|
724 | n/a | """ |
---|
725 | n/a | allHelpSources = (self.GetExtraHelpSourceList('default') + |
---|
726 | n/a | self.GetExtraHelpSourceList('user') ) |
---|
727 | n/a | return allHelpSources |
---|
728 | n/a | |
---|
729 | n/a | def GetFont(self, root, configType, section): |
---|
730 | n/a | """Retrieve a font from configuration (font, font-size, font-bold) |
---|
731 | n/a | Intercept the special value 'TkFixedFont' and substitute |
---|
732 | n/a | the actual font, factoring in some tweaks if needed for |
---|
733 | n/a | appearance sakes. |
---|
734 | n/a | |
---|
735 | n/a | The 'root' parameter can normally be any valid Tkinter widget. |
---|
736 | n/a | |
---|
737 | n/a | Return a tuple (family, size, weight) suitable for passing |
---|
738 | n/a | to tkinter.Font |
---|
739 | n/a | """ |
---|
740 | n/a | family = self.GetOption(configType, section, 'font', default='courier') |
---|
741 | n/a | size = self.GetOption(configType, section, 'font-size', type='int', |
---|
742 | n/a | default='10') |
---|
743 | n/a | bold = self.GetOption(configType, section, 'font-bold', default=0, |
---|
744 | n/a | type='bool') |
---|
745 | n/a | if (family == 'TkFixedFont'): |
---|
746 | n/a | f = Font(name='TkFixedFont', exists=True, root=root) |
---|
747 | n/a | actualFont = Font.actual(f) |
---|
748 | n/a | family = actualFont['family'] |
---|
749 | n/a | size = actualFont['size'] |
---|
750 | n/a | if size <= 0: |
---|
751 | n/a | size = 10 # if font in pixels, ignore actual size |
---|
752 | n/a | bold = actualFont['weight'] == 'bold' |
---|
753 | n/a | return (family, size, 'bold' if bold else 'normal') |
---|
754 | n/a | |
---|
755 | n/a | def LoadCfgFiles(self): |
---|
756 | n/a | "Load all configuration files." |
---|
757 | n/a | for key in self.defaultCfg: |
---|
758 | n/a | self.defaultCfg[key].Load() |
---|
759 | n/a | self.userCfg[key].Load() #same keys |
---|
760 | n/a | |
---|
761 | n/a | def SaveUserCfgFiles(self): |
---|
762 | n/a | "Write all loaded user configuration files to disk." |
---|
763 | n/a | for key in self.userCfg: |
---|
764 | n/a | self.userCfg[key].Save() |
---|
765 | n/a | |
---|
766 | n/a | |
---|
767 | n/a | idleConf = IdleConf() |
---|
768 | n/a | |
---|
769 | n/a | |
---|
770 | n/a | _warned = set() |
---|
771 | n/a | def _warn(msg, *key): |
---|
772 | n/a | key = (msg,) + key |
---|
773 | n/a | if key not in _warned: |
---|
774 | n/a | try: |
---|
775 | n/a | print(msg, file=sys.stderr) |
---|
776 | n/a | except OSError: |
---|
777 | n/a | pass |
---|
778 | n/a | _warned.add(key) |
---|
779 | n/a | |
---|
780 | n/a | |
---|
781 | n/a | # TODO Revise test output, write expanded unittest |
---|
782 | n/a | # |
---|
783 | n/a | if __name__ == '__main__': |
---|
784 | n/a | from zlib import crc32 |
---|
785 | n/a | line, crc = 0, 0 |
---|
786 | n/a | |
---|
787 | n/a | def sprint(obj): |
---|
788 | n/a | global line, crc |
---|
789 | n/a | txt = str(obj) |
---|
790 | n/a | line += 1 |
---|
791 | n/a | crc = crc32(txt.encode(encoding='utf-8'), crc) |
---|
792 | n/a | print(txt) |
---|
793 | n/a | #print('***', line, crc, '***') # uncomment for diagnosis |
---|
794 | n/a | |
---|
795 | n/a | def dumpCfg(cfg): |
---|
796 | n/a | print('\n', cfg, '\n') # has variable '0xnnnnnnnn' addresses |
---|
797 | n/a | for key in sorted(cfg.keys()): |
---|
798 | n/a | sections = cfg[key].sections() |
---|
799 | n/a | sprint(key) |
---|
800 | n/a | sprint(sections) |
---|
801 | n/a | for section in sections: |
---|
802 | n/a | options = cfg[key].options(section) |
---|
803 | n/a | sprint(section) |
---|
804 | n/a | sprint(options) |
---|
805 | n/a | for option in options: |
---|
806 | n/a | sprint(option + ' = ' + cfg[key].Get(section, option)) |
---|
807 | n/a | |
---|
808 | n/a | dumpCfg(idleConf.defaultCfg) |
---|
809 | n/a | dumpCfg(idleConf.userCfg) |
---|
810 | n/a | print('\nlines = ', line, ', crc = ', crc, sep='') |
---|