<commit_before>from .prefs_utils import get_pref
from ..rfb_logger import rfb_log
from .. import rfb_logger
from .. import rman_constants
from ..rman_constants import RFB_ADDON_PATH
import os
import bpy
import json
import xml.etree.ElementTree as ET
import subprocess
import platform
import sys

__RMAN_ENV_CONFIG__ = None

class RmanEnvConfig(object):

    def __init__(self):
        self.rmantree = ''
        self.rmantree_from_json = False
        self.rman_version = ''
        self.rman_version_major = 0
        self.rman_version_minor = 0
        self.rman_version_modifier = ''
        self.rman_it_path = ''
        self.rman_lq_path = ''
        self.rman_tractor_path = ''
        self.is_ncr_license = False

    def config_environment(self):

        self.setenv('RMANTREE', self.rmantree)
        self._append_to_path(os.path.join(self.rmantree, 'bin'))
        self._set_it_path()
        self._set_localqueue_path()
        self._config_pythonpath()
        self._set_ocio()
        self._parse_license()

    def getenv(self, k, default=None):
        return os.environ.get(k, default)

    def setenv(self, k, val):
        os.environ[k] = val

    def copyenv(self):
        return os.environ.copy()

    def read_envvars_file(self):
        bl_config_path = bpy.utils.user_resource('CONFIG')
        jsonfile = ''
        for f in os.listdir(bl_config_path):
            if not f.endswith('.json'):
                continue
            if f == 'rfb_envvars.json':
                jsonfile = os.path.join(bl_config_path, f)
                break
        if jsonfile == '':
            return

        rfb_log().warning("Reading rfb_envvars.json")
        jdata = json.load(open(jsonfile))
        environment = jdata.get('environment', list())

        for var, val in environment.items():
            rfb_log().warning("Setting envvar %s to: %s" % (var, val['value']))  
            self.setenv(var, val['value'])  
            if var == 'RMANTREE':
                self.rmantree_from_json = True
                
        # Re-init the log level in case RFB_LOG_LEVEL was set
        rfb_logger.init_log_level()

        # Also, set logger file, if any
        rfb_log_file = self.getenv('RFB_LOG_FILE')
        if rfb_log_file:
            rfb_logger.set_file_logger(rfb_log_file)

    def get_shader_registration_paths(self):
        paths = []
        rmantree = self.rmantree
        paths.append(os.path.join(rmantree, 'lib', 'shaders'))    
        paths.append(os.path.join(rmantree, 'lib', 'plugins', 'Args'))
        paths.append(os.path.join(RFB_ADDON_PATH, 'Args'))

        RMAN_SHADERPATH = self.getenv('RMAN_SHADERPATH', '')
        for p in RMAN_SHADERPATH.split(os.path.pathsep):
            paths.append(p)

        RMAN_RIXPLUGINPATH = self.getenv('RMAN_RIXPLUGINPATH', '')
        for p in RMAN_RIXPLUGINPATH.split(os.path.pathsep):
            paths.append(os.path.join(p, 'Args'))

        return paths        

    def _config_pythonpath(self):

        if platform.system() == 'Windows':
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'Lib', 'site-packages')
        else:
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'site-packages')
        sys.path.append(rman_packages)        
        sys.path.append(os.path.join(self.rmantree, 'bin'))
        pythonbindings = os.path.join(self.rmantree, 'bin', 'pythonbindings')
        sys.path.append(pythonbindings)          

    def _append_to_path(self, path):        
        if path is not None:
            self.setenv('PATH', path + os.pathsep + self.getenv('PATH'))

    def _set_it_path(self):

        if platform.system() == 'Windows':
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it.exe')
        elif platform.system() == 'Darwin':
            self.rman_it_path = os.path.join(
                self.rmantree, 'bin', 'it.app', 'Contents', 'MacOS', 'it')
        else:
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it')

    def _set_localqueue_path(self):
        if platform.system() == 'Windows':
            self.rman_lq_path = os.path.join(self.rmantree, 'bin', 'LocalQueue.exe')
        elif platform.system() == 'Darwin':
            self.rman_lq_path = os.path.join(
                self.rmantree, 'bin', 'LocalQueue.app', 'Contents', 'MacOS', 'LocalQueue')
        else:
            self.rman_lq_path= os.path.join(self.rmantree, 'bin', 'LocalQueue')

    def _set_tractor_path(self):
        base = ""
        if platform.system() == 'Windows':
            # default installation path
            base = r'C:\Program Files\Pixar'

        elif platform.system() == 'Darwin':
            base = '/Applications/Pixar'

        elif platform.system() == 'Linux':
            base = '/opt/pixar'

        latestver = 0.0
        guess = ''
        for d in os.listdir(base):
            if "Tractor" in d:
                vstr = d.split('-')[1]
                vf = float(vstr)
                if vf >= latestver:
                    latestver = vf
                    guess = os.path.join(base, d)
        tractor_dir = guess

        if tractor_dir:
            self.rman_tractor_path = os.path.join(tractor_dir, 'bin', 'tractor-spool')

    def get_blender_ocio_config(self):
        # return rman's version filmic-blender OCIO config
        ocioconfig = os.path.join(self.rmantree, 'lib', 'ocio', 'filmic-blender', 'config.ocio')

        return ocioconfig            

    def _set_ocio(self):
        # make sure we set OCIO env var
        # so that "it" will also get the correct configuration
        path = self.getenv('OCIO', '')
        if path == '':
            self.setenv('OCIO', self.get_blender_ocio_config())

    def _parse_license(self):
        pixar_license = os.path.join(self.rmantree, '..', 'pixar.license')
        pixar_license = os.environ.get('PIXAR_LICENSE_FILE', pixar_license)

        if not os.path.isfile(pixar_license):
            self.is_ncr_license = False
            return

        tree = ET.parse(pixar_license)
        root = tree.getroot()
        license_info = None
        for child in root:
            if child.tag == 'LicenseInfo':
                license_info = child
                break
        if not license_info:
            self.is_ncr_license = False
            return

        serial_num = None
        for child in license_info:
            if child.tag == 'SerialNumber':
                serial_num = child
                break

        self.is_ncr_license = (serial_num.text == 'Non-commercial') 

def _parse_version(s):
    major_vers, minor_vers = s.split('.')
    vers_modifier = ''
    for v in ['b', 'rc']:
        if v in minor_vers:
            i = minor_vers.find(v)
            vers_modifier = minor_vers[i:]
            minor_vers = minor_vers[:i]
            break
    return int(major_vers), int(minor_vers), vers_modifier                  

# return the major, minor rman version
def _get_rman_version(rmantree):

    try:        
        prman = 'prman.exe' if platform.system() == 'Windows' else 'prman'
        exe = os.path.join(rmantree, 'bin', prman)
        desc = subprocess.check_output(<commit_msg>Switch to using the new rman_utils.license module. For now, we're just using it to determine if we have an NCR license, but we should expand the usage to include querying whether or not a render license is available before we go to render.<commit_after>from .prefs_utils import get_pref
from ..rfb_logger import rfb_log
from .. import rfb_logger
from .. import rman_constants
from ..rman_constants import RFB_ADDON_PATH
import os
import bpy
import json
import subprocess
import platform
import sys

__RMAN_ENV_CONFIG__ = None

class RmanEnvConfig(object):

    def __init__(self):
        self.rmantree = ''
        self.rmantree_from_json = False
        self.rman_version = ''
        self.rman_version_major = 0
        self.rman_version_minor = 0
        self.rman_version_modifier = ''
        self.rman_it_path = ''
        self.rman_lq_path = ''
        self.rman_tractor_path = ''
        self.is_ncr_license = False
        self.license_info = None

    def config_environment(self):

        self.setenv('RMANTREE', self.rmantree)
        self._append_to_path(os.path.join(self.rmantree, 'bin'))
        self._set_it_path()
        self._set_localqueue_path()
        self._config_pythonpath()
        self._set_ocio()
        self._get_license_info()

    def getenv(self, k, default=None):
        return os.environ.get(k, default)

    def setenv(self, k, val):
        os.environ[k] = val

    def copyenv(self):
        return os.environ.copy()

    def read_envvars_file(self):
        bl_config_path = bpy.utils.user_resource('CONFIG')
        jsonfile = ''
        for f in os.listdir(bl_config_path):
            if not f.endswith('.json'):
                continue
            if f == 'rfb_envvars.json':
                jsonfile = os.path.join(bl_config_path, f)
                break
        if jsonfile == '':
            return

        rfb_log().warning("Reading rfb_envvars.json")
        jdata = json.load(open(jsonfile))
        environment = jdata.get('environment', list())

        for var, val in environment.items():
            rfb_log().warning("Setting envvar %s to: %s" % (var, val['value']))  
            self.setenv(var, val['value'])  
            if var == 'RMANTREE':
                self.rmantree_from_json = True
                
        # Re-init the log level in case RFB_LOG_LEVEL was set
        rfb_logger.init_log_level()

        # Also, set logger file, if any
        rfb_log_file = self.getenv('RFB_LOG_FILE')
        if rfb_log_file:
            rfb_logger.set_file_logger(rfb_log_file)

    def get_shader_registration_paths(self):
        paths = []
        rmantree = self.rmantree
        paths.append(os.path.join(rmantree, 'lib', 'shaders'))    
        paths.append(os.path.join(rmantree, 'lib', 'plugins', 'Args'))
        paths.append(os.path.join(RFB_ADDON_PATH, 'Args'))

        RMAN_SHADERPATH = self.getenv('RMAN_SHADERPATH', '')
        for p in RMAN_SHADERPATH.split(os.path.pathsep):
            paths.append(p)

        RMAN_RIXPLUGINPATH = self.getenv('RMAN_RIXPLUGINPATH', '')
        for p in RMAN_RIXPLUGINPATH.split(os.path.pathsep):
            paths.append(os.path.join(p, 'Args'))

        return paths        

    def _config_pythonpath(self):

        if platform.system() == 'Windows':
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'Lib', 'site-packages')
        else:
            rman_packages = os.path.join(self.rmantree, 'lib', 'python3.7', 'site-packages')
        sys.path.append(rman_packages)        
        sys.path.append(os.path.join(self.rmantree, 'bin'))
        pythonbindings = os.path.join(self.rmantree, 'bin', 'pythonbindings')
        sys.path.append(pythonbindings)          

    def _append_to_path(self, path):        
        if path is not None:
            self.setenv('PATH', path + os.pathsep + self.getenv('PATH'))

    def _set_it_path(self):

        if platform.system() == 'Windows':
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it.exe')
        elif platform.system() == 'Darwin':
            self.rman_it_path = os.path.join(
                self.rmantree, 'bin', 'it.app', 'Contents', 'MacOS', 'it')
        else:
            self.rman_it_path = os.path.join(self.rmantree, 'bin', 'it')

    def _set_localqueue_path(self):
        if platform.system() == 'Windows':
            self.rman_lq_path = os.path.join(self.rmantree, 'bin', 'LocalQueue.exe')
        elif platform.system() == 'Darwin':
            self.rman_lq_path = os.path.join(
                self.rmantree, 'bin', 'LocalQueue.app', 'Contents', 'MacOS', 'LocalQueue')
        else:
            self.rman_lq_path= os.path.join(self.rmantree, 'bin', 'LocalQueue')

    def _set_tractor_path(self):
        base = ""
        if platform.system() == 'Windows':
            # default installation path
            base = r'C:\Program Files\Pixar'

        elif platform.system() == 'Darwin':
            base = '/Applications/Pixar'

        elif platform.system() == 'Linux':
            base = '/opt/pixar'

        latestver = 0.0
        guess = ''
        for d in os.listdir(base):
            if "Tractor" in d:
                vstr = d.split('-')[1]
                vf = float(vstr)
                if vf >= latestver:
                    latestver = vf
                    guess = os.path.join(base, d)
        tractor_dir = guess

        if tractor_dir:
            self.rman_tractor_path = os.path.join(tractor_dir, 'bin', 'tractor-spool')

    def get_blender_ocio_config(self):
        # return rman's version filmic-blender OCIO config
        ocioconfig = os.path.join(self.rmantree, 'lib', 'ocio', 'filmic-blender', 'config.ocio')

        return ocioconfig            

    def _set_ocio(self):
        # make sure we set OCIO env var
        # so that "it" will also get the correct configuration
        path = self.getenv('OCIO', '')
        if path == '':
            self.setenv('OCIO', self.get_blender_ocio_config())

    def _get_license_info(self):
        from rman_utils import license as rman_license_info

        self.license_info = rman_license_info.get_license_info(self.rmantree)
        self.is_ncr_license = self.license_info.is_ncr_license

def _parse_version(s):
    major_vers, minor_vers = s.split('.')
    vers_modifier = ''
    for v in ['b', 'rc']:
        if v in minor_vers:
            i = minor_vers.find(v)
            vers_modifier = minor_vers[i:]
            minor_vers = minor_vers[:i]
            break
    return int(major_vers), int(minor_vers), vers_modifier                  

# return the major, minor rman version
def _get_rman_version(rmantree):

    try:        
        prman = 'prman.exe' if platform.system() == 'Windows' else 'prman'
        exe = os.path.join(rmantree, 'bin', prman)
        desc = subprocess.check_output(
{'fraction_non_alphanumeric': 0.11912739716261496, 'fraction_numerical': 0.0012832394667427105, 'mean_word_length': 2.1389572611322443, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 1}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7459573', 'n_tokens_mistral': 4626, 'n_tokens_neox': 4498, 'n_words': 924}