File: Config.py

package info (click to toggle)
fofix-dfsg 3.121-2
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 27,016 kB
  • ctags: 4,131
  • sloc: python: 44,002; makefile: 99; perl: 42; sh: 39
file content (523 lines) | stat: -rwxr-xr-x 16,054 bytes parent folder | download | duplicates (4)
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
#####################################################################
# -*- coding: iso-8859-1 -*-                                        #
#                                                                   #
# Frets on Fire                                                     #
# Copyright (C) 2006 Sami Ky�stil�                                  #
#               2008 myfingershurt                                  #
#               2008 Capo                                           #
#               2008 Glorandwarf                                    #
#                                                                   #
# This program is free software; you can redistribute it and/or     #
# modify it under the terms of the GNU General Public License       #
# as published by the Free Software Foundation; either version 2    #
# of the License, or (at your option) any later version.            #
#                                                                   #
# This program is distributed in the hope that it will be useful,   #
# but WITHOUT ANY WARRANTY; without even the implied warranty of    #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the     #
# GNU General Public License for more details.                      #
#                                                                   #
# You should have received a copy of the GNU General Public License #
# along with this program; if not, write to the Free Software       #
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,        #
# MA  02110-1301, USA.                                              #
#####################################################################

from ConfigParser import ConfigParser
import Log
import Resource
import os

encoding  = "iso-8859-1"
config    = None
prototype = {}

logIniReads = 0   #MFH - INI reads disabled by default during the startup period
logUndefinedGets = 0 

class MyConfigParser(ConfigParser):
  def write(self, fp, type = 0):
      if type == 1:
        return self.writeController(fp)
      elif type == 2:
        return self.writePlayer(fp)
      if self._defaults:
        fp.write("[%s]\n" % DEFAULTSECT)
        for (key, value) in self._defaults.items():
          fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
      sections = sorted(self._sections)
      for section in sections:
        if section == "theme":
          continue
        elif section == "controller":
          continue
        elif section == "player":
          continue
        fp.write("[%s]\n" % section)
        sectList = self._sections[section].items()
        sectList.sort()
        for key, value in sectList:
          if key != "__name__":
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
        
  def writeTheme(self, fp):
      if self._defaults:
        fp.write("[%s]\n" % DEFAULTSECT)
        for (key, value) in self._defaults.items():
          fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
      sections = sorted(self._sections)
      for section in sections:
        if section != "theme":
          continue
        fp.write("[%s]\n" % section)
        sectList = self._sections[section].items()
        sectList.sort()
        for key, value in sectList:
          if key != "__name__":
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
  
  def writeController(self, fp):
      if self._defaults:
        fp.write("[%s]\n" % DEFAULTSECT)
        for (key, value) in self._defaults.items():
          fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
      sections = sorted(self._sections)
      for section in sections:
        if section != "controller":
          continue
        fp.write("[%s]\n" % section)
        sectList = self._sections[section].items()
        sectList.sort()
        for key, value in sectList:
          if key != "__name__":
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
  
  def writePlayer(self, fp):
      if self._defaults:
        fp.write("[%s]\n" % DEFAULTSECT)
        for (key, value) in self._defaults.items():
          fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
      sections = sorted(self._sections)
      for section in sections:
        if section != "player":
          continue
        fp.write("[%s]\n" % section)
        sectList = self._sections[section].items()
        sectList.sort()
        for key, value in sectList:
          if key != "__name__":
            fp.write("%s = %s\n" % (key, str(value).replace('\n', '\n\t')))
        fp.write("\n")
        
class Option:
  """A prototype configuration key."""
  def __init__(self, **args):
    for key, value in args.items():
      setattr(self, key, value)
      
def define(section, option, type, default = None, text = None, options = None, prototype = prototype, tipText = None):
  """
  Define a configuration key.
  
  @param section:    Section name
  @param option:     Option name
  @param type:       Key type (e.g. str, int, ...)
  @param default:    Default value for the key
  @param text:       Text description for the key
  @param options:    Either a mapping of values to text descriptions
                    (e.g. {True: 'Yes', False: 'No'}) or a list of possible values
  @param prototype:  Configuration prototype mapping
  @param tipText:    Helpful tip text to display in option menus.
  """
  if not section in prototype:
    prototype[section] = {}
    
  if type == bool and not options:
    options = [True, False]
    
  prototype[section][option] = Option(type = type, default = default, text = text, options = options, tipText = tipText)

def load(fileName = None, setAsDefault = False, type = 0):
  """Load a configuration with the default prototype"""
  global config, logIniReads, logUndefinedGets
  c = Config(prototype, fileName, type)
  if setAsDefault and not config:
    config = c
  logIniReads = c.get("game", "log_ini_reads")
  logUndefinedGets = c.get("game", "log_undefined_gets")
  return c

#def unLoad():   #MFH - to unload the global config object for later reload
#  global config
#  config = None

class Config:
  """A configuration registry."""
  def __init__(self, prototype, fileName = None, type = 0):
    """
    @param prototype:  The configuration protype mapping
    @param fileName:   The file that holds this configuration registry
    """
    self.prototype = prototype

    # read configuration
    self.config = MyConfigParser()

    if fileName:
      if not os.path.isfile(fileName):
        path = Resource.getWritableResourcePath()
        fileName = os.path.join(path, fileName)
      self.config.read(fileName)
  
    self.fileName  = fileName
    self.type = type
  
    # fix the defaults and non-existing keys
    for section, options in prototype.items():
      if not self.config.has_section(section):
        self.config.add_section(section)
      for option in options.keys():
        type    = options[option].type
        default = options[option].default
        if not self.config.has_option(section, option):
          self.config.set(section, option, str(default))
    
  def get(self, section, option):
    """
    Read a configuration key.
    
    @param section:   Section name
    @param option:    Option name
    @return:          Key value
    """
    
    global logIniReads, logUndefinedGets

    try:
      type    = self.prototype[section][option].type
      default = self.prototype[section][option].default
    except KeyError:
      if logUndefinedGets == 1:
        Log.warn("Config key %s.%s not defined while reading %s." % (section, option, self.fileName))
      type, default = str, None
  
    value = self.config.has_option(section, option) and self.config.get(section, option) or default
    if type == bool:
      value = str(value).lower()
      if value in ("1", "true", "yes", "on"):
        value = True
      elif value in ("none", ""):
        value = default #allows None-default bools to return None
      else:
        value = False
    else:
      try:
        value = type(value)
      except:
        value = None
      
    #myfingershurt: verbose log output
    if logIniReads == 1:
      Log.debug("Config.get: %s.%s = %s" % (section, option, value))
    return value
  
  def getOptions(self, section, option):
    """
    Read the preset options of a configuration key.
    
    @param section:   Section name
    @param option:    Option name
    @return:          Tuple of Key list and Values list
    """
    global logIniReads, logUndefinedGets


    try:
      options = self.prototype[section][option].options.values()
      keys    = self.prototype[section][option].options.keys()
      type    = self.prototype[section][option].type
    except KeyError:
      if logUndefinedGets == 1:
        Log.warn("Config key %s.%s not defined while reading %s." % (section, option, self.fileName))
      type = None
      
    optionList = []
  
    if type != None:
      for i in range(len(options)):
        value = keys[i]
        if type == bool:
          value = str(value).lower()
          if value in ("1", "true", "yes", "on"):
            value = True
          else:
            value = False
        else:
          try:
            value = type(value)
          except:
            value = None
        optionList.append(value)
      
    #myfingershurt: verbose log output
    if logIniReads == 1:
      Log.debug("Config.getOptions: %s.%s = %s" % (section, option, str(optionList)))
    return optionList, options
  
  def getTipText(self, section, option):
    """
    Return the tip text for a configuration key.
    
    @param section:   Section name
    @param option:    Option name
    @return:          Tip Text String
    """
    
    global logIniReads, logUndefinedGets

    try:
      text = self.prototype[section][option].tipText
    except KeyError:
      if logUndefinedGets == 1:
        Log.warn("Config key %s.%s not defined while reading %s." % (section, option, self.fileName))
      text = None
      
    #myfingershurt: verbose log output
    if logIniReads == 1:
      Log.debug("Config.getTipText: %s.%s = %s" % (section, option, text))
    return text

#-------------------------
# glorandwarf: returns the default value of a configuration key
  def getDefault(self, section, option):
    """
    Read the default value of a configuration key.
    
    @param section:   Section name
    @param option:    Option name
    @return:          Key value
    """
    global logIniReads, logUndefinedGets


    try:
      type    = self.prototype[section][option].type
      default = self.prototype[section][option].default
    except KeyError:
      if logUndefinedGets == 1:
        Log.warn("Config key %s.%s not defined while reading %s." % (section, option, self.fileName))
      type, default = str, None
  
    value = default
    if type == bool:
      value = str(value).lower()
      if value in ("1", "true", "yes", "on"):
        value = True
      else:
        value = False
    else:
      try:
        value = type(value)
      except:
        value = None
      
    #myfingershurt: verbose log output
    if logIniReads == 1:
      Log.debug("Config.getDefault: %s.%s = %s" % (section, option, value))
    return value
#-------------------------

  def set(self, section, option, value):
    """
    Set the value of a configuration key.
    
    @param section:   Section name
    @param option:    Option name
    @param value:     Value name
    """

    global logUndefinedGets

    try:
      prototype[section][option]
    except KeyError:
      if logUndefinedGets == 1:
        Log.warn("Config key %s.%s not defined while writing %s." % (section, option, self.fileName))
    
    if not self.config.has_section(section):
      self.config.add_section(section)

    if type(value) == unicode:
      value = value.encode(encoding)
    else:
      value = str(value)

    self.config.set(section, option, value)
    
    f = open(self.fileName, "w")
    self.config.write(f, self.type)
    f.close()

  def getModOptions1(self, twoChord, hopo8th, compact = False):
    #For use with single digit flags
    #Do not change the order

    #0    
    #Value 0 not used / 1 used
    if twoChord > 0:
      twoChordUsed = 1
    else:
      twoChordUsed = 0

    #1      
    #Value 0 off / 1 on
    disableVBPMUsed = int(self.get("game", "disable_vbpm"))

    #2    
    #Value 0 on / 1 on - removed.
    hopoDisableUsed = 0

    #3
    #Value 0 FoF / 1 RFmod
    hopoMarks = 1

    #4    
    #Value 0 FoF / 1 RFmod / 2 RFmod2
    hopoStyle = int(self.get("game", "hopo_system"))

    #5    
    #Value 0 FoF / 1 GH / 2 Custom
    pov = int(self.get("fretboard", "point_of_view"))

    #6    
    #Value 0 FoF / 1 Capo -- akedrou: no game effect - removing key.
    margin = 0

    #7    
    #Value 0 no / 1 yes
    hopo8thUsed = int(hopo8th)

    #8    
    #Value 0 bpm / 1 difficulty
    boardSpeed = 0

    encode = "%d%d%d%d%d%d%d%d%d" % (twoChordUsed, disableVBPMUsed, hopoDisableUsed, hopoMarks, hopoStyle, pov, margin, hopo8thUsed, boardSpeed)
    #return encode
    return "000000000"
  
  def getModOptions2(self):
    #For use with more than single digit flags
    #Do not change order
    #Will be used for some of the Cmod values
    encode = ""
    boardSpeedMult = 0
    return encode
    

  def prettyModOptions(self, modOptions):
    encode = ""
    
    modOptions1, mod2 = modOptions.split(',', 2)

    if modOptions1 != "" and modOptions1 != "Default":
      if modOptions1[0] == '1':
        encode += "2"
      if modOptions1[1] == '1':
        encode += "v"
      if modOptions1[2] == '1':
        encode += "h"
      if modOptions1[3] == '1':
        encode += "m"
      if modOptions1[4] == '1':
        encode += "k"
      elif modOptions1[4] == '2':
        encode += "K"
      if modOptions1[5] == '1':
        encode += "p"
      elif modOptions1[5] == '2':
        encode += "P"
      if modOptions1[6] == '1':
        encode += "C"
      if modOptions1[7] == '1':
        encode += "9"
      if modOptions1[8] == '1':
        encode += "d"

    if mod2 != "" and mod2 != "Default":
      encode += ","
      modOptions2 = mod2.split(',')
      if modOptions2[0] != "":
        encode += "BS=%s" % (modOptions2[0])
    return encode
  
def get(section, option):
  """
  Read the value of a global configuration key.
  
  @param section:   Section name
  @param option:    Option name
  @return:          Key value
  """
  global config
  
  #MFH - for init config.gets
  #if config == None:
  #  load()

  return config.get(section, option)
  
def set(section, option, value):
  """
  Write the value of a global configuration key.
  
  @param section:   Section name
  @param option:    Option name
  @param value:     New key value
  """
  global config
  return config.set(section, option, value)

#-------------------------
# glorandwarf: returns the default value of the configuration key
def getDefault(section, option):
  """
  Read the default value of a global configuration key.
  
  @param section:   Section name
  @param option:    Option name
  @return:          Key value
  """
  global config
  return config.getDefault(section, option)

def getTipText(section, option):
  """
  Return the tip text for a global configuration key.
  
  @param section:   Section name
  @param option:    Option name
  @return:          Tip Text String
  """
  global config
  return config.getTipText(section, option)

#-------------------------
def getOptions(section, option):
  """
  Read the default value of a global configuration key.
  
  @param section:   Section name
  @param option:    Option name
  @return:          Tuple of Key list and Values list
  """
  global config
  return config.getOptions(section, option)

#-------------------------