###################################################################### # Copyright (c) 2007, Petteri Aimonen # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice and this list of conditions. # * Redistributions in binary form must reproduce the above copyright # notice and this list of conditions in the documentation and/or other # materials provided with the distribution. '''Keeps track of settings''' import codecs import ConfigParser import os import sys import atexit from pymisc import lineends class MyConfigParser(ConfigParser.RawConfigParser): def set(self, section, option, value): # Everything read from file is a string, so make them strings # when set in runtime also. if not isinstance(value, basestring): value = unicode(value) ConfigParser.RawConfigParser.set(self, section, option, value) def write(self, fp): """Write an .ini-format representation of the configuration state.""" # Rewritten to be UTF-8 and platform-specific line-end compatible self.writesection(fp, ConfigParser.DEFAULTSECT, self._defaults.items()) for section, valuedict in self._sections.items(): self.writesection(fp, section, valuedict.items()) def writesection(self, fp, section, items): '''Write one section to config file''' fp.write('[' + section + ']' + lineends()) for key, value in items: fp.write(key + ' = ' + unicode(value) + lineends()) fp.write(lineends()) if hasattr(sys, "frozen") and sys.frozen == "windows_exe": myfile = sys.executable else: myfile = __file__ myfile = unicode(myfile, sys.getfilesystemencoding()) configdir = os.path.dirname(os.path.abspath(myfile)) head, tail = os.path.split(configdir) if tail == 'src': configdir = head configfile = os.path.join(configdir, 'config.ini') defaults = { 'basedir': configdir, 'dbfile': "sikavalvonta.db", 'backupdir': "backups", 'animalfeed_datapath': '', 'animalfeed_filecount': 30, 'groupfeed_datafile': '', 'keepbackups': 10, 'keepfeeddata': 120, 'keepimportlogs': 30 } parser = MyConfigParser(defaults) parser.add_section("NOTICES") parser.set("NOTICES", "smallfeed", 200) parser.set("NOTICES", "feeddelta", 50.) parser.set("NOTICES", "feeddeltaperiod", 3) parser.set("NOTICES", "groupfeedperiod", 7) parser.add_section("GUI") parser.set("GUI", 'graphcols', 2) parser.set("GUI", 'mainwindow_w', 800) parser.set("GUI", 'mainwindow_h', 700) parser.set("GUI", 'mainwindow_sash', 150) parser.set("GUI", 'mainwindow_max', True) parser.set("GUI", 'language', 'en') newfile = not os.path.isfile(configfile) if not newfile: f = codecs.open(configfile, 'rU', 'utf-8') parser.readfp(f) os.chdir(parser.get("DEFAULT", "basedir")) def saveconfig(): '''Save configuration file to disc.''' f = codecs.open(configfile, 'w', 'utf-8') parser.write(f) atexit.register(saveconfig)