当前位置: 首页>>代码示例>>Python>>正文


Python Tools.str2bool方法代码示例

本文整理汇总了Python中rapuma.core.tools.Tools.str2bool方法的典型用法代码示例。如果您正苦于以下问题:Python Tools.str2bool方法的具体用法?Python Tools.str2bool怎么用?Python Tools.str2bool使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在rapuma.core.tools.Tools的用法示例。


在下文中一共展示了Tools.str2bool方法的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Xetex

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class Xetex (Manager) :

    # Shared values
    xmlConfFile     = 'xetex.xml'

    def __init__(self, project, cfg, cType) :
        '''Do the primary initialization for this manager.'''

        super(Xetex, self).__init__(project, cfg)

#        import pdb; pdb.set_trace()

        # Create all the values we can right now for this manager.
        # Others will be created at run time when we know the cid.
        self.tools                  = Tools()
        self.project                = project
        self.local                  = project.local
        self.log                    = project.log
        self.cfg                    = cfg
        self.pid                    = project.projectIDCode
        self.gid                    = project.gid
        self.cType                  = cType
        self.Ctype                  = cType.capitalize()
        self.mType                  = project.projectMediaIDCode
        self.renderer               = 'xetex'
        self.manager                = self.cType + '_' + self.renderer.capitalize()
        self.managers               = project.managers
        self.pg_back                = ProjBackground(self.pid, self.gid)
        self.fmt_diagnose           = ProjDiagnose(self.pid, self.gid)
        self.proj_config            = Config(self.pid, self.gid)
        self.proj_config.getProjectConfig()
        self.proj_config.getLayoutConfig()
        self.proj_config.getFontConfig()
        self.proj_config.getMacroConfig()
        # Bring in some manager objects we will need
        self.proj_font              = ProjFont(self.pid)
        self.proj_illustration      = ProjIllustration(self.pid, self.gid)
        self.proj_hyphenation       = ProjHyphenation(self.pid, self.gid)
        self.usfmData               = UsfmData()
        self.cidChapNumDict         = self.usfmData.cidChapNumDict()
        self.cidPtIdDict            = self.usfmData.cidPtIdDict()
        # Get config objs
        self.projectConfig          = self.proj_config.projectConfig
        self.layoutConfig           = self.proj_config.layoutConfig
        self.fontConfig             = self.proj_config.fontConfig
        self.macroConfig            = self.proj_config.macroConfig
        self.userConfig             = self.project.userConfig
        self.macPackId              = self.projectConfig['CompTypes'][self.Ctype]['macroPackage']
        # Some config settings

        self.pdfViewerCmd           = self.tools.getPdfViewerCommand(self.userConfig, self.projectConfig)
        self.sourceEditor           = self.projectConfig['CompTypes'][self.Ctype]['sourceEditor']
        self.useBackground          = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useBackground'])
        self.useDiagnostic          = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDiagnostic'])
        self.useDocInfo             = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDocInfo'])

        # Get settings for this component
        self.managerSettings = self.projectConfig['Managers'][self.manager]
        for k, v in self.managerSettings.iteritems() :
            if v == 'True' or v == 'False' :
                setattr(self, k, self.tools.str2bool(v))
            else :
                setattr(self, k, v)

        # Set some Booleans (this comes after persistant values are set)
        # Setting hyphenation is a 2 step process, first check global, then group
        self.useHyphenation         = False
        if self.tools.str2bool(self.projectConfig['ProjectInfo']['hyphenationOn']) :
            if self.tools.str2bool(self.projectConfig['Groups'][self.gid]['useHyphenation']) :
                self.useHyphenation = True
                
        # In case the macro is not installed we need to skip over this
        try :
            self.chapNumOffSingChap     = self.tools.str2bool(self.macroConfig['Macros'][self.macPackId]['ChapterVerse']['omitChapterNumberOnSingleChapterBook'])
        except :
            self.chapNumOffSingChap     = None
        # Make any dependent folders if needed
        if not os.path.isdir(self.local.projGidFolder) :
            os.makedirs(self.local.projGidFolder)

        # Record some error codes
        # FIXME: much more needs to be done with this
        self.xetexErrorCodes =  {
            0   : 'Rendering succeful.',
            256 : 'Something really awful happened.'
                                }

        # Log messages for this module
        self.errorCodes     = {

            '1005' : ['ERR', 'PDF viewer failed with error: [<<1>>]'],
            '1010' : ['ERR', 'Style file [<<1>>] could not be created.'],
            '1040' : ['LOG', 'Created: [<<1>>]'],

            '0420' : ['WRN', 'TeX settings file has been frozen for debugging purposes.'],
            '0440' : ['LOG', 'Created: [<<1>>]'],
            '0460' : ['LOG', 'Settings changed in [<<1>>], [<<2>>] needed to be recreated.'],
            '0465' : ['LOG', 'File: [<<1>>] missing, created a new one.'],
            '0470' : ['ERR', 'Macro package [<<1>>] is not recognized by the system.'],

#.........这里部分代码省略.........
开发者ID:sillsdev,项目名称:rapuma,代码行数:103,代码来源:xetex.py

示例2: ProjData

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]

#.........这里部分代码省略.........
#        # Add helper scripts if needed
#        if self.tools.str2bool(self.userConfig['System']['autoHelperScripts']) :
#            ProjCommander(self.pid).updateScripts()

#        # Finish here (We will leave the project backup in place)
#        self.log.writeToLog(self.errorCodes['3530'], [self.tools.fName(backup),projHome])


    def restoreExternalBackup (self, source, target = None, force = False) :
        '''Restore a non-existant project from an external backup to a target folder.
        If no target is provided the project will be installed in the default project
        folder. The source path and ZIP file must be valid'''

        # Get/make the (localized) project home reference
        projHome = self.getProjHome(target)

#        import pdb; pdb.set_trace()

        # Create the source backup file name
#        source = os.path.join(source, self.pid + '.zip')

# FIXME: This needs some review and rework

        # Restore the backup
        if self.backupRestore(source, projHome) :

            # Permission for executables is lost in the zip, fix them here
            self.tools.fixExecutables(projHome)

            # If this is a new project we will need to register it now
            self.registerProject(projHome)

            # Add helper scripts if needed
            if self.tools.str2bool(self.userConfig['System']['autoHelperScripts']) :
                ProjCommander(self.pid).updateScripts()

            # Finish here (We will leave the backup-backup in place)
            self.tools.terminal('\nRapuma backup [' + self.pid + '] has been restored to: ' + projHome + '\n')
            
            return True


###############################################################################
############################ Cloud Backup Functions ###########################
###############################################################################
####################### Error Code Block Series = 4000 ########################
###############################################################################


    def isNewerThanCloud (self, cloud, projectConfig) :
        '''Compare time stamps between the cloud and the local project.
        Return True if the local project is newer or the same age as
        the copy in the cloud. Return True if the project does not
        exist in the local copy of the cloud.'''

        # First see if it exists
        cConfig = self.getConfig(cloud)
        if not cConfig :
            return True
        elif not cConfig.has_key('Backup') :
            return True
        elif not cConfig['Backup'].has_key('lastCloudPush') :
            return True
        # Check local for key
        if not projectConfig.has_key('Backup') :
            return False
开发者ID:jstnlth,项目名称:rapuma,代码行数:70,代码来源:proj_data.py

示例3: ProjBackground

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class ProjBackground (object) :

    def __init__(self, pid, gid = None) :
        '''Intitate the whole class and create the object.'''

#        import pdb; pdb.set_trace()

        self.pid                        = pid
        self.gid                        = gid
        self.local                      = ProjLocal(pid, gid)
        self.tools                      = Tools()
        self.proj_config                = Config(pid, gid)
        self.proj_config.getProjectConfig()
        self.proj_config.getLayoutConfig()
        self.projectConfig              = self.proj_config.projectConfig
        self.layoutConfig               = self.proj_config.layoutConfig
        self.log                        = ProjLog(pid)
        self.user                       = UserConfig()
        self.userConfig                 = self.user.userConfig
        self.projHome                   = os.path.join(os.environ['RAPUMA_PROJECTS'], self.pid)
        self.mmToPx                     = 72 / 25.4
        # For debugging purposes a switch can be set here for verbose
        # message output via the terminal
        self.debugMode                  = self.tools.str2bool(self.userConfig['System']['debugging'])

        # Log messages for this module
        self.errorCodes     = {

            '0000' : ['MSG', 'Placeholder message'],
            '1110' : ['MSG', 'File exsits: [<<1>>]. Use \"force\" to remove it.'],
            '1280' : ['ERR', 'Failed to merge background file with command: [<<1>>]. This is the error: [<<2>>]'],
            '1290' : ['ERR', 'Failed to convert background file [<<1>>]. Error: [<<2>>] The command was: [<<3>>]'],
            '1300' : ['MSG', 'Background merge operation in process, please wait...'],
            '1305' : ['MSG', 'Adding document information, please wait...'],
            '1310' : ['WRN', 'Failed to add background component: [<<1>>] with error: [<<2>>]'],
            '1320' : ['MSG', 'New background created.']

        }


###############################################################################
############################### Basic Functions ###############################
###############################################################################
######################## Error Code Block Series = 1000 #######################
###############################################################################

    def turnOnBackground (self) :
        '''Change the layout config settings to turn on the background.'''

        if not self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useBackground']) :
            self.layoutConfig['DocumentFeatures']['useBackground'] = True
            self.tools.writeConfFile(self.layoutConfig)


    def turnOffBackground (self) :
        '''Change the layout config settings to turn off the background.'''

        if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useBackground']) :
            self.layoutConfig['DocumentFeatures']['useBackground'] = False
            self.tools.writeConfFile(self.layoutConfig)


    def turnOnDocInfo (self) :
        '''Change the layout config settings to turn on the doc info in the background.'''

        if not self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDocInfo']) :
            self.layoutConfig['DocumentFeatures']['useDocInfo'] = True
            self.tools.writeConfFile(self.layoutConfig)


    def turnOffDocInfo (self) :
        '''Change the layout config settings to turn off the doc info in the background.'''

        if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDocInfo']) :
            self.layoutConfig['DocumentFeatures']['useDocInfo'] = False
            self.tools.writeConfFile(self.layoutConfig)


    def addBackground (self, target) :
        '''Add a background (watermark) to a rendered PDF file. This will
        figure out what the background is to be composed of and create
        a master background page. Using force will cause it to be remade.'''

        # Do a quick check if the background needs to be remade
        # The background normally is not remade if one already exists.
        # If one is there, it can be remade if regenerate is set to
        # to True. Obviously, if one is not there, it will be made.
        if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['regenerateBackground']) :
            self.createBackground()
        else :
            # If there isn't one, make it
            if not os.path.exists(self.local.backgroundFile) :
                self.createBackground()

        # Merge target with the project's background file in the Illustraton folder
        self.log.writeToLog(self.errorCodes['1300'])

        # Create a special name for the file with the background
        # Then merge and save it
        viewFile = self.tools.alterFileName(target, 'view')
#.........这里部分代码省略.........
开发者ID:sillsdev,项目名称:rapuma,代码行数:103,代码来源:proj_background.py

示例4: Pdftk

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class Pdftk (Manager) :

    # Shared values
    xmlConfFile     = 'pdftk.xml'

    def __init__(self, project, cfg, cType) :
        '''Do the primary initialization for this manager.'''

        super(Pdftk, self).__init__(project, cfg)

#        import pdb; pdb.set_trace()

        # Create all the values we can right now for this manager.
        # Others will be created at run time when we know the cid.
        self.tools                  = Tools()
        self.project                = project
        self.local                  = project.local
        self.log                    = project.log
        self.cfg                    = cfg
        self.pid                    = project.projectIDCode
        self.gid                    = project.gid
        self.cType                  = cType
        self.Ctype                  = cType.capitalize()
        self.mType                  = project.projectMediaIDCode
        self.renderer               = 'pdftk'
        self.manager                = self.cType + '_' + self.renderer.capitalize()
        self.managers               = project.managers
        self.pg_back                = ProjBackground(self.pid, self.gid)
        self.fmt_diagnose           = ProjDiagnose(self.pid, self.gid)
        self.proj_config            = Config(self.pid, self.gid)
        self.proj_config.getProjectConfig()
        self.proj_config.getLayoutConfig()
        # Get config objs
        self.projectConfig          = self.proj_config.projectConfig
        self.layoutConfig           = self.proj_config.layoutConfig
        self.userConfig             = self.project.userConfig
        # Some config settings
        self.pdfViewerCmd           = self.tools.getPdfViewerCommand(self.userConfig, self.projectConfig)
        self.useBackground          = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useBackground'])
        self.useDocInfo             = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDocInfo'])

        # Get settings for this component
        self.managerSettings = self.projectConfig['Managers'][self.manager]
        for k, v in self.managerSettings.iteritems() :
            if v == 'True' or v == 'False' :
                setattr(self, k, self.tools.str2bool(v))
            else :
                setattr(self, k, v)

        # Make any dependent folders if needed
        if not os.path.isdir(self.local.projGidFolder) :
            os.makedirs(self.local.projGidFolder)


        # Log messages for this module
        self.errorCodes     = {

            '0000' : ['MSG', 'Messages for the pdftk module.'],

            '5010' : ['ERR', 'Subprocess failed with this error: <<1>>'],
            '5020' : ['MSG', 'PDF merge was successful. Output = <<1>>'],
            '5200' : ['ERR', 'Rendered file not found: <<1>>'],
            '5210' : ['WRN', 'PDF viewing is disabled.'],
            '5720' : ['MSG', 'Saved rendered file to: [<<1>>]'],
            '5730' : ['ERR', 'Failed to save rendered file to: [<<1>>]']

        }


###############################################################################
############################ Manager Level Functions ##########################
###############################################################################
######################## Error Code Block Series = 1000 #######################
###############################################################################

    def sourceListFromCidList (self, cidList) :
        '''Return a sourceList derived from a given cidList.'''

        sourceList = []
        for cid in cidList :
            sourceList.append(self.sourceFromCid(cid))

        return sourceList

    def sourceFromCid (self, cid) :
        '''Return the full path with file name derived from a valid cid.'''
        
        return os.path.join(self.local.projComponentFolder, cid, cid + '.pdf')


###############################################################################
################################# Main Function ###############################
###############################################################################
######################## Error Code Block Series = 5000 #######################
###############################################################################

    def run (self, gid, cidList, pgRange, override, save) :
        '''This will check all the dependencies for a group and then
        use pdftk to "render" the whole group or a subset of components
        and even a page range in a single component.'''
#.........这里部分代码省略.........
开发者ID:sillsdev,项目名称:rapuma,代码行数:103,代码来源:pdftk.py

示例5: ProjIllustration

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]

#.........这里部分代码省略.........
        # we will just make it local for now
        self.proj_config.getMacroConfig()
        macroConfig = self.proj_config.macroConfig

        cType = self.projectConfig['Groups'][self.gid]['cType']
        if cType == 'usfm' :
            piclistFile = self.getCidPiclistFile(cid)
        elif cType == 'map' :
            piclistFile = self.getCidPiclistFile(self.gid)
        else :
            self.log.writeToLog(self.errorCodes['0010'], [cType])

        macPackId = self.projectConfig['CompTypes'][cType.capitalize()]['macroPackage']
        cvSep = macroConfig['Macros'][macPackId]['Illustrations']['chapterVerseSeperator']
        thisRef = ''
        trueCid = cid
        obj = {}

        # Change cid for map cType
        # Note: The piclist IDs must be three characters long but need not be recognized USFM
        # file IDs. As such, we adjust the code to recognize 'map' as our ID for map rendering
        # operations. This seems to work for now.
#        if self.cType == 'map' :
#            cid = 'map'

        with codecs.open(piclistFile, "w", encoding='utf_8') as writeObject :
            writeObject.write('% This is an auto-generated usfmTex piclist file for this project.\n')
            writeObject.write('% Do not bother editing this file.\n\n')

            for i in self.illustrationConfig[self.gid].keys() :
                obj = self.illustrationConfig[self.gid][i]
                thisRef = ''
                # Filter out if needed with this
                if not self.tools.str2bool(obj['useThisIllustration']) :
                    continue
                # Is a caption going to be used on this illustration?
                caption = ''
                if self.illustrationConfig[self.gid][i]['bid'] == cid :
                    if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useCaptions']) \
                        and self.tools.str2bool(self.illustrationConfig[self.gid][i]['useThisCaption']) :
                        if obj['caption'] :
                            caption = obj['caption']
                # Work out if we want a caption reference or not for this illustration
                if self.illustrationConfig[self.gid][i]['bid'] == cid :
                    if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useCaptionReferences']) \
                        and self.tools.str2bool(self.illustrationConfig[self.gid][i]['useThisCaptionRef']) :
                        if obj['location'] :
                            thisRef = obj['location']
                        else :
                            thisRef = obj['chapter'] + cvSep + obj['verse']

                    # If we made it this far we can output the line
                    writeObject.write(obj['bid'] + ' ' + obj['chapter'] + '.' + obj['verse'] + \
                        ' |' + obj['fileName'] + '|' + obj['width'] + '|' + obj['position'] + \
                            '|' + obj['scale'] + '|' + obj['copyright'] + '|' + caption + '|' + thisRef + ' \n')
        # Report to log
        self.log.writeToLog(self.errorCodes['0265'], [trueCid])
        return True


###############################################################################
######################## Illustration Remove Functions ########################
###############################################################################
######################## Error Code Block Series = 1000 #######################
###############################################################################
开发者ID:jstnlth,项目名称:rapuma,代码行数:69,代码来源:proj_illustration.py

示例6: ProjBinding

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class ProjBinding (object) :

    def __init__(self, pid) :
        '''Do the primary initialization for this manager.'''

        self.pid                = pid
        self.tools              = Tools()
        self.user               = UserConfig()
        self.userConfig         = self.user.userConfig
        self.config             = Config(pid)
        self.pg_back            = ProjBackground(self.pid)
        self.config.getProjectConfig()
        self.config.getLayoutConfig()
        self.projectConfig      = self.config.projectConfig
        self.layoutConfig       = self.config.layoutConfig
        self.useBackground      = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useBackground'])
        self.useDocInfo         = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDocInfo'])
        self.projHome           = os.path.join(os.environ['RAPUMA_PROJECTS'], self.pid)
        self.local              = ProjLocal(self.pid)
        self.log                = ProjLog(self.pid)
        self.pdfViewerCmd       = self.tools.getPdfViewerCommand(self.userConfig, self.projectConfig)

        # Log messages for this module
        self.errorCodes     = {
            '0205' : ['MSG', 'Unassigned message.'],
            '0210' : ['MSG', 'No contents are specified for binding.'],
            '0215' : ['ERR', 'Failed to bind contents into the [<<1>>] fille. Got error: [<<2>>]'],
            '0220' : ['ERR', 'Could not copy [<<1>>] temp file to [<<2>>] saved binding file.'],
            '0230' : ['MSG', 'Completed proccessing on the [<<1>>] binding file.'],
            '0235' : ['ERR', 'Failed to complete proccessing on the [<<1>>] binding file.'],
            '0240' : ['LOG', 'Recorded [<<1>>] rendered pages in the [<<2>>] binding file.'],
            '0260' : ['ERR', 'PDF viewer failed with this error: [<<1>>]'],
            '0265' : ['ERR', 'Rendered file not found: <<1>>'],
            '0270' : ['WRN', 'PDF viewing is disabled.'],
            '0280' : ['ERR', 'GS PDF file merge failed with this error: [<<1>>]'],
            '0300' : ['MSG', 'File binding operation in process, please wait...']

        }


###############################################################################
############################## Binding Functions ##############################
###############################################################################
######################## Error Code Block Series = 200 ########################
###############################################################################

#        import pdb; pdb.set_trace()


    def bind (self, save = False) :
        '''Bind all groups in the order they are indicated by group bindOrder
        settings. Note, because binding spans groups and the main body
        (project.py) mainly just works on one group at a time, this has to
        be called from outside project and project needs to be reinitialized
        each time a group is rendered from here.'''

#        import pdb; pdb.set_trace()

        # Get the order of the groups to be bound.
        bindOrder = {}
        # Put a safty in here in case there are no groups yet
        if not self.projectConfig.has_key('Groups') :
            return False

        # Build the bindOrder dict with ord num as key and file name as value
        for gid in self.projectConfig['Groups'].keys() :
            if not self.projectConfig['Groups'][gid].has_key('bindingOrder') :
                self.projectConfig['Groups'][gid]['bindingOrder'] = 0
                self.tools.writeConfFile(self.projectConfig)
            if int(self.projectConfig['Groups'][gid]['bindingOrder']) > 0 :
                gidPdfFile = os.path.join(self.local.projComponentFolder, gid, gid + '.pdf')
#                bindOrder[self.projectConfig['Groups'][gid]['bindingOrder']] = self.projectConfig['Groups'][gid]['bindingFile']
                bindOrder[self.projectConfig['Groups'][gid]['bindingOrder']] = gidPdfFile
        bindGrpNum = len(bindOrder)
        # Need not keep going if nothing was found
        if bindGrpNum == 0 :
            self.log.writeToLog(self.errorCodes['0210'])
            return False

        # Make an ordered key list
        keyList = bindOrder.keys()
        keyList.sort()

        # Output the bind files in order according to the list we made
        fileList = []
        for key in keyList :
            fileList.append(bindOrder[key])

        # First merge the master pages together
        tempFile = self.mergePdfFilesGs(fileList)

        # Now add background and doc info if requested
        bgFile = ''
        if self.useBackground :
            bgFile = self.pg_back.addBackground(tempFile)
        if self.useDocInfo :
            if bgFile :
                bgFile = self.pg_back.addDocInfo(bgFile)
            else :
                bgFile = self.pg_back.addDocInfo(tempFile)
#.........这里部分代码省略.........
开发者ID:sillsdev,项目名称:rapuma,代码行数:103,代码来源:proj_binding.py

示例7: ProjDiagnose

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class ProjDiagnose (object) :

    def __init__(self, pid, gid = None) :
        '''Intitate the whole class and create the object.'''

#        import pdb; pdb.set_trace()

        self.pid                        = pid
        self.gid                        = gid
        self.local                      = ProjLocal(pid, gid)
        self.tools                      = Tools()
        self.proj_config                = Config(pid, gid)
        self.proj_config.getProjectConfig()
        self.proj_config.getLayoutConfig()
        self.layoutConfig               = self.proj_config.layoutConfig
        self.user                       = UserConfig()
        self.userConfig                 = self.user.userConfig
        self.log                        = ProjLog(pid)

        # to [px] is 72/25.4 
        self.mmToPx                     = 72 / 25.4
        # page width [px]
        self.paperPxWidth               = round(self.mmToPx * float(self.layoutConfig['PageLayout']['pageWidth']),1)
        # page height [px]
        self.paperPxHeight              = round(self.mmToPx * float(self.layoutConfig['PageLayout']['pageHeight']),1)

        # Log messages for this module
        self.errorCodes     = {

            '0000' : ['MSG', 'Placeholder message'],
            '1310' : ['WRN', 'Failed to add diagnostic component: [<<1>>] with error: [<<2>>]']

        }


###############################################################################
############################### Create Functions ##############################
###############################################################################
######################## Error Code Block Series = 1000 #######################
###############################################################################


    def turnOnDiagnostic (self) :
        '''Change the layout config settings to turn on the diagnostic layer.'''

        if not self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDiagnostic']) :
            self.layoutConfig['DocumentFeatures']['useDiagnostic'] = True
            self.tools.writeConfFile(self.layoutConfig)


    def turnOffDiagnostic (self) :
        '''Change the layout config settings to turn off the diagnostic layer.'''

        if self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDiagnostic']) :
            self.layoutConfig['DocumentFeatures']['useDiagnostic'] = False
            self.tools.writeConfFile(self.layoutConfig)


    def addTransparency (self, target, force = False) :
        '''Add a transparent layer to a rendered PDF file. This will
        add in diagnosing format issues. Using force will cause any
        existing layer file to be remade.'''

        # Do a quick check if the transparency needs to be remade
        # The transparency normally is not remade if one already exists.
        # If one is there, it can be remade in two ways, with a force
        # or a regenerate command.
        if force :
            self.createDiagnostic()
        elif self.tools.str2bool(self.layoutConfig['DocumentFeatures']['regenerateTransparency']) :
            self.createDiagnostic()
        else :
            # If there isn't one, make it
            if not os.path.exists(self.local.diagnosticFile) :
                self.createDiagnostic()

        # Create a special temp named file for the target
        tmpTarget = tempfile.NamedTemporaryFile().name
        # Copy the target to the tmpTarget
        shutil.copy(target, tmpTarget)
        # Overlay the transparency diagnostic file over the tmpTarget
        self.tools.mergePdfFilesPdftk(tmpTarget, self.local.diagnosticFile)

        # Create a special name for the file with the background
        # Then merge and save it
        viewFile = self.tools.alterFileName(target, 'view')

        # Copy the results back to the target (should be done now)
        shutil.copy(tmpTarget, viewFile)

        # Not returning a file name would mean it failed
        if os.path.exists(viewFile) :
            return viewFile


    def createDiagnostic (self) :
        '''Create a diagnostic transparency (file) that will be
        superimposed over the page contents to help diagnose format
        issues. This will overwrite any existing transparency file and
        will add each recognoized diagnostic type found in the 
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_diagnose.py

示例8: UsfmTex

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class UsfmTex (object) :

    def __init__(self, layoutConfig) :
        '''Do the primary initialization for this class.'''

        self.tools                          = Tools()
        self.layoutConfig                   = layoutConfig

        # Log messages for this module
        self.errorCodes     = {

            '0000' : ['MSG', 'Placeholder message'],

        }



###############################################################################
############################ Macro Level Functions ############################
###############################################################################
####################### Error Code Block Series = 1000 ########################
###############################################################################

    def getTitleColumns (self) :
        '''Return 2 if titleColumnsTwo is True.'''

        if self.tools.str2bool(self.layoutConfig['PageLayout']['titleColumnsTwo']) :
            return 2
        else :
            return 1


    def getIntroColumns (self) :
        '''Return 2 if introColumnsTwo is True.'''

        if self.tools.str2bool(self.layoutConfig['PageLayout']['introColumnsTwo']) :
            return 2
        else :
            return 1


    def getBodyColumns (self) :
        '''Return 2 if bodyColumnsTwo is True.'''

        if self.tools.str2bool(self.layoutConfig['PageLayout']['bodyColumnsTwo']) :
            return 2
        else :
            return 1


    def getHeaderPosition (self) :
        '''Return the calculated relative position of the header based
        on the top margin setting.'''

        tm              = float(self.layoutConfig['PageLayout']['topMargin'])
        hp              = float(self.layoutConfig['PageLayout']['headerPosition'])

        return float("{0:.2f}".format(round(hp / tm, 2)))


    def getFooterPosition (self) :
        '''Return the calculated relative position of the footer based
        on the bottom margin setting.'''

        bm              = float(self.layoutConfig['PageLayout']['bottomMargin'])
        hp              = float(self.layoutConfig['PageLayout']['footerPosition'])

        return float("{0:.2f}".format(round(hp / bm, 2)))


    def getMarginUnit (self) :
        '''Calculate the basic margin unit for the macro package. This will be
        based on the largest amount set for the top, bottom and side margins.'''

        tm              = float(self.layoutConfig['PageLayout']['topMargin'])
        bm              = float(self.layoutConfig['PageLayout']['bottomMargin'])
        im              = float(self.layoutConfig['PageLayout']['insideMargin'])
        om              = float(self.layoutConfig['PageLayout']['outsideMargin'])
        # Adjust for binding gutter setting (extra insideMargin)
        if self.getBindingGutterWidth() :
            im          = im - self.getBindingGutterWidth()

        return max(float(u) for u in [tm, bm, im, om])


    def getTopMarginFactor (self) :
        '''Calculate the top margin factor based on what the base margin
        and top margin settings are.'''

        marginUnit      = self.getMarginUnit()
        topMargin       = float(self.layoutConfig['PageLayout']['topMargin'])

        return float("{0:.2f}".format(round(topMargin / marginUnit, 2)))


    def getBottomMarginFactor (self) :
        '''Calculate the bottom margin factor based on what the base margin
        and bottom margin settings are.'''

        marginUnit      = self.getMarginUnit()
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:usfmTex.py

示例9: Usfm

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]

#.........这里部分代码省略.........
        '''Does USFM specific rendering of a USFM component'''

#        import pdb; pdb.set_trace()

        # If the whole group is being rendered, we need to preprocess it
        cids = []
        if not cidList :
            cids = self.projectConfig['Groups'][gid]['cidList']
        else :
            cids = cidList

        # Preprocess all subcomponents (one or more)
        # Stop if it breaks at any point
        for cid in cids :
            if not self.preProcessGroup(gid, [cid]) :
                return False

        # With everything in place we can render the component.
        # Note: We pass the cidList straight through
        self.project.managers['usfm_' + self.renderer.capitalize()].run(gid, cidList, pages, override, save)

        return True


    def preProcessGroup (self, gid, cidList) :
        '''This will prepare a component group for rendering by checking for
        and/or creating any dependents it needs to render properly.'''

#        import pdb; pdb.set_trace()

        # Get some relevant settings
        # FIXME: Note page border has not really been implemented yet.
        # It is different from backgound management
        useIllustrations        = self.tools.str2bool(self.projectConfig['Groups'][gid]['useIllustrations'])
        useManualAdjustments    = self.tools.str2bool(self.projectConfig['Groups'][gid]['useManualAdjustments'])

        # See if the working text is present for each subcomponent in the
        # component and try to install it if it is not
        for cid in cidList :
            cType = self.cfg['cType']
            cidUsfm = self.getCidPath(cid)
            # Test for source here and die if it isn't there
            if not os.path.isfile(cidUsfm) :
                self.log.writeToLog(self.errorCodes['0220'], [cidUsfm], 'usfm.preProcessGroup():0220')
            # Add/manage the dependent files for this cid

# FIXME: Some changes may be needed here to guide creation of adjustment files
            # Component adjustment file
            cidAdjFile = self.getCidAdjPath(cid)
            if useManualAdjustments :
                self.createCompAdjustmentFile(cid)
            else :
                # If no adjustments, remove any exsiting file
                if os.path.isfile(cidAdjFile) :
                    os.remove(cidAdjFile)
            # Component piclist file
            cidPiclistFile = self.proj_illustration.getCidPiclistFile(cid)
            if useIllustrations :
                if self.proj_illustration.hasIllustrations(cid) :
                    # Check for missing illustrations (die here if not found)
                    if self.proj_illustration.missingIllustrations(cid) :
                        self.log.writeToLog(self.errorCodes['0300'])
                    # Create piclist file if not there or if the config has changed
                    if not os.path.isfile(cidPiclistFile) or self.tools.isOlder(cidPiclistFile, self.local.illustrationConfFile) :
                        # Now make a fresh version of the piclist file
                        if self.proj_illustration.createPiclistFile(cid) :
开发者ID:jstnlth,项目名称:rapuma,代码行数:70,代码来源:usfm.py

示例10: ProjBinding

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class ProjBinding (object) :

    def __init__(self, pid) :
        '''Do the primary initialization for this manager.'''

        self.pid                = pid
        self.tools              = Tools()
        self.user               = UserConfig()
        self.userConfig         = self.user.userConfig
        self.config             = Config(pid)
        self.pg_back            = ProjBackground(self.pid)
        self.config.getProjectConfig()
        self.config.getLayoutConfig()
        self.projectConfig      = self.config.projectConfig
        self.layoutConfig       = self.config.layoutConfig
        self.useBackground      = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useBackground'])
        self.useDocInfo         = self.tools.str2bool(self.layoutConfig['DocumentFeatures']['useDocInfo'])
        self.projHome           = os.path.join(self.userConfig['Resources']['projects'], self.pid)
        self.local              = ProjLocal(self.pid)
        self.log                = ProjLog(self.pid)
        self.pdfViewerCmd       = self.userConfig['System']['pdfViewerCommand']


        # Log messages for this module
        self.errorCodes     = {
            '0205' : ['MSG', 'Unassigned message.'],
            '0210' : ['MSG', 'No contents are specified for binding.'],
            '0215' : ['ERR', 'Failed to bind contents into the [<<1>>] fille. Got error: [<<2>>]'],
            '0220' : ['ERR', 'Could not copy [<<1>>] temp file to [<<2>>] saved binding file.'],
            '0230' : ['MSG', 'Completed proccessing on the [<<1>>] binding file.'],
            '0235' : ['ERR', 'Failed to complete proccessing on the [<<1>>] binding file.'],
            '0240' : ['LOG', 'Recorded [<<1>>] rendered pages in the [<<2>>] binding file.'],
            '0260' : ['ERR', 'PDF viewer failed with this error: [<<1>>]'],
            '0265' : ['ERR', 'Rendered file not found: <<1>>'],
            '0270' : ['WRN', 'PDF viewing is disabled.'],
            '0280' : ['ERR', 'GS PDF file merge failed with this error: [<<1>>]'],
            '0300' : ['MSG', 'File binding operation in process, please wait...']

        }


###############################################################################
############################## Binding Functions ##############################
###############################################################################
######################## Error Code Block Series = 200 ########################
###############################################################################

#        import pdb; pdb.set_trace()


    def bind (self, save = False) :
        '''Bind all groups in the order they are indicated by group bindOrder
        settings. Note, because binding spans groups and the main body
        (project.py) mainly just works on one group at a time, this has to
        be called from outside project and project needs to be reinitialized
        each time a group is rendered from here.'''

#        import pdb; pdb.set_trace()

        # Get the order of the groups to be bound.
        bindOrder = {}
        # Put a safty in here in case there are no groups yet
        if not self.projectConfig.has_key('Groups') :
            return False

        # Build the bindOrder dict with ord num as key and file name as value
        for gid in self.projectConfig['Groups'].keys() :
            if not self.projectConfig['Groups'][gid].has_key('bindingOrder') :
                self.projectConfig['Groups'][gid]['bindingOrder'] = 0
                self.tools.writeConfFile(self.projectConfig)
            if int(self.projectConfig['Groups'][gid]['bindingOrder']) > 0 :
                gidPdfFile = os.path.join(self.local.projComponentFolder, gid, gid + '.pdf')
#                bindOrder[self.projectConfig['Groups'][gid]['bindingOrder']] = self.projectConfig['Groups'][gid]['bindingFile']
                bindOrder[self.projectConfig['Groups'][gid]['bindingOrder']] = gidPdfFile
        bindGrpNum = len(bindOrder)
        # Need not keep going if nothing was found
        if bindGrpNum == 0 :
            self.log.writeToLog(self.errorCodes['0210'])
            return False

        # Make an ordered key list
        keyList = bindOrder.keys()
        keyList.sort()

        # Output the bind files in order according to the list we made
        fileList = []
        for key in keyList :
            fileList.append(bindOrder[key])

        # First merge the master pages together
        tempFile = self.mergePdfFilesGs(fileList)

        # Now add background and doc info if requested
        bgFile = ''
        if self.useBackground :
            bgFile = self.pg_back.addBackground(tempFile)
        if self.useDocInfo :
            if bgFile :
                bgFile = self.pg_back.addDocInfo(bgFile)
            else :
#.........这里部分代码省略.........
开发者ID:jstnlth,项目名称:rapuma,代码行数:103,代码来源:proj_binding.py

示例11: ProjHyphenation

# 需要导入模块: from rapuma.core.tools import Tools [as 别名]
# 或者: from rapuma.core.tools.Tools import str2bool [as 别名]
class ProjHyphenation (object) :

    def __init__(self, pid, gid=None) :
        '''Do the primary initialization for this class.'''

#        import pdb; pdb.set_trace()

        self.pid                        = pid
        self.gid                        = gid
        self.tools                      = Tools()
        self.local                      = ProjLocal(pid)
        self.user                       = UserConfig()
        self.userConfig                 = self.user.userConfig
        self.proj_config                = Config(pid, gid)
        self.proj_config.getProjectConfig()
        self.projectConfig              = self.proj_config.projectConfig
        self.log                        = ProjLog(pid)
        self.hyphenationOn              = self.tools.str2bool(self.projectConfig['ProjectInfo']['hyphenationOn'])
        # Get lid and sid, if these do not exist, we need to catch it during processing
        self.plid                       = self.projectConfig['ProjectInfo']['languageCode']
        self.psid                       = self.projectConfig['ProjectInfo']['scriptCode']
        if gid :
            self.glid                   = self.projectConfig['Groups'][gid]['groupLanguageCode']
            self.gsid                   = self.projectConfig['Groups'][gid]['groupScriptCode']

        # Determine the prefix for the target files, this should match the 
        # system for everthing to work.
        if gid :
            if self.glid and self.gsid :
                self.prefix                 = self.glid + '-' + self.gsid + '_'
            else :
                self.prefix                 = self.plid + '-' + self.psid + '_'
        else :
            self.prefix                 = self.plid + '-' + self.psid + '_'

        # File names
        self.rpmHyphCharTexFile         = self.local.rpmHyphCharTexFile
        self.rpmHyphExcTexFile          = self.local.rpmHyphExcTexFile
        self.rpmHyphSetTexFile          = self.local.rpmHyphSetTexFile

        # Folder paths
        self.projHyphenationFolder      = self.local.projHyphenationFolder
        self.rapumaHyphenationFolder    = self.local.rapumaHyphenationFolder

        # Log messages for this module
        self.errorCodes     = {

            '0000' : ['MSG', 'Placeholder message'],
            '1100' : ['ERR', 'Language and/or writing system codes for the project have not been properly set. Please set these values before continuing. Check Hyphenation documentation for more information.'],
            '1200' : ['ERR', 'The path and/or file name given does not appear to be valid: [<<1>>]'],
            '1300' : ['ERR', 'Rapuma is looking for a file named: [<<1>>], it cannot be found. Are all the files correctly named? Check Hyphenation documentation for more information.'],
            '1400' : ['ERR', 'One or more hyphenation files were found in this project. Please use "remove" to get them out first, then "add" to replace with the files you want.'],
            '1500' : ['MSG', 'Copied file: [<<1>>] to folder: [<<2>>]'],
            '1550' : ['ERR', 'Copied file failed for file: [<<1>>]'],
            '1600' : ['MSG', 'Added hyphenation files to the project.'],
            '2000' : ['LOG', 'When trying to remove hyphenation files, this file was not found: [<<1>>]'],
            '2100' : ['LOG', 'Set ProjectInfo/hyphenationOn to False, turning off hyphenation for the project.'],
            '2600' : ['MSG', 'Removed all hyphenation files from the project.'],
            '3500' : ['MSG', 'Updated file: [<<1>>]'],
            '3600' : ['MSG', 'The updating of hyphenation files is complete.']

        }

        # Build some file names that are shared by other functions and modules
        # Note these names will not be any good if the lid and sid are not there.
        self.projHyphExcTexFile     = os.path.join(self.projHyphenationFolder, self.prefix + self.tools.fName(self.rpmHyphExcTexFile))
        self.projHyphCharTexFile    = os.path.join(self.projHyphenationFolder, self.prefix + self.tools.fName(self.rpmHyphCharTexFile))
        self.projHyphSetTexFile     = os.path.join(self.projHyphenationFolder, self.prefix + self.tools.fName(self.rpmHyphSetTexFile))
        self.projHyphFiles          = [self.projHyphCharTexFile, self.projHyphExcTexFile, self.projHyphSetTexFile]
        self.baseFileNames          = [self.tools.fName(self.rpmHyphCharTexFile), self.tools.fName(self.rpmHyphExcTexFile), self.tools.fName(self.rpmHyphSetTexFile)]

###############################################################################
############################ Hyphenation Functions ############################
###############################################################################
######################## Error Code Block Series = 1000 #######################
###############################################################################

    def crossCheckSettings (self) :
        '''Cross check settings and die here if we are missing anything.'''
        
        # May need to add more things to check
        if not self.plid or not self.psid :
            self.log.writeToLog(self.errorCodes['1100'])


    def addHyphenationFiles (self, path = None) :
        '''Import necessary hyphenation files from the specified path.
        If no path is given and a file is not found in the project,
        create place holder file(s) that the user will modify.'''

        self.crossCheckSettings()

        # If needed, logically assemble the target file names. This is what
        # Rapuma is expecting to see.
        if path :
            # Check to see if the path given is valid. It should only be a folder, not a file.
            if not os.path.isdir(path) :
                self.log.writeToLog(self.errorCodes['1200'], [path])

            # Check to see if the files we need are at the specified location
#.........这里部分代码省略.........
开发者ID:sillsdev,项目名称:rapuma,代码行数:103,代码来源:proj_hyphenation.py


注:本文中的rapuma.core.tools.Tools.str2bool方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。