summaryrefslogtreecommitdiffstats
path: root/Lib/idlelib/configHandler.py
blob: ba1845715a6e7652223a62d9d1249d0f288d970a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
"""
Provides access to stored idle configuration information.
"""
# Throughout this module there is an emphasis on returning useable defaults
# when a problem occurs in returning a requested configuration value back to
# idle. This is to allow idle to continue to function in spite of errors in
# the retrieval of config information. When a default is returned instead of
# a requested config value, a message is printed to stderr to aid in 
# configuration problem notification and resolution. 

import os
import sys
from ConfigParser import ConfigParser, NoOptionError, NoSectionError

class IdleConfParser(ConfigParser):
    """
    A ConfigParser specialised for idle configuration file handling
    """
    def __init__(self, cfgFile, cfgDefaults=None):
        """
        cfgFile - string, fully specified configuration file name
        """
        self.file=cfgFile
        ConfigParser.__init__(self,defaults=cfgDefaults)
    
    def Get(self, section, option, type=None): #,default=None)
        """
        Get an option value for given section/option or return default.
        If type is specified, return as type.
        """
        if type=='bool': 
            getVal=self.getboolean
        elif type=='int': 
            getVal=self.getint
        else: 
            getVal=self.get
        if self.has_option(section,option):
            #return getVal(section, option, raw, vars)
            return getVal(section, option)

    def GetOptionList(self,section):
        """
        Get an option list for given section
        """
        if self.has_section:
            return self.options(section)
        else:  #return a default value
            return []

    def Load(self):
        """ 
        Load the configuration file from disk 
        """
        self.read(self.file)
        
class IdleUserConfParser(IdleConfParser):
    """
    IdleConfigParser specialised for user configuration handling
    """
    def Save(self):
        """
        write loaded user configuration file back to disk
        """
        # this is a user config, it can be written to disk
        self.write()

class IdleConf:
    """
    holds config parsers for all idle config files:
    default config files
        (idle install dir)/config-main.def
        (idle install dir)/config-extensions.def
        (idle install dir)/config-highlight.def
        (idle install dir)/config-keys.def
    user config  files
        (user home dir)/.idlerc/config-main.cfg
        (user home dir)/.idlerc/config-extensions.cfg
        (user home dir)/.idlerc/config-highlight.cfg
        (user home dir)/.idlerc/config-keys.cfg
    """
    def __init__(self):
        self.defaultCfg={}
        self.userCfg={}
        self.cfg={}
        self.CreateConfigHandlers()
        self.LoadCfgFiles()
        #self.LoadCfg()
            
    def CreateConfigHandlers(self):
        """
        set up a dictionary of config parsers for default and user 
        configurations respectively
        """
        #build idle install path
        if __name__ != '__main__': # we were imported
            idledir=os.path.dirname(__file__)
        else: # we were exec'ed (for testing only)
            idledir=os.path.abspath(sys.path[0])
        #print idledir
        try: #build user home path
            userdir = os.environ['HOME'] #real home directory
        except KeyError:
            userdir = os.getcwd() #hack for os'es without real homedirs
        userdir=os.path.join(userdir,'.idlerc')
        #print userdir
        if not os.path.exists(userdir):
            os.mkdir(userdir)
        configTypes=('main','extensions','highlight','keys')
        defCfgFiles={}
        usrCfgFiles={}
        for cfgType in configTypes: #build config file names
            defCfgFiles[cfgType]=os.path.join(idledir,'config-'+cfgType+'.def')                    
            usrCfgFiles[cfgType]=os.path.join(userdir,'config-'+cfgType+'.cfg')                    
        for cfgType in configTypes: #create config parsers
            self.defaultCfg[cfgType]=IdleConfParser(defCfgFiles[cfgType])
            self.userCfg[cfgType]=IdleUserConfParser(usrCfgFiles[cfgType])
    
    def GetOption(self, configType, section, option, default=None, type=None):
        """
        Get an option value for given config type and given general 
        configuration section/option or return a default. If type is specified,
        return as type. Firstly the user configuration is checked, with a 
        fallback to the default configuration, and a final 'catch all' 
        fallback to a useable passed-in default if the option isn't present in 
        either the user or the default configuration.
        configType must be one of ('main','extensions','highlight','keys')
        If a default is returned a warning is printed to stderr.
        """
        if self.userCfg[configType].has_option(section,option):
            return self.userCfg[configType].Get(section, option, type=type)
        elif self.defaultCfg[configType].has_option(section,option):
            return self.defaultCfg[configType].Get(section, option, type=type)
        else:
            warning=('\n Warning: configHandler.py - IdleConf.GetOption -\n'+
                       ' problem retrieving configration option '+`option`+'\n'+
                       ' from section '+`section`+'.\n'+
                       ' returning default value: '+`default`+'\n')
            sys.stderr.write(warning)
            return default
    
    def GetSectionList(self, configSet, configType):
        """
        Get a list of sections from either the user or default config for 
        the given config type.
        configSet must be either 'user' or 'default' 
        configType must be one of ('extensions','highlight','keys')
        """
        if not (configType in ('extensions','highlight','keys')):
            raise 'Invalid configType specified'
        if configSet == 'user':
            cfgParser=self.userCfg[configType]
        elif configSet == 'default':
            cfgParser=self.defaultCfg[configType]
        else:
            raise 'Invalid configSet specified'
        
        return cfgParser.sections()
    
    def GetHighlight(self, theme, element, fgBg=None):
        """
        return individual highlighting theme elements.
        fgBg - string ('fg'or'bg') or None, if None return a dictionary
        containing fg and bg colours (appropriate for passing to Tkinter in, 
        e.g., a tag_config call), otherwise fg or bg colour only as specified. 
        """
        #get some fallback defaults
        defaultFg=self.GetOption('highlight', theme, 'normal' + "-foreground",
            default='#000000')
        defaultBg=self.GetOption('highlight', theme, 'normal' + "-background",
            default='#ffffff')
        #try for requested element colours
        fore = self.GetOption('highlight', theme, element + "-foreground")
        back = None
        if element == 'cursor': #there is no config value for cursor bg
            back = None
        else:    
            back = self.GetOption('highlight', theme, element + "-background")
        #fall back if required
        if not fore: fore=defaultFg
        if not back: back=defaultBg
        highlight={"foreground": fore,"background": back}
        if not fgBg: #return dict of both colours
            return highlight
        else: #return specified colour only
            if fgBg == 'fg':
                return highlight["foreground"]
            if fgBg == 'bg':
                return highlight["background"]
            else:    
                raise 'Invalid fgBg specified'
            

    def GetTheme(self, name=None):
        """
        Gets the requested theme or returns a final fallback theme in case 
        one can't be obtained from either the user or default config files.
        """
        pass
    
    def CurrentTheme(self):
        """
        Returns the name of the currently active theme        
        """
        return self.GetOption('main','Theme','name',default='')
        

    def CurrentKeys(self):
        """
        Returns the name of the currently active theme        
        """
        return self.GetOption('main','Keys','name',default='')
    
    def GetExtensions(self, activeOnly=1):
        """
        Gets a list of all idle extensions declared in the config files.
        activeOnly - boolean, if true only return active (enabled) extensions
        """
        extns=self.GetSectionList('default','extensions')
        userExtns=self.GetSectionList('user','extensions')
        for extn in userExtns:
            if extn not in extns: #user has added own extension
                extns.append(extn) 
        if activeOnly:
            activeExtns=[]
            for extn in extns:
                if self.GetOption('extensions',extn,'enable',default=1,type='bool'):
                    #the extension is enabled
                    activeExtns.append(extn)
            return activeExtns
        else:
            return extns        

    def GetKeyBinding(self, keySetName, eventStr):
        """
        returns the keybinding for a specific event.
        keySetName - string, name of key binding set
        eventStr - string, the virtual event we want the binding for, 
                   represented as a string, eg. '<<event>>'
        """
        eventName=eventStr[2:-2] #trim off the angle brackets
        binding=self.GetOption('keys',keySetName,eventName,default='').split()
        return binding

    def GetKeys(self, keySetName=None):
        """
        returns the requested set of keybindings, with fallbacks if required.
        """
        #keybindings loaded from the config file(s) are loaded _over_ these
        #defaults, so if there is a problem getting any binding there will
        #be an 'ultimate last resort fallback' to the CUA-ish bindings
        #defined here.
        keyBindings={
            '<<Copy>>': ['<Control-c>', '<Control-C>'],
            '<<Cut>>': ['<Control-x>', '<Control-X>'],
            '<<Paste>>': ['<Control-v>', '<Control-V>'],
            '<<beginning-of-line>>': ['<Control-a>', '<Home>'],
            '<<center-insert>>': ['<Control-l>'],
            '<<close-all-windows>>': ['<Control-q>'],
            '<<close-window>>': ['<Alt-F4>'],
            '<<dump-undo-state>>': ['<Control-backslash>'],
            '<<end-of-file>>': ['<Control-d>'],
            '<<python-docs>>': ['<F1>'],
            '<<python-context-help>>': ['<Shift-F1>'], 
            '<<history-next>>': ['<Alt-n>'],
            '<<history-previous>>': ['<Alt-p>'],
            '<<interrupt-execution>>': ['<Control-c>'],
            '<<open-class-browser>>': ['<Alt-c>'],
            '<<open-module>>': ['<Alt-m>'],
            '<<open-new-window>>': ['<Control-n>'],
            '<<open-window-from-file>>': ['<Control-o>'],
            '<<plain-newline-and-indent>>': ['<Control-j>'],
            '<<redo>>': ['<Control-y>'],
            '<<remove-selection>>': ['<Escape>'],
            '<<save-copy-of-window-as-file>>': ['<Alt-Shift-s>'],
            '<<save-window-as-file>>': ['<Alt-s>'],
            '<<save-window>>': ['<Control-s>'],
            '<<select-all>>': ['<Alt-a>'],
            '<<toggle-auto-coloring>>': ['<Control-slash>'],
            '<<undo>>': ['<Control-z>'],
            '<<find-again>>': ['<Control-g>', '<F3>'],
            '<<find-in-files>>': ['<Alt-F3>'],
            '<<find-selection>>': ['<Control-F3>'],
            '<<find>>': ['<Control-f>'],
            '<<replace>>': ['<Control-h>'],
            '<<goto-line>>': ['<Alt-g>'] }
        
        if keySetName:
            for event in keyBindings.keys():
                binding=self.GetKeyBinding(keySetName,event)
                if binding: #otherwise will keep default
                    keyBindings[event]=binding
            
        return keyBindings

    
    def LoadCfgFiles(self):
        """ 
        load all configuration files.
        """
        for key in self.defaultCfg.keys():
            self.defaultCfg[key].Load()                    
            self.userCfg[key].Load() #same keys                    

    def SaveUserCfgFiles(self):
        """
        write all loaded user configuration files back to disk
        """
        for key in self.userCfg.keys():
            self.userCfg[key].Save()    

idleConf=IdleConf()

### module test
if __name__ == '__main__':
    def dumpCfg(cfg):
        print '\n',cfg,'\n'
        for key in cfg.keys():
            sections=cfg[key].sections()
            print key
            print sections
            for section in sections:
                options=cfg[key].options(section)
                print section    
                print options
                for option in options:
                    print option, '=', cfg[key].Get(section,option)
    dumpCfg(idleConf.defaultCfg)
    dumpCfg(idleConf.userCfg)
    print idleConf.userCfg['main'].Get('Theme','name')
    #print idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal')