コード例 #1
0
 def testReadFileName(self):
     """Can read text"""
     goodDict = {'second': 
                     {'good': 'yes',
                      'bad': 'no',
                       'available': 'yes',
                       'funny-name_mate': 'crusty the clown'}, 
                 'main': 
                     {'running': u'on\t\u0100\u01100',
                      'testing': 'false',
                      'two words': 'are better than one',
                      'no_value': '',
                      'power': 'on',
                      'level': '5'}}
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     assert self.c._sections == goodDict, self.c._sections
     # Can read unicode filenames
     self.c = ConfigParser()
     self.c.read(u'temp.ini')
     assert self.c._sections == goodDict, self.c._sections
     # Can read funny string object filenames
     class MyStr(str):
         """Simply overrides string to make it a different type"""
     self.c.read(MyStr('temp.ini'))
     assert self.c._sections == goodDict, self.c._sections
コード例 #2
0
 def testUnicodeFileName(self):
     """
     Should be able to write to unicode filenames
     """
     # Invent a unicode filename
     dirName = unicode('\xc4\x80\xc4\x900', 'utf8')
     fn = os.path.join(dirName, dirName)
     fn += '.ini'
     if not os.path.exists(dirName):
         os.mkdir(dirName)
     # Write some test data to our unicode file
     file_ = open(fn, 'wb')
     file_.write(TEST_TEXT)
     file_.close()
     # See if we can read and write it
     self.c.read(fn)
     self.assertEquals(self.c.main.power, 'on')
     self.c.main.power = 'off'
     self.c.write()
     # Check that it was written ok
     c2 = ConfigParser()
     c2.read(fn)
     self.assertEquals(c2.main.power, 'off')
     # Clean up
     os.remove(fn)
     os.rmdir(dirName)
コード例 #3
0
 def testUnicodeFileName(self):
     """
     Should be able to write to unicode filenames
     """
     # Invent a unicode filename
     dirName = unicode('\xc4\x80\xc4\x900', 'utf8')
     fn = os.path.join(dirName, dirName)
     fn += '.ini'
     if not os.path.exists(dirName):
         os.mkdir(dirName)
     # Write some test data to our unicode file
     file_ = open(fn, 'wb')
     file_.write(TEST_TEXT)
     file_.close()
     # See if we can read and write it
     self.c.read(fn)
     self.assertEquals(self.c.main.power, 'on')
     self.c.main.power = 'off'
     self.c.write()
     # Check that it was written ok
     c2 = ConfigParser()
     c2.read(fn)
     self.assertEquals(c2.main.power, 'off')
     # Clean up
     os.remove(fn)
     os.rmdir(dirName)
コード例 #4
0
 def setUp(self):
     """
     Creates an application and
     almost launches it.
     """
     # Make whatever config class that application uses only look for our
     # Set up our customised config file
     logFileName = Path('tmp/app data/test.conf')
     sys.argv[0] = 'exe/exe'
     Config._getConfigPathOptions = lambda s: [logFileName]
     if not logFileName.dirname().exists():
         logFileName.dirname().makedirs()
     confParser = ConfigParser()
     self._setupConfigFile(confParser)
     confParser.write(logFileName)
     # Start up the app and friends
     if G.application is None:
         G.application = Application()
         
     self.app = G.application
     G.application = self.app
     self.app.loadConfiguration()
     self.app.preLaunch()
     self.client = FakeClient()
     self.package = Package('temp')
     self.session = FakeSession()
     self.app.webServer.root.bindNewPackage(self.package, self.session)
     self.mainpage = self.app.webServer.root.mainpages[self.session.uid]['temp']
     self.mainpage.idevicePane.client = self.client
コード例 #5
0
ファイル: utils.py プロジェクト: UstadMobile/eXePUB
    def setUp(self):
        """
        Creates an application and
        almost launches it.
        """
        # Make whatever config class that application uses only look for our
        # Set up our customised config file
        logFileName = Path('tmp/app data/test.conf')
        sys.argv[0] = 'exe/exe'
        Config._getConfigPathOptions = lambda s: [logFileName]
        if not logFileName.dirname().exists():
            logFileName.dirname().makedirs()
        confParser = ConfigParser()
        self._setupConfigFile(confParser)
        confParser.write(logFileName)
        # Start up the app and friends
        if G.application is None:
            G.application = Application()

        self.app = G.application
        G.application = self.app
        self.app.loadConfiguration()
        self.app.preLaunch()
        self.client = FakeClient()
        self.package = Package('temp')
        self.session = FakeSession()
        self.app.webServer.root.bindNewPackage(self.package, self.session)
        self.mainpage = self.app.webServer.root.mainpages[
            self.session.uid]['temp']
        self.mainpage.idevicePane.client = self.client
コード例 #6
0
 def testCreation(self):
     """
     When one creates a section with the same name
     as an existing section the existing section should
     just be returned
     """
     mysec = Section('main', self.c)
     assert mysec is self.c.main
     othersec = Section('main', self.c)
     assert othersec is mysec is self.c.main is self.c._sections['main']
     newsec = Section('newsection', self.c)
     assert newsec is \
            self.c.addSection('newsection') is \
            self.c.newsection is \
            self.c._sections['newsection']
     newsec2 = self.c.addSection('newsection2')
     assert newsec2 is \
            self.c.addSection('newsection2') is \
            Section('newsection2', self.c) is \
            self.c.newsection2 is \
            self.c._sections['newsection2'] and \
            newsec2 is not newsec
     # Different parent should create new object
     otherConf = ConfigParser()
     sec1 = otherConf.addSection('x')
     sec2 = self.c.addSection('x')
     assert sec1 is not sec2
コード例 #7
0
 def testCreation(self):
     """
     When one creates a section with the same name
     as an existing section the existing section should
     just be returned
     """
     mysec = Section('main', self.c)
     assert mysec is self.c.main
     othersec = Section('main', self.c)
     assert othersec is mysec is self.c.main is self.c._sections['main']
     newsec = Section('newsection', self.c)
     assert newsec is \
            self.c.addSection('newsection') is \
            self.c.newsection is \
            self.c._sections['newsection']
     newsec2 = self.c.addSection('newsection2')
     assert newsec2 is \
            self.c.addSection('newsection2') is \
            Section('newsection2', self.c) is \
            self.c.newsection2 is \
            self.c._sections['newsection2'] and \
            newsec2 is not newsec
     # Different parent should create new object
     otherConf = ConfigParser()
     sec1 = otherConf.addSection('x')
     sec2 = self.c.addSection('x')
     assert sec1 is not sec2
コード例 #8
0
 def setUp(self):
     """
     Creates a ConfigParser to play with and
     reads in the test text
     """
     self.c = ConfigParser()
     file_ = testFile()
     self.c.read(file_)
コード例 #9
0
 def testFromScratch(self):
     """
     Tests adding stuff from nothing
     """
     x = ConfigParser()
     testing = x.addSection('testing')
     assert x.testing is testing
     testing.myval = 4
     self.assertEquals(x.get('testing', 'myval'), '4')
コード例 #10
0
 def testFromScratch(self):
     """
     Tests adding stuff from nothing
     """
     x = ConfigParser()
     testing = x.addSection('testing')
     assert x.testing is testing
     testing.myval = 4
     self.assertEquals(x.get('testing', 'myval'), '4')
コード例 #11
0
 def testStringIO(self):
     file_ = testFile()
     c = ConfigParser()
     c.read(file_)
     c.autoWrite = True
     assert 'Matthew' not in self.getVal(file_)
     c.main.name = 'Matthew'
     assert 'name = Matthew' in self.getVal(file_), self.getVal(file_)
     del c.main.name
     assert 'Matthew' not in self.getVal(file_)
コード例 #12
0
 def testStringIO(self):
     file_ = testFile()
     c = ConfigParser()
     c.read(file_)
     c.autoWrite = True
     assert 'Matthew' not in self.getVal(file_)
     c.main.name = 'Matthew'
     assert 'name = Matthew' in self.getVal(file_), self.getVal(file_)
     del c.main.name
     assert 'Matthew' not in self.getVal(file_)
コード例 #13
0
 def testUpgradeAppDir(self):
     """
     Tests that config files with
     'appDataDir' are upgraded to 'configDir'
     """
     # Write the old style config file
     configPath = Path(u'test.exe.conf')
     if configPath.exists():
         configPath.remove()
     oldParser = ConfigParser()
     system = oldParser.addSection('system')
     system.appDataDir = 'my old app data dir'
     oldParser.write(configPath)
     del system
     del oldParser
     # Make the config instance load it
     Config._getConfigPathOptions = lambda self: ['test.exe.conf']
     myconfig = Config()
     myconfig.loadSettings()
     # Check if it reads the old value into the new variable
     assert not hasattr(myconfig, 'appDataDir')
     self.assertEquals(myconfig.configPath, 'test.exe.conf')
     self.assertEquals(myconfig.configDir, 'my old app data dir')
     # Check if it has upgraded the file and added in some nice default values
     newParser = ConfigParser()
     newParser.read(configPath)
     self.assertEquals(newParser.system.configDir, 'my old app data dir')
コード例 #14
0
 def testReadFileName(self):
     """Can read text"""
     goodDict = {'second': 
                     {'good': 'yes',
                      'bad': 'no',
                       'available': 'yes',
                       'funny-name_mate': 'crusty the clown'}, 
                 'main': 
                     {'running': u'on\t\u0100\u01100',
                      'testing': 'false',
                      'two words': 'are better than one',
                      'no_value': '',
                      'power': 'on',
                      'level': '5'}}
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     assert self.c._sections == goodDict, self.c._sections
     # Can read unicode filenames
     self.c = ConfigParser()
     self.c.read(u'temp.ini')
     assert self.c._sections == goodDict, self.c._sections
     # Can read funny string object filenames
     class MyStr(str):
         """Simply overrides string to make it a different type"""
     self.c.read(MyStr('temp.ini'))
     assert self.c._sections == goodDict, self.c._sections
コード例 #15
0
 def __init__(self):
     """
     Initialise
     """
     self.configPath = None
     self.configParser = ConfigParser()
     self.exePath = Path(sys.argv[0]).abspath()
     self.webDir = self.exePath.dirname()
     self.xulDir = self.exePath.dirname()
     self.localeDir = self.exePath.dirname() / "locale"
     self.port = 51235
     self.dataDir = Path(".")
     self.configDir = Path(".")
     self.browserPath = Path("firefox")
     self.locale = chooseDefaultLocale(self.localeDir)
     self.styles = []
     self._overrideDefaultVals()
     self.webDir = Path(self.webDir)
     if not (self.webDir / "scripts").isdir() and (self.webDir / "webui").isdir():
         self.webDir /= "webui"
     self.xulDir = Path(self.xulDir)
     if not (self.xulDir / "scripts").isdir() and (self.xulDir / "xului").isdir():
         self.xulDir /= "xului"
     self.__setConfigPath()
     self._writeDefaultConfigFile()
     self.loadSettings()
     self.setupLogging()
     self.loadStyles()
     self.loadLocales()
コード例 #16
0
 def setUp(self):
     """
     Creates a ConfigParser to play with and
     reads in the test text
     """
     self.c = ConfigParser()
     file_ = testFile()
     self.c.read(file_)
コード例 #17
0
ファイル: testconfig.py プロジェクト: KatiaBorges/exeLearning
 def testUpgradeAppDir(self):
     """
     Tests that config files with
     'appDataDir' are upgraded to 'configDir'
     """
     # Write the old style config file
     configPath = Path(u'test.exe.conf')
     if configPath.exists():
         configPath.remove()
     oldParser = ConfigParser()
     system = oldParser.addSection('system')
     system.appDataDir = 'my old app data dir'
     oldParser.write(configPath)
     del system
     del oldParser
     # Make the config instance load it
     Config._getConfigPathOptions = lambda self: ['test.exe.conf']
     myconfig = Config()
     myconfig.loadSettings()
     # Check if it reads the old value into the new variable
     assert not hasattr(myconfig, 'appDataDir')
     self.assertEquals(myconfig.configPath, 'test.exe.conf')
     self.assertEquals(myconfig.configDir, 'my old app data dir')
     # Check if it has upgraded the file and added in some nice default values
     newParser = ConfigParser()
     newParser.read(configPath)
     self.assertEquals(newParser.system.configDir, 'my old app data dir')
コード例 #18
0
 def check_application_for_test(cls):
     logFileName = Path('tmp/app data/test.conf')
     sys.argv[0] = 'exe/exe'
     Config._getConfigPathOptions = lambda s: [logFileName]
     if not logFileName.dirname().exists():
         logFileName.dirname().makedirs()
     confParser = ConfigParser()
     SuperTestCase.update_config_parser(confParser)
     confParser.write(logFileName)
     
     if G.application is None:
         G.application = Application()
     
         G.application.loadConfiguration()
         SuperTestCase.update_config_parser(G.application.config.configParser)
         G.application.config.loadSettings()
         
         G.application.preLaunch()
コード例 #19
0
 def setUp(self):
     """
     Creates an application and 
     almost launches it.
     """
     logFileName = Path('tmp/app data/test.conf')
     Config._getConfigPathOptions = lambda s: [logFileName]
     if not logFileName.dirname().exists():
         logFileName.dirname().makedirs()
     confParser = ConfigParser()
     self._setupConfigFile(confParser)
     confParser.write(logFileName)
     self.app = Application()
     self.app.loadConfiguration()
     self.app.preLaunch()
     self.client = FakeClient()
     self.package = Package('temp')
     self.app.webServer.root.bindNewPackage(self.package)
     self.mainpage = self.app.webServer.root.children['temp']
コード例 #20
0
ファイル: utils.py プロジェクト: UstadMobile/eXePUB
    def check_application_for_test(cls):
        logFileName = Path('tmp/app data/test.conf')
        sys.argv[0] = 'exe/exe'
        Config._getConfigPathOptions = lambda s: [logFileName]
        if not logFileName.dirname().exists():
            logFileName.dirname().makedirs()
        confParser = ConfigParser()
        SuperTestCase.update_config_parser(confParser)
        confParser.write(logFileName)

        if G.application is None:
            G.application = Application()

            G.application.loadConfiguration()
            SuperTestCase.update_config_parser(
                G.application.config.configParser)
            G.application.config.loadSettings()

            G.application.preLaunch()
コード例 #21
0
 def testUnicodeSet(self):
     """
     Should be able to set unicode option values
     with both python internal unicode strings
     or raw string containing utf8 encoded data
     """
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     self.c.set('main', 'power', '\xc4\x80\xc4\x900')
     self.c.set('main', 'name', unicode('\xc4\x80\xc4\x900', 'utf8'))
     self.c.set('newSecy', 'unicode', unicode('\xc4\x80\xc4\x900', 'utf8'))
     self.c.write('temp.ini')
     c2 = ConfigParser()
     c2.read('temp.ini')
     val = unicode('\xc4\x80\xc4\x900', 'utf8')
     self.assertEquals(c2.main.power, val)
     self.assertEquals(c2.main.name, val)
     self.assertEquals(c2.newSecy.unicode, val)
コード例 #22
0
 def testUnicodeSet(self):
     """
     Should be able to set unicode option values
     with both python internal unicode strings
     or raw string containing utf8 encoded data
     """
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     self.c.set('main', 'power', '\xc4\x80\xc4\x900')
     self.c.set('main', 'name', unicode('\xc4\x80\xc4\x900', 'utf8'))
     self.c.set('newSecy', 'unicode', unicode('\xc4\x80\xc4\x900', 'utf8'))
     self.c.write('temp.ini')
     c2 = ConfigParser()
     c2.read('temp.ini')
     val = unicode('\xc4\x80\xc4\x900', 'utf8')
     self.assertEquals(c2.main.power, val)
     self.assertEquals(c2.main.name, val)
     self.assertEquals(c2.newSecy.unicode, val)
コード例 #23
0
 def setUp(self):
     """
     Creates an application and 
     almost launches it.
     """
     # Make whatever config class that application uses only look for our
     # Set up our customised config file
     logFileName = Path('tmp/app data/test.conf')
     Config._getConfigPathOptions = lambda s: [logFileName]
     if not logFileName.dirname().exists():
         logFileName.dirname().makedirs()
     confParser = ConfigParser()
     self._setupConfigFile(confParser)
     confParser.write(logFileName)
     # Start up the app and friends
     self.app = Application()
     self.app.loadConfiguration()
     self.app.preLaunch()
     self.client = FakeClient()
     self.package = Package('temp')
     self.app.webServer.root.bindNewPackage(self.package)
     self.mainpage = self.app.webServer.root.children['temp']
コード例 #24
0
ファイル: utils.py プロジェクト: KatiaBorges/exeLearning
 def setUp(self):
     """
     Creates an application and 
     almost launches it.
     """
     # Make whatever config class that application uses only look for our
     # Set up our customised config file
     logFileName = Path('tmp/app data/test.conf')
     Config._getConfigPathOptions = lambda s: [logFileName]
     if not logFileName.dirname().exists():
         logFileName.dirname().makedirs()
     confParser = ConfigParser()
     self._setupConfigFile(confParser)
     confParser.write(logFileName)
     # Start up the app and friends
     self.app = Application()
     self.app.loadConfiguration()
     self.app.preLaunch()
     self.client = FakeClient()
     self.package = Package('temp')
     self.app.webServer.root.bindNewPackage(self.package)
     self.mainpage = self.app.webServer.root.children['temp']
コード例 #25
0
 def testShortening(self):
     """There was a bug (Issue 66) where when a longer name was read
     and a shorter name was written, the extra characters of the 
     longer name would remain in the entry"""
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     self.c.set('second', 'available', 'abcdefghijklmnop')
     self.c.write('temp.ini')
     c2 = ConfigParser()
     c2.read('temp.ini')
     c2.set('second', 'available', 'short')
     c2.write('temp.ini')
     self.c.read('temp.ini')
     assert self.c.get('second', 'available', '') == 'short', \
         self.c.get('second', 'available', '')
コード例 #26
0
 def testShortening(self):
     """There was a bug (Issue 66) where when a longer name was read
     and a shorter name was written, the extra characters of the 
     longer name would remain in the entry"""
     file_ = open('temp.ini', 'w')
     file_.write(TEST_TEXT)
     file_.close()
     self.c.read('temp.ini')
     self.c.set('second', 'available', 'abcdefghijklmnop')
     self.c.write('temp.ini')
     c2 = ConfigParser()
     c2.read('temp.ini')
     c2.set('second', 'available', 'short')
     c2.write('temp.ini')
     self.c.read('temp.ini')
     assert self.c.get('second', 'available', '') == 'short', \
         self.c.get('second', 'available', '')
コード例 #27
0
 def __init__(self):
     """
     Initialise
     """
     self.configPath = None
     self.configParser = ConfigParser(self.onWrite)
     self.exePath     = Path(sys.argv[0]).abspath()
     self.webDir      = self.exePath.dirname()
     self.xulDir      = self.exePath.dirname()
     self.localeDir   = self.exePath.dirname()/"locale"
     self.port        = 51235
     self.dataDir     = Path(".")
     self.configDir   = Path(".")
     self.browserPath = Path("firefox")
     self.locale = chooseDefaultLocale(self.localeDir)
     self.styles      = []
     self.recentProjects = []
     self.hiddeniDevices = []
     self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                 "attachment"]
     self.assumeMediaPlugins = False;
     self._overrideDefaultVals()
     self.webDir = Path(self.webDir)
     if not (self.webDir/'scripts').isdir() \
        and (self.webDir/'webui').isdir():
         self.webDir /= 'webui'
     self.xulDir = Path(self.xulDir)
     if not (self.xulDir/'scripts').isdir() \
        and (self.xulDir/'xului').isdir():
         self.xulDir /= 'xului'
     self.__setConfigPath()
     self._writeDefaultConfigFile()
     self.loadSettings()
     self.setupLogging()
     self.loadStyles()
     self.loadLocales()
コード例 #28
0
 def testUpgradeAppDir(self):
     """
     Tests that config files with
     'appDataDir' are upgraded to 'configDir'
     """
     configPath = Path(u'test.exe.conf')
     if configPath.exists():
         configPath.remove()
     oldParser = ConfigParser()
     system = oldParser.addSection('system')
     system.appDataDir = 'my old app data dir'
     oldParser.write(configPath)
     del system
     del oldParser
     Config._getConfigPathOptions = lambda self: ['test.exe.conf']
     myconfig = Config()
     myconfig.loadSettings()
     assert not hasattr(myconfig, 'appDataDir')
     self.assertEquals(myconfig.configPath, 'test.exe.conf')
     self.assertEquals(myconfig.configDir, 'my old app data dir')
     newParser = ConfigParser()
     newParser.read(configPath)
     self.assertEquals(newParser.system.configDir, 'my old app data dir')
コード例 #29
0
class Config(object):
    """
    The Config class contains the configuration information for eXe.
    """

    # To build link to git revision
    baseGitWebURL = 'https://forja.cenatic.es/plugins/scmgit/cgi-bin/gitweb.cgi?p=iteexe/iteexe.git'

    # Class attributes
    optionNames = {
        'system': ('webDir', 'jsDir', 'port', 'dataDir',
                   'configDir', 'localeDir', 'browser', 'mediaProfilePath',
                   'videoMediaConverter_ogv', 'videoMediaConverter_3gp',
                   'videoMediaConverter_mpg',
                   'videoMediaConverter_avi', 'audioMediaConverter_ogg',
                   'audioMediaConverter_au', 'audioMediaConverter_mp3',
                   'audioMediaConverter_wav', 'ffmpegPath'),
        'user': ('locale', 'lastDir', 'showPreferencesOnStart','defaultStyle', 'showIdevicesGrouped','docType','editorMode'),
    }

    idevicesCategories = {
        'activity': [x_('Non-Interactive Activities')],
        'reading activity': [x_('Non-Interactive Activities')],
        'dropdown activity': [x_('Interactive Activities')],
        'java applet': [x_('Non-Textual Information')],
        'wiki article': [x_('Non-Textual Information')],
        'case study': [x_('Non-Interactive Activities')],
        'preknowledge': [x_('Textual Information')],
        'scorm quiz': [x_('Interactive Activities')],
        'fpd - multi choice activity': [x_('FPD')],
        'fpd - cloze activity': [x_('FPD')],
        'fpd - cloze activity (modified)': [x_('FPD')],
        'fpd - multi select activity': [x_('FPD')],
        'fpd - true/false activity': [x_('FPD')],
        'fpd - situation': [x_('FPD')],
        'fpd - quotation': [x_('FPD')],
        'fpd - you should know': [x_('FPD')],
        'fpd - highlighted': [x_('FPD')],
        'fpd - translation': [x_('FPD')],
        'fpd - guidelines students': [x_('FPD')],
        'fpd - guidelines teacher': [x_('FPD')],
        'fpd - a step ahead': [x_('FPD')],
        'fpd - a piece of advice': [x_('FPD')],
        'fpd - think about it (with feedback)': [x_('FPD')],
        'fpd - think about it (without feedback)': [x_('FPD')],
        'fpd - free text': [x_('FPD')],
        'image gallery': [x_('Non-Textual Information')],
        'image magnifier': [x_('Non-Textual Information')],
        'note': [x_('Textual Information')],
        'objectives': [x_('Textual Information')],
        'multi-choice': [x_('Interactive Activities')],
        'multi-select': [x_('Interactive Activities')],
        'true-false question': [x_('Interactive Activities')],
        'reflection': [x_('Non-Interactive Activities')],
        'cloze activity': [x_('Interactive Activities')],
        'rss': [x_('Non-Textual Information')],
        'external web site': [x_('Non-Textual Information')],
        'free text': [x_('Textual Information')],
        'click in order game': [x_('Experimental')],
        'hangman game': [x_('Experimental')],
        'place the objects': [x_('Interactive Activities')],
        'memory match game': [x_('Experimental')],
        'file attachments': [x_('Non-Textual Information')],
        'sort items': [x_('Experimental')],
        'sort items': [x_('Interactive Activities')],
        'scorm test cloze': [x_('Interactive Activities')],
        'scorm test cloze (multiple options)': [x_('Interactive Activities')],
        'scorm test dropdown': [x_('Interactive Activities')],
        'scorm test multiple choice': [x_('Interactive Activities')]
    }
    
    @classmethod
    def getConfigPath(cls):
        obj = cls.__new__(cls)
        obj.configParser = ConfigParser()
        obj._overrideDefaultVals()
        obj.__setConfigPath()
        return obj.configPath

    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        # Set default values
        # exePath is the whole path and filename of the exe executable
        self.exePath     = Path(sys.argv[0]).abspath()
        # webDir is the parent directory for styles,scripts and templates
        self.webDir      = self.exePath.dirname()
        self.jsDir       = self.exePath.dirname()
        # localeDir is the base directory where all the locales are stored
        self.localeDir   = self.exePath.dirname()/"locale"
        # port is the port the exe webserver will listen on 
        # (previous default, which earlier users might still use, was 8081)
        self.port        = 51235
        # dataDir is the default directory that is shown to the user
        # to save packages and exports in
        self.dataDir     = Path(".")
        # configDir is the dir for storing user profiles
        # and user made idevices and the config file
        self.configDir   = Path(".")
		#FM: New Styles Directory path
        self.stylesDir =Path(self.configDir/'style').abspath()
        #FM: Default Style name
        self.defaultStyle= u"standardwhite"
        # browser is the name of a predefined browser specified at http://docs.python.org/library/webbrowser.html.
        # None for system default
        self.browser = None
        # docType  is the HTML export format
        self.docType = 'XHTML' 
        # locale is the language of the user
        self.locale = chooseDefaultLocale(self.localeDir)
        # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
        # available values = "enable_all", "disable_autotop", or "disable_all"
        self.internalAnchors = "enable_all"
        self.lastDir = None
        self.showPreferencesOnStart = "1"
        self.showIdevicesGrouped = "1"
        # tinymce option
        self.editorMode = 'permissive' 
        # styleSecureMode : if this [user] key is = 0  , exelearning can run python files in styles
        # as websitepage.py , ... ( deactivate secure mode )
        self.styleSecureMode="1"
        # styles is the list of style names available for loading
        self.styles      = []
        # The documents that we've recently looked at
        self.recentProjects = []
        # canonical (English) names of iDevices not to show in the iDevice pane
        self.hiddeniDevices = []
        #Media conversion programs used for XML export system
        self.videoMediaConverter_ogv = ""
        self.videoMediaConverter_3gp = ""
        self.videoMediaConverter_avi = ""
        self.videoMediaConverter_mpg = ""
        self.audioMediaConverter_ogg = ""
        self.audioMediaConverter_au = ""
        self.audioMediaConverter_mp3 = ""
        self.audioMediaConverter_wav = ""
        self.ffmpegPath = ""
        self.mediaProfilePath = self.exePath.dirname()/'mediaprofiles'
        
        # likewise, a canonical (English) names of iDevices not to show in the
        # iDevice pane but, contrary to the hiddens, these are ones that the 
        # configuration can specify to turn ON:
        self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                    "attachment"]
        # by default, only allow embedding of media types for which a 
        # browser plugin is found:
        self.assumeMediaPlugins = False;
        # Let our children override our defaults depending
        # on the OS that we're running on
        self._overrideDefaultVals()
        # Try to make the defaults a little intelligent
        # Under devel trees, webui is the default webdir
        self.webDir = Path(self.webDir)
        if not (self.webDir/'scripts').isdir() \
           and (self.webDir/'webui').isdir():
            self.webDir /= 'webui'
        self.jsDir = Path(self.jsDir)
        if not (self.jsDir/'scripts').isdir() \
           and (self.jsDir/'jsui').isdir():
            self.jsDir /= 'jsui'
        # Find where the config file will be saved
        self.__setConfigPath()
        # Fill in any undefined config options with our defaults
        self._writeDefaultConfigFile()
        # Now we are ready to serve the application
        self.loadSettings()
        self.setupLogging()
        self.loadLocales()
        self.loadStyles()



    def _overrideDefaultVals(self):
        """
        Override this to override the
        default config values
        """

    def _getConfigPathOptions(self):
        """
        Override this to give a list of
        possible config filenames
        in order of preference
        """
        return ['exe.conf']


    def _writeDefaultConfigFile(self):
        """
        [Over]writes 'self.configPath' with a default config file 
        (auto write is on so we don't need to write the file at the end)
        """
        if not G.application.portable:
            for sectionName, optionNames in self.optionNames.items():
                for optionName in optionNames:
                    defaultVal = getattr(self, optionName)
                    self.configParser.setdefault(sectionName, 
                                             optionName, 
                                             defaultVal)
                    # Logging can't really be changed from inside the program at the moment...
            self.configParser.setdefault('logging', 'root', 'INFO')


    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        # If there's an EXECONF environment variable, use it
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        # Otherwise find the most appropriate existing file
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                # If no config files exist, create and use the
                # first one on the list
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        # Now make our configParser
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True


    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section('system'):
            system = self.configParser.system
            if system.has_option('appDataDir'):
                # Older config files had configDir stored as appDataDir
                self.configDir = Path(system.appDataDir)
                self.stylesDir =Path(self.configDir)/'style'
                # We'll just upgrade their config file for them for now...
                system.configDir = self.configDir
                system.stylesDir =Path(self.configDir)/'style'
                del system.appDataDir
                
                self.audioMediaConverter_au = system.audioMediaConverter_au
                self.audioMediaConverter_wav = system.audioMediaConverter_wav
                self.videoMediaConverter_ogv = system.videoMediaConverter_ogv
                self.videoMediaConverter_3gp = system.videoMediaConverter_3gp
                self.videoMediaConverter_avi = system.videoMediaConverter_avi
                self.videoMediaConverter_mpg = system.videoMediaConverter_mpg
                self.audioMediaConverter_ogg = system.audioMediaConverter_ogg
                self.audioMediaConverter_mp3 = system.audioMediaConverter_mp3
                self.ffmpegPath = system.ffmpegPath
            
            self.mediaProfilePath = system.mediaProfilePath
                
            if system.has_option('greDir'):
                # No longer used, system should automatically support
                del system.greDir


    def loadSettings(self):
        """
        Loads the settings from the exe.conf file.
        Overrides the defaults set in __init__
        """
        # Set up the parser so that if a certain value is not in the config
        # file, it will use the value from our default values
        def defVal(dummy, option):
            """If something is not in the config file, just use the default in
            'self'"""
            return getattr(self, option)
        self.configParser.defaultValue = defVal
        self.upgradeFile()
        # System Section
        if self.configParser.has_section('system'):
            system = self.configParser.system

            
            self.port           = int(system.port)
            self.browser        = None if system.browser == u"None" else system.browser
            
            
            if not G.application.portable:
                self.dataDir        = Path(system.dataDir)
                self.configDir      = Path(system.configDir)
                self.webDir         = Path(system.webDir)
                self.stylesDir      = Path(self.configDir)/'style'
                self.jsDir          = Path(system.jsDir)
            else:
                self.stylesDir      = Path(self.webDir/'style').abspath()
            
            self.assumeMediaPlugins = False;
            if self.configParser.has_option('system', \
                    'assumeMediaPlugins'):
               value = system.assumeMediaPlugins.strip().lower()
               if value == "1" or value == "yes" or value == "true" or \
                   value == "on":
                       self.assumeMediaPlugins = True;

        # If the dataDir points to some other dir, fix it
        if not self.dataDir.isdir():
            self.dataDir = tempfile.gettempdir()
        # make the webDir absolute, to hide path joins of relative paths
        self.webDir = self.webDir.expand().abspath()
        # If the configDir doesn't exist (as it may be a default setting with a
        # new installation) create it
        if not self.configDir.exists():
            self.configDir.mkdir()
		
        if not G.application.standalone: 
             #FM: Copy styles         
            if not os.path.exists(self.stylesDir) or not os.listdir(self.stylesDir):
                self.copyStyles() 
            else:
                self.updateStyles()                      
        else:
            if G.application.portable:
                if os.name == 'posix': 
                    self.stylesDir      = Path(self.webDir/'..'/'..'/'..'/'style')
                else: 
                    self.stylesDir      = Path(self.webDir/'..'/'style')
                if not os.path.exists(self.stylesDir) or not os.listdir(self.stylesDir): 
                    self.copyStyles()
            else:
                self.stylesDir     = Path(self.webDir/'style').abspath()
            
               
        # Get the list of recently opened projects
        self.recentProjects = []
        if self.configParser.has_section('recent_projects'):
            recentProjectsSection = self.configParser.recent_projects
            # recentProjectsSection.items() is in the wrong order, keys are alright.
            # Sorting list by key before adding to self.recentProjects, to avoid wrong ordering
            # in Recent Projects menu list
            recentProjectsItems = recentProjectsSection.items();
            recentProjectsItems.sort()
            for key, path in recentProjectsItems:
                self.recentProjects.append(path)
                
        # Load the list of "hidden" iDevices
        self.hiddeniDevices = []
        if self.configParser.has_section('idevices'):
            idevicesSection = self.configParser.idevices
            for key,value in idevicesSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "0" or value == "no" or value == "false" or \
                        value == "off":
                    self.hiddeniDevices.append(key.lower())

        #self.deprecatediDevices = [ "flash with text", "flash movie", ...]
        # and UN-Load from the list of "deprecated" iDevices
        if self.configParser.has_section('deprecated'):
            deprecatedSection = self.configParser.deprecated
            for key,value in deprecatedSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "1" or value == "yes" or value == "true" or \
                        value == "on":
                    if key.lower() in self.deprecatediDevices:
                        self.deprecatediDevices.remove(key.lower())

        # Load the "user" section
        if self.configParser.has_section('user'):
            if self.configParser.user.has_option('editorMode'):
                self.editorMode = self.configParser.user.editorMode
            if self.configParser.user.has_option('docType'):
                self.docType = self.configParser.user.docType
                common.setExportDocType(self.configParser.user.docType)
            if self.configParser.user.has_option('defaultStyle'):
                self.defaultStyle= self.configParser.user.defaultStyle
            if self.configParser.user.has_option('styleSecureMode'):
                self.styleSecureMode= self.configParser.user.styleSecureMode
            if self.configParser.user.has_option('internalAnchors'):
                self.internalAnchors = self.configParser.user.internalAnchors
            if self.configParser.user.has_option('lastDir'):
                self.lastDir = self.configParser.user.lastDir
            if self.configParser.user.has_option('showPreferencesOnStart'):
                self.showPreferencesOnStart = self.configParser.user.showPreferencesOnStart
            if self.configParser.user.has_option('showIdevicesGrouped'):
                self.showIdevicesGrouped = self.configParser.user.showIdevicesGrouped
            if self.configParser.user.has_option('locale'):
                self.locale = self.configParser.user.locale
                return
        self.locale = chooseDefaultLocale(self.localeDir)

    def onWrite(self, configParser):
        """
        Called just before the config file is written.
        We use it to fill out any settings that are stored here and 
        not in the config parser itself
        """
        # Recent projects
        self.configParser.delete('recent_projects')
        recentProjectsSection = self.configParser.addSection('recent_projects')
        for num, path in enumerate(self.recentProjects):
            recentProjectsSection[str(num)] = path

    def setupLogging(self):
        """
        setup logging file
        """
        try:
            hdlr = RotatingFileHandler(self.configDir/'exe.log', 'a', 
                                       500000, 10)
            hdlr.doRollover()
        except OSError:
            # ignore the error we get if the log file is logged
            hdlr = logging.FileHandler(self.configDir/'exe.log')

        format = "%(asctime)s %(name)s %(levelname)s %(message)s"
        log    = logging.getLogger()
        hdlr.setFormatter(logging.Formatter(format))
        log.addHandler(hdlr)

        loggingLevels = {"DEBUG"    : logging.DEBUG,
                         "INFO"     : logging.INFO,
                         "WARNING"  : logging.WARNING,
                         "ERROR"    : logging.ERROR,
                         "CRITICAL" : logging.CRITICAL }

    
        if self.configParser.has_section('logging'):
            for logger, level in self.configParser._sections["logging"].items():
                if logger == "root":
                    logging.getLogger().setLevel(loggingLevels[level])
                else:
                    logging.getLogger(logger).setLevel(loggingLevels[level])
        if not G.application.portable:
            log.info("************** eXe logging started **************")
            log.info("version     = %s" % version.version)
            log.info("configPath  = %s" % self.configPath)
            log.info("exePath     = %s" % self.exePath)
            log.info("libPath     = %s" % Path(twisted.__path__[0]).splitpath()[0])
            log.info("browser     = %s" % self.browser)
            log.info("webDir      = %s" % self.webDir)
            log.info("jsDir       = %s" % self.jsDir)
            log.info("localeDir   = %s" % self.localeDir)
            log.info("port        = %d" % self.port)
            log.info("dataDir     = %s" % self.dataDir)
            log.info("configDir   = %s" % self.configDir)
            log.info("locale      = %s" % self.locale)
            log.info("internalAnchors = %s" % self.internalAnchors)
                    

    def loadStyles(self):
        """
        Scans the eXe style directory and builds a list of styles
        """
        self.styleStore = StyleStore(self)
        listStyles = self.styleStore.getStyles()
        for style in listStyles:
            self.styles.append(style)
            #print style
            
    def copyStyles(self):
        bkstyle=self.webDir/'style'
        dststyle=self.stylesDir
        if os.path.exists(bkstyle):            
            if os.path.exists(dststyle) and not os.listdir(self.stylesDir): shutil.rmtree(dststyle)                 
            shutil.copytree(bkstyle,dststyle )
            
    def updateStyles(self):
        bkstyle=self.webDir/'style'
        dststyle=self.stylesDir
        if os.stat(bkstyle).st_mtime - os.stat(dststyle).st_mtime > 1:
            for name in os.listdir(bkstyle):
                bksdirstyle=os.path.join(bkstyle, name)
                dstdirstyle=os.path.join(dststyle, name)
                if os.path.isdir(bksdirstyle):
                    if os.path.exists(dstdirstyle):shutil.rmtree(dstdirstyle)
                    shutil.copytree(bksdirstyle, dstdirstyle)
                else:
                    shutil.copy(bksdirstyle, dstdirstyle)                    
                    

    def loadLocales(self):
        """
        Scans the eXe locale directory and builds a list of locales
        """
        log = logging.getLogger()
        log.debug("loadLocales")
        gettext.install('exe', self.localeDir, True)
        self.locales = {}
        for subDir in self.localeDir.dirs():
            if (subDir/'LC_MESSAGES'/'exe.mo').exists():
                self.locales[subDir.basename()] = \
                    gettext.translation('exe', 
                                        self.localeDir, 
                                        languages=[str(subDir.basename())])
                if subDir.basename() == self.locale:
                    locale = subDir.basename()
                    log.debug(" loading locale %s" % locale)
                    self.locales[locale].install(unicode=True)
                    __builtins__['c_'] = lambda s: self.locales[locale].ugettext(s) if s else s
コード例 #30
0
    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        # Set default values
        # exePath is the whole path and filename of the exe executable
        self.exePath     = Path(sys.argv[0]).abspath()
        # webDir is the parent directory for styles,scripts and templates
        self.webDir      = self.exePath.dirname()
        self.jsDir       = self.exePath.dirname()
        # localeDir is the base directory where all the locales are stored
        self.localeDir   = self.exePath.dirname()/"locale"
        # port is the port the exe webserver will listen on 
        # (previous default, which earlier users might still use, was 8081)
        self.port        = 51235
        # dataDir is the default directory that is shown to the user
        # to save packages and exports in
        self.dataDir     = Path(".")
        # configDir is the dir for storing user profiles
        # and user made idevices and the config file
        self.configDir   = Path(".")
		#FM: New Styles Directory path
        self.stylesDir =Path(self.configDir/'style').abspath()
        #FM: Default Style name
        self.defaultStyle= u"standardwhite"
        # browser is the name of a predefined browser specified at http://docs.python.org/library/webbrowser.html.
        # None for system default
        self.browser = None
        # docType  is the HTML export format
        self.docType = 'XHTML' 
        # locale is the language of the user
        self.locale = chooseDefaultLocale(self.localeDir)
        # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
        # available values = "enable_all", "disable_autotop", or "disable_all"
        self.internalAnchors = "enable_all"
        self.lastDir = None
        self.showPreferencesOnStart = "1"
        self.showIdevicesGrouped = "1"
        # tinymce option
        self.editorMode = 'permissive' 
        # styleSecureMode : if this [user] key is = 0  , exelearning can run python files in styles
        # as websitepage.py , ... ( deactivate secure mode )
        self.styleSecureMode="1"
        # styles is the list of style names available for loading
        self.styles      = []
        # The documents that we've recently looked at
        self.recentProjects = []
        # canonical (English) names of iDevices not to show in the iDevice pane
        self.hiddeniDevices = []
        #Media conversion programs used for XML export system
        self.videoMediaConverter_ogv = ""
        self.videoMediaConverter_3gp = ""
        self.videoMediaConverter_avi = ""
        self.videoMediaConverter_mpg = ""
        self.audioMediaConverter_ogg = ""
        self.audioMediaConverter_au = ""
        self.audioMediaConverter_mp3 = ""
        self.audioMediaConverter_wav = ""
        self.ffmpegPath = ""
        self.mediaProfilePath = self.exePath.dirname()/'mediaprofiles'
        
        # likewise, a canonical (English) names of iDevices not to show in the
        # iDevice pane but, contrary to the hiddens, these are ones that the 
        # configuration can specify to turn ON:
        self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                    "attachment"]
        # by default, only allow embedding of media types for which a 
        # browser plugin is found:
        self.assumeMediaPlugins = False;
        # Let our children override our defaults depending
        # on the OS that we're running on
        self._overrideDefaultVals()
        # Try to make the defaults a little intelligent
        # Under devel trees, webui is the default webdir
        self.webDir = Path(self.webDir)
        if not (self.webDir/'scripts').isdir() \
           and (self.webDir/'webui').isdir():
            self.webDir /= 'webui'
        self.jsDir = Path(self.jsDir)
        if not (self.jsDir/'scripts').isdir() \
           and (self.jsDir/'jsui').isdir():
            self.jsDir /= 'jsui'
        # Find where the config file will be saved
        self.__setConfigPath()
        # Fill in any undefined config options with our defaults
        self._writeDefaultConfigFile()
        # Now we are ready to serve the application
        self.loadSettings()
        self.setupLogging()
        self.loadLocales()
        self.loadStyles()
コード例 #31
0
class Config(object):
    """
    The Config class contains the configuration information for eXe.
    """

    # To build link to git revision
    baseGitWebURL = 'https://github.com/exelearning/iteexe'

    # Class attributes
    optionNames = {
        'system': ('webDir', 'jsDir', 'port', 'dataDir',
                   'configDir', 'localeDir', 'stylesRepository',
                   'browser', 'mediaProfilePath',
                   'videoMediaConverter_ogv', 'videoMediaConverter_3gp',
                   'videoMediaConverter_mpg',
                   'videoMediaConverter_avi', 'audioMediaConverter_ogg',
                   'audioMediaConverter_au', 'audioMediaConverter_mp3',
                   'audioMediaConverter_wav', 'ffmpegPath'),
        'user': ('locale', 'lastDir', 'showPreferencesOnStart',
                 'defaultStyle', 'showIdevicesGrouped', 'docType', 'editorMode', 'editorVersion', 'defaultLicense'),
    }

    idevicesCategories = {
        'activity': [x_('Non-Interactive Activities')],
        'reading activity': [x_('Non-Interactive Activities')],
        'dropdown activity': [x_('Interactive Activities')],
        'java applet': [x_('Non-Textual Information')],
        'wiki article': [x_('Non-Textual Information')],
        'case study': [x_('Non-Interactive Activities')],
        'preknowledge': [x_('Textual Information')],
        'scorm quiz': [x_('Interactive Activities')],
        'fpd - multi choice activity': [x_('FPD')],
        'fpd - cloze activity': [x_('FPD')],
        'fpd - cloze activity (modified)': [x_('FPD')],
        'fpd - multi select activity': [x_('FPD')],
        'fpd - true/false activity': [x_('FPD')],
        'fpd - situation': [x_('FPD')],
        'fpd - quotation': [x_('FPD')],
        'fpd - you should know': [x_('FPD')],
        'fpd - highlighted': [x_('FPD')],
        'fpd - translation': [x_('FPD')],
        'fpd - guidelines students': [x_('FPD')],
        'fpd - guidelines teacher': [x_('FPD')],
        'fpd - a step ahead': [x_('FPD')],
        'fpd - a piece of advice': [x_('FPD')],
        'fpd - think about it (with feedback)': [x_('FPD')],
        'fpd - think about it (without feedback)': [x_('FPD')],
        'fpd - free text': [x_('FPD')],
        'image gallery': [x_('Non-Textual Information')],
        'image magnifier': [x_('Non-Textual Information')],
        'note': [x_('Textual Information')],
        'objectives': [x_('Textual Information')],
        'multi-choice': [x_('Interactive Activities')],
        'multi-select': [x_('Interactive Activities')],
        'true-false question': [x_('Interactive Activities')],
        'reflection': [x_('Non-Interactive Activities')],
        'cloze activity': [x_('Interactive Activities')],
        'rss': [x_('Non-Textual Information')],
        'external web site': [x_('Non-Textual Information')],
        'free text': [x_('Textual Information')],
        'click in order game': [x_('Experimental')],
        'hangman game': [x_('Experimental')],
        'place the objects': [x_('Interactive Activities')],
        'memory match game': [x_('Experimental')],
        'file attachments': [x_('Non-Textual Information')],
        'sort items': [x_('Experimental')]
    }

    @classmethod
    def getConfigPath(cls):
        obj = cls.__new__(cls)
        obj.configParser = ConfigParser()
        obj._overrideDefaultVals()
        obj.__setConfigPath()
        return obj.configPath

    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        # Set default values
        # exePath is the whole path and filename of the exe executable
        self.exePath     = Path(sys.argv[0]).abspath()
        # webDir is the parent directory for styles,scripts and templates
        self.webDir      = self.exePath.dirname()
        self.jsDir       = self.exePath.dirname()
        self.locales     = {}
        # localeDir is the base directory where all the locales are stored
        self.localeDir   = self.exePath.dirname()/"locale"
        # port is the port the exe webserver will listen on
        # (previous default, which earlier users might still use, was 8081)
        self.port        = 51235
        # dataDir is the default directory that is shown to the user
        # to save packages and exports in
        self.dataDir     = Path(".")
        # configDir is the dir for storing user profiles
        # and user made idevices and the config file
        self.configDir   = Path(".")
        # FM: New Styles Directory path
        self.stylesDir   = Path(self.configDir/'style').abspath()
        # FM: Default Style name
        self.defaultStyle = u"INTEF"
        # Styles repository XML-RPC endpoint
        # self.stylesRepository = 'http://www.exelearning.es/xmlrpc.php'
        self.stylesRepository = 'http://www.exelearning.net/xmlrpc.php'
        # browser is the name of a predefined browser specified
        # at http://docs.python.org/library/webbrowser.html.
        # None for system default
        self.browser = None
        # docType  is the HTML export format
        self.docType = 'HTML5'
        # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
        # available values = "enable_all", "disable_autotop", or "disable_all"
        self.internalAnchors = "enable_all"
        self.lastDir = None
        self.showPreferencesOnStart = "1"
        self.showIdevicesGrouped = "1"
        # tinymce option
        self.editorMode = 'permissive'
        self.editorVersion = '4'
        # styleSecureMode : if this [user] key is = 0  , exelearning can run python files in styles
        # as websitepage.py , ... ( deactivate secure mode )
        self.styleSecureMode = "1"
        # styles is the list of style names available for loading
        self.styles = []
        # The documents that we've recently looked at
        self.recentProjects = []
        # canonical (English) names of iDevices not to show in the iDevice pane
        self.hiddeniDevices = []
        # Media conversion programs used for XML export system
        self.videoMediaConverter_ogv = ""
        self.videoMediaConverter_3gp = ""
        self.videoMediaConverter_avi = ""
        self.videoMediaConverter_mpg = ""
        self.audioMediaConverter_ogg = ""
        self.audioMediaConverter_au = ""
        self.audioMediaConverter_mp3 = ""
        self.audioMediaConverter_wav = ""
        self.ffmpegPath = ""
        self.mediaProfilePath = self.exePath.dirname()/'mediaprofiles'

        # likewise, a canonical (English) names of iDevices not to show in the
        # iDevice pane but, contrary to the hiddens, these are ones that the
        # configuration can specify to turn ON:
        self.deprecatediDevices = ["flash with text", "flash movie", "mp3",
                                   "attachment"]
        # by default, only allow embedding of media types for which a
        # browser plugin is found:

        self.defaultLicense='creative commons: attribution - share alike 4.0'

        self.assumeMediaPlugins = False
        # Let our children override our defaults depending
        # on the OS that we're running on
        self._overrideDefaultVals()
        # locale is the language of the user. localeDir can be overridden
        # that's why we must set it _after_ the call to _overrideDefaultVals()
        self.locale = chooseDefaultLocale(self.localeDir)
        # Try to make the defaults a little intelligent
        # Under devel trees, webui is the default webdir
        self.webDir = Path(self.webDir)
        if not (self.webDir/'scripts').isdir() \
           and (self.webDir/'webui').isdir():
            self.webDir /= 'webui'
        self.jsDir = Path(self.jsDir)
        if not (self.jsDir/'scripts').isdir() \
           and (self.jsDir/'jsui').isdir():
            self.jsDir /= 'jsui'
        # Find where the config file will be saved
        self.__setConfigPath()
        # Fill in any undefined config options with our defaults
        self._writeDefaultConfigFile()
        # Now we are ready to serve the application
        self.loadSettings()
        self.setupLogging()
        self.loadLocales()
        self.loadStyles()

    def _overrideDefaultVals(self):
        """
        Override this to override the
        default config values
        """

    def _getConfigPathOptions(self):
        """
        Override this to give a list of
        possible config filenames
        in order of preference
        """
        return ['exe.conf']

    def _writeDefaultConfigFile(self):
        """
        [Over]writes 'self.configPath' with a default config file
        (auto write is on so we don't need to write the file at the end)
        """
        if not G.application.portable:
            for sectionName, optionNames in self.optionNames.items():
                for optionName in optionNames:
                    defaultVal = getattr(self, optionName)
                    self.configParser.setdefault(sectionName,
                                                 optionName,
                                                 defaultVal)
            # Logging can't really be changed from inside the program at the moment...
            self.configParser.setdefault('logging', 'root', 'INFO')

    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        # If there's an EXECONF environment variable, use it
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        # Otherwise find the most appropriate existing file
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                # If no config files exist, create and use the
                # first one on the list
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        # Now make our configParser
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True

    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section('system'):
            system = self.configParser.system
            if system.has_option('appDataDir'):
                # Older config files had configDir stored as appDataDir
                self.configDir = Path(system.appDataDir)
                self.stylesDir = Path(self.configDir)/'style'
                # We'll just upgrade their config file for them for now...
                system.configDir = self.configDir
                system.stylesDir = Path(self.configDir)/'style'
                del system.appDataDir

                self.audioMediaConverter_au = system.audioMediaConverter_au
                self.audioMediaConverter_wav = system.audioMediaConverter_wav
                self.videoMediaConverter_ogv = system.videoMediaConverter_ogv
                self.videoMediaConverter_3gp = system.videoMediaConverter_3gp
                self.videoMediaConverter_avi = system.videoMediaConverter_avi
                self.videoMediaConverter_mpg = system.videoMediaConverter_mpg
                self.audioMediaConverter_ogg = system.audioMediaConverter_ogg
                self.audioMediaConverter_mp3 = system.audioMediaConverter_mp3
                self.ffmpegPath = system.ffmpegPath

            self.mediaProfilePath = system.mediaProfilePath

            if system.has_option('greDir'):
                # No longer used, system should automatically support
                del system.greDir
            if system.has_option('xulDir'):
                del system.xulDir
            # if system.has_option('browser'):
            #    del system.browser

    def loadSettings(self):
        """
        Loads the settings from the exe.conf file.
        Overrides the defaults set in __init__
        """
        # Set up the parser so that if a certain value is not in the config
        # file, it will use the value from our default values
        def defVal(dummy, option):
            """If something is not in the config file, just use the default in
            'self'"""
            return getattr(self, option)
        self.configParser.defaultValue = defVal
        self.upgradeFile()
        # System Section
        if self.configParser.has_section('system'):
            system = self.configParser.system

            self.port           = int(system.port)
            self.browser        = None if system.browser == u"None" else system.browser
            self.stylesRepository = system.stylesRepository

            if not G.application.portable:
                self.dataDir        = Path(system.dataDir)
                self.configDir      = Path(system.configDir)
                self.webDir         = Path(system.webDir)
                self.stylesDir      = Path(self.configDir)/'style'
                self.jsDir          = Path(system.jsDir)
            else:
                self.stylesDir      = Path(self.webDir/'style').abspath()

            self.assumeMediaPlugins = False
            if self.configParser.has_option('system', 'assumeMediaPlugins'):
                value = system.assumeMediaPlugins.strip().lower()
                if value == "1" or value == "yes" or value == "true" or value == "on":
                    self.assumeMediaPlugins = True

        # If the dataDir points to some other dir, fix it
        if not self.dataDir.isdir():
            self.dataDir = tempfile.gettempdir()
        # make the webDir absolute, to hide path joins of relative paths
        self.webDir = self.webDir.expand().abspath()
        # If the configDir doesn't exist (as it may be a default setting with a
        # new installation) create it
        if not self.configDir.exists():
            self.configDir.mkdir()

        if not G.application.standalone:
            # FM: Copy styles
            if not os.path.exists(self.stylesDir) or not os.listdir(self.stylesDir):
                self.copyStyles()
            else:
                self.updateStyles()
        else:
            if G.application.portable:
                if os.name == 'posix':
                    self.stylesDir = Path(self.webDir/'..'/'..'/'..'/'style')
                else:
                    self.stylesDir = Path(self.webDir/'..'/'style')
                if not os.path.exists(self.stylesDir) or not os.listdir(self.stylesDir):
                    self.copyStyles()
            else:
                self.stylesDir = Path(self.webDir/'style').abspath()

        # Get the list of recently opened projects
        self.recentProjects = []
        if self.configParser.has_section('recent_projects'):
            recentProjectsSection = self.configParser.recent_projects
            # recentProjectsSection.items() is in the wrong order, keys are alright.
            # Sorting list by key before adding to self.recentProjects, to avoid wrong ordering
            # in Recent Projects menu list
            recentProjectsItems = recentProjectsSection.items()
            recentProjectsItems.sort()
            for key, path in recentProjectsItems:
                self.recentProjects.append(path)

        # Load the list of "hidden" iDevices
        self.hiddeniDevices = []
        if self.configParser.has_section('idevices'):
            idevicesSection = self.configParser.idevices
            for key, value in idevicesSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "0" or value == "no" or value == "false" or \
                        value == "off":
                    self.hiddeniDevices.append(key.lower())

        # self.deprecatediDevices = [ "flash with text", "flash movie", ...]
        # and UN-Load from the list of "deprecated" iDevices
        if self.configParser.has_section('deprecated'):
            deprecatedSection = self.configParser.deprecated
            for key, value in deprecatedSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "1" or value == "yes" or value == "true" or \
                        value == "on":
                    if key.lower() in self.deprecatediDevices:
                        self.deprecatediDevices.remove(key.lower())

        # Load the "user" section
        if self.configParser.has_section('user'):
            if self.configParser.user.has_option('editorMode'):
                self.editorMode = self.configParser.user.editorMode
            if self.configParser.user.has_option('editorVersion'):
                self.editorVersion = self.configParser.user.editorVersion
            if self.configParser.user.has_option('docType'):
                self.docType = self.configParser.user.docType
                common.setExportDocType(self.configParser.user.docType)
            if self.configParser.user.has_option('defaultStyle'):
                self.defaultStyle = self.configParser.user.defaultStyle
            if self.configParser.user.has_option('styleSecureMode'):
                self.styleSecureMode = self.configParser.user.styleSecureMode
            if self.configParser.user.has_option('internalAnchors'):
                self.internalAnchors = self.configParser.user.internalAnchors
            if self.configParser.user.has_option('lastDir'):
                self.lastDir = self.configParser.user.lastDir
            if self.configParser.user.has_option('showPreferencesOnStart'):
                self.showPreferencesOnStart = self.configParser.user.showPreferencesOnStart
            if self.configParser.user.has_option('showIdevicesGrouped'):
                self.showIdevicesGrouped = self.configParser.user.showIdevicesGrouped
            if self.configParser.user.has_option('locale'):
                self.locale = self.configParser.user.locale
            if self.configParser.user.has_option('defaultLicense'):
                self.defaultLicense = self.configParser.user.defaultLicense

    def onWrite(self, configParser):
        """
        Called just before the config file is written.
        We use it to fill out any settings that are stored here and
        not in the config parser itself
        """
        # Recent projects
        self.configParser.delete('recent_projects')
        recentProjectsSection = self.configParser.addSection('recent_projects')
        for num, path in enumerate(self.recentProjects):
            recentProjectsSection[str(num)] = path

    def setupLogging(self):
        """
        setup logging file
        """
        try:
            hdlr = RotatingFileHandler(self.configDir/'exe.log', 'a',
                                       500000, 10)
            hdlr.doRollover()
        except OSError:
            # ignore the error we get if the log file is logged
            hdlr = logging.FileHandler(self.configDir/'exe.log')

        format = "%(asctime)s %(name)s %(levelname)s %(message)s"
        log    = logging.getLogger()
        hdlr.setFormatter(logging.Formatter(format))
        log.addHandler(hdlr)

        loggingLevels = {"DEBUG"    : logging.DEBUG,
                         "INFO"     : logging.INFO,
                         "WARNING"  : logging.WARNING,
                         "ERROR"    : logging.ERROR,
                         "CRITICAL" : logging.CRITICAL}

        if self.configParser.has_section('logging'):
            for logger, level in self.configParser._sections["logging"].items():
                if logger == "root":
                    logging.getLogger().setLevel(loggingLevels[level])
                else:
                    logging.getLogger(logger).setLevel(loggingLevels[level])
        if not G.application.portable:
            log.info("************** eXe logging started **************")
            log.info("version     = %s" % version.version)
            log.info("configPath  = %s" % self.configPath)
            log.info("exePath     = %s" % self.exePath)
            log.info("libPath     = %s" % Path(twisted.__path__[0]).splitpath()[0])
            log.info("browser     = %s" % self.browser)
            log.info("webDir      = %s" % self.webDir)
            log.info("jsDir       = %s" % self.jsDir)
            log.info("localeDir   = %s" % self.localeDir)
            log.info("port        = %d" % self.port)
            log.info("dataDir     = %s" % self.dataDir)
            log.info("configDir   = %s" % self.configDir)
            log.info("locale      = %s" % self.locale)
            log.info("internalAnchors = %s" % self.internalAnchors)
            log.info("License = %s" % self.defaultLicense)

    def loadStyles(self):
        """
        Scans the eXe style directory and builds a list of styles
        """
        self.styleStore = StyleStore(self)
        listStyles = self.styleStore.getStyles()
        for style in listStyles:
            self.styles.append(style)
            # print style

    def copyStyles(self):
        bkstyle = self.webDir/'style'
        dststyle = self.stylesDir
        if os.path.exists(bkstyle):
            if os.path.exists(dststyle) and not os.listdir(self.stylesDir):
                shutil.rmtree(dststyle)
            shutil.copytree(bkstyle, dststyle)

    def updateStyles(self):
        bkstyle = self.webDir/'style'
        dststyle = self.stylesDir
        if os.stat(bkstyle).st_mtime - os.stat(dststyle).st_mtime > 1:
            for name in os.listdir(bkstyle):
                bksdirstyle = os.path.join(bkstyle, name)
                dstdirstyle = os.path.join(dststyle, name)
                if os.path.isdir(bksdirstyle):
                    if os.path.exists(dstdirstyle):
                        shutil.rmtree(dstdirstyle)
                    shutil.copytree(bksdirstyle, dstdirstyle)
                else:
                    shutil.copy(bksdirstyle, dstdirstyle)

    def loadLocales(self):
        """
        Scans the eXe locale directory and builds a list of locales
        """
        log = logging.getLogger()
        log.debug("loadLocales")
        gettext.install('exe', self.localeDir, True)
        for subDir in self.localeDir.dirs():
            if (subDir/'LC_MESSAGES'/'exe.mo').exists():
                self.locales[subDir.basename()] = \
                    gettext.translation('exe',
                                        self.localeDir,
                                        languages=[str(subDir.basename())])
        if self.locale not in self.locales:
            self.locale = 'en'
        log.debug("loading locale %s" % self.locale)
        self.locales[self.locale].install(unicode=True)
        __builtins__['c_'] = lambda s: self.locales[self.locale].ugettext(s) if s else s
コード例 #32
0
    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        # Set default values
        # exePath is the whole path and filename of the exe executable
        self.exePath     = Path(sys.argv[0]).abspath()
        # webDir is the parent directory for styles,scripts and templates
        self.webDir      = self.exePath.dirname()
        self.jsDir       = self.exePath.dirname()
        self.locales     = {}
        # localeDir is the base directory where all the locales are stored
        self.localeDir   = self.exePath.dirname()/"locale"
        # port is the port the exe webserver will listen on
        # (previous default, which earlier users might still use, was 8081)
        self.port        = 51235
        # dataDir is the default directory that is shown to the user
        # to save packages and exports in
        self.dataDir     = Path(".")
        # configDir is the dir for storing user profiles
        # and user made idevices and the config file
        self.configDir   = Path(".")
        # FM: New Styles Directory path
        self.stylesDir   = Path(self.configDir/'style').abspath()
        # FM: Default Style name
        self.defaultStyle = u"INTEF"
        # Styles repository XML-RPC endpoint
        # self.stylesRepository = 'http://www.exelearning.es/xmlrpc.php'
        self.stylesRepository = 'http://www.exelearning.net/xmlrpc.php'
        # browser is the name of a predefined browser specified
        # at http://docs.python.org/library/webbrowser.html.
        # None for system default
        self.browser = None
        # docType  is the HTML export format
        self.docType = 'HTML5'
        # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
        # available values = "enable_all", "disable_autotop", or "disable_all"
        self.internalAnchors = "enable_all"
        self.lastDir = None
        self.showPreferencesOnStart = "1"
        self.showIdevicesGrouped = "1"
        # tinymce option
        self.editorMode = 'permissive'
        self.editorVersion = '4'
        # styleSecureMode : if this [user] key is = 0  , exelearning can run python files in styles
        # as websitepage.py , ... ( deactivate secure mode )
        self.styleSecureMode = "1"
        # styles is the list of style names available for loading
        self.styles = []
        # The documents that we've recently looked at
        self.recentProjects = []
        # canonical (English) names of iDevices not to show in the iDevice pane
        self.hiddeniDevices = []
        # Media conversion programs used for XML export system
        self.videoMediaConverter_ogv = ""
        self.videoMediaConverter_3gp = ""
        self.videoMediaConverter_avi = ""
        self.videoMediaConverter_mpg = ""
        self.audioMediaConverter_ogg = ""
        self.audioMediaConverter_au = ""
        self.audioMediaConverter_mp3 = ""
        self.audioMediaConverter_wav = ""
        self.ffmpegPath = ""
        self.mediaProfilePath = self.exePath.dirname()/'mediaprofiles'

        # likewise, a canonical (English) names of iDevices not to show in the
        # iDevice pane but, contrary to the hiddens, these are ones that the
        # configuration can specify to turn ON:
        self.deprecatediDevices = ["flash with text", "flash movie", "mp3",
                                   "attachment"]
        # by default, only allow embedding of media types for which a
        # browser plugin is found:

        self.defaultLicense='creative commons: attribution - share alike 4.0'

        self.assumeMediaPlugins = False
        # Let our children override our defaults depending
        # on the OS that we're running on
        self._overrideDefaultVals()
        # locale is the language of the user. localeDir can be overridden
        # that's why we must set it _after_ the call to _overrideDefaultVals()
        self.locale = chooseDefaultLocale(self.localeDir)
        # Try to make the defaults a little intelligent
        # Under devel trees, webui is the default webdir
        self.webDir = Path(self.webDir)
        if not (self.webDir/'scripts').isdir() \
           and (self.webDir/'webui').isdir():
            self.webDir /= 'webui'
        self.jsDir = Path(self.jsDir)
        if not (self.jsDir/'scripts').isdir() \
           and (self.jsDir/'jsui').isdir():
            self.jsDir /= 'jsui'
        # Find where the config file will be saved
        self.__setConfigPath()
        # Fill in any undefined config options with our defaults
        self._writeDefaultConfigFile()
        # Now we are ready to serve the application
        self.loadSettings()
        self.setupLogging()
        self.loadLocales()
        self.loadStyles()
コード例 #33
0
 def getConfigPath(cls):
     obj = cls.__new__(cls)
     obj.configParser = ConfigParser()
     obj._overrideDefaultVals()
     obj.__setConfigPath()
     return obj.configPath
コード例 #34
0
 def setUp(self):
     """
     Creates a ConfigParser to play with
     """
     self.c = ConfigParser()
コード例 #35
0
ファイル: config.py プロジェクト: kohnle-lernmodule/palama
class Config:
    """
    The Config class contains the configuration information for eXe.
    """

    # Class attributes
    optionNames = {
        'idevices': ('someone', ),
        'system': ('webDir', 'xulDir', 'port', 'dataDir', 'configDir',
                   'localeDir', 'browserPath'),
        'user': ('locale', ),
    }

    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        # Set default values
        # idevices is the list of hidden idevices selected by the user
        self.someone = 0
        # exePath is the whole path and filename of the exe executable
        self.exePath = Path(sys.argv[0]).abspath()
        # webDir is the parent directory for styles,scripts and templates
        self.webDir = self.exePath.dirname()
        # xulDir is the parent directory for styles,scripts and templates
        self.xulDir = self.exePath.dirname()
        # localeDir is the base directory where all the locales are stored
        self.localeDir = self.exePath.dirname() / "locale"
        # port is the port the exe webserver will listen on
        # (previous default, which earlier users might still use, was 8081)
        self.port = 51235
        # dataDir is the default directory that is shown to the user
        # to save packages and exports in
        self.dataDir = Path(".")
        # configDir is the dir for storing user profiles
        # and user made idevices and the config file
        self.configDir = Path(".")
        # browserPath is the entire pathname to firefox
        self.browserPath = Path("firefox")
        # locale is the language of the user
        self.locale = chooseDefaultLocale(self.localeDir)
        # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
        # available values = "enable_all", "disable_autotop", or "disable_all"
        self.internalAnchors = "enable_all"
        # styles is the list of style names available for loading
        self.styles = []
        # The documents that we've recently looked at
        self.recentProjects = []
        # canonical (English) names of iDevices not to show in the iDevice pane
        self.hiddeniDevices = []
        # likewise, a canonical (English) names of iDevices not to show in the
        # iDevice pane but, contrary to the hiddens, these are ones that the
        # configuration can specify to turn ON:
        self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                    "attachment"]
        # by default, only allow embedding of media types for which a
        # browser plugin is found:
        self.assumeMediaPlugins = False
        # Let our children override our defaults depending
        # on the OS that we're running on
        self._overrideDefaultVals()
        # Try to make the defaults a little intelligent
        # Under devel trees, webui is the default webdir
        self.webDir = Path(self.webDir)
        if not (self.webDir/'scripts').isdir() \
           and (self.webDir/'webui').isdir():
            self.webDir /= 'webui'
        # Under devel trees, xului is the default xuldir
        self.xulDir = Path(self.xulDir)
        if not (self.xulDir/'scripts').isdir() \
           and (self.xulDir/'xului').isdir():
            self.xulDir /= 'xului'
        # Find where the config file will be saved
        self.__setConfigPath()
        # Fill in any undefined config options with our defaults
        self._writeDefaultConfigFile()
        # Now we are ready to serve the application
        self.loadSettings()
        self.setupLogging()
        self.loadStyles()
        self.loadLocales()

    def _overrideDefaultVals(self):
        """
        Override this to override the
        default config values
        """

    def _getConfigPathOptions(self):
        """
        Override this to give a list of
        possible config filenames
        in order of preference
        """
        return ['exe.conf']

    def _writeDefaultConfigFile(self):
        """
        [Over]writes 'self.configPath' with a default config file 
        (auto write is on so we don't need to write the file at the end)
        """
        for sectionName, optionNames in self.optionNames.items():
            for optionName in optionNames:
                defaultVal = getattr(self, optionName)
                self.configParser.setdefault(sectionName, optionName,
                                             defaultVal)
        # Logging can't really be changed from inside the program at the moment...
        self.configParser.setdefault('logging', 'root', 'INFO')

    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        # If there's an EXECONF environment variable, use it
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        # Otherwise find the most appropriate existing file
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                # If no config files exist, create and use the
                # first one on the list
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        # Now make our configParser
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True

    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section('system'):
            system = self.configParser.system
            if system.has_option('appDataDir'):
                # Older config files had configDir stored as appDataDir
                self.configDir = Path(system.appDataDir)
                # We'll just upgrade their config file for them for now...
                system.configDir = self.configDir
                del system.appDataDir
            if system.has_option('greDir'):
                # No longer used, system should automatically support
                del system.greDir

    def loadSettings(self):
        """
        Loads the settings from the exe.conf file.
        Overrides the defaults set in __init__
        """

        # Set up the parser so that if a certain value is not in the config
        # file, it will use the value from our default values
        def defVal(dummy, option):
            """If something is not in the config file, just use the default in
            'self'"""
            return getattr(self, option)

        self.configParser.defaultValue = defVal
        self.upgradeFile()
        # System Section
        if self.configParser.has_section('system'):
            system = self.configParser.system
            self.webDir = Path(system.webDir)
            self.xulDir = Path(system.xulDir)
            self.localeDir = Path(system.localeDir)
            self.port = int(system.port)
            self.browserPath = Path(system.browserPath)
            self.dataDir = Path(system.dataDir)
            self.configDir = Path(system.configDir)

            self.assumeMediaPlugins = False
            if self.configParser.has_option('system', \
                    'assumeMediaPlugins'):
                value = system.assumeMediaPlugins.strip().lower()
                if value == "1" or value == "yes" or value == "true" or \
                    value == "on":
                    self.assumeMediaPlugins = True

        # If the dataDir points to some other dir, fix it
        if not self.dataDir.isdir():
            self.dataDir = tempfile.gettempdir()
        # make the webDir absolute, to hide path joins of relative paths
        self.webDir = self.webDir.expand().abspath()
        # If the configDir doesn't exist (as it may be a default setting with a
        # new installation) create it
        if not self.configDir.exists():
            self.configDir.mkdir()

        # Get the list of recently opened projects
        self.recentProjects = []
        if self.configParser.has_section('recent_projects'):
            recentProjectsSection = self.configParser.recent_projects
            for key, path in recentProjectsSection.items():
                self.recentProjects.append(path)

        # Load the list of "hidden" iDevices
        self.hiddeniDevices = []
        if self.configParser.has_section('idevices'):
            idevicesSection = self.configParser.idevices
            for key, value in idevicesSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "0" or value == "no" or value == "false" or \
                        value == "off":
                    self.hiddeniDevices.append(key.lower())

        #self.deprecatediDevices = [ "flash with text", "flash movie", ...]
        # and UN-Load from the list of "deprecated" iDevices
        if self.configParser.has_section('deprecated'):
            deprecatedSection = self.configParser.deprecated
            for key, value in deprecatedSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "1" or value == "yes" or value == "true" or \
                        value == "on":
                    if key.lower() in self.deprecatediDevices:
                        self.deprecatediDevices.remove(key.lower())

        # Load the "user" section
        if self.configParser.has_section('user'):
            if self.configParser.user.has_option('internalAnchors'):
                self.internalAnchors = self.configParser.user.internalAnchors
            if self.configParser.user.has_option('locale'):
                self.locale = self.configParser.user.locale
                return
        self.locale = chooseDefaultLocale(self.localeDir)

    def onWrite(self, configParser):
        """
        Called just before the config file is written.
        We use it to fill out any settings that are stored here and 
        not in the config parser itself
        """
        # Recent projects
        self.configParser.delete('recent_projects')
        recentProjectsSection = self.configParser.addSection('recent_projects')
        for num, path in enumerate(self.recentProjects):
            recentProjectsSection[str(num)] = path

    def setupLogging(self):
        """
        setup logging file
        """
        try:
            hdlr = RotatingFileHandler(self.configDir / 'exe.log', 'a', 500000,
                                       10)
            hdlr.doRollover()
        except OSError:
            # ignore the error we get if the log file is logged
            hdlr = logging.FileHandler(self.configDir / 'exe.log')

        format = "%(asctime)s %(name)s %(levelname)s %(message)s"
        log = logging.getLogger()
        hdlr.setFormatter(logging.Formatter(format))
        log.addHandler(hdlr)

        loggingLevels = {
            "DEBUG": logging.DEBUG,
            "INFO": logging.INFO,
            "WARNING": logging.WARNING,
            "ERROR": logging.ERROR,
            "CRITICAL": logging.CRITICAL
        }

        if self.configParser.has_section('logging'):
            for logger, level in self.configParser._sections["logging"].items(
            ):
                if logger == "root":
                    logging.getLogger().setLevel(loggingLevels[level])
                else:
                    logging.getLogger(logger).setLevel(loggingLevels[level])

        log.info("************** eXe logging started **************")
        log.info("configPath  = %s" % self.configPath)
        log.info("exePath     = %s" % self.exePath)
        log.info("browserPath = %s" % self.browserPath)
        log.info("webDir      = %s" % self.webDir)
        log.info("xulDir      = %s" % self.xulDir)
        log.info("localeDir   = %s" % self.localeDir)
        log.info("port        = %d" % self.port)
        log.info("dataDir     = %s" % self.dataDir)
        log.info("configDir   = %s" % self.configDir)
        log.info("locale      = %s" % self.locale)
        log.info("internalAnchors = %s" % self.internalAnchors)

    def loadStyles(self):
        """
        Scans the eXe style directory and builds a list of styles
        """
        log = logging.getLogger()
        self.styles = []
        styleDir = self.webDir / "style"

        log.debug("loadStyles from %s" % styleDir)

        for subDir in styleDir.dirs():
            styleSheet = subDir / 'content.css'
            log.debug(" checking %s" % styleSheet)
            if styleSheet.exists():
                style = subDir.basename()
                log.debug(" loading style %s" % style)
                self.styles.append(style)

    def loadLocales(self):
        """
        Scans the eXe locale directory and builds a list of locales
        """
        log = logging.getLogger()
        log.debug("loadLocales")
        gettext.install('exe', self.localeDir, True)
        self.locales = {}
        for subDir in self.localeDir.dirs():
            if (subDir / 'LC_MESSAGES' / 'exe.mo').exists():
                self.locales[subDir.basename()] = \
                    gettext.translation('exe',
                                        self.localeDir,
                                        languages=[str(subDir.basename())])
                if subDir.basename() == self.locale:
                    locale = subDir.basename()
                    log.debug(" loading locale %s" % locale)
                    self.locales[locale].install(unicode=True)


# ===========================================================================
コード例 #36
0
class TestSections(unittest.TestCase):
    """
    Tests Section objects.
    Section objects allow an easy way to read and write
    """

    def setUp(self):
        """
        Creates a ConfigParser to play with and
        reads in the test text
        """
        self.c = ConfigParser()
        file_ = testFile()
        self.c.read(file_)

    def testSectionCreation(self):
        """
        Tests that the configuration object
        creates the section objects ok
        """
        assert isinstance(self.c.main, Section)
        assert isinstance(self.c.second, Section)
        self.failUnlessRaises(AttributeError, lambda: self.c.notexist)

    def testFromScratch(self):
        """
        Tests adding stuff from nothing
        """
        x = ConfigParser()
        testing = x.addSection('testing')
        assert x.testing is testing
        testing.myval = 4
        self.assertEquals(x.get('testing', 'myval'), '4')

    def testAttributeRead(self):
        """
        Tests that we can read attributes from sections
        """
        assert self.c.main.level == '5'
        assert self.c.main.power == 'on'
        self.failUnlessRaises(AttributeError, lambda: self.c.main.notexist)

    def testAttributeWrite(self):
        """
        Tests that we can set attributes with sections
        """
        self.c.main.level = 7
        # Should be automatically converted to string also :)
        self.assertEquals(self.c.get('main', 'level'), '7')
        self.c.main.new = 'hello'
        assert self.c.get('main', 'new') == 'hello'

    def testAttributeDel(self):
        """
        Tests that we can remove attributes from the config file
        by removing the sections
        """
        del self.c.main.level
        assert not self.c.has_option('main', 'level')

    def testSectionDel(self):
        """
        Tests that we can remove whole sections
        by deleting them
        """
        del self.c.main
        assert not self.c.has_section('main')
        def delete(): del self.c.notexist
        self.failUnlessRaises(AttributeError, delete)

    def testParserIn(self):
        """
        To test if a section exists, use the in operator
        """
        assert 'main' in self.c
        assert 'notexist' not in self.c
        # Dotted format
        assert 'main.level' in self.c
        assert 'main.notexist' not in self.c
        # And the sections can do it too
        assert 'notexist' not in self.c.main
        # Also the hasattr should give the same result
        assert hasattr(self.c, 'main')
        assert not hasattr(self.c, 'notexist')
        assert hasattr(self.c, 'main.level')
        assert hasattr(self.c.main, 'level')
        assert not hasattr(self.c.main, 'notexist')

    def testGet(self):
        """
        System should have a get section for those funny
        names that can't be attributes
        """
        assert self.c.second.get('funny-name_mate') == 'crusty the clown'

    def testCreation(self):
        """
        When one creates a section with the same name
        as an existing section the existing section should
        just be returned
        """
        mysec = Section('main', self.c)
        assert mysec is self.c.main
        othersec = Section('main', self.c)
        assert othersec is mysec is self.c.main is self.c._sections['main']
        newsec = Section('newsection', self.c)
        assert newsec is \
               self.c.addSection('newsection') is \
               self.c.newsection is \
               self.c._sections['newsection']
        newsec2 = self.c.addSection('newsection2')
        assert newsec2 is \
               self.c.addSection('newsection2') is \
               Section('newsection2', self.c) is \
               self.c.newsection2 is \
               self.c._sections['newsection2'] and \
               newsec2 is not newsec
        # Different parent should create new object
        otherConf = ConfigParser()
        sec1 = otherConf.addSection('x')
        sec2 = self.c.addSection('x')
        assert sec1 is not sec2

    def testDynamicDefaultValues(self):
        """
        Should be able to set the default value.
        Default default is to raise ValueError or AttributeError
        """
        # Default default behaviour
        self.failUnlessRaises(ValueError, self.c.get, 'main', 'not exists')
        self.failUnlessRaises(AttributeError, lambda: self.c.main.notexists)
        self.failUnlessRaises(AttributeError, lambda: self.c.notexists.notexists)
        # Try with default as None
        self.c.defaultValue = None
        assert self.c.get('main', 'not exists') is None, self.c.get('main', 'not exists')
        assert self.c.main.notexists is None
        self.failUnlessRaises(AttributeError, lambda: self.c.notexists.notexists) # This cannot be helped
        # Try with a string default
        self.c.defaultValue = 'Happy Face'
        assert self.c.get('main', 'not exists') == 'Happy Face'
        assert self.c.main.notexists == 'Happy Face'
        # Now try with a callable default!. Freaky!
        self.c.defaultValue = lambda opt, val: '%s.%s' % (opt, val)
        assert self.c.get('main', 'not exists') == 'main.not exists'
        assert self.c.main.notexists == 'main.notexists'
        assert self.c.second.notexists == 'second.notexists'
コード例 #37
0
class TestConfigParser(unittest.TestCase):
    """
    Tests the main ConfigParser class
    """

    def setUp(self):
        """
        Creates a ConfigParser to play with
        """
        self.c = ConfigParser()

    def testRead(self):
        """Ensures that it can read from a file correctly"""
        file_ = testFile()
        self.c.read(file_)
        assert self.c._sections == {'second':
                                       {'good': 'yes',
                                        'bad': 'no',
                                         'available': 'yes',
                                         'funny-name_mate': 'crusty the clown'}, 
                                    'main': 
                                        {'running': u'on\t\u0100\u01100',
                                         'testing': 'false',
                                         'two words': 'are better than one',
                                         'no_value': '',
                                         'power': 'on', 'level': '5'}
                                    }, self.c._sections

    def testReadFileName(self):
        """Can read text"""
        goodDict = {'second': 
                        {'good': 'yes',
                         'bad': 'no',
                          'available': 'yes',
                          'funny-name_mate': 'crusty the clown'}, 
                    'main': 
                        {'running': u'on\t\u0100\u01100',
                         'testing': 'false',
                         'two words': 'are better than one',
                         'no_value': '',
                         'power': 'on',
                         'level': '5'}}
        file_ = open('temp.ini', 'w')
        file_.write(TEST_TEXT)
        file_.close()
        self.c.read('temp.ini')
        assert self.c._sections == goodDict, self.c._sections
        # Can read unicode filenames
        self.c = ConfigParser()
        self.c.read(u'temp.ini')
        assert self.c._sections == goodDict, self.c._sections
        # Can read funny string object filenames
        class MyStr(str):
            """Simply overrides string to make it a different type"""
        self.c.read(MyStr('temp.ini'))
        assert self.c._sections == goodDict, self.c._sections

    def testWrite(self):
        """Test that it writes the file nicely"""
        file_ = testFile()
        self.c.read(file_)
        # Remove an option
        del self.c._sections['main']['testing']
        # Change an option
        self.c._sections['second']['bad'] = 'definately not!   '
        # Add an option
        self.c._sections['second']['squishy'] = 'Indeed'
        # Add a section at the end
        self.c._sections['middle'] = {'is here': 'yes'}
        # write the file
        file_.seek(0)
        self.c.write(file_)
        file_.seek(0)
        result = file_.readlines()
        result = map(unicode, result, ['utf8']*len(result))
        goodResult = ['nosection=here\n',
                      '[main]\n',
                      'level=5\n',
                      'power : on\n',
                      u'running =on\t\u0100\u01100\n',
                      'two words = \tare better than one\n',
                      'no_value = \n',
                      '\n', '\n',
                      '[second]\n',
                      'good :yes\n',
                      'bad:\tdefinately not!   \n',
                      '# comment=1\n',
                      '~comment2=2\n',
                      'available\t=   yes\n',
                      'funny-name_mate: crusty the clown\n',
                      'squishy = Indeed\n',
                      '\n',
                      '[middle]\n',
                      'is here = yes']
        if result != goodResult:
            print
            for good, got in zip(goodResult, result):
                if good != got:
                    print 'Different', repr(good), repr(got)
            self.fail('See above printout')

    def testWriteNewFile(self):
        """Shouldn't have any trouble writing a write only file"""
        file_ = open('temp.ini', 'w')
        self.c.set('main', 'testing', 'de repente')
        self.c.write(file_)
        file_.close()
        file_ = open('temp.ini')
        try:
            data = file_.read()
            assert data == '[main]\ntesting = de repente', data
        finally:
            file_.close()
            os.remove('temp.ini')

    def testWriteFromFileName(self):
        """If we pass write a file name, it should open or create that file
        and write or update it"""
        if os.path.exists('temp.ini'):
            os.remove('temp.ini')
        self.c.set('main', 'testing', 'de repente')
        self.c.write('temp.ini')
        file_ = open('temp.ini')
        try:
            data = file_.read()
            assert data == '[main]\ntesting = de repente', data
        finally:
            file_.close()
            os.remove('temp.ini')
        # Test updating an existing file
        self.c.set('main', 'testing', 'ok')
        self.c.write('temp.ini')
        file_ = open('temp.ini')
        try:
            data = file_.read()
            assert data == '[main]\ntesting = ok', data
        finally:
            file_.close()
            os.remove('temp.ini')

    def testGet(self):
        """Tests the get method"""
        file_ = testFile()
        self.c.read(file_)
        assert self.c.get('main', 'testing') == 'false'
        assert self.c.get('main', 'not exists', 'default') == 'default'
        self.failUnlessRaises(ValueError, self.c.get, 'main', 'not exists')

    def testSet(self):
        """Test the set method"""
        file_ = testFile()
        self.c.read(file_)
        # An existing option
        self.c.set('main', 'testing', 'perhaps')
        assert self.c._sections['main']['testing'] == 'perhaps'
        # A new and numeric option
        self.c.set('main', 'new option', 4.1)
        self.assertEquals(self.c._sections['main']['new option'], '4.1')
        # A new option in a new section
        self.c.set('new section', 'new option', 4.1)
        assert self.c._sections['new section']['new option'] == '4.1'

    def testDel(self):
        """Should be able to delete a section and/or a value in a section"""
        file_ = testFile()
        self.c.read(file_)
        assert self.c._sections['main']['level'] == '5'
        self.c.delete('main', 'level')
        assert not self.c._sections['main'].has_key('level')
        self.c.delete('main')
        assert not self.c._sections.has_key('main')

    def testShortening(self):
        """There was a bug (Issue 66) where when a longer name was read
        and a shorter name was written, the extra characters of the 
        longer name would remain in the entry"""
        file_ = open('temp.ini', 'w')
        file_.write(TEST_TEXT)
        file_.close()
        self.c.read('temp.ini')
        self.c.set('second', 'available', 'abcdefghijklmnop')
        self.c.write('temp.ini')
        c2 = ConfigParser()
        c2.read('temp.ini')
        c2.set('second', 'available', 'short')
        c2.write('temp.ini')
        self.c.read('temp.ini')
        assert self.c.get('second', 'available', '') == 'short', \
            self.c.get('second', 'available', '')

    def testUnicodeSet(self):
        """
        Should be able to set unicode option values
        with both python internal unicode strings
        or raw string containing utf8 encoded data
        """
        file_ = open('temp.ini', 'w')
        file_.write(TEST_TEXT)
        file_.close()
        self.c.read('temp.ini')
        self.c.set('main', 'power', '\xc4\x80\xc4\x900')
        self.c.set('main', 'name', unicode('\xc4\x80\xc4\x900', 'utf8'))
        self.c.set('newSecy', 'unicode', unicode('\xc4\x80\xc4\x900', 'utf8'))
        self.c.write('temp.ini')
        c2 = ConfigParser()
        c2.read('temp.ini')
        val = unicode('\xc4\x80\xc4\x900', 'utf8')
        self.assertEquals(c2.main.power, val)
        self.assertEquals(c2.main.name, val)
        self.assertEquals(c2.newSecy.unicode, val)

    def testUnicodeFileName(self):
        """
        Should be able to write to unicode filenames
        """
        # Invent a unicode filename
        dirName = unicode('\xc4\x80\xc4\x900', 'utf8')
        fn = os.path.join(dirName, dirName)
        fn += '.ini'
        if not os.path.exists(dirName):
            os.mkdir(dirName)
        # Write some test data to our unicode file
        file_ = open(fn, 'wb')
        file_.write(TEST_TEXT)
        file_.close()
        # See if we can read and write it
        self.c.read(fn)
        self.assertEquals(self.c.main.power, 'on')
        self.c.main.power = 'off'
        self.c.write()
        # Check that it was written ok
        c2 = ConfigParser()
        c2.read(fn)
        self.assertEquals(c2.main.power, 'off')
        # Clean up
        os.remove(fn)
        os.rmdir(dirName)
コード例 #38
0
class Config:
    """
    The Config class contains the configuration information for eXe.
    """
    optionNames = {
        'system': ('webDir', 'xulDir', 'port', 'dataDir', 
                   'configDir', 'localeDir', 'browserPath'),
        'user': ('locale',),
    }
    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        self.exePath     = Path(sys.argv[0]).abspath()
        self.webDir      = self.exePath.dirname()
        self.xulDir      = self.exePath.dirname()
        self.localeDir   = self.exePath.dirname()/"locale"
        self.port        = 51235
        self.dataDir     = Path(".")
        self.configDir   = Path(".")
        self.browserPath = Path("firefox")
        self.locale = chooseDefaultLocale(self.localeDir)
        self.styles      = []
        self.recentProjects = []
        self.hiddeniDevices = []
        self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                    "attachment"]
        self.assumeMediaPlugins = False;
        self._overrideDefaultVals()
        self.webDir = Path(self.webDir)
        if not (self.webDir/'scripts').isdir() \
           and (self.webDir/'webui').isdir():
            self.webDir /= 'webui'
        self.xulDir = Path(self.xulDir)
        if not (self.xulDir/'scripts').isdir() \
           and (self.xulDir/'xului').isdir():
            self.xulDir /= 'xului'
        self.__setConfigPath()
        self._writeDefaultConfigFile()
        self.loadSettings()
        self.setupLogging()
        self.loadStyles()
        self.loadLocales()
    def _overrideDefaultVals(self):
        """
        Override this to override the
        default config values
        """
    def _getConfigPathOptions(self):
        """
        Override this to give a list of
        possible config filenames
        in order of preference
        """
        return ['exe.conf']
    def _writeDefaultConfigFile(self):
        """
        [Over]writes 'self.configPath' with a default config file 
        (auto write is on so we don't need to write the file at the end)
        """
        for sectionName, optionNames in self.optionNames.items():
            for optionName in optionNames:
                defaultVal = getattr(self, optionName)
                self.configParser.setdefault(sectionName, 
                                             optionName, 
                                             defaultVal)
        self.configParser.setdefault('logging', 'root', 'INFO')
    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True
    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section('system'):
            system = self.configParser.system
            if system.has_option('appDataDir'):
                self.configDir = Path(system.appDataDir)
                system.configDir = self.configDir
                del system.appDataDir
            if system.has_option('greDir'):
                del system.greDir
    def loadSettings(self):
        """
        Loads the settings from the exe.conf file.
        Overrides the defaults set in __init__
        """
        def defVal(dummy, option):
            """If something is not in the config file, just use the default in
            'self'"""
            return getattr(self, option)
        self.configParser.defaultValue = defVal
        self.upgradeFile()
        if self.configParser.has_section('system'):
            system = self.configParser.system
            self.webDir         = Path(system.webDir)
            self.xulDir         = Path(system.xulDir)
            self.localeDir      = Path(system.localeDir)
            self.port           = int(system.port)
            self.browserPath    = Path(system.browserPath)
            self.dataDir        = Path(system.dataDir)
            self.configDir      = Path(system.configDir)
            self.assumeMediaPlugins = False;
            if self.configParser.has_option('system', \
                    'assumeMediaPlugins'):
               value = system.assumeMediaPlugins.strip().lower()
               if value == "1" or value == "yes" or value == "true" or \
                   value == "on":
                       self.assumeMediaPlugins = True;
        if not self.dataDir.isdir():
            self.dataDir = tempfile.gettempdir()
        self.webDir = self.webDir.expand().abspath()
        if not self.configDir.exists():
            self.configDir.mkdir()
        self.recentProjects = []
        if self.configParser.has_section('recent_projects'):
            recentProjectsSection = self.configParser.recent_projects
            for key, path in recentProjectsSection.items():
                self.recentProjects.append(path)
        self.hiddeniDevices = []
        if self.configParser.has_section('idevices'):
            idevicesSection = self.configParser.idevices
            for key,value in idevicesSection.items():
                value = value.strip().lower()
                if value == "0" or value == "no" or value == "false" or \
                        value == "off":
                    self.hiddeniDevices.append(key.lower())
        if self.configParser.has_section('deprecated'):
            deprecatedSection = self.configParser.deprecated
            for key,value in deprecatedSection.items():
                value = value.strip().lower()
                if value == "1" or value == "yes" or value == "true" or \
                        value == "on":
                    if key.lower() in self.deprecatediDevices:
                        self.deprecatediDevices.remove(key.lower())
        if self.configParser.has_section('user'):
            if self.configParser.user.has_option('locale'):
                self.locale = self.configParser.user.locale
                return
        self.locale = chooseDefaultLocale(self.localeDir)
    def onWrite(self, configParser):
        """
        Called just before the config file is written.
        We use it to fill out any settings that are stored here and 
        not in the config parser itself
        """
        self.configParser.delete('recent_projects')
        recentProjectsSection = self.configParser.addSection('recent_projects')
        for num, path in enumerate(self.recentProjects):
            recentProjectsSection[str(num)] = path
    def setupLogging(self):
        """
        setup logging file
        """
        try:
            hdlr = RotatingFileHandler(self.configDir/'exe.log', 'a', 
                                       500000, 10)
            hdlr.doRollover()
        except OSError:
            hdlr = logging.FileHandler(self.configDir/'exe.log')
        format = "%(asctime)s %(name)s %(levelname)s %(message)s"
        log    = logging.getLogger()
        hdlr.setFormatter(logging.Formatter(format))
        log.addHandler(hdlr)
        loggingLevels = {"DEBUG"    : logging.DEBUG,
                         "INFO"     : logging.INFO,
                         "WARNING"  : logging.WARNING,
                         "ERROR"    : logging.ERROR,
                         "CRITICAL" : logging.CRITICAL }
        if self.configParser.has_section('logging'):
            for logger, level in self.configParser._sections["logging"].items():
                if logger == "root":
                    logging.getLogger().setLevel(loggingLevels[level])
                else:
                    logging.getLogger(logger).setLevel(loggingLevels[level])
        log.info("************** eXe logging started **************")
        log.info("configPath  = %s" % self.configPath)
        log.info("exePath     = %s" % self.exePath)
        log.info("browserPath = %s" % self.browserPath)
        log.info("webDir      = %s" % self.webDir)
        log.info("xulDir      = %s" % self.xulDir)
        log.info("localeDir   = %s" % self.localeDir)
        log.info("port        = %d" % self.port)
        log.info("dataDir     = %s" % self.dataDir)
        log.info("configDir   = %s" % self.configDir)
        log.info("locale      = %s" % self.locale)
    def loadStyles(self):
        """
        Scans the eXe style directory and builds a list of styles
        """
        log = logging.getLogger()
        self.styles = []
        styleDir    = self.webDir/"style"
        log.debug("loadStyles from %s" % styleDir)
        for subDir in styleDir.dirs():
            styleSheet = subDir/'content.css'
            log.debug(" checking %s" % styleSheet)
            if styleSheet.exists():
                style = subDir.basename()
                log.debug(" loading style %s" % style)
                self.styles.append(style)
    def loadLocales(self):
        """
        Scans the eXe locale directory and builds a list of locales
        """
        log = logging.getLogger()
        log.debug("loadLocales")
        gettext.install('exe', self.localeDir, True)
        self.locales = {}
        for subDir in self.localeDir.dirs():
            if (subDir/'LC_MESSAGES'/'exe.mo').exists():
                self.locales[subDir.basename()] = \
                    gettext.translation('exe', 
                                        self.localeDir, 
                                        languages=[str(subDir.basename())])
                if subDir.basename() == self.locale:
                    locale = subDir.basename()
                    log.debug(" loading locale %s" % locale)
                    self.locales[locale].install(unicode=True)
コード例 #39
0
ファイル: config.py プロジェクト: KatiaBorges/exeLearning
 def __init__(self):
     """
     Initialise
     """
     self.configPath = None
     self.configParser = ConfigParser(self.onWrite)
     # Set default values
     # exePath is the whole path and filename of the exe executable
     self.exePath     = Path(sys.argv[0]).abspath()
     # webDir is the parent directory for styles,scripts and templates
     self.webDir      = self.exePath.dirname()
     # xulDir is the parent directory for styles,scripts and templates
     self.xulDir      = self.exePath.dirname()
     # localeDir is the base directory where all the locales are stored
     self.localeDir   = self.exePath.dirname()/"locale"
     # port is the port the exe webserver will listen on 
     # (previous default, which earlier users might still use, was 8081)
     self.port        = 51235
     # dataDir is the default directory that is shown to the user
     # to save packages and exports in
     self.dataDir     = Path(".")
     # configDir is the dir for storing user profiles
     # and user made idevices and the config file
     self.configDir   = Path(".")
     # browserPath is the entire pathname to firefox
     self.browserPath = Path("firefox")
     # locale is the language of the user
     self.locale = chooseDefaultLocale(self.localeDir)
     # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
     # available values = "enable_all", "disable_autotop", or "disable_all"
     self.internalAnchors = "enable_all"
     # styles is the list of style names available for loading
     self.styles      = []
     # The documents that we've recently looked at
     self.recentProjects = []
     # canonical (English) names of iDevices not to show in the iDevice pane
     self.hiddeniDevices = []
     # likewise, a canonical (English) names of iDevices not to show in the
     # iDevice pane but, contrary to the hiddens, these are ones that the 
     # configuration can specify to turn ON:
     self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                 "attachment"]
     # by default, only allow embedding of media types for which a 
     # browser plugin is found:
     self.assumeMediaPlugins = False;
     # Let our children override our defaults depending
     # on the OS that we're running on
     self._overrideDefaultVals()
     # Try to make the defaults a little intelligent
     # Under devel trees, webui is the default webdir
     self.webDir = Path(self.webDir)
     if not (self.webDir/'scripts').isdir() \
        and (self.webDir/'webui').isdir():
         self.webDir /= 'webui'
     # Under devel trees, xului is the default xuldir
     self.xulDir = Path(self.xulDir)
     if not (self.xulDir/'scripts').isdir() \
        and (self.xulDir/'xului').isdir():
         self.xulDir /= 'xului'
     # Latex distribution path if environment wasn't set properly
     self.latexpath = ""
     # Find where the config file will be saved
     self.__setConfigPath()
     # Fill in any undefined config options with our defaults
     self._writeDefaultConfigFile()
     # Now we are ready to serve the application
     self.loadSettings()
     self.setupLogging()
     self.loadStyles()
     self.loadLocales()
コード例 #40
0
ファイル: config.py プロジェクト: KatiaBorges/exeLearning
class Config:
    """
    The Config class contains the configuration information for eXe.
    """

    # Class attributes
    optionNames = {
        'system': ('webDir', 'xulDir', 'port', 'dataDir', 
                   'configDir', 'localeDir', 'browserPath', ),
        'user': ('locale', 'latexpath'),
    }

    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser(self.onWrite)
        # Set default values
        # exePath is the whole path and filename of the exe executable
        self.exePath     = Path(sys.argv[0]).abspath()
        # webDir is the parent directory for styles,scripts and templates
        self.webDir      = self.exePath.dirname()
        # xulDir is the parent directory for styles,scripts and templates
        self.xulDir      = self.exePath.dirname()
        # localeDir is the base directory where all the locales are stored
        self.localeDir   = self.exePath.dirname()/"locale"
        # port is the port the exe webserver will listen on 
        # (previous default, which earlier users might still use, was 8081)
        self.port        = 51235
        # dataDir is the default directory that is shown to the user
        # to save packages and exports in
        self.dataDir     = Path(".")
        # configDir is the dir for storing user profiles
        # and user made idevices and the config file
        self.configDir   = Path(".")
        # browserPath is the entire pathname to firefox
        self.browserPath = Path("firefox")
        # locale is the language of the user
        self.locale = chooseDefaultLocale(self.localeDir)
        # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
        # available values = "enable_all", "disable_autotop", or "disable_all"
        self.internalAnchors = "enable_all"
        # styles is the list of style names available for loading
        self.styles      = []
        # The documents that we've recently looked at
        self.recentProjects = []
        # canonical (English) names of iDevices not to show in the iDevice pane
        self.hiddeniDevices = []
        # likewise, a canonical (English) names of iDevices not to show in the
        # iDevice pane but, contrary to the hiddens, these are ones that the 
        # configuration can specify to turn ON:
        self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                    "attachment"]
        # by default, only allow embedding of media types for which a 
        # browser plugin is found:
        self.assumeMediaPlugins = False;
        # Let our children override our defaults depending
        # on the OS that we're running on
        self._overrideDefaultVals()
        # Try to make the defaults a little intelligent
        # Under devel trees, webui is the default webdir
        self.webDir = Path(self.webDir)
        if not (self.webDir/'scripts').isdir() \
           and (self.webDir/'webui').isdir():
            self.webDir /= 'webui'
        # Under devel trees, xului is the default xuldir
        self.xulDir = Path(self.xulDir)
        if not (self.xulDir/'scripts').isdir() \
           and (self.xulDir/'xului').isdir():
            self.xulDir /= 'xului'
        # Latex distribution path if environment wasn't set properly
        self.latexpath = ""
        # Find where the config file will be saved
        self.__setConfigPath()
        # Fill in any undefined config options with our defaults
        self._writeDefaultConfigFile()
        # Now we are ready to serve the application
        self.loadSettings()
        self.setupLogging()
        self.loadStyles()
        self.loadLocales()


    def _overrideDefaultVals(self):
        """
        Override this to override the
        default config values
        """

    def _getConfigPathOptions(self):
        """
        Override this to give a list of
        possible config filenames
        in order of preference
        """
        return ['exe.conf']


    def _writeDefaultConfigFile(self):
        """
        [Over]writes 'self.configPath' with a default config file 
        (auto write is on so we don't need to write the file at the end)
        """
        for sectionName, optionNames in self.optionNames.items():
            for optionName in optionNames:
                defaultVal = getattr(self, optionName)
                self.configParser.setdefault(sectionName, 
                                             optionName, 
                                             defaultVal)
        # Logging can't really be changed from inside the program at the moment...
        self.configParser.setdefault('logging', 'root', 'INFO')


    def _getWinFolder(self, code):
        """
        Gets one of the windows famous directorys
        depending on 'code'
        Possible values can be found at:
        http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/enums/csidl.asp#CSIDL_WINDOWS
        """
        from ctypes import WinDLL, create_unicode_buffer
        dll = WinDLL('shell32')
        # The '5' and the '0' from the below call come from
        # google: "ShellSpecialConstants site:msdn.microsoft.com"
        result = create_unicode_buffer(260)
        resource = dll.SHGetFolderPathW(None, code, None, 0, result)
        if resource != 0: 
            return Path('')
        else: 
            return Path(result.value)

        
    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        # If there's an EXECONF environment variable, use it
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        # Otherwise find the most appropriate existing file
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                # If no config files exist, create and use the
                # first one on the list
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        # Now make our configParser
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True


    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section('system'):
            system = self.configParser.system
            if system.has_option('appDataDir'):
                # Older config files had configDir stored as appDataDir
                self.configDir = Path(system.appDataDir)
                # We'll just upgrade their config file for them for now...
                system.configDir = self.configDir
                del system.appDataDir
            if system.has_option('greDir'):
                # No longer used, system should automatically support
                del system.greDir


    def loadSettings(self):
        """
        Loads the settings from the exe.conf file.
        Overrides the defaults set in __init__
        """
        # Set up the parser so that if a certain value is not in the config
        # file, it will use the value from our default values
        def defVal(dummy, option):
            """If something is not in the config file, just use the default in
            'self'"""
            return getattr(self, option)
        self.configParser.defaultValue = defVal
        self.upgradeFile()
        # System Section
        if self.configParser.has_section('system'):
            system = self.configParser.system
            self.webDir         = Path(system.webDir)
            self.xulDir         = Path(system.xulDir)
            self.localeDir      = Path(system.localeDir)
            self.port           = int(system.port)
            self.browserPath    = Path(system.browserPath)
            self.dataDir        = Path(system.dataDir)
            self.configDir      = Path(system.configDir)
            
            self.assumeMediaPlugins = False;
            if self.configParser.has_option('system', \
                    'assumeMediaPlugins'):
               value = system.assumeMediaPlugins.strip().lower()
               if value == "1" or value == "yes" or value == "true" or \
                   value == "on":
                       self.assumeMediaPlugins = True;

        # If the dataDir points to some other dir, fix it
        if not self.dataDir.isdir():
            self.dataDir = tempfile.gettempdir()
        # make the webDir absolute, to hide path joins of relative paths
        self.webDir = self.webDir.expand().abspath()
        # If the configDir doesn't exist (as it may be a default setting with a
        # new installation) create it
        if not self.configDir.exists():
            self.configDir.mkdir()
                
        # Get the list of recently opened projects
        self.recentProjects = []
        if self.configParser.has_section('recent_projects'):
            recentProjectsSection = self.configParser.recent_projects
            for key, path in recentProjectsSection.items():
                self.recentProjects.append(path)
                
        # Load the list of "hidden" iDevices
        self.hiddeniDevices = []
        if self.configParser.has_section('idevices'):
            idevicesSection = self.configParser.idevices
            for key,value in idevicesSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "0" or value == "no" or value == "false" or \
                        value == "off":
                    self.hiddeniDevices.append(key.lower())

        #self.deprecatediDevices = [ "flash with text", "flash movie", ...]
        # and UN-Load from the list of "deprecated" iDevices
        if self.configParser.has_section('deprecated'):
            deprecatedSection = self.configParser.deprecated
            for key,value in deprecatedSection.items():
                # emulate standard library's getboolean()
                value = value.strip().lower()
                if value == "1" or value == "yes" or value == "true" or \
                        value == "on":
                    if key.lower() in self.deprecatediDevices:
                        self.deprecatediDevices.remove(key.lower())

        # Load the "user" section
        if self.configParser.has_section('user'):
            if self.configParser.user.has_option('internalAnchors'):
                self.internalAnchors = self.configParser.user.internalAnchors
            if self.configParser.user.has_option('locale'):
                self.locale = self.configParser.user.locale
                return
        self.locale = chooseDefaultLocale(self.localeDir)

    def onWrite(self, configParser):
        """
        Called just before the config file is written.
        We use it to fill out any settings that are stored here and 
        not in the config parser itself
        """
        # Recent projects
        self.configParser.delete('recent_projects')
        recentProjectsSection = self.configParser.addSection('recent_projects')
        for num, path in enumerate(self.recentProjects):
            recentProjectsSection[str(num)] = path

    def setupLogging(self):
        """
        setup logging file
        """
        try:
            hdlr = RotatingFileHandler(self.configDir/'exe.log', 'a', 
                                       500000, 10)
            hdlr.doRollover()
        except OSError:
            # ignore the error we get if the log file is logged
            hdlr = logging.FileHandler(self.configDir/'exe.log')

        format = "%(asctime)s %(name)s %(levelname)s %(message)s"
        log    = logging.getLogger()
        hdlr.setFormatter(logging.Formatter(format))
        log.addHandler(hdlr)

        loggingLevels = {"DEBUG"    : logging.DEBUG,
                         "INFO"     : logging.INFO,
                         "WARNING"  : logging.WARNING,
                         "ERROR"    : logging.ERROR,
                         "CRITICAL" : logging.CRITICAL }

    
        if self.configParser.has_section('logging'):
            for logger, level in self.configParser._sections["logging"].items():
                if logger == "root":
                    logging.getLogger().setLevel(loggingLevels[level])
                else:
                    logging.getLogger(logger).setLevel(loggingLevels[level])

        log.info("************** eXe logging started **************")
        log.info("configPath  = %s" % self.configPath)
        log.info("exePath     = %s" % self.exePath)
        log.info("browserPath = %s" % self.browserPath)
        log.info("webDir      = %s" % self.webDir)
        log.info("xulDir      = %s" % self.xulDir)
        log.info("localeDir   = %s" % self.localeDir)
        log.info("port        = %d" % self.port)
        log.info("dataDir     = %s" % self.dataDir)
        log.info("configDir   = %s" % self.configDir)
        log.info("locale      = %s" % self.locale)
        log.info("internalAnchors = %s" % self.internalAnchors)
                    

    def loadStyles(self):
        """
        Scans the eXe style directory and builds a list of styles
        """
        log = logging.getLogger()
        self.styles = [] 
        styleDir    = self.webDir/"style"
        localeStyleDir = self.configDir / "style"
        if not os.path.exists(localeStyleDir):
            os.makedirs(localeStyleDir)

        log.debug("loadStyles from %s" % styleDir)

        for subDir in styleDir.dirs():
            if self.__checkStyle(subDir):
                styleName = subDir.basename()
                log.debug(" adding style to style/%s" % styleName)
                self.styles.append(styleName)
        # adding style from config to style/locale
        for subDir in localeStyleDir.dirs():
            if self.__checkStyle(subDir):
                styleName = "locale/" + subDir.basename()
                log.debug(" adding locale style to style/%s" % styleName)
                self.styles.append(styleName)

    def __checkStyle(self, style):
        '''Checks if it's valid style'''
        styleSheet = style / 'content.css'
        return styleSheet.exists()


    def loadLocales(self):
        """
        Scans the eXe locale directory and builds a list of locales
        """
        log = logging.getLogger()
        log.debug("loadLocales")
        gettext.install('exe', self.localeDir, True)
        self.locales = {}
        for subDir in self.localeDir.dirs():
            if (subDir/'LC_MESSAGES'/'exe.mo').exists():
                self.locales[subDir.basename()] = \
                    gettext.translation('exe', 
                                        self.localeDir, 
                                        languages=[str(subDir.basename())])
                if subDir.basename() == self.locale:
                    locale = subDir.basename()
                    log.debug(" loading locale %s" % locale)
                    self.locales[locale].install(unicode=True)
コード例 #41
0
class TestSections(unittest.TestCase):
    """
    Tests Section objects.
    Section objects allow an easy way to read and write
    """

    def setUp(self):
        """
        Creates a ConfigParser to play with and
        reads in the test text
        """
        self.c = ConfigParser()
        file_ = testFile()
        self.c.read(file_)

    def testSectionCreation(self):
        """
        Tests that the configuration object
        creates the section objects ok
        """
        assert isinstance(self.c.main, Section)
        assert isinstance(self.c.second, Section)
        self.failUnlessRaises(AttributeError, lambda: self.c.notexist)

    def testFromScratch(self):
        """
        Tests adding stuff from nothing
        """
        x = ConfigParser()
        testing = x.addSection('testing')
        assert x.testing is testing
        testing.myval = 4
        self.assertEquals(x.get('testing', 'myval'), '4')

    def testAttributeRead(self):
        """
        Tests that we can read attributes from sections
        """
        assert self.c.main.level == '5'
        assert self.c.main.power == 'on'
        self.failUnlessRaises(AttributeError, lambda: self.c.main.notexist)

    def testAttributeWrite(self):
        """
        Tests that we can set attributes with sections
        """
        self.c.main.level = 7
        # Should be automatically converted to string also :)
        self.assertEquals(self.c.get('main', 'level'), '7')
        self.c.main.new = 'hello'
        assert self.c.get('main', 'new') == 'hello'

    def testAttributeDel(self):
        """
        Tests that we can remove attributes from the config file
        by removing the sections
        """
        del self.c.main.level
        assert not self.c.has_option('main', 'level')

    def testSectionDel(self):
        """
        Tests that we can remove whole sections
        by deleting them
        """
        del self.c.main
        assert not self.c.has_section('main')
        def delete(): del self.c.notexist
        self.failUnlessRaises(AttributeError, delete)

    def testParserIn(self):
        """
        To test if a section exists, use the in operator
        """
        assert 'main' in self.c
        assert 'notexist' not in self.c
        # Dotted format
        assert 'main.level' in self.c
        assert 'main.notexist' not in self.c
        # And the sections can do it too
        assert 'notexist' not in self.c.main
        # Also the hasattr should give the same result
        assert hasattr(self.c, 'main')
        assert not hasattr(self.c, 'notexist')
        assert hasattr(self.c, 'main.level')
        assert hasattr(self.c.main, 'level')
        assert not hasattr(self.c.main, 'notexist')

    def testGet(self):
        """
        System should have a get section for those funny
        names that can't be attributes
        """
        assert self.c.second.get('funny-name_mate') == 'crusty the clown'

    def testCreation(self):
        """
        When one creates a section with the same name
        as an existing section the existing section should
        just be returned
        """
        mysec = Section('main', self.c)
        assert mysec is self.c.main
        othersec = Section('main', self.c)
        assert othersec is mysec is self.c.main is self.c._sections['main']
        newsec = Section('newsection', self.c)
        assert newsec is \
               self.c.addSection('newsection') is \
               self.c.newsection is \
               self.c._sections['newsection']
        newsec2 = self.c.addSection('newsection2')
        assert newsec2 is \
               self.c.addSection('newsection2') is \
               Section('newsection2', self.c) is \
               self.c.newsection2 is \
               self.c._sections['newsection2'] and \
               newsec2 is not newsec
        # Different parent should create new object
        otherConf = ConfigParser()
        sec1 = otherConf.addSection('x')
        sec2 = self.c.addSection('x')
        assert sec1 is not sec2

    def testDynamicDefaultValues(self):
        """
        Should be able to set the default value.
        Default default is to raise ValueError or AttributeError
        """
        # Default default behaviour
        self.failUnlessRaises(ValueError, self.c.get, 'main', 'not exists')
        self.failUnlessRaises(AttributeError, lambda: self.c.main.notexists)
        self.failUnlessRaises(AttributeError, lambda: self.c.notexists.notexists)
        # Try with default as None
        self.c.defaultValue = None
        assert self.c.get('main', 'not exists') is None, self.c.get('main', 'not exists')
        assert self.c.main.notexists is None
        self.failUnlessRaises(AttributeError, lambda: self.c.notexists.notexists) # This cannot be helped
        # Try with a string default
        self.c.defaultValue = 'Happy Face'
        assert self.c.get('main', 'not exists') == 'Happy Face'
        assert self.c.main.notexists == 'Happy Face'
        # Now try with a callable default!. Freaky!
        self.c.defaultValue = lambda opt, val: '%s.%s' % (opt, val)
        assert self.c.get('main', 'not exists') == 'main.not exists'
        assert self.c.main.notexists == 'main.notexists'
        assert self.c.second.notexists == 'second.notexists'
コード例 #42
0
ファイル: config.py プロジェクト: kohnle-lernmodule/palama
 def __init__(self):
     """
     Initialise
     """
     self.configPath = None
     self.configParser = ConfigParser(self.onWrite)
     # Set default values
     # idevices is the list of hidden idevices selected by the user
     self.someone = 0
     # exePath is the whole path and filename of the exe executable
     self.exePath = Path(sys.argv[0]).abspath()
     # webDir is the parent directory for styles,scripts and templates
     self.webDir = self.exePath.dirname()
     # xulDir is the parent directory for styles,scripts and templates
     self.xulDir = self.exePath.dirname()
     # localeDir is the base directory where all the locales are stored
     self.localeDir = self.exePath.dirname() / "locale"
     # port is the port the exe webserver will listen on
     # (previous default, which earlier users might still use, was 8081)
     self.port = 51235
     # dataDir is the default directory that is shown to the user
     # to save packages and exports in
     self.dataDir = Path(".")
     # configDir is the dir for storing user profiles
     # and user made idevices and the config file
     self.configDir = Path(".")
     # browserPath is the entire pathname to firefox
     self.browserPath = Path("firefox")
     # locale is the language of the user
     self.locale = chooseDefaultLocale(self.localeDir)
     # internalAnchors indicate which exe_tmp_anchor tags to generate for each tinyMCE field
     # available values = "enable_all", "disable_autotop", or "disable_all"
     self.internalAnchors = "enable_all"
     # styles is the list of style names available for loading
     self.styles = []
     # The documents that we've recently looked at
     self.recentProjects = []
     # canonical (English) names of iDevices not to show in the iDevice pane
     self.hiddeniDevices = []
     # likewise, a canonical (English) names of iDevices not to show in the
     # iDevice pane but, contrary to the hiddens, these are ones that the
     # configuration can specify to turn ON:
     self.deprecatediDevices = [ "flash with text", "flash movie", "mp3", \
                                 "attachment"]
     # by default, only allow embedding of media types for which a
     # browser plugin is found:
     self.assumeMediaPlugins = False
     # Let our children override our defaults depending
     # on the OS that we're running on
     self._overrideDefaultVals()
     # Try to make the defaults a little intelligent
     # Under devel trees, webui is the default webdir
     self.webDir = Path(self.webDir)
     if not (self.webDir/'scripts').isdir() \
        and (self.webDir/'webui').isdir():
         self.webDir /= 'webui'
     # Under devel trees, xului is the default xuldir
     self.xulDir = Path(self.xulDir)
     if not (self.xulDir/'scripts').isdir() \
        and (self.xulDir/'xului').isdir():
         self.xulDir /= 'xului'
     # Find where the config file will be saved
     self.__setConfigPath()
     # Fill in any undefined config options with our defaults
     self._writeDefaultConfigFile()
     # Now we are ready to serve the application
     self.loadSettings()
     self.setupLogging()
     self.loadStyles()
     self.loadLocales()
コード例 #43
0
 def setUp(self):
     """
     Creates a ConfigParser to play with
     """
     self.c = ConfigParser()
コード例 #44
0
class Config:
    """
    The Config class contains the configuration information for eXe.
    """

    optionNames = {
        "system": ("webDir", "xulDir", "port", "dataDir", "configDir", "localeDir", "browserPath"),
        "user": ("locale",),
    }

    def __init__(self):
        """
        Initialise
        """
        self.configPath = None
        self.configParser = ConfigParser()
        self.exePath = Path(sys.argv[0]).abspath()
        self.webDir = self.exePath.dirname()
        self.xulDir = self.exePath.dirname()
        self.localeDir = self.exePath.dirname() / "locale"
        self.port = 51235
        self.dataDir = Path(".")
        self.configDir = Path(".")
        self.browserPath = Path("firefox")
        self.locale = chooseDefaultLocale(self.localeDir)
        self.styles = []
        self._overrideDefaultVals()
        self.webDir = Path(self.webDir)
        if not (self.webDir / "scripts").isdir() and (self.webDir / "webui").isdir():
            self.webDir /= "webui"
        self.xulDir = Path(self.xulDir)
        if not (self.xulDir / "scripts").isdir() and (self.xulDir / "xului").isdir():
            self.xulDir /= "xului"
        self.__setConfigPath()
        self._writeDefaultConfigFile()
        self.loadSettings()
        self.setupLogging()
        self.loadStyles()
        self.loadLocales()

    def _overrideDefaultVals(self):
        """
        Override this to override the
        default config values
        """

    def _getConfigPathOptions(self):
        """
        Override this to give a list of
        possible config filenames
        in order of preference
        """
        return ["exe.conf"]

    def _writeDefaultConfigFile(self):
        """
        [Over]writes 'self.configPath' with a default config file 
        (auto write is on so we don't need to write the file at the end)
        """
        for sectionName, optionNames in self.optionNames.items():
            for optionName in optionNames:
                defaultVal = getattr(self, optionName)
                self.configParser.setdefault(sectionName, optionName, defaultVal)
        self.configParser.setdefault("logging", "root", "INFO")

    def __setConfigPath(self):
        """
        sets self.configPath to the filename of the config file that we'll
        use.
        In descendant classes set self.configFileOptions to a list
        of directories where the configDir should be in order of preference.
        If no config files can be found in these dirs, it will
        force creation of the config file in the top dir
        """
        self.configPath = None
        configFileOptions = map(Path, self._getConfigPathOptions())
        if "EXECONF" in os.environ:
            envconf = Path(os.environ["EXECONF"])
            if envconf.isfile():
                self.configPath = os.environ["EXECONF"]
        if self.configPath is None:
            for confPath in configFileOptions:
                if confPath.isfile():
                    self.configPath = confPath
                    break
            else:
                self.configPath = configFileOptions[0]
                folder = self.configPath.abspath().dirname()
                if not folder.exists():
                    folder.makedirs()
                self.configPath.touch()
        self.configParser.read(self.configPath)
        self.configParser.autoWrite = True

    def upgradeFile(self):
        """
        Called before loading the config file,
        removes or upgrades any old settings.
        """
        if self.configParser.has_section("system"):
            system = self.configParser.system
            if system.has_option("appDataDir"):
                self.configDir = Path(system.appDataDir)
                system.configDir = self.configDir
                del system.appDataDir
            if system.has_option("greDir"):
                del system.greDir

    def loadSettings(self):
        """
        Loads the settings from the exe.conf file.
        Overrides the defaults set in __init__
        """

        def defVal(dummy, option):
            """If something is not in the config file, just use the default in
            'self'"""
            return getattr(self, option)

        self.configParser.defaultValue = defVal
        self.upgradeFile()
        if self.configParser.has_section("system"):
            system = self.configParser.system
            self.webDir = Path(system.webDir)
            self.xulDir = Path(system.xulDir)
            self.localeDir = Path(system.localeDir)
            self.port = int(system.port)
            self.browserPath = Path(system.browserPath)
            self.dataDir = Path(system.dataDir)
            self.configDir = Path(system.configDir)
        if not self.dataDir.isdir():
            self.dataDir = tempfile.gettempdir()
        self.webDir = self.webDir.expand().abspath()
        if not self.configDir.exists():
            self.configDir.mkdir()
        if self.configParser.has_section("user"):
            if self.configParser.user.has_option("locale"):
                self.locale = self.configParser.user.locale
                return
        self.locale = chooseDefaultLocale(self.localeDir)

    def setupLogging(self):
        """
        setup logging file
        """
        try:
            hdlr = RotatingFileHandler(self.configDir / "exe.log", "a", 500000, 10)
            hdlr.doRollover()
        except OSError:
            hdlr = logging.FileHandler(self.configDir / "exe.log")
        format = "%(asctime)s %(name)s %(levelname)s %(message)s"
        log = logging.getLogger()
        hdlr.setFormatter(logging.Formatter(format))
        log.addHandler(hdlr)
        loggingLevels = {
            "DEBUG": logging.DEBUG,
            "INFO": logging.INFO,
            "WARNING": logging.WARNING,
            "ERROR": logging.ERROR,
            "CRITICAL": logging.CRITICAL,
        }
        if self.configParser.has_section("logging"):
            for logger, level in self.configParser._sections["logging"].items():
                if logger == "root":
                    logging.getLogger().setLevel(loggingLevels[level])
                else:
                    logging.getLogger(logger).setLevel(loggingLevels[level])
        log.info("************** eXe logging started **************")
        log.info("configPath  = %s" % self.configPath)
        log.info("exePath     = %s" % self.exePath)
        log.info("browserPath = %s" % self.browserPath)
        log.info("webDir      = %s" % self.webDir)
        log.info("xulDir      = %s" % self.xulDir)
        log.info("localeDir   = %s" % self.localeDir)
        log.info("port        = %d" % self.port)
        log.info("dataDir     = %s" % self.dataDir)
        log.info("configDir   = %s" % self.configDir)
        log.info("locale      = %s" % self.locale)

    def loadStyles(self):
        """
        Scans the eXe style directory and builds a list of styles
        """
        log = logging.getLogger()
        self.styles = []
        styleDir = self.webDir / "style"
        log.debug("loadStyles from %s" % styleDir)
        for subDir in styleDir.dirs():
            styleSheet = subDir / "content.css"
            log.debug(" checking %s" % styleSheet)
            if styleSheet.exists():
                style = subDir.basename()
                log.debug(" loading style %s" % style)
                self.styles.append(style)

    def loadLocales(self):
        """
        Scans the eXe locale directory and builds a list of locales
        """
        log = logging.getLogger()
        log.debug("loadLocales")
        gettext.install("exe", self.localeDir, True)
        self.locales = {}
        for subDir in self.localeDir.dirs():
            if (subDir / "LC_MESSAGES" / "exe.mo").exists():
                self.locales[subDir.basename()] = gettext.translation(
                    "exe", self.localeDir, languages=[str(subDir.basename())]
                )
                if subDir.basename() == self.locale:
                    locale = subDir.basename()
                    log.debug(" loading locale %s" % locale)
                    self.locales[locale].install(unicode=True)
コード例 #45
0
class TestConfigParser(unittest.TestCase):
    """
    Tests the main ConfigParser class
    """

    def setUp(self):
        """
        Creates a ConfigParser to play with
        """
        self.c = ConfigParser()

    def testRead(self):
        """Ensures that it can read from a file correctly"""
        file_ = testFile()
        self.c.read(file_)
        assert self.c._sections == {'second':
                                       {'good': 'yes',
                                        'bad': 'no',
                                         'available': 'yes',
                                         'funny-name_mate': 'crusty the clown'}, 
                                    'main': 
                                        {'running': u'on\t\u0100\u01100',
                                         'testing': 'false',
                                         'two words': 'are better than one',
                                         'no_value': '',
                                         'power': 'on', 'level': '5'}
                                    }, self.c._sections

    def testReadFileName(self):
        """Can read text"""
        goodDict = {'second': 
                        {'good': 'yes',
                         'bad': 'no',
                          'available': 'yes',
                          'funny-name_mate': 'crusty the clown'}, 
                    'main': 
                        {'running': u'on\t\u0100\u01100',
                         'testing': 'false',
                         'two words': 'are better than one',
                         'no_value': '',
                         'power': 'on',
                         'level': '5'}}
        file_ = open('temp.ini', 'w')
        file_.write(TEST_TEXT)
        file_.close()
        self.c.read('temp.ini')
        assert self.c._sections == goodDict, self.c._sections
        # Can read unicode filenames
        self.c = ConfigParser()
        self.c.read(u'temp.ini')
        assert self.c._sections == goodDict, self.c._sections
        # Can read funny string object filenames
        class MyStr(str):
            """Simply overrides string to make it a different type"""
        self.c.read(MyStr('temp.ini'))
        assert self.c._sections == goodDict, self.c._sections

    def testWrite(self):
        """Test that it writes the file nicely"""
        file_ = testFile()
        self.c.read(file_)
        # Remove an option
        del self.c._sections['main']['testing']
        # Change an option
        self.c._sections['second']['bad'] = 'definately not!   '
        # Add an option
        self.c._sections['second']['squishy'] = 'Indeed'
        # Add a section at the end
        self.c._sections['middle'] = {'is here': 'yes'}
        # write the file
        file_.seek(0)
        self.c.write(file_)
        file_.seek(0)
        result = file_.readlines()
        result = map(unicode, result, ['utf8']*len(result))
        goodResult = ['nosection=here\n',
                      '[main]\n',
                      'level=5\n',
                      'power : on\n',
                      u'running =on\t\u0100\u01100\n',
                      'two words = \tare better than one\n',
                      'no_value = \n',
                      '\n', '\n',
                      '[second]\n',
                      'good :yes\n',
                      'bad:\tdefinately not!   \n',
                      '# comment=1\n',
                      '~comment2=2\n',
                      'available\t=   yes\n',
                      'funny-name_mate: crusty the clown\n',
                      'squishy = Indeed\n',
                      '\n',
                      '[middle]\n',
                      'is here = yes']
        if result != goodResult:
            print
            for good, got in zip(goodResult, result):
                if good != got:
                    print 'Different', repr(good), repr(got)
            self.fail('See above printout')

    def testWriteNewFile(self):
        """Shouldn't have any trouble writing a write only file"""
        file_ = open('temp.ini', 'w')
        self.c.set('main', 'testing', 'de repente')
        self.c.write(file_)
        file_.close()
        file_ = open('temp.ini')
        try:
            data = file_.read()
            assert data == '[main]\ntesting = de repente', data
        finally:
            file_.close()
            os.remove('temp.ini')

    def testWriteFromFileName(self):
        """If we pass write a file name, it should open or create that file
        and write or update it"""
        if os.path.exists('temp.ini'):
            os.remove('temp.ini')
        self.c.set('main', 'testing', 'de repente')
        self.c.write('temp.ini')
        file_ = open('temp.ini')
        try:
            data = file_.read()
            assert data == '[main]\ntesting = de repente', data
        finally:
            file_.close()
            os.remove('temp.ini')
        # Test updating an existing file
        self.c.set('main', 'testing', 'ok')
        self.c.write('temp.ini')
        file_ = open('temp.ini')
        try:
            data = file_.read()
            assert data == '[main]\ntesting = ok', data
        finally:
            file_.close()
            os.remove('temp.ini')

    def testGet(self):
        """Tests the get method"""
        file_ = testFile()
        self.c.read(file_)
        assert self.c.get('main', 'testing') == 'false'
        assert self.c.get('main', 'not exists', 'default') == 'default'
        self.failUnlessRaises(ValueError, self.c.get, 'main', 'not exists')

    def testSet(self):
        """Test the set method"""
        file_ = testFile()
        self.c.read(file_)
        # An existing option
        self.c.set('main', 'testing', 'perhaps')
        assert self.c._sections['main']['testing'] == 'perhaps'
        # A new and numeric option
        self.c.set('main', 'new option', 4.1)
        self.assertEquals(self.c._sections['main']['new option'], '4.1')
        # A new option in a new section
        self.c.set('new section', 'new option', 4.1)
        assert self.c._sections['new section']['new option'] == '4.1'

    def testDel(self):
        """Should be able to delete a section and/or a value in a section"""
        file_ = testFile()
        self.c.read(file_)
        assert self.c._sections['main']['level'] == '5'
        self.c.delete('main', 'level')
        assert not self.c._sections['main'].has_key('level')
        self.c.delete('main')
        assert not self.c._sections.has_key('main')

    def testShortening(self):
        """There was a bug (Issue 66) where when a longer name was read
        and a shorter name was written, the extra characters of the 
        longer name would remain in the entry"""
        file_ = open('temp.ini', 'w')
        file_.write(TEST_TEXT)
        file_.close()
        self.c.read('temp.ini')
        self.c.set('second', 'available', 'abcdefghijklmnop')
        self.c.write('temp.ini')
        c2 = ConfigParser()
        c2.read('temp.ini')
        c2.set('second', 'available', 'short')
        c2.write('temp.ini')
        self.c.read('temp.ini')
        assert self.c.get('second', 'available', '') == 'short', \
            self.c.get('second', 'available', '')

    def testUnicodeSet(self):
        """
        Should be able to set unicode option values
        with both python internal unicode strings
        or raw string containing utf8 encoded data
        """
        file_ = open('temp.ini', 'w')
        file_.write(TEST_TEXT)
        file_.close()
        self.c.read('temp.ini')
        self.c.set('main', 'power', '\xc4\x80\xc4\x900')
        self.c.set('main', 'name', unicode('\xc4\x80\xc4\x900', 'utf8'))
        self.c.set('newSecy', 'unicode', unicode('\xc4\x80\xc4\x900', 'utf8'))
        self.c.write('temp.ini')
        c2 = ConfigParser()
        c2.read('temp.ini')
        val = unicode('\xc4\x80\xc4\x900', 'utf8')
        self.assertEquals(c2.main.power, val)
        self.assertEquals(c2.main.name, val)
        self.assertEquals(c2.newSecy.unicode, val)

    def testUnicodeFileName(self):
        """
        Should be able to write to unicode filenames
        """
        # Invent a unicode filename
        dirName = unicode('\xc4\x80\xc4\x900', 'utf8')
        fn = os.path.join(dirName, dirName)
        fn += '.ini'
        if not os.path.exists(dirName):
            os.mkdir(dirName)
        # Write some test data to our unicode file
        file_ = open(fn, 'wb')
        file_.write(TEST_TEXT)
        file_.close()
        # See if we can read and write it
        self.c.read(fn)
        self.assertEquals(self.c.main.power, 'on')
        self.c.main.power = 'off'
        self.c.write()
        # Check that it was written ok
        c2 = ConfigParser()
        c2.read(fn)
        self.assertEquals(c2.main.power, 'off')
        # Clean up
        os.remove(fn)
        os.rmdir(dirName)