Path: blob/master/modules/java/generator/gen_java.py
16337 views
#!/usr/bin/env python12import sys, re, os.path, errno, fnmatch3import json4import logging5from shutil import copyfile6from pprint import pformat7from string import Template89if sys.version_info[0] >= 3:10from io import StringIO11else:12from cStringIO import StringIO1314SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))1516# list of modules + files remap17config = None18ROOT_DIR = None19FILES_REMAP = {}20def checkFileRemap(path):21path = os.path.realpath(path)22if path in FILES_REMAP:23return FILES_REMAP[path]24assert path[-3:] != '.in', path25return path2627total_files = 028updated_files = 02930module_imports = []31module_j_code = None32module_jn_code = None3334# list of class names, which should be skipped by wrapper generator35# the list is loaded from misc/java/gen_dict.json defined for the module and its dependencies36class_ignore_list = []3738# list of constant names, which should be skipped by wrapper generator39# ignored constants can be defined using regular expressions40const_ignore_list = []4142# list of private constants43const_private_list = []4445# { Module : { public : [[name, val],...], private : [[]...] } }46missing_consts = {}4748# c_type : { java/jni correspondence }49# Complex data types are configured for each module using misc/java/gen_dict.json5051type_dict = {52# "simple" : { j_type : "?", jn_type : "?", jni_type : "?", suffix : "?" },53"" : { "j_type" : "", "jn_type" : "long", "jni_type" : "jlong" }, # c-tor ret_type54"void" : { "j_type" : "void", "jn_type" : "void", "jni_type" : "void" },55"env" : { "j_type" : "", "jn_type" : "", "jni_type" : "JNIEnv*"},56"cls" : { "j_type" : "", "jn_type" : "", "jni_type" : "jclass"},57"bool" : { "j_type" : "boolean", "jn_type" : "boolean", "jni_type" : "jboolean", "suffix" : "Z" },58"char" : { "j_type" : "char", "jn_type" : "char", "jni_type" : "jchar", "suffix" : "C" },59"int" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },60"long" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },61"float" : { "j_type" : "float", "jn_type" : "float", "jni_type" : "jfloat", "suffix" : "F" },62"double" : { "j_type" : "double", "jn_type" : "double", "jni_type" : "jdouble", "suffix" : "D" },63"size_t" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },64"__int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },65"int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },66"double[]": { "j_type" : "double[]", "jn_type" : "double[]", "jni_type" : "jdoubleArray", "suffix" : "_3D" }67}6869# Defines a rule to add extra prefixes for names from specific namespaces.70# In example, cv::fisheye::stereoRectify from namespace fisheye is wrapped as fisheye_stereoRectify71namespaces_dict = {}7273# { class : { func : {j_code, jn_code, cpp_code} } }74ManualFuncs = {}7576# { class : { func : { arg_name : {"ctype" : ctype, "attrib" : [attrib]} } } }77func_arg_fix = {}7879def read_contents(fname):80with open(fname, 'r') as f:81data = f.read()82return data8384def mkdir_p(path):85''' mkdir -p '''86try:87os.makedirs(path)88except OSError as exc:89if exc.errno == errno.EEXIST and os.path.isdir(path):90pass91else:92raise9394T_JAVA_START_INHERITED = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class_inherited.prolog'))95T_JAVA_START_ORPHAN = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class.prolog'))96T_JAVA_START_MODULE = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_module.prolog'))97T_CPP_MODULE = Template(read_contents(os.path.join(SCRIPT_DIR, 'templates/cpp_module.template')))9899class GeneralInfo():100def __init__(self, type, decl, namespaces):101self.namespace, self.classpath, self.classname, self.name = self.parseName(decl[0], namespaces)102103# parse doxygen comments104self.params={}105self.annotation=[]106if type == "class":107docstring="// C++: class " + self.name + "\n//javadoc: " + self.name108else:109docstring=""110if len(decl)>5 and decl[5]:111#logging.info('docstring: %s', decl[5])112if re.search("(@|\\\\)deprecated", decl[5]):113self.annotation.append("@Deprecated")114115self.docstring = docstring116117def parseName(self, name, namespaces):118'''119input: full name and available namespaces120returns: (namespace, classpath, classname, name)121'''122name = name[name.find(" ")+1:].strip() # remove struct/class/const prefix123spaceName = ""124localName = name # <classes>.<name>125for namespace in sorted(namespaces, key=len, reverse=True):126if name.startswith(namespace + "."):127spaceName = namespace128localName = name.replace(namespace + ".", "")129break130pieces = localName.split(".")131if len(pieces) > 2: # <class>.<class>.<class>.<name>132return spaceName, ".".join(pieces[:-1]), pieces[-2], pieces[-1]133elif len(pieces) == 2: # <class>.<name>134return spaceName, pieces[0], pieces[0], pieces[1]135elif len(pieces) == 1: # <name>136return spaceName, "", "", pieces[0]137else:138return spaceName, "", "" # error?!139140def fullName(self, isCPP=False):141result = ".".join([self.fullClass(), self.name])142return result if not isCPP else get_cname(result)143144def fullClass(self, isCPP=False):145result = ".".join([f for f in [self.namespace] + self.classpath.split(".") if len(f)>0])146return result if not isCPP else get_cname(result)147148class ConstInfo(GeneralInfo):149def __init__(self, decl, addedManually=False, namespaces=[], enumType=None):150GeneralInfo.__init__(self, "const", decl, namespaces)151self.cname = get_cname(self.name)152self.value = decl[1]153self.enumType = enumType154self.addedManually = addedManually155if self.namespace in namespaces_dict:156self.name = '%s_%s' % (namespaces_dict[self.namespace], self.name)157158def __repr__(self):159return Template("CONST $name=$value$manual").substitute(name=self.name,160value=self.value,161manual="(manual)" if self.addedManually else "")162163def isIgnored(self):164for c in const_ignore_list:165if re.match(c, self.name):166return True167return False168169def normalize_field_name(name):170return name.replace(".","_").replace("[","").replace("]","").replace("_getNativeObjAddr()","_nativeObj")171172def normalize_class_name(name):173return re.sub(r"^cv\.", "", name).replace(".", "_")174175def get_cname(name):176return name.replace(".", "::")177178def cast_from(t):179if t in type_dict and "cast_from" in type_dict[t]:180return type_dict[t]["cast_from"]181return t182183def cast_to(t):184if t in type_dict and "cast_to" in type_dict[t]:185return type_dict[t]["cast_to"]186return t187188class ClassPropInfo():189def __init__(self, decl): # [f_ctype, f_name, '', '/RW']190self.ctype = decl[0]191self.name = decl[1]192self.rw = "/RW" in decl[3]193194def __repr__(self):195return Template("PROP $ctype $name").substitute(ctype=self.ctype, name=self.name)196197class ClassInfo(GeneralInfo):198def __init__(self, decl, namespaces=[]): # [ 'class/struct cname', ': base', [modlist] ]199GeneralInfo.__init__(self, "class", decl, namespaces)200self.cname = get_cname(self.name)201self.methods = []202self.methods_suffixes = {}203self.consts = [] # using a list to save the occurrence order204self.private_consts = []205self.imports = set()206self.props= []207self.jname = self.name208self.smart = None # True if class stores Ptr<T>* instead of T* in nativeObj field209self.j_code = None # java code stream210self.jn_code = None # jni code stream211self.cpp_code = None # cpp code stream212for m in decl[2]:213if m.startswith("="):214self.jname = m[1:]215self.base = ''216if decl[1]:217#self.base = re.sub(r"\b"+self.jname+r"\b", "", decl[1].replace(":", "")).strip()218self.base = re.sub(r"^.*:", "", decl[1].split(",")[0]).strip().replace(self.jname, "")219220def __repr__(self):221return Template("CLASS $namespace::$classpath.$name : $base").substitute(**self.__dict__)222223def getAllImports(self, module):224return ["import %s;" % c for c in sorted(self.imports) if not c.startswith('org.opencv.'+module)]225226def addImports(self, ctype):227if ctype in type_dict:228if "j_import" in type_dict[ctype]:229self.imports.add(type_dict[ctype]["j_import"])230if "v_type" in type_dict[ctype]:231self.imports.add("java.util.List")232self.imports.add("java.util.ArrayList")233self.imports.add("org.opencv.utils.Converters")234if type_dict[ctype]["v_type"] in ("Mat", "vector_Mat"):235self.imports.add("org.opencv.core.Mat")236237def getAllMethods(self):238result = []239result.extend([fi for fi in sorted(self.methods) if fi.isconstructor])240result.extend([fi for fi in sorted(self.methods) if not fi.isconstructor])241return result242243def addMethod(self, fi):244self.methods.append(fi)245246def getConst(self, name):247for cand in self.consts + self.private_consts:248if cand.name == name:249return cand250return None251252def addConst(self, constinfo):253# choose right list (public or private)254consts = self.consts255for c in const_private_list:256if re.match(c, constinfo.name):257consts = self.private_consts258break259consts.append(constinfo)260261def initCodeStreams(self, Module):262self.j_code = StringIO()263self.jn_code = StringIO()264self.cpp_code = StringIO();265if self.base:266self.j_code.write(T_JAVA_START_INHERITED)267else:268if self.name != Module:269self.j_code.write(T_JAVA_START_ORPHAN)270else:271self.j_code.write(T_JAVA_START_MODULE)272# misc handling273if self.name == Module:274for i in module_imports or []:275self.imports.add(i)276if module_j_code:277self.j_code.write(module_j_code)278if module_jn_code:279self.jn_code.write(module_jn_code)280281def cleanupCodeStreams(self):282self.j_code.close()283self.jn_code.close()284self.cpp_code.close()285286def generateJavaCode(self, m, M):287return Template(self.j_code.getvalue() + "\n\n" + \288self.jn_code.getvalue() + "\n}\n").substitute(\289module = m,290name = self.name,291jname = self.jname,292imports = "\n".join(self.getAllImports(M)),293docs = self.docstring,294annotation = "\n".join(self.annotation),295base = self.base)296297def generateCppCode(self):298return self.cpp_code.getvalue()299300class ArgInfo():301def __init__(self, arg_tuple): # [ ctype, name, def val, [mod], argno ]302self.pointer = False303ctype = arg_tuple[0]304if ctype.endswith("*"):305ctype = ctype[:-1]306self.pointer = True307self.ctype = ctype308self.name = arg_tuple[1]309self.defval = arg_tuple[2]310self.out = ""311if "/O" in arg_tuple[3]:312self.out = "O"313if "/IO" in arg_tuple[3]:314self.out = "IO"315316def __repr__(self):317return Template("ARG $ctype$p $name=$defval").substitute(ctype=self.ctype,318p=" *" if self.pointer else "",319name=self.name,320defval=self.defval)321322class FuncInfo(GeneralInfo):323def __init__(self, decl, namespaces=[]): # [ funcname, return_ctype, [modifiers], [args] ]324GeneralInfo.__init__(self, "func", decl, namespaces)325self.cname = get_cname(decl[0])326self.jname = self.name327self.isconstructor = self.name == self.classname328if "[" in self.name:329self.jname = "getelem"330if self.namespace in namespaces_dict:331self.jname = '%s_%s' % (namespaces_dict[self.namespace], self.jname)332for m in decl[2]:333if m.startswith("="):334self.jname = m[1:]335self.static = ["","static"][ "/S" in decl[2] ]336self.ctype = re.sub(r"^CvTermCriteria", "TermCriteria", decl[1] or "")337self.args = []338func_fix_map = func_arg_fix.get(self.jname, {})339for a in decl[3]:340arg = a[:]341arg_fix_map = func_fix_map.get(arg[1], {})342arg[0] = arg_fix_map.get('ctype', arg[0]) #fixing arg type343arg[3] = arg_fix_map.get('attrib', arg[3]) #fixing arg attrib344self.args.append(ArgInfo(arg))345346def __repr__(self):347return Template("FUNC <$ctype $namespace.$classpath.$name $args>").substitute(**self.__dict__)348349def __lt__(self, other):350return self.__repr__() < other.__repr__()351352353class JavaWrapperGenerator(object):354def __init__(self):355self.cpp_files = []356self.clear()357358def clear(self):359self.namespaces = set(["cv"])360self.classes = { "Mat" : ClassInfo([ 'class Mat', '', [], [] ], self.namespaces) }361self.module = ""362self.Module = ""363self.ported_func_list = []364self.skipped_func_list = []365self.def_args_hist = {} # { def_args_cnt : funcs_cnt }366367def add_class(self, decl):368classinfo = ClassInfo(decl, namespaces=self.namespaces)369if classinfo.name in class_ignore_list:370logging.info('ignored: %s', classinfo)371return372name = classinfo.name373if self.isWrapped(name) and not classinfo.base:374logging.warning('duplicated: %s', classinfo)375return376self.classes[name] = classinfo377if name in type_dict and not classinfo.base:378logging.warning('duplicated: %s', classinfo)379return380type_dict.setdefault(name, {}).update(381{ "j_type" : classinfo.jname,382"jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),383"jni_name" : "(*("+classinfo.fullName(isCPP=True)+"*)%(n)s_nativeObj)", "jni_type" : "jlong",384"suffix" : "J",385"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)386}387)388type_dict.setdefault(name+'*', {}).update(389{ "j_type" : classinfo.jname,390"jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),391"jni_name" : "("+classinfo.fullName(isCPP=True)+"*)%(n)s_nativeObj", "jni_type" : "jlong",392"suffix" : "J",393"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)394}395)396397# missing_consts { Module : { public : [[name, val],...], private : [[]...] } }398if name in missing_consts:399if 'private' in missing_consts[name]:400for (n, val) in missing_consts[name]['private']:401classinfo.private_consts.append( ConstInfo([n, val], addedManually=True) )402if 'public' in missing_consts[name]:403for (n, val) in missing_consts[name]['public']:404classinfo.consts.append( ConstInfo([n, val], addedManually=True) )405406# class props407for p in decl[3]:408if True: #"vector" not in p[0]:409classinfo.props.append( ClassPropInfo(p) )410else:411logging.warning("Skipped property: [%s]" % name, p)412413if classinfo.base:414classinfo.addImports(classinfo.base)415type_dict.setdefault("Ptr_"+name, {}).update(416{ "j_type" : classinfo.jname,417"jn_type" : "long", "jn_args" : (("__int64", ".getNativeObjAddr()"),),418"jni_name" : "*((Ptr<"+classinfo.fullName(isCPP=True)+">*)%(n)s_nativeObj)", "jni_type" : "jlong",419"suffix" : "J",420"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)421}422)423logging.info('ok: class %s, name: %s, base: %s', classinfo, name, classinfo.base)424425def add_const(self, decl, enumType=None): # [ "const cname", val, [], [] ]426constinfo = ConstInfo(decl, namespaces=self.namespaces, enumType=enumType)427if constinfo.isIgnored():428logging.info('ignored: %s', constinfo)429elif not self.isWrapped(constinfo.classname):430logging.info('class not found: %s', constinfo)431else:432ci = self.getClass(constinfo.classname)433duplicate = ci.getConst(constinfo.name)434if duplicate:435if duplicate.addedManually:436logging.info('manual: %s', constinfo)437else:438logging.warning('duplicated: %s', constinfo)439else:440ci.addConst(constinfo)441logging.info('ok: %s', constinfo)442443def add_enum(self, decl): # [ "enum cname", "", [], [] ]444enumType = decl[0].rsplit(" ", 1)[1]445if enumType.endswith("<unnamed>"):446enumType = None447else:448ctype = normalize_class_name(enumType)449type_dict[ctype] = { "cast_from" : "int", "cast_to" : get_cname(enumType), "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" }450const_decls = decl[3]451452for decl in const_decls:453self.add_const(decl, enumType)454455def add_func(self, decl):456fi = FuncInfo(decl, namespaces=self.namespaces)457classname = fi.classname or self.Module458if classname in class_ignore_list:459logging.info('ignored: %s', fi)460elif classname in ManualFuncs and fi.jname in ManualFuncs[classname]:461logging.info('manual: %s', fi)462elif not self.isWrapped(classname):463logging.warning('not found: %s', fi)464else:465self.getClass(classname).addMethod(fi)466logging.info('ok: %s', fi)467# calc args with def val468cnt = len([a for a in fi.args if a.defval])469self.def_args_hist[cnt] = self.def_args_hist.get(cnt, 0) + 1470471def save(self, path, buf):472global total_files, updated_files473total_files += 1474if os.path.exists(path):475with open(path, "rt") as f:476content = f.read()477if content == buf:478return479with open(path, "wt") as f:480f.write(buf)481updated_files += 1482483def gen(self, srcfiles, module, output_path, output_jni_path, output_java_path, common_headers):484self.clear()485self.module = module486self.Module = module.capitalize()487# TODO: support UMat versions of declarations (implement UMat-wrapper for Java)488parser = hdr_parser.CppHeaderParser(generate_umat_decls=False)489490self.add_class( ['class ' + self.Module, '', [], []] ) # [ 'class/struct cname', ':bases', [modlist] [props] ]491492# scan the headers and build more descriptive maps of classes, consts, functions493includes = [];494for hdr in common_headers:495logging.info("\n===== Common header : %s =====", hdr)496includes.append('#include "' + hdr + '"')497for hdr in srcfiles:498decls = parser.parse(hdr)499self.namespaces = parser.namespaces500logging.info("\n\n===== Header: %s =====", hdr)501logging.info("Namespaces: %s", parser.namespaces)502if decls:503includes.append('#include "' + hdr + '"')504else:505logging.info("Ignore header: %s", hdr)506for decl in decls:507logging.info("\n--- Incoming ---\n%s", pformat(decl[:5], 4)) # without docstring508name = decl[0]509if name.startswith("struct") or name.startswith("class"):510self.add_class(decl)511elif name.startswith("const"):512self.add_const(decl)513elif name.startswith("enum"):514# enum515self.add_enum(decl)516else: # function517self.add_func(decl)518519logging.info("\n\n===== Generating... =====")520moduleCppCode = StringIO()521package_path = os.path.join(output_java_path, module)522mkdir_p(package_path)523for ci in self.classes.values():524if ci.name == "Mat":525continue526ci.initCodeStreams(self.Module)527self.gen_class(ci)528classJavaCode = ci.generateJavaCode(self.module, self.Module)529self.save("%s/%s/%s.java" % (output_java_path, module, ci.jname), classJavaCode)530moduleCppCode.write(ci.generateCppCode())531ci.cleanupCodeStreams()532cpp_file = os.path.abspath(os.path.join(output_jni_path, module + ".inl.hpp"))533self.cpp_files.append(cpp_file)534self.save(cpp_file, T_CPP_MODULE.substitute(m = module, M = module.upper(), code = moduleCppCode.getvalue(), includes = "\n".join(includes)))535self.save(os.path.join(output_path, module+".txt"), self.makeReport())536537def makeReport(self):538'''539Returns string with generator report540'''541report = StringIO()542total_count = len(self.ported_func_list)+ len(self.skipped_func_list)543report.write("PORTED FUNCs LIST (%i of %i):\n\n" % (len(self.ported_func_list), total_count))544report.write("\n".join(self.ported_func_list))545report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % (len(self.skipped_func_list), total_count))546report.write("".join(self.skipped_func_list))547for i in self.def_args_hist.keys():548report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i]))549return report.getvalue()550551def fullTypeName(self, t):552if self.isWrapped(t):553return self.getClass(t).fullName(isCPP=True)554else:555return cast_from(t)556557def gen_func(self, ci, fi, prop_name=''):558logging.info("%s", fi)559j_code = ci.j_code560jn_code = ci.jn_code561cpp_code = ci.cpp_code562563# c_decl564# e.g: void add(Mat src1, Mat src2, Mat dst, Mat mask = Mat(), int dtype = -1)565if prop_name:566c_decl = "%s %s::%s" % (fi.ctype, fi.classname, prop_name)567else:568decl_args = []569for a in fi.args:570s = a.ctype or ' _hidden_ '571if a.pointer:572s += "*"573elif a.out:574s += "&"575s += " " + a.name576if a.defval:577s += " = "+a.defval578decl_args.append(s)579c_decl = "%s %s %s(%s)" % ( fi.static, fi.ctype, fi.cname, ", ".join(decl_args) )580581# java comment582j_code.write( "\n //\n // C++: %s\n //\n\n" % c_decl )583# check if we 'know' all the types584if fi.ctype not in type_dict: # unsupported ret type585msg = "// Return type '%s' is not supported, skipping the function\n\n" % fi.ctype586self.skipped_func_list.append(c_decl + "\n" + msg)587j_code.write( " "*4 + msg )588logging.warning("SKIP:" + c_decl.strip() + "\t due to RET type " + fi.ctype)589return590for a in fi.args:591if a.ctype not in type_dict:592if not a.defval and a.ctype.endswith("*"):593a.defval = 0594if a.defval:595a.ctype = ''596continue597msg = "// Unknown type '%s' (%s), skipping the function\n\n" % (a.ctype, a.out or "I")598self.skipped_func_list.append(c_decl + "\n" + msg)599j_code.write( " "*4 + msg )600logging.warning("SKIP:" + c_decl.strip() + "\t due to ARG type " + a.ctype + "/" + (a.out or "I"))601return602603self.ported_func_list.append(c_decl)604605# jn & cpp comment606jn_code.write( "\n // C++: %s\n" % c_decl )607cpp_code.write( "\n//\n// %s\n//\n" % c_decl )608609# java args610args = fi.args[:] # copy611j_signatures=[]612suffix_counter = int(ci.methods_suffixes.get(fi.jname, -1))613while True:614suffix_counter += 1615ci.methods_suffixes[fi.jname] = suffix_counter616# java native method args617jn_args = []618# jni (cpp) function args619jni_args = [ArgInfo([ "env", "env", "", [], "" ]), ArgInfo([ "cls", "", "", [], "" ])]620j_prologue = []621j_epilogue = []622c_prologue = []623c_epilogue = []624if type_dict[fi.ctype]["jni_type"] == "jdoubleArray":625fields = type_dict[fi.ctype]["jn_args"]626c_epilogue.append( \627("jdoubleArray _da_retval_ = env->NewDoubleArray(%(cnt)i); " +628"jdouble _tmp_retval_[%(cnt)i] = {%(args)s}; " +629"env->SetDoubleArrayRegion(_da_retval_, 0, %(cnt)i, _tmp_retval_);") %630{ "cnt" : len(fields), "args" : ", ".join(["(jdouble)_retval_" + f[1] for f in fields]) } )631if fi.classname and fi.ctype and not fi.static: # non-static class method except c-tor632# adding 'self'633jn_args.append ( ArgInfo([ "__int64", "nativeObj", "", [], "" ]) )634jni_args.append( ArgInfo([ "__int64", "self", "", [], "" ]) )635ci.addImports(fi.ctype)636for a in args:637if not a.ctype: # hidden638continue639ci.addImports(a.ctype)640if "v_type" in type_dict[a.ctype]: # pass as vector641if type_dict[a.ctype]["v_type"] in ("Mat", "vector_Mat"): #pass as Mat or vector_Mat642jn_args.append ( ArgInfo([ "__int64", "%s_mat.nativeObj" % a.name, "", [], "" ]) )643jni_args.append ( ArgInfo([ "__int64", "%s_mat_nativeObj" % a.name, "", [], "" ]) )644c_prologue.append( type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";" )645c_prologue.append( "Mat& %(n)s_mat = *((Mat*)%(n)s_mat_nativeObj)" % {"n" : a.name} + ";" )646if "I" in a.out or not a.out:647if type_dict[a.ctype]["v_type"] == "vector_Mat":648j_prologue.append( "List<Mat> %(n)s_tmplm = new ArrayList<Mat>((%(n)s != null) ? %(n)s.size() : 0);" % {"n" : a.name } )649j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s, %(n)s_tmplm);" % {"n" : a.name, "t" : a.ctype} )650else:651if not type_dict[a.ctype]["j_type"].startswith("MatOf"):652j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s);" % {"n" : a.name, "t" : a.ctype} )653else:654j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )655c_prologue.append( "Mat_to_%(t)s( %(n)s_mat, %(n)s );" % {"n" : a.name, "t" : a.ctype} )656else:657if not type_dict[a.ctype]["j_type"].startswith("MatOf"):658j_prologue.append( "Mat %s_mat = new Mat();" % a.name )659else:660j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )661if "O" in a.out:662if not type_dict[a.ctype]["j_type"].startswith("MatOf"):663j_epilogue.append("Converters.Mat_to_%(t)s(%(n)s_mat, %(n)s);" % {"t" : a.ctype, "n" : a.name})664j_epilogue.append( "%s_mat.release();" % a.name )665c_epilogue.append( "%(t)s_to_Mat( %(n)s, %(n)s_mat );" % {"n" : a.name, "t" : a.ctype} )666else: #pass as list667jn_args.append ( ArgInfo([ a.ctype, a.name, "", [], "" ]) )668jni_args.append ( ArgInfo([ a.ctype, "%s_list" % a.name , "", [], "" ]) )669c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")670if "I" in a.out or not a.out:671c_prologue.append("%(n)s = List_to_%(t)s(env, %(n)s_list);" % {"n" : a.name, "t" : a.ctype})672if "O" in a.out:673c_epilogue.append("Copy_%s_to_List(env,%s,%s_list);" % (a.ctype, a.name, a.name))674else:675fields = type_dict[a.ctype].get("jn_args", ((a.ctype, ""),))676if "I" in a.out or not a.out or self.isWrapped(a.ctype): # input arg, pass by primitive fields677for f in fields:678jn_args.append ( ArgInfo([ f[0], a.name + f[1], "", [], "" ]) )679jni_args.append( ArgInfo([ f[0], a.name + normalize_field_name(f[1]), "", [], "" ]) )680if "O" in a.out and not self.isWrapped(a.ctype): # out arg, pass as double[]681jn_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )682jni_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )683j_prologue.append( "double[] %s_out = new double[%i];" % (a.name, len(fields)) )684c_epilogue.append( \685"jdouble tmp_%(n)s[%(cnt)i] = {%(args)s}; env->SetDoubleArrayRegion(%(n)s_out, 0, %(cnt)i, tmp_%(n)s);" %686{ "n" : a.name, "cnt" : len(fields), "args" : ", ".join(["(jdouble)" + a.name + f[1] for f in fields]) } )687if type_dict[a.ctype]["j_type"] in ('bool', 'int', 'long', 'float', 'double'):688j_epilogue.append('if(%(n)s!=null) %(n)s[0] = (%(t)s)%(n)s_out[0];' % {'n':a.name,'t':type_dict[a.ctype]["j_type"]})689else:690set_vals = []691i = 0692for f in fields:693set_vals.append( "%(n)s%(f)s = %(t)s%(n)s_out[%(i)i]" %694{"n" : a.name, "t": ("("+type_dict[f[0]]["j_type"]+")", "")[f[0]=="double"], "f" : f[1], "i" : i}695)696i += 1697j_epilogue.append( "if("+a.name+"!=null){ " + "; ".join(set_vals) + "; } ")698699# calculate java method signature to check for uniqueness700j_args = []701for a in args:702if not a.ctype: #hidden703continue704jt = type_dict[a.ctype]["j_type"]705if a.out and jt in ('bool', 'int', 'long', 'float', 'double'):706jt += '[]'707j_args.append( jt + ' ' + a.name )708j_signature = type_dict[fi.ctype]["j_type"] + " " + \709fi.jname + "(" + ", ".join(j_args) + ")"710logging.info("java: " + j_signature)711712if(j_signature in j_signatures):713if args:714args.pop()715continue716else:717break718719# java part:720# private java NATIVE method decl721# e.g.722# private static native void add_0(long src1, long src2, long dst, long mask, int dtype);723jn_code.write( Template(\724" private static native $type $name($args);\n").substitute(\725type = type_dict[fi.ctype].get("jn_type", "double[]"), \726name = fi.jname + '_' + str(suffix_counter), \727args = ", ".join(["%s %s" % (type_dict[a.ctype]["jn_type"], normalize_field_name(a.name)) for a in jn_args])728) );729730# java part:731732#java doc comment733f_name = fi.jname734if fi.classname:735f_name = fi.classname + "::" + fi.jname736java_doc = "//javadoc: " + f_name + "(%s)" % ", ".join([a.name for a in args if a.ctype])737j_code.write(" "*4 + java_doc + "\n")738739if fi.docstring:740lines = StringIO(fi.docstring)741for line in lines:742j_code.write(" "*4 + line + "\n")743if fi.annotation:744j_code.write(" "*4 + "\n".join(fi.annotation) + "\n")745746# public java wrapper method impl (calling native one above)747# e.g.748# public static void add( Mat src1, Mat src2, Mat dst, Mat mask, int dtype )749# { add_0( src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype ); }750ret_type = fi.ctype751if fi.ctype.endswith('*'):752ret_type = ret_type[:-1]753ret_val = type_dict[ret_type]["j_type"] + " retVal = "754tail = ""755ret = "return retVal;"756if "v_type" in type_dict[ret_type]:757j_type = type_dict[ret_type]["j_type"]758if type_dict[ret_type]["v_type"] in ("Mat", "vector_Mat"):759tail = ")"760if j_type.startswith('MatOf'):761ret_val += j_type + ".fromNativeAddr("762else:763ret_val = "Mat retValMat = new Mat("764j_prologue.append( j_type + ' retVal = new Array' + j_type+'();')765j_epilogue.append('Converters.Mat_to_' + ret_type + '(retValMat, retVal);')766elif ret_type.startswith("Ptr_"):767ret_val = type_dict[fi.ctype]["j_type"] + " retVal = " + type_dict[ret_type]["j_type"] + ".__fromPtr__("768tail = ")"769elif ret_type == "void":770ret_val = ""771ret = "return;"772elif ret_type == "": # c-tor773if fi.classname and ci.base:774ret_val = "super( "775tail = " )"776else:777ret_val = "nativeObj = "778ret = "return;"779elif self.isWrapped(ret_type): # wrapped class780ret_val = type_dict[ret_type]["j_type"] + " retVal = new " + self.getClass(ret_type).jname + "("781tail = ")"782elif "jn_type" not in type_dict[ret_type]:783ret_val = type_dict[fi.ctype]["j_type"] + " retVal = new " + type_dict[ret_type]["j_type"] + "("784tail = ")"785786static = "static"787if fi.classname:788static = fi.static789790j_code.write( Template(\791""" public $static $j_type $j_name($j_args)792{793$prologue794$ret_val$jn_name($jn_args_call)$tail;795$epilogue796$ret797}798799"""800).substitute(\801ret = ret, \802ret_val = ret_val, \803tail = tail, \804prologue = "\n ".join(j_prologue), \805epilogue = "\n ".join(j_epilogue), \806static=static, \807j_type=type_dict[fi.ctype]["j_type"], \808j_name=fi.jname, \809j_args=", ".join(j_args), \810jn_name=fi.jname + '_' + str(suffix_counter), \811jn_args_call=", ".join( [a.name for a in jn_args] ),\812)813)814815816# cpp part:817# jni_func(..) { _retval_ = cv_func(..); return _retval_; }818ret = "return _retval_;"819default = "return 0;"820if fi.ctype == "void":821ret = "return;"822default = "return;"823elif not fi.ctype: # c-tor824ret = "return (jlong) _retval_;"825elif "v_type" in type_dict[fi.ctype]: # c-tor826if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"):827ret = "return (jlong) _retval_;"828else: # returned as jobject829ret = "return _retval_;"830elif fi.ctype == "String":831ret = "return env->NewStringUTF(_retval_.c_str());"832default = 'return env->NewStringUTF("");'833elif self.isWrapped(fi.ctype): # wrapped class:834ret = "return (jlong) new %s(_retval_);" % self.fullTypeName(fi.ctype)835elif fi.ctype.startswith('Ptr_'):836c_prologue.append("typedef Ptr<%s> %s;" % (self.fullTypeName(fi.ctype[4:]), fi.ctype))837ret = "return (jlong)(new %(ctype)s(_retval_));" % { 'ctype':fi.ctype }838elif self.isWrapped(ret_type): # pointer to wrapped class:839ret = "return (jlong) _retval_;"840elif type_dict[fi.ctype]["jni_type"] == "jdoubleArray":841ret = "return _da_retval_;"842843# hack: replacing func call with property set/get844name = fi.name845if prop_name:846if args:847name = prop_name + " = "848else:849name = prop_name + ";//"850851cvname = fi.fullName(isCPP=True)852retval = self.fullTypeName(fi.ctype) + " _retval_ = "853if fi.ctype == "void":854retval = ""855elif fi.ctype == "String":856retval = "cv::" + retval857elif "v_type" in type_dict[fi.ctype]: # vector is returned858retval = type_dict[fi.ctype]['jni_var'] % {"n" : '_ret_val_vector_'} + " = "859if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"):860c_epilogue.append("Mat* _retval_ = new Mat();")861c_epilogue.append(fi.ctype+"_to_Mat(_ret_val_vector_, *_retval_);")862else:863c_epilogue.append("jobject _retval_ = " + fi.ctype + "_to_List(env, _ret_val_vector_);")864if len(fi.classname)>0:865if not fi.ctype: # c-tor866retval = fi.fullClass(isCPP=True) + "* _retval_ = "867cvname = "new " + fi.fullClass(isCPP=True)868elif fi.static:869cvname = fi.fullName(isCPP=True)870else:871cvname = ("me->" if not self.isSmartClass(ci) else "(*me)->") + name872c_prologue.append(\873"%(cls)s* me = (%(cls)s*) self; //TODO: check for NULL" \874% { "cls" : self.smartWrap(ci, fi.fullClass(isCPP=True))} \875)876cvargs = []877for a in args:878if a.pointer:879jni_name = "&%(n)s"880else:881jni_name = "%(n)s"882if not a.out and not "jni_var" in type_dict[a.ctype]:883# explicit cast to C type to avoid ambiguous call error on platforms (mingw)884# where jni types are different from native types (e.g. jint is not the same as int)885jni_name = "(%s)%s" % (cast_to(a.ctype), jni_name)886if not a.ctype: # hidden887jni_name = a.defval888cvargs.append( type_dict[a.ctype].get("jni_name", jni_name) % {"n" : a.name})889if "v_type" not in type_dict[a.ctype]:890if ("I" in a.out or not a.out or self.isWrapped(a.ctype)) and "jni_var" in type_dict[a.ctype]: # complex type891c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")892if a.out and "I" not in a.out and not self.isWrapped(a.ctype) and a.ctype:893c_prologue.append("%s %s;" % (a.ctype, a.name))894895rtype = type_dict[fi.ctype].get("jni_type", "jdoubleArray")896clazz = ci.jname897cpp_code.write ( Template( \898"""899${namespace}900901JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname ($argst);902903JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname904($args)905{906static const char method_name[] = "$module::$fname()";907try {908LOGD("%s", method_name);909$prologue910$retval$cvname( $cvargs );911$epilogue$ret912} catch(const std::exception &e) {913throwJavaException(env, &e, method_name);914} catch (...) {915throwJavaException(env, 0, method_name);916}917$default918}919920921""" ).substitute( \922rtype = rtype, \923module = self.module.replace('_', '_1'), \924clazz = clazz.replace('_', '_1'), \925fname = (fi.jname + '_' + str(suffix_counter)).replace('_', '_1'), \926args = ", ".join(["%s %s" % (type_dict[a.ctype].get("jni_type"), a.name) for a in jni_args]), \927argst = ", ".join([type_dict[a.ctype].get("jni_type") for a in jni_args]), \928prologue = "\n ".join(c_prologue), \929epilogue = " ".join(c_epilogue) + ("\n " if c_epilogue else ""), \930ret = ret, \931cvname = cvname, \932cvargs = ", ".join(cvargs), \933default = default, \934retval = retval, \935namespace = ('using namespace ' + ci.namespace.replace('.', '::') + ';') if ci.namespace else ''936) )937938# adding method signature to dictionarry939j_signatures.append(j_signature)940941# processing args with default values942if args and args[-1].defval:943args.pop()944else:945break946947948949def gen_class(self, ci):950logging.info("%s", ci)951# constants952if ci.private_consts:953logging.info("%s", ci.private_consts)954ci.j_code.write("""955private static final int956%s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in ci.private_consts])957)958if ci.consts:959enumTypes = set(map(lambda c: c.enumType, ci.consts))960grouped_consts = {enumType: [c for c in ci.consts if c.enumType == enumType] for enumType in enumTypes}961for typeName, consts in grouped_consts.items():962logging.info("%s", consts)963if typeName:964typeName = typeName.rsplit(".", 1)[-1]965###################### Utilize Java enums ######################966# ci.j_code.write("""967# public enum {1} {{968# {0};969#970# private final int id;971# {1}(int id) {{ this.id = id; }}972# {1}({1} _this) {{ this.id = _this.id; }}973# public int getValue() {{ return id; }}974# }}\n\n""".format((",\n"+" "*8).join(["%s(%s)" % (c.name, c.value) for c in consts]), typeName)975# )976################################################################977ci.j_code.write("""978// C++: enum {1}979public static final int980{0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]), typeName)981)982else:983ci.j_code.write("""984// C++: enum <unnamed>985public static final int986{0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]))987)988# methods989for fi in ci.getAllMethods():990self.gen_func(ci, fi)991# props992for pi in ci.props:993# getter994getter_name = ci.fullName() + ".get_" + pi.name995fi = FuncInfo( [getter_name, pi.ctype, [], []], self.namespaces ) # [ funcname, return_ctype, [modifiers], [args] ]996self.gen_func(ci, fi, pi.name)997if pi.rw:998#setter999setter_name = ci.fullName() + ".set_" + pi.name1000fi = FuncInfo( [ setter_name, "void", [], [ [pi.ctype, pi.name, "", [], ""] ] ], self.namespaces)1001self.gen_func(ci, fi, pi.name)10021003# manual ports1004if ci.name in ManualFuncs:1005for func in ManualFuncs[ci.name].keys():1006ci.j_code.write ( "\n".join(ManualFuncs[ci.name][func]["j_code"]) )1007ci.jn_code.write( "\n".join(ManualFuncs[ci.name][func]["jn_code"]) )1008ci.cpp_code.write( "\n".join(ManualFuncs[ci.name][func]["cpp_code"]) )10091010if ci.name != self.Module or ci.base:1011# finalize()1012ci.j_code.write(1013"""1014@Override1015protected void finalize() throws Throwable {1016delete(nativeObj);1017}1018""" )10191020ci.jn_code.write(1021"""1022// native support for java finalize()1023private static native void delete(long nativeObj);1024""" )10251026# native support for java finalize()1027ci.cpp_code.write( \1028"""1029//1030// native support for java finalize()1031// static void %(cls)s::delete( __int64 self )1032//1033JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete(JNIEnv*, jclass, jlong);10341035JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete1036(JNIEnv*, jclass, jlong self)1037{1038delete (%(cls)s*) self;1039}10401041""" % {"module" : module.replace('_', '_1'), "cls" : self.smartWrap(ci, ci.fullName(isCPP=True)), "j_cls" : ci.jname.replace('_', '_1')}1042)10431044def getClass(self, classname):1045return self.classes[classname or self.Module]10461047def isWrapped(self, classname):1048name = classname or self.Module1049return name in self.classes10501051def isSmartClass(self, ci):1052'''1053Check if class stores Ptr<T>* instead of T* in nativeObj field1054'''1055if ci.smart != None:1056return ci.smart10571058# if parents are smart (we hope) then children are!1059# if not we believe the class is smart if it has "create" method1060ci.smart = False1061if ci.base or ci.name == 'Algorithm':1062ci.smart = True1063else:1064for fi in ci.methods:1065if fi.name == "create":1066ci.smart = True1067break10681069return ci.smart10701071def smartWrap(self, ci, fullname):1072'''1073Wraps fullname with Ptr<> if needed1074'''1075if self.isSmartClass(ci):1076return "Ptr<" + fullname + ">"1077return fullname10781079def finalize(self, output_jni_path):1080list_file = os.path.join(output_jni_path, "opencv_jni.hpp")1081self.save(list_file, '\n'.join(['#include "%s"' % f for f in self.cpp_files]))108210831084def copy_java_files(java_files_dir, java_base_path, default_package_path='org/opencv/'):1085global total_files, updated_files1086java_files = []1087re_filter = re.compile(r'^.+\.(java|aidl)(.in)?$')1088for root, dirnames, filenames in os.walk(java_files_dir):1089java_files += [os.path.join(root, filename) for filename in filenames if re_filter.match(filename)]1090java_files = [f.replace('\\', '/') for f in java_files]10911092re_package = re.compile(r'^package +(.+);')1093re_prefix = re.compile(r'^.+[\+/]([^\+]+).(java|aidl)(.in)?$')1094for java_file in java_files:1095src = checkFileRemap(java_file)1096with open(src, 'r') as f:1097package_line = f.readline()1098m = re_prefix.match(java_file)1099target_fname = (m.group(1) + '.' + m.group(2)) if m else os.path.basename(java_file)1100m = re_package.match(package_line)1101if m:1102package = m.group(1)1103package_path = package.replace('.', '/')1104else:1105package_path = default_package_path1106#print(java_file, package_path, target_fname)1107dest = os.path.join(java_base_path, os.path.join(package_path, target_fname))1108assert dest[-3:] != '.in', dest + ' | ' + target_fname1109mkdir_p(os.path.dirname(dest))1110total_files += 11111if (not os.path.exists(dest)) or (os.stat(src).st_mtime - os.stat(dest).st_mtime > 1):1112copyfile(src, dest)1113updated_files += 1111411151116if __name__ == "__main__":1117# initialize logger1118logging.basicConfig(filename='gen_java.log', format=None, filemode='w', level=logging.INFO)1119handler = logging.StreamHandler()1120handler.setLevel(logging.WARNING)1121logging.getLogger().addHandler(handler)11221123# parse command line parameters1124import argparse1125arg_parser = argparse.ArgumentParser(description='OpenCV Java Wrapper Generator')1126arg_parser.add_argument('-p', '--parser', required=True, help='OpenCV header parser')1127arg_parser.add_argument('-c', '--config', required=True, help='OpenCV modules config')11281129args=arg_parser.parse_args()11301131# import header parser1132hdr_parser_path = os.path.abspath(args.parser)1133if hdr_parser_path.endswith(".py"):1134hdr_parser_path = os.path.dirname(hdr_parser_path)1135sys.path.append(hdr_parser_path)1136import hdr_parser11371138with open(args.config) as f:1139config = json.load(f)11401141ROOT_DIR = config['rootdir']; assert os.path.exists(ROOT_DIR)1142FILES_REMAP = { os.path.realpath(os.path.join(ROOT_DIR, f['src'])): f['target'] for f in config['files_remap'] }1143logging.info("\nRemapped configured files (%d):\n%s", len(FILES_REMAP), pformat(FILES_REMAP))11441145dstdir = "./gen"1146jni_path = os.path.join(dstdir, 'cpp'); mkdir_p(jni_path)1147java_base_path = os.path.join(dstdir, 'java'); mkdir_p(java_base_path)1148java_test_base_path = os.path.join(dstdir, 'test'); mkdir_p(java_test_base_path)11491150for (subdir, target_subdir) in [('src/java', 'java'), ('android/java', None), ('android-21/java', None)]:1151if target_subdir is None:1152target_subdir = subdir1153java_files_dir = os.path.join(SCRIPT_DIR, subdir)1154if os.path.exists(java_files_dir):1155target_path = os.path.join(dstdir, target_subdir); mkdir_p(target_path)1156copy_java_files(java_files_dir, target_path)11571158# launch Java Wrapper generator1159generator = JavaWrapperGenerator()11601161gen_dict_files = []11621163print("JAVA: Processing OpenCV modules: %d" % len(config['modules']))1164for e in config['modules']:1165(module, module_location) = (e['name'], os.path.join(ROOT_DIR, e['location']))1166logging.info("\n=== MODULE: %s (%s) ===\n" % (module, module_location))11671168java_path = os.path.join(java_base_path, 'org/opencv')1169mkdir_p(java_path)11701171module_imports = []1172module_j_code = None1173module_jn_code = None1174srcfiles = []1175common_headers = []11761177misc_location = os.path.join(module_location, 'misc/java')11781179srcfiles_fname = os.path.join(misc_location, 'filelist')1180if os.path.exists(srcfiles_fname):1181with open(srcfiles_fname) as f:1182srcfiles = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()]1183else:1184re_bad = re.compile(r'(private|.inl.hpp$|_inl.hpp$|.details.hpp$|_winrt.hpp$|/cuda/)')1185# .h files before .hpp1186h_files = []1187hpp_files = []1188for root, dirnames, filenames in os.walk(os.path.join(module_location, 'include')):1189h_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.h')]1190hpp_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.hpp')]1191srcfiles = h_files + hpp_files1192srcfiles = [f for f in srcfiles if not re_bad.search(f.replace('\\', '/'))]1193logging.info("\nFiles (%d):\n%s", len(srcfiles), pformat(srcfiles))11941195common_headers_fname = os.path.join(misc_location, 'filelist_common')1196if os.path.exists(common_headers_fname):1197with open(common_headers_fname) as f:1198common_headers = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()]1199logging.info("\nCommon headers (%d):\n%s", len(common_headers), pformat(common_headers))12001201gendict_fname = os.path.join(misc_location, 'gen_dict.json')1202if os.path.exists(gendict_fname):1203with open(gendict_fname) as f:1204gen_type_dict = json.load(f)1205class_ignore_list += gen_type_dict.get("class_ignore_list", [])1206const_ignore_list += gen_type_dict.get("const_ignore_list", [])1207const_private_list += gen_type_dict.get("const_private_list", [])1208missing_consts.update(gen_type_dict.get("missing_consts", {}))1209type_dict.update(gen_type_dict.get("type_dict", {}))1210ManualFuncs.update(gen_type_dict.get("ManualFuncs", {}))1211func_arg_fix.update(gen_type_dict.get("func_arg_fix", {}))1212namespaces_dict.update(gen_type_dict.get("namespaces_dict", {}))1213if 'module_j_code' in gen_type_dict:1214module_j_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_j_code'])))1215if 'module_jn_code' in gen_type_dict:1216module_jn_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_jn_code'])))1217module_imports += gen_type_dict.get("module_imports", [])12181219java_files_dir = os.path.join(misc_location, 'src/java')1220if os.path.exists(java_files_dir):1221copy_java_files(java_files_dir, java_base_path, 'org/opencv/' + module)12221223java_test_files_dir = os.path.join(misc_location, 'test')1224if os.path.exists(java_test_files_dir):1225copy_java_files(java_test_files_dir, java_test_base_path, 'org/opencv/test/' + module)12261227if len(srcfiles) > 0:1228generator.gen(srcfiles, module, dstdir, jni_path, java_path, common_headers)1229else:1230logging.info("No generated code for module: %s", module)1231generator.finalize(jni_path)12321233print('Generated files: %d (updated %d)' % (total_files, updated_files))123412351236