2013-04-11 22:34:04 +08:00
|
|
|
#!/usr/bin/env python
|
2012-11-24 02:57:22 +08:00
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
import sys, re, os.path, errno, fnmatch
|
2017-06-10 13:57:10 +08:00
|
|
|
import json
|
2014-09-19 19:31:38 +08:00
|
|
|
import logging
|
2019-06-05 18:44:03 +08:00
|
|
|
import codecs
|
2017-12-29 12:15:30 +08:00
|
|
|
from shutil import copyfile
|
2014-10-17 23:36:24 +08:00
|
|
|
from pprint import pformat
|
2012-10-17 07:18:30 +08:00
|
|
|
from string import Template
|
|
|
|
|
2014-09-19 19:31:38 +08:00
|
|
|
if sys.version_info[0] >= 3:
|
|
|
|
from io import StringIO
|
|
|
|
else:
|
2019-06-07 21:30:16 +08:00
|
|
|
import io
|
|
|
|
class StringIO(io.StringIO):
|
|
|
|
def write(self, s):
|
|
|
|
if isinstance(s, str):
|
|
|
|
s = unicode(s) # noqa: F821
|
|
|
|
return super(StringIO, self).write(s)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
|
|
|
|
# list of modules + files remap
|
|
|
|
config = None
|
|
|
|
ROOT_DIR = None
|
|
|
|
FILES_REMAP = {}
|
|
|
|
def checkFileRemap(path):
|
|
|
|
path = os.path.realpath(path)
|
|
|
|
if path in FILES_REMAP:
|
|
|
|
return FILES_REMAP[path]
|
|
|
|
assert path[-3:] != '.in', path
|
|
|
|
return path
|
|
|
|
|
|
|
|
total_files = 0
|
|
|
|
updated_files = 0
|
|
|
|
|
|
|
|
module_imports = []
|
|
|
|
module_j_code = None
|
|
|
|
module_jn_code = None
|
|
|
|
|
2017-06-10 13:57:10 +08:00
|
|
|
# list of class names, which should be skipped by wrapper generator
|
|
|
|
# the list is loaded from misc/java/gen_dict.json defined for the module and its dependencies
|
|
|
|
class_ignore_list = []
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2017-06-10 13:57:10 +08:00
|
|
|
# list of constant names, which should be skipped by wrapper generator
|
|
|
|
# ignored constants can be defined using regular expressions
|
|
|
|
const_ignore_list = []
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2017-06-10 13:57:10 +08:00
|
|
|
# list of private constants
|
|
|
|
const_private_list = []
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2017-06-10 13:57:10 +08:00
|
|
|
# { Module : { public : [[name, val],...], private : [[]...] } }
|
|
|
|
missing_consts = {}
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# c_type : { java/jni correspondence }
|
2017-06-10 13:57:10 +08:00
|
|
|
# Complex data types are configured for each module using misc/java/gen_dict.json
|
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
type_dict = {
|
|
|
|
# "simple" : { j_type : "?", jn_type : "?", jni_type : "?", suffix : "?" },
|
|
|
|
"" : { "j_type" : "", "jn_type" : "long", "jni_type" : "jlong" }, # c-tor ret_type
|
|
|
|
"void" : { "j_type" : "void", "jn_type" : "void", "jni_type" : "void" },
|
|
|
|
"env" : { "j_type" : "", "jn_type" : "", "jni_type" : "JNIEnv*"},
|
|
|
|
"cls" : { "j_type" : "", "jn_type" : "", "jni_type" : "jclass"},
|
|
|
|
"bool" : { "j_type" : "boolean", "jn_type" : "boolean", "jni_type" : "jboolean", "suffix" : "Z" },
|
2015-08-26 21:19:26 +08:00
|
|
|
"char" : { "j_type" : "char", "jn_type" : "char", "jni_type" : "jchar", "suffix" : "C" },
|
2012-10-17 07:18:30 +08:00
|
|
|
"int" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
|
|
|
|
"long" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
|
|
|
|
"float" : { "j_type" : "float", "jn_type" : "float", "jni_type" : "jfloat", "suffix" : "F" },
|
|
|
|
"double" : { "j_type" : "double", "jn_type" : "double", "jni_type" : "jdouble", "suffix" : "D" },
|
|
|
|
"size_t" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
|
|
|
|
"__int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
|
|
|
|
"int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
|
2019-04-05 22:15:51 +08:00
|
|
|
"double[]": { "j_type" : "double[]", "jn_type" : "double[]", "jni_type" : "jdoubleArray", "suffix" : "_3D" },
|
|
|
|
'string' : { # std::string, see "String" in modules/core/misc/java/gen_dict.json
|
|
|
|
'j_type': 'String',
|
|
|
|
'jn_type': 'String',
|
|
|
|
'jni_name': 'n_%(n)s',
|
|
|
|
'jni_type': 'jstring',
|
|
|
|
'jni_var': 'const char* utf_%(n)s = env->GetStringUTFChars(%(n)s, 0); std::string n_%(n)s( utf_%(n)s ? utf_%(n)s : "" ); env->ReleaseStringUTFChars(%(n)s, utf_%(n)s)',
|
|
|
|
'suffix': 'Ljava_lang_String_2',
|
|
|
|
'j_import': 'java.lang.String'
|
|
|
|
},
|
2020-01-28 18:16:03 +08:00
|
|
|
'vector_string': { # std::vector<std::string>, see "vector_String" in modules/core/misc/java/gen_dict.json
|
|
|
|
'j_type': 'List<String>',
|
|
|
|
'jn_type': 'List<String>',
|
|
|
|
'jni_type': 'jobject',
|
|
|
|
'jni_var': 'std::vector< std::string > %(n)s',
|
|
|
|
'suffix': 'Ljava_util_List',
|
|
|
|
'v_type': 'string',
|
|
|
|
'j_import': 'java.lang.String'
|
|
|
|
},
|
2012-10-17 07:18:30 +08:00
|
|
|
}
|
|
|
|
|
2018-07-17 18:41:46 +08:00
|
|
|
# Defines a rule to add extra prefixes for names from specific namespaces.
|
|
|
|
# In example, cv::fisheye::stereoRectify from namespace fisheye is wrapped as fisheye_stereoRectify
|
|
|
|
namespaces_dict = {}
|
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
# { class : { func : {j_code, jn_code, cpp_code} } }
|
2017-06-10 13:57:10 +08:00
|
|
|
ManualFuncs = {}
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2013-06-10 18:37:01 +08:00
|
|
|
# { class : { func : { arg_name : {"ctype" : ctype, "attrib" : [attrib]} } } }
|
2017-06-10 13:57:10 +08:00
|
|
|
func_arg_fix = {}
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
def read_contents(fname):
|
|
|
|
with open(fname, 'r') as f:
|
|
|
|
data = f.read()
|
|
|
|
return data
|
|
|
|
|
|
|
|
def mkdir_p(path):
|
|
|
|
''' mkdir -p '''
|
|
|
|
try:
|
|
|
|
os.makedirs(path)
|
|
|
|
except OSError as exc:
|
|
|
|
if exc.errno == errno.EEXIST and os.path.isdir(path):
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise
|
2014-10-17 23:36:24 +08:00
|
|
|
|
2020-12-02 04:42:15 +08:00
|
|
|
def make_jname(m):
|
|
|
|
return "Cv"+m if (m[0] in "0123456789") else m
|
|
|
|
|
|
|
|
def make_jmodule(m):
|
|
|
|
return "cv"+m if (m[0] in "0123456789") else m
|
|
|
|
|
|
|
|
def make_namespace(ci):
|
|
|
|
return ('using namespace ' + ci.namespace.replace('.', '::') + ';') if ci.namespace and ci.namespace != 'cv' else ''
|
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
T_JAVA_START_INHERITED = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class_inherited.prolog'))
|
|
|
|
T_JAVA_START_ORPHAN = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class.prolog'))
|
|
|
|
T_JAVA_START_MODULE = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_module.prolog'))
|
|
|
|
T_CPP_MODULE = Template(read_contents(os.path.join(SCRIPT_DIR, 'templates/cpp_module.template')))
|
2014-10-17 23:36:24 +08:00
|
|
|
|
|
|
|
class GeneralInfo():
|
2017-11-16 21:48:12 +08:00
|
|
|
def __init__(self, type, decl, namespaces):
|
2020-11-13 14:27:18 +08:00
|
|
|
self.symbol_id, self.parent_id, self.namespace, self.classpath, self.classname, self.name = self.parseName(decl[0], namespaces)
|
|
|
|
self.cname = get_cname(self.symbol_id)
|
2017-11-16 21:48:12 +08:00
|
|
|
|
|
|
|
# parse doxygen comments
|
|
|
|
self.params={}
|
|
|
|
self.annotation=[]
|
|
|
|
if type == "class":
|
2019-06-05 18:44:03 +08:00
|
|
|
docstring="// C++: class " + self.name + "\n"
|
2017-11-16 21:48:12 +08:00
|
|
|
else:
|
|
|
|
docstring=""
|
2019-06-05 18:44:03 +08:00
|
|
|
|
2017-11-16 21:48:12 +08:00
|
|
|
if len(decl)>5 and decl[5]:
|
2019-06-05 18:44:03 +08:00
|
|
|
doc = decl[5]
|
|
|
|
|
|
|
|
#logging.info('docstring: %s', doc)
|
|
|
|
if re.search("(@|\\\\)deprecated", doc):
|
2017-11-16 21:48:12 +08:00
|
|
|
self.annotation.append("@Deprecated")
|
|
|
|
|
2019-06-05 18:44:03 +08:00
|
|
|
docstring += sanitize_java_documentation_string(doc, type)
|
|
|
|
|
2017-11-16 21:48:12 +08:00
|
|
|
self.docstring = docstring
|
2014-09-19 19:31:38 +08:00
|
|
|
|
|
|
|
def parseName(self, name, namespaces):
|
|
|
|
'''
|
|
|
|
input: full name and available namespaces
|
|
|
|
returns: (namespace, classpath, classname, name)
|
|
|
|
'''
|
|
|
|
name = name[name.find(" ")+1:].strip() # remove struct/class/const prefix
|
2020-11-13 14:27:18 +08:00
|
|
|
parent = name[:name.rfind('.')].strip()
|
|
|
|
if len(parent) == 0:
|
|
|
|
parent = None
|
2014-09-19 19:31:38 +08:00
|
|
|
spaceName = ""
|
|
|
|
localName = name # <classes>.<name>
|
|
|
|
for namespace in sorted(namespaces, key=len, reverse=True):
|
|
|
|
if name.startswith(namespace + "."):
|
|
|
|
spaceName = namespace
|
|
|
|
localName = name.replace(namespace + ".", "")
|
|
|
|
break
|
|
|
|
pieces = localName.split(".")
|
|
|
|
if len(pieces) > 2: # <class>.<class>.<class>.<name>
|
2020-11-13 14:27:18 +08:00
|
|
|
return name, parent, spaceName, ".".join(pieces[:-1]), pieces[-2], pieces[-1]
|
2014-09-19 19:31:38 +08:00
|
|
|
elif len(pieces) == 2: # <class>.<name>
|
2020-11-13 14:27:18 +08:00
|
|
|
return name, parent, spaceName, pieces[0], pieces[0], pieces[1]
|
2014-09-19 19:31:38 +08:00
|
|
|
elif len(pieces) == 1: # <name>
|
2020-11-13 14:27:18 +08:00
|
|
|
return name, parent, spaceName, "", "", pieces[0]
|
2014-09-19 19:31:38 +08:00
|
|
|
else:
|
2020-11-13 14:27:18 +08:00
|
|
|
return name, parent, spaceName, "", "" # error?!
|
2014-09-19 19:31:38 +08:00
|
|
|
|
2020-11-13 14:27:18 +08:00
|
|
|
def fullNameOrigin(self):
|
|
|
|
result = self.symbol_id
|
|
|
|
return result
|
|
|
|
|
|
|
|
def fullNameJAVA(self):
|
|
|
|
result = '.'.join([self.fullParentNameJAVA(), self.jname])
|
|
|
|
return result
|
2014-09-19 19:31:38 +08:00
|
|
|
|
2020-11-13 14:27:18 +08:00
|
|
|
def fullNameCPP(self):
|
|
|
|
result = self.cname
|
|
|
|
return result
|
|
|
|
|
|
|
|
def fullParentNameJAVA(self):
|
2014-09-19 19:31:38 +08:00
|
|
|
result = ".".join([f for f in [self.namespace] + self.classpath.split(".") if len(f)>0])
|
2020-11-13 14:27:18 +08:00
|
|
|
return result
|
|
|
|
|
|
|
|
def fullParentNameCPP(self):
|
|
|
|
result = get_cname(self.parent_id)
|
|
|
|
return result
|
2013-02-18 15:23:44 +08:00
|
|
|
|
2014-09-19 19:31:38 +08:00
|
|
|
class ConstInfo(GeneralInfo):
|
2018-08-28 03:39:24 +08:00
|
|
|
def __init__(self, decl, addedManually=False, namespaces=[], enumType=None):
|
2017-11-16 21:48:12 +08:00
|
|
|
GeneralInfo.__init__(self, "const", decl, namespaces)
|
2014-09-19 19:31:38 +08:00
|
|
|
self.value = decl[1]
|
2018-08-28 03:39:24 +08:00
|
|
|
self.enumType = enumType
|
2012-10-17 07:18:30 +08:00
|
|
|
self.addedManually = addedManually
|
2018-07-17 18:41:46 +08:00
|
|
|
if self.namespace in namespaces_dict:
|
2020-11-13 14:27:18 +08:00
|
|
|
prefix = namespaces_dict[self.namespace]
|
|
|
|
if prefix:
|
|
|
|
self.name = '%s_%s' % (prefix, self.name)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return Template("CONST $name=$value$manual").substitute(name=self.name,
|
|
|
|
value=self.value,
|
|
|
|
manual="(manual)" if self.addedManually else "")
|
|
|
|
|
|
|
|
def isIgnored(self):
|
|
|
|
for c in const_ignore_list:
|
|
|
|
if re.match(c, self.name):
|
|
|
|
return True
|
|
|
|
return False
|
|
|
|
|
2018-08-28 03:39:24 +08:00
|
|
|
def normalize_field_name(name):
|
|
|
|
return name.replace(".","_").replace("[","").replace("]","").replace("_getNativeObjAddr()","_nativeObj")
|
|
|
|
|
|
|
|
def normalize_class_name(name):
|
|
|
|
return re.sub(r"^cv\.", "", name).replace(".", "_")
|
|
|
|
|
|
|
|
def get_cname(name):
|
|
|
|
return name.replace(".", "::")
|
|
|
|
|
|
|
|
def cast_from(t):
|
|
|
|
if t in type_dict and "cast_from" in type_dict[t]:
|
|
|
|
return type_dict[t]["cast_from"]
|
|
|
|
return t
|
|
|
|
|
|
|
|
def cast_to(t):
|
|
|
|
if t in type_dict and "cast_to" in type_dict[t]:
|
|
|
|
return type_dict[t]["cast_to"]
|
|
|
|
return t
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
class ClassPropInfo():
|
2012-10-17 07:18:30 +08:00
|
|
|
def __init__(self, decl): # [f_ctype, f_name, '', '/RW']
|
|
|
|
self.ctype = decl[0]
|
|
|
|
self.name = decl[1]
|
|
|
|
self.rw = "/RW" in decl[3]
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return Template("PROP $ctype $name").substitute(ctype=self.ctype, name=self.name)
|
|
|
|
|
2014-09-19 19:31:38 +08:00
|
|
|
class ClassInfo(GeneralInfo):
|
|
|
|
def __init__(self, decl, namespaces=[]): # [ 'class/struct cname', ': base', [modlist] ]
|
2017-11-16 21:48:12 +08:00
|
|
|
GeneralInfo.__init__(self, "class", decl, namespaces)
|
2014-10-17 23:36:24 +08:00
|
|
|
self.methods = []
|
2012-10-17 07:18:30 +08:00
|
|
|
self.methods_suffixes = {}
|
2018-02-14 00:28:11 +08:00
|
|
|
self.consts = [] # using a list to save the occurrence order
|
2012-10-17 07:18:30 +08:00
|
|
|
self.private_consts = []
|
|
|
|
self.imports = set()
|
|
|
|
self.props= []
|
|
|
|
self.jname = self.name
|
2016-10-14 23:21:17 +08:00
|
|
|
self.smart = None # True if class stores Ptr<T>* instead of T* in nativeObj field
|
2014-10-17 23:36:24 +08:00
|
|
|
self.j_code = None # java code stream
|
|
|
|
self.jn_code = None # jni code stream
|
|
|
|
self.cpp_code = None # cpp code stream
|
2012-10-17 07:18:30 +08:00
|
|
|
for m in decl[2]:
|
|
|
|
if m.startswith("="):
|
|
|
|
self.jname = m[1:]
|
2021-07-02 18:41:41 +08:00
|
|
|
if m == '/Simple':
|
|
|
|
self.smart = False
|
2020-11-13 14:27:18 +08:00
|
|
|
|
|
|
|
if self.classpath:
|
|
|
|
prefix = self.classpath.replace('.', '_')
|
|
|
|
self.name = '%s_%s' % (prefix, self.name)
|
|
|
|
self.jname = '%s_%s' % (prefix, self.jname)
|
|
|
|
|
|
|
|
if self.namespace in namespaces_dict:
|
|
|
|
prefix = namespaces_dict[self.namespace]
|
|
|
|
if prefix:
|
|
|
|
self.name = '%s_%s' % (prefix, self.name)
|
|
|
|
self.jname = '%s_%s' % (prefix, self.jname)
|
|
|
|
|
2020-12-02 04:42:15 +08:00
|
|
|
self.jname = make_jname(self.jname)
|
2012-10-17 07:18:30 +08:00
|
|
|
self.base = ''
|
|
|
|
if decl[1]:
|
2020-11-16 12:30:45 +08:00
|
|
|
# FIXIT Use generator to find type properly instead of hacks below
|
|
|
|
base_class = re.sub(r"^: ", "", decl[1])
|
|
|
|
base_class = re.sub(r"^cv::", "", base_class)
|
|
|
|
base_class = base_class.replace('::', '.')
|
|
|
|
base_info = ClassInfo(('class {}'.format(base_class), '', [], [], None, None), [self.namespace])
|
|
|
|
base_type_name = base_info.name
|
|
|
|
if not base_type_name in type_dict:
|
|
|
|
base_type_name = re.sub(r"^.*:", "", decl[1].split(",")[0]).strip().replace(self.jname, "")
|
|
|
|
self.base = base_type_name
|
|
|
|
self.addImports(self.base)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def __repr__(self):
|
2016-08-05 21:34:57 +08:00
|
|
|
return Template("CLASS $namespace::$classpath.$name : $base").substitute(**self.__dict__)
|
2014-10-17 23:36:24 +08:00
|
|
|
|
|
|
|
def getAllImports(self, module):
|
2019-05-28 14:34:02 +08:00
|
|
|
return ["import %s;" % c for c in sorted(self.imports) if not c.startswith('org.opencv.'+module)
|
|
|
|
and (not c.startswith('java.lang.') or c.count('.') != 2)]
|
2014-10-17 23:36:24 +08:00
|
|
|
|
|
|
|
def addImports(self, ctype):
|
2017-06-10 13:57:10 +08:00
|
|
|
if ctype in type_dict:
|
|
|
|
if "j_import" in type_dict[ctype]:
|
|
|
|
self.imports.add(type_dict[ctype]["j_import"])
|
|
|
|
if "v_type" in type_dict[ctype]:
|
2014-10-17 23:36:24 +08:00
|
|
|
self.imports.add("java.util.List")
|
2017-06-10 13:57:10 +08:00
|
|
|
self.imports.add("java.util.ArrayList")
|
2014-10-17 23:36:24 +08:00
|
|
|
self.imports.add("org.opencv.utils.Converters")
|
2017-06-10 13:57:10 +08:00
|
|
|
if type_dict[ctype]["v_type"] in ("Mat", "vector_Mat"):
|
|
|
|
self.imports.add("org.opencv.core.Mat")
|
2014-10-17 23:36:24 +08:00
|
|
|
|
|
|
|
def getAllMethods(self):
|
|
|
|
result = []
|
2020-11-13 03:47:54 +08:00
|
|
|
result += [fi for fi in self.methods if fi.isconstructor]
|
|
|
|
result += [fi for fi in self.methods if not fi.isconstructor]
|
2014-10-17 23:36:24 +08:00
|
|
|
return result
|
|
|
|
|
|
|
|
def addMethod(self, fi):
|
|
|
|
self.methods.append(fi)
|
|
|
|
|
|
|
|
def getConst(self, name):
|
|
|
|
for cand in self.consts + self.private_consts:
|
|
|
|
if cand.name == name:
|
|
|
|
return cand
|
|
|
|
return None
|
|
|
|
|
|
|
|
def addConst(self, constinfo):
|
|
|
|
# choose right list (public or private)
|
|
|
|
consts = self.consts
|
|
|
|
for c in const_private_list:
|
|
|
|
if re.match(c, constinfo.name):
|
|
|
|
consts = self.private_consts
|
|
|
|
break
|
|
|
|
consts.append(constinfo)
|
|
|
|
|
|
|
|
def initCodeStreams(self, Module):
|
|
|
|
self.j_code = StringIO()
|
|
|
|
self.jn_code = StringIO()
|
2019-06-05 18:44:03 +08:00
|
|
|
self.cpp_code = StringIO()
|
2017-01-03 20:48:25 +08:00
|
|
|
if self.base:
|
|
|
|
self.j_code.write(T_JAVA_START_INHERITED)
|
2014-10-17 23:36:24 +08:00
|
|
|
else:
|
2017-01-03 20:48:25 +08:00
|
|
|
if self.name != Module:
|
|
|
|
self.j_code.write(T_JAVA_START_ORPHAN)
|
|
|
|
else:
|
|
|
|
self.j_code.write(T_JAVA_START_MODULE)
|
2014-10-17 23:36:24 +08:00
|
|
|
# misc handling
|
2017-12-29 12:15:30 +08:00
|
|
|
if self.name == Module:
|
|
|
|
for i in module_imports or []:
|
|
|
|
self.imports.add(i)
|
|
|
|
if module_j_code:
|
|
|
|
self.j_code.write(module_j_code)
|
|
|
|
if module_jn_code:
|
|
|
|
self.jn_code.write(module_jn_code)
|
2014-10-17 23:36:24 +08:00
|
|
|
|
|
|
|
def cleanupCodeStreams(self):
|
|
|
|
self.j_code.close()
|
|
|
|
self.jn_code.close()
|
|
|
|
self.cpp_code.close()
|
|
|
|
|
|
|
|
def generateJavaCode(self, m, M):
|
2019-05-28 14:34:02 +08:00
|
|
|
return Template(self.j_code.getvalue() + "\n\n" +
|
|
|
|
self.jn_code.getvalue() + "\n}\n").substitute(
|
2014-10-17 23:36:24 +08:00
|
|
|
module = m,
|
2020-12-02 04:42:15 +08:00
|
|
|
jmodule = make_jmodule(m),
|
2014-10-17 23:36:24 +08:00
|
|
|
name = self.name,
|
|
|
|
jname = self.jname,
|
|
|
|
imports = "\n".join(self.getAllImports(M)),
|
2017-11-16 21:48:12 +08:00
|
|
|
docs = self.docstring,
|
2019-06-05 18:44:03 +08:00
|
|
|
annotation = "\n" + "\n".join(self.annotation) if self.annotation else "",
|
2014-10-17 23:36:24 +08:00
|
|
|
base = self.base)
|
|
|
|
|
|
|
|
def generateCppCode(self):
|
|
|
|
return self.cpp_code.getvalue()
|
|
|
|
|
|
|
|
class ArgInfo():
|
2012-10-17 07:18:30 +08:00
|
|
|
def __init__(self, arg_tuple): # [ ctype, name, def val, [mod], argno ]
|
|
|
|
self.pointer = False
|
|
|
|
ctype = arg_tuple[0]
|
|
|
|
if ctype.endswith("*"):
|
|
|
|
ctype = ctype[:-1]
|
|
|
|
self.pointer = True
|
|
|
|
self.ctype = ctype
|
|
|
|
self.name = arg_tuple[1]
|
|
|
|
self.defval = arg_tuple[2]
|
|
|
|
self.out = ""
|
|
|
|
if "/O" in arg_tuple[3]:
|
|
|
|
self.out = "O"
|
|
|
|
if "/IO" in arg_tuple[3]:
|
|
|
|
self.out = "IO"
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return Template("ARG $ctype$p $name=$defval").substitute(ctype=self.ctype,
|
|
|
|
p=" *" if self.pointer else "",
|
|
|
|
name=self.name,
|
|
|
|
defval=self.defval)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2014-09-19 19:31:38 +08:00
|
|
|
class FuncInfo(GeneralInfo):
|
|
|
|
def __init__(self, decl, namespaces=[]): # [ funcname, return_ctype, [modifiers], [args] ]
|
2017-11-16 21:48:12 +08:00
|
|
|
GeneralInfo.__init__(self, "func", decl, namespaces)
|
2018-08-28 03:39:24 +08:00
|
|
|
self.cname = get_cname(decl[0])
|
2014-09-19 19:31:38 +08:00
|
|
|
self.jname = self.name
|
2014-10-17 23:36:24 +08:00
|
|
|
self.isconstructor = self.name == self.classname
|
2014-09-19 19:31:38 +08:00
|
|
|
if "[" in self.name:
|
2012-10-17 07:18:30 +08:00
|
|
|
self.jname = "getelem"
|
|
|
|
for m in decl[2]:
|
2020-11-13 14:27:18 +08:00
|
|
|
if m.startswith("="): # alias from WRAP_AS
|
2012-10-17 07:18:30 +08:00
|
|
|
self.jname = m[1:]
|
2020-11-13 14:27:18 +08:00
|
|
|
if self.classpath and self.classname != self.classpath:
|
|
|
|
prefix = self.classpath.replace('.', '_')
|
|
|
|
self.classname = prefix #'%s_%s' % (prefix, self.classname)
|
|
|
|
if self.isconstructor:
|
|
|
|
self.name = prefix #'%s_%s' % (prefix, self.name)
|
|
|
|
self.jname = prefix #'%s_%s' % (prefix, self.jname)
|
|
|
|
|
|
|
|
if self.namespace in namespaces_dict:
|
|
|
|
prefix = namespaces_dict[self.namespace]
|
|
|
|
if prefix:
|
|
|
|
if self.classname:
|
|
|
|
self.classname = '%s_%s' % (prefix, self.classname)
|
|
|
|
if self.isconstructor:
|
|
|
|
self.jname = '%s_%s' % (prefix, self.jname)
|
|
|
|
else:
|
|
|
|
self.jname = '%s_%s' % (prefix, self.jname)
|
|
|
|
|
2020-12-02 04:42:15 +08:00
|
|
|
self.jname = make_jname(self.jname)
|
2012-10-17 07:18:30 +08:00
|
|
|
self.static = ["","static"][ "/S" in decl[2] ]
|
|
|
|
self.ctype = re.sub(r"^CvTermCriteria", "TermCriteria", decl[1] or "")
|
|
|
|
self.args = []
|
2017-06-10 13:57:10 +08:00
|
|
|
func_fix_map = func_arg_fix.get(self.jname, {})
|
2012-10-17 07:18:30 +08:00
|
|
|
for a in decl[3]:
|
|
|
|
arg = a[:]
|
2013-06-10 18:37:01 +08:00
|
|
|
arg_fix_map = func_fix_map.get(arg[1], {})
|
|
|
|
arg[0] = arg_fix_map.get('ctype', arg[0]) #fixing arg type
|
|
|
|
arg[3] = arg_fix_map.get('attrib', arg[3]) #fixing arg attrib
|
2014-09-19 19:31:38 +08:00
|
|
|
self.args.append(ArgInfo(arg))
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2020-11-13 14:27:18 +08:00
|
|
|
def fullClassJAVA(self):
|
|
|
|
return self.fullParentNameJAVA()
|
|
|
|
|
|
|
|
def fullClassCPP(self):
|
|
|
|
return self.fullParentNameCPP()
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def __repr__(self):
|
|
|
|
return Template("FUNC <$ctype $namespace.$classpath.$name $args>").substitute(**self.__dict__)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2015-08-26 18:07:37 +08:00
|
|
|
def __lt__(self, other):
|
|
|
|
return self.__repr__() < other.__repr__()
|
|
|
|
|
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
class JavaWrapperGenerator(object):
|
|
|
|
def __init__(self):
|
2017-12-29 12:15:30 +08:00
|
|
|
self.cpp_files = []
|
2012-10-17 07:18:30 +08:00
|
|
|
self.clear()
|
|
|
|
|
|
|
|
def clear(self):
|
2020-11-13 03:47:54 +08:00
|
|
|
self.namespaces = ["cv"]
|
2021-07-02 18:41:41 +08:00
|
|
|
classinfo_Mat = ClassInfo([ 'class cv.Mat', '', ['/Simple'], [] ], self.namespaces)
|
2020-11-13 14:27:18 +08:00
|
|
|
self.classes = { "Mat" : classinfo_Mat }
|
2012-10-17 07:18:30 +08:00
|
|
|
self.module = ""
|
|
|
|
self.Module = ""
|
|
|
|
self.ported_func_list = []
|
|
|
|
self.skipped_func_list = []
|
|
|
|
self.def_args_hist = {} # { def_args_cnt : funcs_cnt }
|
|
|
|
|
|
|
|
def add_class(self, decl):
|
2014-09-19 19:31:38 +08:00
|
|
|
classinfo = ClassInfo(decl, namespaces=self.namespaces)
|
2012-10-17 07:18:30 +08:00
|
|
|
if classinfo.name in class_ignore_list:
|
2014-09-19 19:31:38 +08:00
|
|
|
logging.info('ignored: %s', classinfo)
|
2012-10-17 07:18:30 +08:00
|
|
|
return
|
|
|
|
name = classinfo.name
|
2017-01-03 20:48:25 +08:00
|
|
|
if self.isWrapped(name) and not classinfo.base:
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.warning('duplicated: %s', classinfo)
|
2012-10-17 07:18:30 +08:00
|
|
|
return
|
|
|
|
self.classes[name] = classinfo
|
2017-01-03 20:48:25 +08:00
|
|
|
if name in type_dict and not classinfo.base:
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.warning('duplicated: %s', classinfo)
|
2012-10-17 07:18:30 +08:00
|
|
|
return
|
2021-07-02 18:41:41 +08:00
|
|
|
if self.isSmartClass(classinfo):
|
|
|
|
jni_name = "*((*(Ptr<"+classinfo.fullNameCPP()+">*)%(n)s_nativeObj).get())"
|
|
|
|
else:
|
|
|
|
jni_name = "(*("+classinfo.fullNameCPP()+"*)%(n)s_nativeObj)"
|
2018-01-04 01:18:39 +08:00
|
|
|
type_dict.setdefault(name, {}).update(
|
2012-10-17 07:18:30 +08:00
|
|
|
{ "j_type" : classinfo.jname,
|
|
|
|
"jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
|
2021-07-02 18:41:41 +08:00
|
|
|
"jni_name" : jni_name,
|
|
|
|
"jni_type" : "jlong",
|
2018-01-04 01:18:39 +08:00
|
|
|
"suffix" : "J",
|
|
|
|
"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
|
|
|
|
}
|
|
|
|
)
|
|
|
|
type_dict.setdefault(name+'*', {}).update(
|
2012-10-17 07:18:30 +08:00
|
|
|
{ "j_type" : classinfo.jname,
|
|
|
|
"jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
|
2021-07-02 18:41:41 +08:00
|
|
|
"jni_name" : "&("+jni_name+")",
|
|
|
|
"jni_type" : "jlong",
|
2018-01-04 01:18:39 +08:00
|
|
|
"suffix" : "J",
|
|
|
|
"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
|
|
|
|
}
|
|
|
|
)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# missing_consts { Module : { public : [[name, val],...], private : [[]...] } }
|
|
|
|
if name in missing_consts:
|
|
|
|
if 'private' in missing_consts[name]:
|
|
|
|
for (n, val) in missing_consts[name]['private']:
|
2014-09-19 19:31:38 +08:00
|
|
|
classinfo.private_consts.append( ConstInfo([n, val], addedManually=True) )
|
2012-10-17 07:18:30 +08:00
|
|
|
if 'public' in missing_consts[name]:
|
|
|
|
for (n, val) in missing_consts[name]['public']:
|
2014-09-19 19:31:38 +08:00
|
|
|
classinfo.consts.append( ConstInfo([n, val], addedManually=True) )
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# class props
|
|
|
|
for p in decl[3]:
|
|
|
|
if True: #"vector" not in p[0]:
|
|
|
|
classinfo.props.append( ClassPropInfo(p) )
|
|
|
|
else:
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.warning("Skipped property: [%s]" % name, p)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
if classinfo.base:
|
2014-10-17 23:36:24 +08:00
|
|
|
classinfo.addImports(classinfo.base)
|
2018-01-04 01:18:39 +08:00
|
|
|
type_dict.setdefault("Ptr_"+name, {}).update(
|
2016-10-13 17:43:55 +08:00
|
|
|
{ "j_type" : classinfo.jname,
|
2017-04-18 16:28:26 +08:00
|
|
|
"jn_type" : "long", "jn_args" : (("__int64", ".getNativeObjAddr()"),),
|
2020-11-13 14:27:18 +08:00
|
|
|
"jni_name" : "*((Ptr<"+classinfo.fullNameCPP()+">*)%(n)s_nativeObj)", "jni_type" : "jlong",
|
2018-01-04 01:18:39 +08:00
|
|
|
"suffix" : "J",
|
|
|
|
"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
|
|
|
|
}
|
|
|
|
)
|
2016-05-31 14:35:50 +08:00
|
|
|
logging.info('ok: class %s, name: %s, base: %s', classinfo, name, classinfo.base)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2018-08-28 03:39:24 +08:00
|
|
|
def add_const(self, decl, enumType=None): # [ "const cname", val, [], [] ]
|
|
|
|
constinfo = ConstInfo(decl, namespaces=self.namespaces, enumType=enumType)
|
2014-10-17 23:36:24 +08:00
|
|
|
if constinfo.isIgnored():
|
|
|
|
logging.info('ignored: %s', constinfo)
|
|
|
|
else:
|
2018-12-18 22:39:31 +08:00
|
|
|
if not self.isWrapped(constinfo.classname):
|
|
|
|
logging.info('class not found: %s', constinfo)
|
|
|
|
constinfo.name = constinfo.classname + '_' + constinfo.name
|
|
|
|
constinfo.classname = ''
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
ci = self.getClass(constinfo.classname)
|
|
|
|
duplicate = ci.getConst(constinfo.name)
|
|
|
|
if duplicate:
|
|
|
|
if duplicate.addedManually:
|
|
|
|
logging.info('manual: %s', constinfo)
|
|
|
|
else:
|
|
|
|
logging.warning('duplicated: %s', constinfo)
|
|
|
|
else:
|
|
|
|
ci.addConst(constinfo)
|
|
|
|
logging.info('ok: %s', constinfo)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2018-08-20 22:35:41 +08:00
|
|
|
def add_enum(self, decl): # [ "enum cname", "", [], [] ]
|
2018-08-28 03:39:24 +08:00
|
|
|
enumType = decl[0].rsplit(" ", 1)[1]
|
|
|
|
if enumType.endswith("<unnamed>"):
|
|
|
|
enumType = None
|
|
|
|
else:
|
|
|
|
ctype = normalize_class_name(enumType)
|
|
|
|
type_dict[ctype] = { "cast_from" : "int", "cast_to" : get_cname(enumType), "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" }
|
2018-08-26 17:38:07 +08:00
|
|
|
const_decls = decl[3]
|
|
|
|
|
|
|
|
for decl in const_decls:
|
2018-08-28 03:39:24 +08:00
|
|
|
self.add_const(decl, enumType)
|
2018-08-20 22:35:41 +08:00
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
def add_func(self, decl):
|
2014-10-17 23:36:24 +08:00
|
|
|
fi = FuncInfo(decl, namespaces=self.namespaces)
|
|
|
|
classname = fi.classname or self.Module
|
2020-11-13 14:27:18 +08:00
|
|
|
class_symbol_id = classname if self.isWrapped(classname) else fi.classpath.replace('.', '_') #('.'.join([fi.namespace, fi.classpath])[3:])
|
2012-10-17 07:18:30 +08:00
|
|
|
if classname in class_ignore_list:
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.info('ignored: %s', fi)
|
|
|
|
elif classname in ManualFuncs and fi.jname in ManualFuncs[classname]:
|
|
|
|
logging.info('manual: %s', fi)
|
2020-11-13 14:27:18 +08:00
|
|
|
elif not self.isWrapped(class_symbol_id):
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.warning('not found: %s', fi)
|
2012-10-17 07:18:30 +08:00
|
|
|
else:
|
2020-11-13 14:27:18 +08:00
|
|
|
self.getClass(class_symbol_id).addMethod(fi)
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.info('ok: %s', fi)
|
|
|
|
# calc args with def val
|
|
|
|
cnt = len([a for a in fi.args if a.defval])
|
|
|
|
self.def_args_hist[cnt] = self.def_args_hist.get(cnt, 0) + 1
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
def save(self, path, buf):
|
2017-12-29 12:15:30 +08:00
|
|
|
global total_files, updated_files
|
|
|
|
total_files += 1
|
|
|
|
if os.path.exists(path):
|
|
|
|
with open(path, "rt") as f:
|
|
|
|
content = f.read()
|
|
|
|
if content == buf:
|
|
|
|
return
|
2019-06-05 18:44:03 +08:00
|
|
|
with codecs.open(path, "w", "utf-8") as f:
|
2017-12-29 12:15:30 +08:00
|
|
|
f.write(buf)
|
|
|
|
updated_files += 1
|
|
|
|
|
|
|
|
def gen(self, srcfiles, module, output_path, output_jni_path, output_java_path, common_headers):
|
2012-10-17 07:18:30 +08:00
|
|
|
self.clear()
|
|
|
|
self.module = module
|
|
|
|
self.Module = module.capitalize()
|
2016-02-08 00:04:39 +08:00
|
|
|
# TODO: support UMat versions of declarations (implement UMat-wrapper for Java)
|
|
|
|
parser = hdr_parser.CppHeaderParser(generate_umat_decls=False)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2020-11-13 14:27:18 +08:00
|
|
|
self.add_class( ['class cv.' + self.Module, '', [], []] ) # [ 'class/struct cname', ':bases', [modlist] [props] ]
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# scan the headers and build more descriptive maps of classes, consts, functions
|
2019-06-05 18:44:03 +08:00
|
|
|
includes = []
|
2016-10-12 22:28:50 +08:00
|
|
|
for hdr in common_headers:
|
|
|
|
logging.info("\n===== Common header : %s =====", hdr)
|
|
|
|
includes.append('#include "' + hdr + '"')
|
2012-10-17 07:18:30 +08:00
|
|
|
for hdr in srcfiles:
|
|
|
|
decls = parser.parse(hdr)
|
2020-11-13 03:47:54 +08:00
|
|
|
self.namespaces = sorted(parser.namespaces)
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.info("\n\n===== Header: %s =====", hdr)
|
2020-11-13 03:47:54 +08:00
|
|
|
logging.info("Namespaces: %s", sorted(parser.namespaces))
|
2015-02-19 21:17:19 +08:00
|
|
|
if decls:
|
|
|
|
includes.append('#include "' + hdr + '"')
|
2016-10-12 22:28:50 +08:00
|
|
|
else:
|
|
|
|
logging.info("Ignore header: %s", hdr)
|
2012-10-17 07:18:30 +08:00
|
|
|
for decl in decls:
|
2017-12-29 12:15:30 +08:00
|
|
|
logging.info("\n--- Incoming ---\n%s", pformat(decl[:5], 4)) # without docstring
|
2012-10-17 07:18:30 +08:00
|
|
|
name = decl[0]
|
|
|
|
if name.startswith("struct") or name.startswith("class"):
|
|
|
|
self.add_class(decl)
|
|
|
|
elif name.startswith("const"):
|
|
|
|
self.add_const(decl)
|
2018-08-20 22:35:41 +08:00
|
|
|
elif name.startswith("enum"):
|
|
|
|
# enum
|
|
|
|
self.add_enum(decl)
|
2012-10-17 07:18:30 +08:00
|
|
|
else: # function
|
|
|
|
self.add_func(decl)
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.info("\n\n===== Generating... =====")
|
|
|
|
moduleCppCode = StringIO()
|
2020-12-02 04:42:15 +08:00
|
|
|
package_path = os.path.join(output_java_path, make_jmodule(module))
|
|
|
|
#print("package path: %s\n" % package_path)
|
2017-12-29 12:15:30 +08:00
|
|
|
mkdir_p(package_path)
|
2020-11-13 03:47:54 +08:00
|
|
|
for ci in sorted(self.classes.values(), key=lambda x: x.symbol_id):
|
2014-10-17 23:36:24 +08:00
|
|
|
if ci.name == "Mat":
|
2012-10-17 07:18:30 +08:00
|
|
|
continue
|
2014-10-17 23:36:24 +08:00
|
|
|
ci.initCodeStreams(self.Module)
|
|
|
|
self.gen_class(ci)
|
|
|
|
classJavaCode = ci.generateJavaCode(self.module, self.Module)
|
2020-12-02 04:42:15 +08:00
|
|
|
self.save("%s/%s.java" % (package_path, ci.jname), classJavaCode)
|
2014-10-17 23:36:24 +08:00
|
|
|
moduleCppCode.write(ci.generateCppCode())
|
|
|
|
ci.cleanupCodeStreams()
|
2017-12-29 12:15:30 +08:00
|
|
|
cpp_file = os.path.abspath(os.path.join(output_jni_path, module + ".inl.hpp"))
|
|
|
|
self.cpp_files.append(cpp_file)
|
|
|
|
self.save(cpp_file, T_CPP_MODULE.substitute(m = module, M = module.upper(), code = moduleCppCode.getvalue(), includes = "\n".join(includes)))
|
|
|
|
self.save(os.path.join(output_path, module+".txt"), self.makeReport())
|
2014-10-17 23:36:24 +08:00
|
|
|
|
|
|
|
def makeReport(self):
|
|
|
|
'''
|
|
|
|
Returns string with generator report
|
|
|
|
'''
|
2012-10-17 07:18:30 +08:00
|
|
|
report = StringIO()
|
2014-10-17 23:36:24 +08:00
|
|
|
total_count = len(self.ported_func_list)+ len(self.skipped_func_list)
|
|
|
|
report.write("PORTED FUNCs LIST (%i of %i):\n\n" % (len(self.ported_func_list), total_count))
|
2012-10-17 07:18:30 +08:00
|
|
|
report.write("\n".join(self.ported_func_list))
|
2014-10-17 23:36:24 +08:00
|
|
|
report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % (len(self.skipped_func_list), total_count))
|
2012-10-17 07:18:30 +08:00
|
|
|
report.write("".join(self.skipped_func_list))
|
2020-11-13 03:47:54 +08:00
|
|
|
for i in sorted(self.def_args_hist.keys()):
|
2012-10-17 07:18:30 +08:00
|
|
|
report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i]))
|
2014-10-17 23:36:24 +08:00
|
|
|
return report.getvalue()
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2020-11-13 14:27:18 +08:00
|
|
|
def fullTypeNameCPP(self, t):
|
2014-10-17 23:36:24 +08:00
|
|
|
if self.isWrapped(t):
|
2020-11-13 14:27:18 +08:00
|
|
|
return self.getClass(t).fullNameCPP()
|
2014-09-19 19:31:38 +08:00
|
|
|
else:
|
2018-08-28 03:39:24 +08:00
|
|
|
return cast_from(t)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def gen_func(self, ci, fi, prop_name=''):
|
|
|
|
logging.info("%s", fi)
|
|
|
|
j_code = ci.j_code
|
|
|
|
jn_code = ci.jn_code
|
|
|
|
cpp_code = ci.cpp_code
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# c_decl
|
|
|
|
# e.g: void add(Mat src1, Mat src2, Mat dst, Mat mask = Mat(), int dtype = -1)
|
|
|
|
if prop_name:
|
|
|
|
c_decl = "%s %s::%s" % (fi.ctype, fi.classname, prop_name)
|
|
|
|
else:
|
|
|
|
decl_args = []
|
|
|
|
for a in fi.args:
|
|
|
|
s = a.ctype or ' _hidden_ '
|
|
|
|
if a.pointer:
|
|
|
|
s += "*"
|
|
|
|
elif a.out:
|
|
|
|
s += "&"
|
|
|
|
s += " " + a.name
|
|
|
|
if a.defval:
|
|
|
|
s += " = "+a.defval
|
|
|
|
decl_args.append(s)
|
|
|
|
c_decl = "%s %s %s(%s)" % ( fi.static, fi.ctype, fi.cname, ", ".join(decl_args) )
|
|
|
|
|
|
|
|
# java comment
|
|
|
|
j_code.write( "\n //\n // C++: %s\n //\n\n" % c_decl )
|
|
|
|
# check if we 'know' all the types
|
|
|
|
if fi.ctype not in type_dict: # unsupported ret type
|
|
|
|
msg = "// Return type '%s' is not supported, skipping the function\n\n" % fi.ctype
|
|
|
|
self.skipped_func_list.append(c_decl + "\n" + msg)
|
|
|
|
j_code.write( " "*4 + msg )
|
2023-07-07 00:27:16 +08:00
|
|
|
logging.info("SKIP:" + c_decl.strip() + "\t due to RET type " + fi.ctype)
|
2012-10-17 07:18:30 +08:00
|
|
|
return
|
|
|
|
for a in fi.args:
|
|
|
|
if a.ctype not in type_dict:
|
2013-04-09 17:10:54 +08:00
|
|
|
if not a.defval and a.ctype.endswith("*"):
|
|
|
|
a.defval = 0
|
|
|
|
if a.defval:
|
|
|
|
a.ctype = ''
|
|
|
|
continue
|
2012-10-17 07:18:30 +08:00
|
|
|
msg = "// Unknown type '%s' (%s), skipping the function\n\n" % (a.ctype, a.out or "I")
|
|
|
|
self.skipped_func_list.append(c_decl + "\n" + msg)
|
|
|
|
j_code.write( " "*4 + msg )
|
2023-07-07 00:27:16 +08:00
|
|
|
logging.info("SKIP:" + c_decl.strip() + "\t due to ARG type " + a.ctype + "/" + (a.out or "I"))
|
2012-10-17 07:18:30 +08:00
|
|
|
return
|
|
|
|
|
|
|
|
self.ported_func_list.append(c_decl)
|
|
|
|
|
|
|
|
# jn & cpp comment
|
|
|
|
jn_code.write( "\n // C++: %s\n" % c_decl )
|
|
|
|
cpp_code.write( "\n//\n// %s\n//\n" % c_decl )
|
|
|
|
|
|
|
|
# java args
|
|
|
|
args = fi.args[:] # copy
|
2016-10-08 06:13:01 +08:00
|
|
|
j_signatures=[]
|
2014-10-17 23:36:24 +08:00
|
|
|
suffix_counter = int(ci.methods_suffixes.get(fi.jname, -1))
|
2012-10-17 07:18:30 +08:00
|
|
|
while True:
|
|
|
|
suffix_counter += 1
|
2014-10-17 23:36:24 +08:00
|
|
|
ci.methods_suffixes[fi.jname] = suffix_counter
|
2012-10-17 07:18:30 +08:00
|
|
|
# java native method args
|
|
|
|
jn_args = []
|
|
|
|
# jni (cpp) function args
|
|
|
|
jni_args = [ArgInfo([ "env", "env", "", [], "" ]), ArgInfo([ "cls", "", "", [], "" ])]
|
|
|
|
j_prologue = []
|
|
|
|
j_epilogue = []
|
|
|
|
c_prologue = []
|
|
|
|
c_epilogue = []
|
|
|
|
if type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
|
|
|
|
fields = type_dict[fi.ctype]["jn_args"]
|
|
|
|
c_epilogue.append( \
|
|
|
|
("jdoubleArray _da_retval_ = env->NewDoubleArray(%(cnt)i); " +
|
|
|
|
"jdouble _tmp_retval_[%(cnt)i] = {%(args)s}; " +
|
|
|
|
"env->SetDoubleArrayRegion(_da_retval_, 0, %(cnt)i, _tmp_retval_);") %
|
2015-10-16 22:10:00 +08:00
|
|
|
{ "cnt" : len(fields), "args" : ", ".join(["(jdouble)_retval_" + f[1] for f in fields]) } )
|
2012-10-17 07:18:30 +08:00
|
|
|
if fi.classname and fi.ctype and not fi.static: # non-static class method except c-tor
|
|
|
|
# adding 'self'
|
|
|
|
jn_args.append ( ArgInfo([ "__int64", "nativeObj", "", [], "" ]) )
|
|
|
|
jni_args.append( ArgInfo([ "__int64", "self", "", [], "" ]) )
|
2014-10-17 23:36:24 +08:00
|
|
|
ci.addImports(fi.ctype)
|
2012-10-17 07:18:30 +08:00
|
|
|
for a in args:
|
|
|
|
if not a.ctype: # hidden
|
|
|
|
continue
|
2014-10-17 23:36:24 +08:00
|
|
|
ci.addImports(a.ctype)
|
2017-06-10 13:57:10 +08:00
|
|
|
if "v_type" in type_dict[a.ctype]: # pass as vector
|
|
|
|
if type_dict[a.ctype]["v_type"] in ("Mat", "vector_Mat"): #pass as Mat or vector_Mat
|
|
|
|
jn_args.append ( ArgInfo([ "__int64", "%s_mat.nativeObj" % a.name, "", [], "" ]) )
|
|
|
|
jni_args.append ( ArgInfo([ "__int64", "%s_mat_nativeObj" % a.name, "", [], "" ]) )
|
|
|
|
c_prologue.append( type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";" )
|
|
|
|
c_prologue.append( "Mat& %(n)s_mat = *((Mat*)%(n)s_mat_nativeObj)" % {"n" : a.name} + ";" )
|
|
|
|
if "I" in a.out or not a.out:
|
|
|
|
if type_dict[a.ctype]["v_type"] == "vector_Mat":
|
|
|
|
j_prologue.append( "List<Mat> %(n)s_tmplm = new ArrayList<Mat>((%(n)s != null) ? %(n)s.size() : 0);" % {"n" : a.name } )
|
|
|
|
j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s, %(n)s_tmplm);" % {"n" : a.name, "t" : a.ctype} )
|
|
|
|
else:
|
|
|
|
if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
|
|
|
|
j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s);" % {"n" : a.name, "t" : a.ctype} )
|
|
|
|
else:
|
|
|
|
j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
|
|
|
|
c_prologue.append( "Mat_to_%(t)s( %(n)s_mat, %(n)s );" % {"n" : a.name, "t" : a.ctype} )
|
2012-10-17 07:18:30 +08:00
|
|
|
else:
|
|
|
|
if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
|
2017-06-10 13:57:10 +08:00
|
|
|
j_prologue.append( "Mat %s_mat = new Mat();" % a.name )
|
2012-10-17 07:18:30 +08:00
|
|
|
else:
|
|
|
|
j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
|
2017-06-10 13:57:10 +08:00
|
|
|
if "O" in a.out:
|
|
|
|
if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
|
|
|
|
j_epilogue.append("Converters.Mat_to_%(t)s(%(n)s_mat, %(n)s);" % {"t" : a.ctype, "n" : a.name})
|
|
|
|
j_epilogue.append( "%s_mat.release();" % a.name )
|
|
|
|
c_epilogue.append( "%(t)s_to_Mat( %(n)s, %(n)s_mat );" % {"n" : a.name, "t" : a.ctype} )
|
|
|
|
else: #pass as list
|
|
|
|
jn_args.append ( ArgInfo([ a.ctype, a.name, "", [], "" ]) )
|
|
|
|
jni_args.append ( ArgInfo([ a.ctype, "%s_list" % a.name , "", [], "" ]) )
|
|
|
|
c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")
|
|
|
|
if "I" in a.out or not a.out:
|
|
|
|
c_prologue.append("%(n)s = List_to_%(t)s(env, %(n)s_list);" % {"n" : a.name, "t" : a.ctype})
|
|
|
|
if "O" in a.out:
|
|
|
|
c_epilogue.append("Copy_%s_to_List(env,%s,%s_list);" % (a.ctype, a.name, a.name))
|
2012-10-17 07:18:30 +08:00
|
|
|
else:
|
|
|
|
fields = type_dict[a.ctype].get("jn_args", ((a.ctype, ""),))
|
2014-10-17 23:36:24 +08:00
|
|
|
if "I" in a.out or not a.out or self.isWrapped(a.ctype): # input arg, pass by primitive fields
|
2012-10-17 07:18:30 +08:00
|
|
|
for f in fields:
|
|
|
|
jn_args.append ( ArgInfo([ f[0], a.name + f[1], "", [], "" ]) )
|
2018-08-28 03:39:24 +08:00
|
|
|
jni_args.append( ArgInfo([ f[0], a.name + normalize_field_name(f[1]), "", [], "" ]) )
|
2017-06-10 13:57:10 +08:00
|
|
|
if "O" in a.out and not self.isWrapped(a.ctype): # out arg, pass as double[]
|
2012-10-17 07:18:30 +08:00
|
|
|
jn_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )
|
|
|
|
jni_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )
|
|
|
|
j_prologue.append( "double[] %s_out = new double[%i];" % (a.name, len(fields)) )
|
2019-05-28 14:34:02 +08:00
|
|
|
c_epilogue.append(
|
2012-10-17 07:18:30 +08:00
|
|
|
"jdouble tmp_%(n)s[%(cnt)i] = {%(args)s}; env->SetDoubleArrayRegion(%(n)s_out, 0, %(cnt)i, tmp_%(n)s);" %
|
2015-10-16 22:10:00 +08:00
|
|
|
{ "n" : a.name, "cnt" : len(fields), "args" : ", ".join(["(jdouble)" + a.name + f[1] for f in fields]) } )
|
2017-06-10 13:57:10 +08:00
|
|
|
if type_dict[a.ctype]["j_type"] in ('bool', 'int', 'long', 'float', 'double'):
|
|
|
|
j_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"]})
|
2012-10-17 07:18:30 +08:00
|
|
|
else:
|
|
|
|
set_vals = []
|
|
|
|
i = 0
|
|
|
|
for f in fields:
|
|
|
|
set_vals.append( "%(n)s%(f)s = %(t)s%(n)s_out[%(i)i]" %
|
|
|
|
{"n" : a.name, "t": ("("+type_dict[f[0]]["j_type"]+")", "")[f[0]=="double"], "f" : f[1], "i" : i}
|
|
|
|
)
|
|
|
|
i += 1
|
|
|
|
j_epilogue.append( "if("+a.name+"!=null){ " + "; ".join(set_vals) + "; } ")
|
|
|
|
|
2016-10-08 06:13:01 +08:00
|
|
|
# calculate java method signature to check for uniqueness
|
|
|
|
j_args = []
|
|
|
|
for a in args:
|
|
|
|
if not a.ctype: #hidden
|
|
|
|
continue
|
|
|
|
jt = type_dict[a.ctype]["j_type"]
|
2017-06-10 13:57:10 +08:00
|
|
|
if a.out and jt in ('bool', 'int', 'long', 'float', 'double'):
|
2016-10-08 06:13:01 +08:00
|
|
|
jt += '[]'
|
|
|
|
j_args.append( jt + ' ' + a.name )
|
|
|
|
j_signature = type_dict[fi.ctype]["j_type"] + " " + \
|
|
|
|
fi.jname + "(" + ", ".join(j_args) + ")"
|
|
|
|
logging.info("java: " + j_signature)
|
|
|
|
|
2019-06-05 18:44:03 +08:00
|
|
|
if j_signature in j_signatures:
|
2016-10-08 06:13:01 +08:00
|
|
|
if args:
|
2017-12-29 12:15:30 +08:00
|
|
|
args.pop()
|
2016-10-08 06:13:01 +08:00
|
|
|
continue
|
|
|
|
else:
|
|
|
|
break
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# java part:
|
|
|
|
# private java NATIVE method decl
|
|
|
|
# e.g.
|
|
|
|
# private static native void add_0(long src1, long src2, long dst, long mask, int dtype);
|
2019-05-28 14:34:02 +08:00
|
|
|
jn_code.write( Template(
|
|
|
|
" private static native $type $name($args);\n").substitute(
|
|
|
|
type = type_dict[fi.ctype].get("jn_type", "double[]"),
|
|
|
|
name = fi.jname + '_' + str(suffix_counter),
|
2018-08-28 03:39:24 +08:00
|
|
|
args = ", ".join(["%s %s" % (type_dict[a.ctype]["jn_type"], normalize_field_name(a.name)) for a in jn_args])
|
2019-06-05 18:44:03 +08:00
|
|
|
) )
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# java part:
|
|
|
|
|
|
|
|
#java doc comment
|
2017-11-16 21:48:12 +08:00
|
|
|
if fi.docstring:
|
2019-06-05 18:44:03 +08:00
|
|
|
lines = fi.docstring.splitlines()
|
|
|
|
returnTag = False
|
|
|
|
javadocParams = []
|
|
|
|
toWrite = []
|
|
|
|
inCode = False
|
|
|
|
for index, line in enumerate(lines):
|
|
|
|
p0 = line.find("@param")
|
|
|
|
if p0 != -1:
|
|
|
|
p0 += 7
|
|
|
|
p1 = line.find(' ', p0)
|
|
|
|
p1 = len(line) if p1 == -1 else p1
|
|
|
|
name = line[p0:p1]
|
|
|
|
javadocParams.append(name)
|
|
|
|
for arg in j_args:
|
|
|
|
if arg.endswith(" " + name):
|
|
|
|
toWrite.append(line);
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
if "<code>" in line:
|
|
|
|
inCode = True
|
|
|
|
if "</code>" in line:
|
|
|
|
inCode = False
|
2020-10-06 12:28:25 +08:00
|
|
|
line = line.replace('@result ', '@return ') # @result is valid in Doxygen, but invalid in Javadoc
|
2019-06-05 18:44:03 +08:00
|
|
|
if "@return " in line:
|
|
|
|
returnTag = True
|
|
|
|
|
|
|
|
if (not inCode and toWrite and not toWrite[-1] and
|
|
|
|
line and not line.startswith("\\") and not line.startswith("<ul>") and not line.startswith("@param")):
|
|
|
|
toWrite.append("<p>");
|
|
|
|
|
|
|
|
if index == len(lines) - 1:
|
|
|
|
for arg in j_args:
|
|
|
|
name = arg[arg.rfind(' ') + 1:]
|
|
|
|
if not name in javadocParams:
|
|
|
|
toWrite.append(" * @param " + name + " automatically generated");
|
|
|
|
if type_dict[fi.ctype]["j_type"] and not returnTag and fi.ctype != "void":
|
|
|
|
toWrite.append(" * @return automatically generated");
|
|
|
|
toWrite.append(line);
|
|
|
|
|
|
|
|
for line in toWrite:
|
2017-11-16 21:48:12 +08:00
|
|
|
j_code.write(" "*4 + line + "\n")
|
|
|
|
if fi.annotation:
|
|
|
|
j_code.write(" "*4 + "\n".join(fi.annotation) + "\n")
|
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
# public java wrapper method impl (calling native one above)
|
|
|
|
# e.g.
|
|
|
|
# public static void add( Mat src1, Mat src2, Mat dst, Mat mask, int dtype )
|
|
|
|
# { add_0( src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype ); }
|
|
|
|
ret_type = fi.ctype
|
|
|
|
if fi.ctype.endswith('*'):
|
|
|
|
ret_type = ret_type[:-1]
|
2019-05-28 14:34:02 +08:00
|
|
|
ret_val = type_dict[ret_type]["j_type"] + " retVal = " if j_epilogue else "return "
|
2012-10-17 07:18:30 +08:00
|
|
|
tail = ""
|
2019-05-28 14:34:02 +08:00
|
|
|
ret = "return retVal;" if j_epilogue else ""
|
2017-06-10 13:57:10 +08:00
|
|
|
if "v_type" in type_dict[ret_type]:
|
2012-10-17 07:18:30 +08:00
|
|
|
j_type = type_dict[ret_type]["j_type"]
|
2017-06-10 13:57:10 +08:00
|
|
|
if type_dict[ret_type]["v_type"] in ("Mat", "vector_Mat"):
|
|
|
|
tail = ")"
|
|
|
|
if j_type.startswith('MatOf'):
|
|
|
|
ret_val += j_type + ".fromNativeAddr("
|
|
|
|
else:
|
|
|
|
ret_val = "Mat retValMat = new Mat("
|
|
|
|
j_prologue.append( j_type + ' retVal = new Array' + j_type+'();')
|
|
|
|
j_epilogue.append('Converters.Mat_to_' + ret_type + '(retValMat, retVal);')
|
2019-05-28 14:34:02 +08:00
|
|
|
ret = "return retVal;"
|
2014-08-29 22:06:16 +08:00
|
|
|
elif ret_type.startswith("Ptr_"):
|
2019-06-05 18:44:03 +08:00
|
|
|
constructor = type_dict[ret_type]["j_type"] + ".__fromPtr__("
|
2019-05-28 14:34:02 +08:00
|
|
|
if j_epilogue:
|
|
|
|
ret_val = type_dict[fi.ctype]["j_type"] + " retVal = " + constructor
|
|
|
|
else:
|
|
|
|
ret_val = "return " + constructor
|
2014-08-29 22:06:16 +08:00
|
|
|
tail = ")"
|
2012-10-17 07:18:30 +08:00
|
|
|
elif ret_type == "void":
|
|
|
|
ret_val = ""
|
2019-05-28 14:34:02 +08:00
|
|
|
ret = ""
|
2012-10-17 07:18:30 +08:00
|
|
|
elif ret_type == "": # c-tor
|
2014-10-17 23:36:24 +08:00
|
|
|
if fi.classname and ci.base:
|
2019-05-28 14:34:02 +08:00
|
|
|
ret_val = "super("
|
|
|
|
tail = ")"
|
2012-10-17 07:18:30 +08:00
|
|
|
else:
|
|
|
|
ret_val = "nativeObj = "
|
2019-05-28 14:34:02 +08:00
|
|
|
ret = ""
|
2014-10-17 23:36:24 +08:00
|
|
|
elif self.isWrapped(ret_type): # wrapped class
|
2019-06-05 18:44:03 +08:00
|
|
|
constructor = self.getClass(ret_type).jname + "("
|
2019-05-28 14:34:02 +08:00
|
|
|
if j_epilogue:
|
|
|
|
ret_val = type_dict[ret_type]["j_type"] + " retVal = new " + constructor
|
|
|
|
else:
|
|
|
|
ret_val = "return new " + constructor
|
2012-10-17 07:18:30 +08:00
|
|
|
tail = ")"
|
|
|
|
elif "jn_type" not in type_dict[ret_type]:
|
2019-06-05 18:44:03 +08:00
|
|
|
constructor = type_dict[ret_type]["j_type"] + "("
|
2019-05-28 14:34:02 +08:00
|
|
|
if j_epilogue:
|
|
|
|
ret_val = type_dict[fi.ctype]["j_type"] + " retVal = new " + constructor
|
|
|
|
else:
|
|
|
|
ret_val = "return new " + constructor
|
2012-10-17 07:18:30 +08:00
|
|
|
tail = ")"
|
|
|
|
|
|
|
|
static = "static"
|
|
|
|
if fi.classname:
|
|
|
|
static = fi.static
|
|
|
|
|
2019-05-28 14:34:02 +08:00
|
|
|
j_code.write( Template(
|
2019-06-05 18:44:03 +08:00
|
|
|
""" public $static$j_type$j_name($j_args) {$prologue
|
2019-05-28 14:34:02 +08:00
|
|
|
$ret_val$jn_name($jn_args_call)$tail;$epilogue$ret
|
2012-10-17 07:18:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
"""
|
2019-05-28 14:34:02 +08:00
|
|
|
).substitute(
|
|
|
|
ret = "\n " + ret if ret else "",
|
|
|
|
ret_val = ret_val,
|
|
|
|
tail = tail,
|
|
|
|
prologue = "\n " + "\n ".join(j_prologue) if j_prologue else "",
|
|
|
|
epilogue = "\n " + "\n ".join(j_epilogue) if j_epilogue else "",
|
|
|
|
static = static + " " if static else "",
|
2019-06-05 18:44:03 +08:00
|
|
|
j_type=type_dict[fi.ctype]["j_type"] + " " if type_dict[fi.ctype]["j_type"] else "",
|
2019-05-28 14:34:02 +08:00
|
|
|
j_name=fi.jname,
|
|
|
|
j_args=", ".join(j_args),
|
|
|
|
jn_name=fi.jname + '_' + str(suffix_counter),
|
|
|
|
jn_args_call=", ".join( [a.name for a in jn_args] ),
|
2012-10-17 07:18:30 +08:00
|
|
|
)
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
# cpp part:
|
|
|
|
# jni_func(..) { _retval_ = cv_func(..); return _retval_; }
|
2019-05-28 14:34:02 +08:00
|
|
|
ret = "return _retval_;" if c_epilogue else ""
|
2012-10-17 07:18:30 +08:00
|
|
|
default = "return 0;"
|
|
|
|
if fi.ctype == "void":
|
2019-05-28 14:34:02 +08:00
|
|
|
ret = ""
|
|
|
|
default = ""
|
2012-10-17 07:18:30 +08:00
|
|
|
elif not fi.ctype: # c-tor
|
2020-05-29 21:20:28 +08:00
|
|
|
if self.isSmartClass(ci):
|
2020-11-13 14:27:18 +08:00
|
|
|
ret = "return (jlong)(new Ptr<%(ctype)s>(_retval_));" % { 'ctype': fi.fullClassCPP() }
|
2020-05-29 21:20:28 +08:00
|
|
|
else:
|
|
|
|
ret = "return (jlong) _retval_;"
|
2017-06-10 13:57:10 +08:00
|
|
|
elif "v_type" in type_dict[fi.ctype]: # c-tor
|
|
|
|
if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"):
|
|
|
|
ret = "return (jlong) _retval_;"
|
2019-04-05 22:15:51 +08:00
|
|
|
elif fi.ctype in ['String', 'string']:
|
2012-10-17 07:18:30 +08:00
|
|
|
ret = "return env->NewStringUTF(_retval_.c_str());"
|
|
|
|
default = 'return env->NewStringUTF("");'
|
2014-10-17 23:36:24 +08:00
|
|
|
elif self.isWrapped(fi.ctype): # wrapped class:
|
2021-07-02 18:41:41 +08:00
|
|
|
ret = None
|
|
|
|
if fi.ctype in self.classes:
|
|
|
|
ret_ci = self.classes[fi.ctype]
|
|
|
|
if self.isSmartClass(ret_ci):
|
|
|
|
ret = "return (jlong)(new Ptr<%(ctype)s>(new %(ctype)s(_retval_)));" % { 'ctype': ret_ci.fullNameCPP() }
|
|
|
|
if ret is None:
|
|
|
|
ret = "return (jlong) new %s(_retval_);" % self.fullTypeNameCPP(fi.ctype)
|
2014-08-29 22:06:16 +08:00
|
|
|
elif fi.ctype.startswith('Ptr_'):
|
2020-11-13 14:27:18 +08:00
|
|
|
c_prologue.append("typedef Ptr<%s> %s;" % (self.fullTypeNameCPP(fi.ctype[4:]), fi.ctype))
|
2016-09-30 21:21:04 +08:00
|
|
|
ret = "return (jlong)(new %(ctype)s(_retval_));" % { 'ctype':fi.ctype }
|
2014-10-17 23:36:24 +08:00
|
|
|
elif self.isWrapped(ret_type): # pointer to wrapped class:
|
2012-10-17 07:18:30 +08:00
|
|
|
ret = "return (jlong) _retval_;"
|
|
|
|
elif type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
|
|
|
|
ret = "return _da_retval_;"
|
|
|
|
|
|
|
|
# hack: replacing func call with property set/get
|
|
|
|
name = fi.name
|
|
|
|
if prop_name:
|
|
|
|
if args:
|
|
|
|
name = prop_name + " = "
|
|
|
|
else:
|
|
|
|
name = prop_name + ";//"
|
|
|
|
|
2020-11-13 14:27:18 +08:00
|
|
|
cvname = fi.fullNameCPP()
|
|
|
|
retval = self.fullTypeNameCPP(fi.ctype) + " _retval_ = " if ret else "return "
|
2012-10-17 07:18:30 +08:00
|
|
|
if fi.ctype == "void":
|
|
|
|
retval = ""
|
2013-03-21 00:46:22 +08:00
|
|
|
elif fi.ctype == "String":
|
2020-11-13 14:27:18 +08:00
|
|
|
retval = "cv::" + self.fullTypeNameCPP(fi.ctype) + " _retval_ = "
|
2019-04-05 22:15:51 +08:00
|
|
|
elif fi.ctype == "string":
|
2019-06-06 00:11:22 +08:00
|
|
|
retval = "std::string _retval_ = "
|
2017-06-10 13:57:10 +08:00
|
|
|
elif "v_type" in type_dict[fi.ctype]: # vector is returned
|
2012-10-17 07:18:30 +08:00
|
|
|
retval = type_dict[fi.ctype]['jni_var'] % {"n" : '_ret_val_vector_'} + " = "
|
2017-06-10 13:57:10 +08:00
|
|
|
if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"):
|
|
|
|
c_epilogue.append("Mat* _retval_ = new Mat();")
|
|
|
|
c_epilogue.append(fi.ctype+"_to_Mat(_ret_val_vector_, *_retval_);")
|
|
|
|
else:
|
2020-01-27 03:18:42 +08:00
|
|
|
if ret:
|
|
|
|
c_epilogue.append("jobject _retval_ = " + fi.ctype + "_to_List(env, _ret_val_vector_);")
|
|
|
|
else:
|
|
|
|
c_epilogue.append("return " + fi.ctype + "_to_List(env, _ret_val_vector_);")
|
2019-05-28 14:34:02 +08:00
|
|
|
if fi.classname:
|
2012-10-17 07:18:30 +08:00
|
|
|
if not fi.ctype: # c-tor
|
2020-05-29 21:20:28 +08:00
|
|
|
if self.isSmartClass(ci):
|
2020-11-13 14:27:18 +08:00
|
|
|
retval = self.smartWrap(ci, fi.fullClassCPP()) + " _retval_ = "
|
|
|
|
cvname = "makePtr<" + fi.fullClassCPP() +">"
|
2020-05-29 21:20:28 +08:00
|
|
|
else:
|
2020-11-13 14:27:18 +08:00
|
|
|
retval = fi.fullClassCPP() + "* _retval_ = "
|
|
|
|
cvname = "new " + fi.fullClassCPP()
|
2012-10-17 07:18:30 +08:00
|
|
|
elif fi.static:
|
2020-11-13 14:27:18 +08:00
|
|
|
cvname = fi.fullNameCPP()
|
2012-10-17 07:18:30 +08:00
|
|
|
else:
|
2016-10-14 23:21:17 +08:00
|
|
|
cvname = ("me->" if not self.isSmartClass(ci) else "(*me)->") + name
|
2019-05-28 14:34:02 +08:00
|
|
|
c_prologue.append(
|
|
|
|
"%(cls)s* me = (%(cls)s*) self; //TODO: check for NULL"
|
2020-11-13 14:27:18 +08:00
|
|
|
% { "cls" : self.smartWrap(ci, fi.fullClassCPP())}
|
2012-10-17 07:18:30 +08:00
|
|
|
)
|
|
|
|
cvargs = []
|
|
|
|
for a in args:
|
|
|
|
if a.pointer:
|
|
|
|
jni_name = "&%(n)s"
|
|
|
|
else:
|
|
|
|
jni_name = "%(n)s"
|
2012-12-31 03:24:39 +08:00
|
|
|
if not a.out and not "jni_var" in type_dict[a.ctype]:
|
|
|
|
# explicit cast to C type to avoid ambiguous call error on platforms (mingw)
|
|
|
|
# where jni types are different from native types (e.g. jint is not the same as int)
|
2018-08-28 03:39:24 +08:00
|
|
|
jni_name = "(%s)%s" % (cast_to(a.ctype), jni_name)
|
2012-10-17 07:18:30 +08:00
|
|
|
if not a.ctype: # hidden
|
|
|
|
jni_name = a.defval
|
|
|
|
cvargs.append( type_dict[a.ctype].get("jni_name", jni_name) % {"n" : a.name})
|
2017-06-10 13:57:10 +08:00
|
|
|
if "v_type" not in type_dict[a.ctype]:
|
2014-10-17 23:36:24 +08:00
|
|
|
if ("I" in a.out or not a.out or self.isWrapped(a.ctype)) and "jni_var" in type_dict[a.ctype]: # complex type
|
2012-10-17 07:18:30 +08:00
|
|
|
c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")
|
2014-10-17 23:36:24 +08:00
|
|
|
if a.out and "I" not in a.out and not self.isWrapped(a.ctype) and a.ctype:
|
2012-10-17 07:18:30 +08:00
|
|
|
c_prologue.append("%s %s;" % (a.ctype, a.name))
|
|
|
|
|
|
|
|
rtype = type_dict[fi.ctype].get("jni_type", "jdoubleArray")
|
2014-10-17 23:36:24 +08:00
|
|
|
clazz = ci.jname
|
2019-05-28 14:34:02 +08:00
|
|
|
cpp_code.write ( Template(
|
2012-10-17 07:18:30 +08:00
|
|
|
"""
|
2020-12-02 04:42:15 +08:00
|
|
|
JNIEXPORT $rtype JNICALL Java_org_opencv_${jmodule}_${clazz}_$fname ($argst);
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2020-12-02 04:42:15 +08:00
|
|
|
JNIEXPORT $rtype JNICALL Java_org_opencv_${jmodule}_${clazz}_$fname
|
2012-10-17 07:18:30 +08:00
|
|
|
($args)
|
|
|
|
{
|
2020-11-13 14:27:18 +08:00
|
|
|
${namespace}
|
2020-12-02 04:42:15 +08:00
|
|
|
static const char method_name[] = "$jmodule::$fname()";
|
2012-10-17 07:18:30 +08:00
|
|
|
try {
|
2019-05-28 14:34:02 +08:00
|
|
|
LOGD("%s", method_name);$prologue
|
|
|
|
$retval$cvname($cvargs);$epilogue$ret
|
2013-08-13 16:04:36 +08:00
|
|
|
} catch(const std::exception &e) {
|
|
|
|
throwJavaException(env, &e, method_name);
|
2012-10-17 07:18:30 +08:00
|
|
|
} catch (...) {
|
2013-08-13 16:04:36 +08:00
|
|
|
throwJavaException(env, 0, method_name);
|
2019-05-28 14:34:02 +08:00
|
|
|
}$default
|
2012-10-17 07:18:30 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
2019-05-28 14:34:02 +08:00
|
|
|
""" ).substitute(
|
|
|
|
rtype = rtype,
|
|
|
|
module = self.module.replace('_', '_1'),
|
2020-12-02 04:42:15 +08:00
|
|
|
jmodule = make_jmodule(self.module.replace('_', '_1')),
|
2019-05-28 14:34:02 +08:00
|
|
|
clazz = clazz.replace('_', '_1'),
|
|
|
|
fname = (fi.jname + '_' + str(suffix_counter)).replace('_', '_1'),
|
|
|
|
args = ", ".join(["%s %s" % (type_dict[a.ctype].get("jni_type"), a.name) for a in jni_args]),
|
|
|
|
argst = ", ".join([type_dict[a.ctype].get("jni_type") for a in jni_args]),
|
|
|
|
prologue = "\n " + "\n ".join(c_prologue) if c_prologue else "",
|
|
|
|
epilogue = "\n " + "\n ".join(c_epilogue) if c_epilogue else "",
|
|
|
|
ret = "\n " + ret if ret else "",
|
|
|
|
cvname = cvname,
|
|
|
|
cvargs = " " + ", ".join(cvargs) + " " if cvargs else "",
|
|
|
|
default = "\n " + default if default else "",
|
|
|
|
retval = retval,
|
2020-12-02 04:42:15 +08:00
|
|
|
namespace = make_namespace(ci)
|
2012-10-17 07:18:30 +08:00
|
|
|
) )
|
|
|
|
|
2019-05-28 14:34:02 +08:00
|
|
|
# adding method signature to dictionary
|
2016-10-08 06:13:01 +08:00
|
|
|
j_signatures.append(j_signature)
|
|
|
|
|
2012-10-17 07:18:30 +08:00
|
|
|
# processing args with default values
|
2018-07-17 18:41:46 +08:00
|
|
|
if args and args[-1].defval:
|
|
|
|
args.pop()
|
|
|
|
else:
|
2012-10-17 07:18:30 +08:00
|
|
|
break
|
|
|
|
|
|
|
|
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def gen_class(self, ci):
|
|
|
|
logging.info("%s", ci)
|
2012-10-17 07:18:30 +08:00
|
|
|
# constants
|
2019-03-02 05:32:03 +08:00
|
|
|
consts_map = {c.name: c for c in ci.private_consts}
|
|
|
|
consts_map.update({c.name: c for c in ci.consts})
|
|
|
|
def const_value(v):
|
|
|
|
if v in consts_map:
|
|
|
|
target = consts_map[v]
|
|
|
|
assert target.value != v
|
|
|
|
return const_value(target.value)
|
|
|
|
return v
|
2012-10-17 07:18:30 +08:00
|
|
|
if ci.private_consts:
|
2014-10-17 23:36:24 +08:00
|
|
|
logging.info("%s", ci.private_consts)
|
|
|
|
ci.j_code.write("""
|
2012-10-17 07:18:30 +08:00
|
|
|
private static final int
|
2019-03-02 05:32:03 +08:00
|
|
|
%s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, const_value(c.value)) for c in ci.private_consts])
|
2012-10-17 07:18:30 +08:00
|
|
|
)
|
|
|
|
if ci.consts:
|
2018-08-28 03:39:24 +08:00
|
|
|
enumTypes = set(map(lambda c: c.enumType, ci.consts))
|
|
|
|
grouped_consts = {enumType: [c for c in ci.consts if c.enumType == enumType] for enumType in enumTypes}
|
2020-11-13 03:47:54 +08:00
|
|
|
for typeName in sorted(grouped_consts.keys(), key=lambda x: str(x) if x is not None else ""):
|
|
|
|
consts = grouped_consts[typeName]
|
2018-08-28 03:39:24 +08:00
|
|
|
logging.info("%s", consts)
|
|
|
|
if typeName:
|
2020-11-13 03:47:54 +08:00
|
|
|
typeNameShort = typeName.rsplit(".", 1)[-1]
|
2018-08-28 03:39:24 +08:00
|
|
|
###################### Utilize Java enums ######################
|
|
|
|
# ci.j_code.write("""
|
|
|
|
# public enum {1} {{
|
|
|
|
# {0};
|
|
|
|
#
|
|
|
|
# private final int id;
|
|
|
|
# {1}(int id) {{ this.id = id; }}
|
|
|
|
# {1}({1} _this) {{ this.id = _this.id; }}
|
|
|
|
# public int getValue() {{ return id; }}
|
|
|
|
# }}\n\n""".format((",\n"+" "*8).join(["%s(%s)" % (c.name, c.value) for c in consts]), typeName)
|
|
|
|
# )
|
|
|
|
################################################################
|
|
|
|
ci.j_code.write("""
|
2020-11-13 03:47:54 +08:00
|
|
|
// C++: enum {1} ({2})
|
2012-10-17 07:18:30 +08:00
|
|
|
public static final int
|
2020-11-14 06:29:14 +08:00
|
|
|
{0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]), typeNameShort, typeName)
|
2018-08-28 03:39:24 +08:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
ci.j_code.write("""
|
|
|
|
// C++: enum <unnamed>
|
|
|
|
public static final int
|
|
|
|
{0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]))
|
|
|
|
)
|
2014-10-17 23:36:24 +08:00
|
|
|
# methods
|
|
|
|
for fi in ci.getAllMethods():
|
|
|
|
self.gen_func(ci, fi)
|
2012-10-17 07:18:30 +08:00
|
|
|
# props
|
|
|
|
for pi in ci.props:
|
2020-11-13 14:27:18 +08:00
|
|
|
basename = ci.fullNameOrigin()
|
2012-10-17 07:18:30 +08:00
|
|
|
# getter
|
2020-11-13 14:27:18 +08:00
|
|
|
getter_name = basename + ".get_" + pi.name
|
2014-09-19 19:31:38 +08:00
|
|
|
fi = FuncInfo( [getter_name, pi.ctype, [], []], self.namespaces ) # [ funcname, return_ctype, [modifiers], [args] ]
|
2014-10-17 23:36:24 +08:00
|
|
|
self.gen_func(ci, fi, pi.name)
|
2012-10-17 07:18:30 +08:00
|
|
|
if pi.rw:
|
|
|
|
#setter
|
2020-11-13 14:27:18 +08:00
|
|
|
setter_name = basename + ".set_" + pi.name
|
2014-09-19 19:31:38 +08:00
|
|
|
fi = FuncInfo( [ setter_name, "void", [], [ [pi.ctype, pi.name, "", [], ""] ] ], self.namespaces)
|
2014-10-17 23:36:24 +08:00
|
|
|
self.gen_func(ci, fi, pi.name)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
# manual ports
|
2014-10-17 23:36:24 +08:00
|
|
|
if ci.name in ManualFuncs:
|
2020-11-13 03:47:54 +08:00
|
|
|
for func in sorted(ManualFuncs[ci.name].keys()):
|
|
|
|
logging.info("manual function: %s", func)
|
|
|
|
fn = ManualFuncs[ci.name][func]
|
|
|
|
ci.j_code.write("\n".join(fn["j_code"]))
|
|
|
|
ci.jn_code.write("\n".join(fn["jn_code"]))
|
|
|
|
ci.cpp_code.write("\n".join(fn["cpp_code"]))
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2017-01-03 20:48:25 +08:00
|
|
|
if ci.name != self.Module or ci.base:
|
2012-10-17 07:18:30 +08:00
|
|
|
# finalize()
|
2014-10-17 23:36:24 +08:00
|
|
|
ci.j_code.write(
|
2012-10-17 07:18:30 +08:00
|
|
|
"""
|
2015-05-19 23:52:59 +08:00
|
|
|
@Override
|
|
|
|
protected void finalize() throws Throwable {
|
2012-10-17 07:18:30 +08:00
|
|
|
delete(nativeObj);
|
|
|
|
}
|
|
|
|
""" )
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
ci.jn_code.write(
|
2012-10-17 07:18:30 +08:00
|
|
|
"""
|
|
|
|
// native support for java finalize()
|
|
|
|
private static native void delete(long nativeObj);
|
|
|
|
""" )
|
|
|
|
|
|
|
|
# native support for java finalize()
|
2019-05-28 14:34:02 +08:00
|
|
|
ci.cpp_code.write(
|
2012-10-17 07:18:30 +08:00
|
|
|
"""
|
|
|
|
//
|
|
|
|
// native support for java finalize()
|
|
|
|
// static void %(cls)s::delete( __int64 self )
|
|
|
|
//
|
|
|
|
JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete(JNIEnv*, jclass, jlong);
|
|
|
|
|
|
|
|
JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete
|
|
|
|
(JNIEnv*, jclass, jlong self)
|
|
|
|
{
|
|
|
|
delete (%(cls)s*) self;
|
|
|
|
}
|
|
|
|
|
2020-11-13 14:27:18 +08:00
|
|
|
""" % {"module" : module.replace('_', '_1'), "cls" : self.smartWrap(ci, ci.fullNameCPP()), "j_cls" : ci.jname.replace('_', '_1')}
|
2012-10-17 07:18:30 +08:00
|
|
|
)
|
|
|
|
|
2014-10-17 23:36:24 +08:00
|
|
|
def getClass(self, classname):
|
|
|
|
return self.classes[classname or self.Module]
|
|
|
|
|
|
|
|
def isWrapped(self, classname):
|
|
|
|
name = classname or self.Module
|
|
|
|
return name in self.classes
|
|
|
|
|
2016-10-14 23:21:17 +08:00
|
|
|
def isSmartClass(self, ci):
|
2014-08-29 22:06:16 +08:00
|
|
|
'''
|
|
|
|
Check if class stores Ptr<T>* instead of T* in nativeObj field
|
|
|
|
'''
|
2016-10-14 23:21:17 +08:00
|
|
|
if ci.smart != None:
|
|
|
|
return ci.smart
|
|
|
|
|
2021-07-02 18:41:41 +08:00
|
|
|
ci.smart = True # smart class is not properly handled in case of base/derived classes
|
2016-10-14 23:21:17 +08:00
|
|
|
return ci.smart
|
2014-08-29 22:06:16 +08:00
|
|
|
|
2016-10-14 23:21:17 +08:00
|
|
|
def smartWrap(self, ci, fullname):
|
2014-08-29 22:06:16 +08:00
|
|
|
'''
|
2014-09-19 19:31:38 +08:00
|
|
|
Wraps fullname with Ptr<> if needed
|
2014-08-29 22:06:16 +08:00
|
|
|
'''
|
2016-10-14 23:21:17 +08:00
|
|
|
if self.isSmartClass(ci):
|
2014-09-19 19:31:38 +08:00
|
|
|
return "Ptr<" + fullname + ">"
|
|
|
|
return fullname
|
2014-08-29 22:06:16 +08:00
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
def finalize(self, output_jni_path):
|
|
|
|
list_file = os.path.join(output_jni_path, "opencv_jni.hpp")
|
|
|
|
self.save(list_file, '\n'.join(['#include "%s"' % f for f in self.cpp_files]))
|
|
|
|
|
|
|
|
|
2018-02-28 21:23:42 +08:00
|
|
|
def copy_java_files(java_files_dir, java_base_path, default_package_path='org/opencv/'):
|
2017-12-29 12:15:30 +08:00
|
|
|
global total_files, updated_files
|
|
|
|
java_files = []
|
2021-06-05 19:46:09 +08:00
|
|
|
re_filter = re.compile(r'^.+\.(java|aidl|kt)(.in)?$')
|
2017-12-29 12:15:30 +08:00
|
|
|
for root, dirnames, filenames in os.walk(java_files_dir):
|
|
|
|
java_files += [os.path.join(root, filename) for filename in filenames if re_filter.match(filename)]
|
|
|
|
java_files = [f.replace('\\', '/') for f in java_files]
|
|
|
|
|
2018-02-28 21:23:42 +08:00
|
|
|
re_package = re.compile(r'^package +(.+);')
|
2021-06-05 19:46:09 +08:00
|
|
|
re_prefix = re.compile(r'^.+[\+/]([^\+]+).(java|aidl|kt)(.in)?$')
|
2017-12-29 12:15:30 +08:00
|
|
|
for java_file in java_files:
|
|
|
|
src = checkFileRemap(java_file)
|
|
|
|
with open(src, 'r') as f:
|
|
|
|
package_line = f.readline()
|
|
|
|
m = re_prefix.match(java_file)
|
|
|
|
target_fname = (m.group(1) + '.' + m.group(2)) if m else os.path.basename(java_file)
|
|
|
|
m = re_package.match(package_line)
|
|
|
|
if m:
|
|
|
|
package = m.group(1)
|
|
|
|
package_path = package.replace('.', '/')
|
|
|
|
else:
|
2018-02-28 21:23:42 +08:00
|
|
|
package_path = default_package_path
|
2017-12-29 12:15:30 +08:00
|
|
|
#print(java_file, package_path, target_fname)
|
|
|
|
dest = os.path.join(java_base_path, os.path.join(package_path, target_fname))
|
|
|
|
assert dest[-3:] != '.in', dest + ' | ' + target_fname
|
|
|
|
mkdir_p(os.path.dirname(dest))
|
|
|
|
total_files += 1
|
|
|
|
if (not os.path.exists(dest)) or (os.stat(src).st_mtime - os.stat(dest).st_mtime > 1):
|
|
|
|
copyfile(src, dest)
|
|
|
|
updated_files += 1
|
|
|
|
|
2019-06-05 18:44:03 +08:00
|
|
|
def sanitize_java_documentation_string(doc, type):
|
|
|
|
if type == "class":
|
|
|
|
doc = doc.replace("@param ", "")
|
|
|
|
|
|
|
|
doc = re.sub(re.compile('\\\\f\\$(.*?)\\\\f\\$', re.DOTALL), '\\(' + r'\1' + '\\)', doc)
|
|
|
|
doc = re.sub(re.compile('\\\\f\\[(.*?)\\\\f\\]', re.DOTALL), '\\(' + r'\1' + '\\)', doc)
|
|
|
|
doc = re.sub(re.compile('\\\\f\\{(.*?)\\\\f\\}', re.DOTALL), '\\(' + r'\1' + '\\)', doc)
|
|
|
|
|
|
|
|
doc = doc.replace("&", "&") \
|
|
|
|
.replace("\\<", "<") \
|
|
|
|
.replace("\\>", ">") \
|
|
|
|
.replace("<", "<") \
|
|
|
|
.replace(">", ">") \
|
|
|
|
.replace("$", "$$") \
|
|
|
|
.replace("@anchor", "") \
|
|
|
|
.replace("@brief ", "").replace("\\brief ", "") \
|
|
|
|
.replace("@cite", "CITE:") \
|
|
|
|
.replace("@code{.cpp}", "<code>") \
|
|
|
|
.replace("@code{.txt}", "<code>") \
|
|
|
|
.replace("@code", "<code>") \
|
|
|
|
.replace("@copydoc", "") \
|
|
|
|
.replace("@copybrief", "") \
|
|
|
|
.replace("@date", "") \
|
|
|
|
.replace("@defgroup", "") \
|
|
|
|
.replace("@details ", "") \
|
|
|
|
.replace("@endcode", "</code>") \
|
|
|
|
.replace("@endinternal", "") \
|
|
|
|
.replace("@file", "") \
|
|
|
|
.replace("@include", "INCLUDE:") \
|
|
|
|
.replace("@ingroup", "") \
|
|
|
|
.replace("@internal", "") \
|
|
|
|
.replace("@overload", "") \
|
|
|
|
.replace("@param[in]", "@param") \
|
|
|
|
.replace("@param[out]", "@param") \
|
|
|
|
.replace("@ref", "REF:") \
|
|
|
|
.replace("@returns", "@return") \
|
|
|
|
.replace("@sa", "SEE:") \
|
|
|
|
.replace("@see", "SEE:") \
|
|
|
|
.replace("@snippet", "SNIPPET:") \
|
|
|
|
.replace("@todo", "TODO:") \
|
|
|
|
.replace("@warning ", "WARNING: ")
|
|
|
|
|
|
|
|
doc = re.sub(re.compile('\\*\\*([^\\*]+?)\\*\\*', re.DOTALL), '<b>' + r'\1' + '</b>', doc)
|
|
|
|
|
|
|
|
lines = doc.splitlines()
|
|
|
|
|
|
|
|
lines = list(map(lambda x: x[x.find('*'):].strip() if x.lstrip().startswith("*") else x, lines))
|
|
|
|
|
|
|
|
listInd = [];
|
|
|
|
indexDiff = 0;
|
|
|
|
for index, line in enumerate(lines[:]):
|
|
|
|
if line.strip().startswith("-"):
|
|
|
|
i = line.find("-")
|
|
|
|
if not listInd or i > listInd[-1]:
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "<ul>")
|
|
|
|
indexDiff += 1
|
|
|
|
listInd.append(i);
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "<li>")
|
|
|
|
indexDiff += 1
|
|
|
|
elif i == listInd[-1]:
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "</li>")
|
|
|
|
indexDiff += 1
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "<li>")
|
|
|
|
indexDiff += 1
|
|
|
|
elif len(listInd) > 1 and i == listInd[-2]:
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "</li>")
|
|
|
|
indexDiff += 1
|
|
|
|
del listInd[-1]
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "</ul>")
|
|
|
|
indexDiff += 1
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "<li>")
|
|
|
|
indexDiff += 1
|
|
|
|
else:
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "</li>")
|
|
|
|
indexDiff += 1
|
|
|
|
del listInd[-1]
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "</ul>")
|
|
|
|
indexDiff += 1
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "<ul>")
|
|
|
|
indexDiff += 1
|
|
|
|
listInd.append(i);
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "<li>")
|
|
|
|
indexDiff += 1
|
|
|
|
lines[index + indexDiff] = lines[index + indexDiff][0:i] + lines[index + indexDiff][i + 1:]
|
|
|
|
else:
|
2023-05-25 04:07:27 +08:00
|
|
|
if listInd and (not line or line == "*" or line.strip().startswith("@note") or line.strip().startswith("@param")):
|
2019-06-05 18:44:03 +08:00
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "</li>")
|
|
|
|
indexDiff += 1
|
|
|
|
del listInd[-1]
|
|
|
|
lines.insert(index + indexDiff, " "*len(listInd) + "</ul>")
|
|
|
|
indexDiff += 1
|
|
|
|
|
|
|
|
i = len(listInd) - 1
|
|
|
|
for value in enumerate(listInd):
|
|
|
|
lines.append(" "*i + " </li>")
|
|
|
|
lines.append(" "*i + "</ul>")
|
|
|
|
i -= 1;
|
|
|
|
|
|
|
|
lines = list(map(lambda x: "* " + x[1:].strip() if x.startswith("*") and x != "*" else x, lines))
|
|
|
|
lines = list(map(lambda x: x if x.startswith("*") else "* " + x if x and x != "*" else "*", lines))
|
|
|
|
|
|
|
|
lines = list(map(lambda x: x
|
|
|
|
.replace("@note", "<b>Note:</b>")
|
|
|
|
, lines))
|
|
|
|
|
|
|
|
lines = list(map(lambda x: re.sub('@b ([\\w:]+?)\\b', '<b>' + r'\1' + '</b>', x), lines))
|
|
|
|
lines = list(map(lambda x: re.sub('@c ([\\w:]+?)\\b', '<tt>' + r'\1' + '</tt>', x), lines))
|
|
|
|
lines = list(map(lambda x: re.sub('`(.*?)`', "{@code " + r'\1' + '}', x), lines))
|
|
|
|
lines = list(map(lambda x: re.sub('@p ([\\w:]+?)\\b', '{@code ' + r'\1' + '}', x), lines))
|
|
|
|
|
|
|
|
hasValues = False
|
|
|
|
for line in lines:
|
|
|
|
if line != "*":
|
|
|
|
hasValues = True
|
|
|
|
break
|
|
|
|
return "/**\n " + "\n ".join(lines) + "\n */" if hasValues else ""
|
2012-10-17 07:18:30 +08:00
|
|
|
|
|
|
|
if __name__ == "__main__":
|
2017-12-29 12:15:30 +08:00
|
|
|
# initialize logger
|
|
|
|
logging.basicConfig(filename='gen_java.log', format=None, filemode='w', level=logging.INFO)
|
|
|
|
handler = logging.StreamHandler()
|
2020-11-13 03:47:54 +08:00
|
|
|
handler.setLevel(os.environ.get('LOG_LEVEL', logging.WARNING))
|
2017-12-29 12:15:30 +08:00
|
|
|
logging.getLogger().addHandler(handler)
|
2012-10-17 07:18:30 +08:00
|
|
|
|
2017-06-10 13:57:10 +08:00
|
|
|
# parse command line parameters
|
|
|
|
import argparse
|
|
|
|
arg_parser = argparse.ArgumentParser(description='OpenCV Java Wrapper Generator')
|
|
|
|
arg_parser.add_argument('-p', '--parser', required=True, help='OpenCV header parser')
|
2017-12-29 12:15:30 +08:00
|
|
|
arg_parser.add_argument('-c', '--config', required=True, help='OpenCV modules config')
|
2017-06-10 13:57:10 +08:00
|
|
|
|
|
|
|
args=arg_parser.parse_args()
|
|
|
|
|
|
|
|
# import header parser
|
|
|
|
hdr_parser_path = os.path.abspath(args.parser)
|
2012-10-17 07:18:30 +08:00
|
|
|
if hdr_parser_path.endswith(".py"):
|
|
|
|
hdr_parser_path = os.path.dirname(hdr_parser_path)
|
|
|
|
sys.path.append(hdr_parser_path)
|
|
|
|
import hdr_parser
|
2017-06-10 13:57:10 +08:00
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
with open(args.config) as f:
|
|
|
|
config = json.load(f)
|
2017-06-10 13:57:10 +08:00
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
ROOT_DIR = config['rootdir']; assert os.path.exists(ROOT_DIR)
|
|
|
|
FILES_REMAP = { os.path.realpath(os.path.join(ROOT_DIR, f['src'])): f['target'] for f in config['files_remap'] }
|
|
|
|
logging.info("\nRemapped configured files (%d):\n%s", len(FILES_REMAP), pformat(FILES_REMAP))
|
2017-06-10 13:57:10 +08:00
|
|
|
|
2017-12-29 12:15:30 +08:00
|
|
|
dstdir = "./gen"
|
|
|
|
jni_path = os.path.join(dstdir, 'cpp'); mkdir_p(jni_path)
|
|
|
|
java_base_path = os.path.join(dstdir, 'java'); mkdir_p(java_base_path)
|
|
|
|
java_test_base_path = os.path.join(dstdir, 'test'); mkdir_p(java_test_base_path)
|
2017-06-10 13:57:10 +08:00
|
|
|
|
2023-12-07 17:56:31 +08:00
|
|
|
for (subdir, target_subdir) in [('src/java', 'java'), ('android/java', None),
|
|
|
|
('android-21/java', None), ('android-24/java', None)]:
|
2017-12-29 12:15:30 +08:00
|
|
|
if target_subdir is None:
|
|
|
|
target_subdir = subdir
|
|
|
|
java_files_dir = os.path.join(SCRIPT_DIR, subdir)
|
|
|
|
if os.path.exists(java_files_dir):
|
|
|
|
target_path = os.path.join(dstdir, target_subdir); mkdir_p(target_path)
|
|
|
|
copy_java_files(java_files_dir, target_path)
|
2017-06-10 13:57:10 +08:00
|
|
|
|
|
|
|
# launch Java Wrapper generator
|
2012-10-17 07:18:30 +08:00
|
|
|
generator = JavaWrapperGenerator()
|
2017-12-29 12:15:30 +08:00
|
|
|
|
|
|
|
gen_dict_files = []
|
|
|
|
|
|
|
|
print("JAVA: Processing OpenCV modules: %d" % len(config['modules']))
|
|
|
|
for e in config['modules']:
|
|
|
|
(module, module_location) = (e['name'], os.path.join(ROOT_DIR, e['location']))
|
|
|
|
logging.info("\n=== MODULE: %s (%s) ===\n" % (module, module_location))
|
|
|
|
|
|
|
|
java_path = os.path.join(java_base_path, 'org/opencv')
|
|
|
|
mkdir_p(java_path)
|
|
|
|
|
|
|
|
module_imports = []
|
|
|
|
module_j_code = None
|
|
|
|
module_jn_code = None
|
|
|
|
srcfiles = []
|
|
|
|
common_headers = []
|
|
|
|
|
|
|
|
misc_location = os.path.join(module_location, 'misc/java')
|
|
|
|
|
|
|
|
srcfiles_fname = os.path.join(misc_location, 'filelist')
|
|
|
|
if os.path.exists(srcfiles_fname):
|
|
|
|
with open(srcfiles_fname) as f:
|
|
|
|
srcfiles = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()]
|
|
|
|
else:
|
2018-11-17 18:59:23 +08:00
|
|
|
re_bad = re.compile(r'(private|.inl.hpp$|_inl.hpp$|.details.hpp$|_winrt.hpp$|/cuda/|/legacy/)')
|
2017-12-29 12:15:30 +08:00
|
|
|
# .h files before .hpp
|
|
|
|
h_files = []
|
|
|
|
hpp_files = []
|
|
|
|
for root, dirnames, filenames in os.walk(os.path.join(module_location, 'include')):
|
|
|
|
h_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.h')]
|
|
|
|
hpp_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.hpp')]
|
|
|
|
srcfiles = h_files + hpp_files
|
|
|
|
srcfiles = [f for f in srcfiles if not re_bad.search(f.replace('\\', '/'))]
|
|
|
|
logging.info("\nFiles (%d):\n%s", len(srcfiles), pformat(srcfiles))
|
|
|
|
|
|
|
|
common_headers_fname = os.path.join(misc_location, 'filelist_common')
|
|
|
|
if os.path.exists(common_headers_fname):
|
|
|
|
with open(common_headers_fname) as f:
|
|
|
|
common_headers = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()]
|
|
|
|
logging.info("\nCommon headers (%d):\n%s", len(common_headers), pformat(common_headers))
|
|
|
|
|
|
|
|
gendict_fname = os.path.join(misc_location, 'gen_dict.json')
|
|
|
|
if os.path.exists(gendict_fname):
|
|
|
|
with open(gendict_fname) as f:
|
|
|
|
gen_type_dict = json.load(f)
|
|
|
|
class_ignore_list += gen_type_dict.get("class_ignore_list", [])
|
|
|
|
const_ignore_list += gen_type_dict.get("const_ignore_list", [])
|
|
|
|
const_private_list += gen_type_dict.get("const_private_list", [])
|
|
|
|
missing_consts.update(gen_type_dict.get("missing_consts", {}))
|
|
|
|
type_dict.update(gen_type_dict.get("type_dict", {}))
|
|
|
|
ManualFuncs.update(gen_type_dict.get("ManualFuncs", {}))
|
|
|
|
func_arg_fix.update(gen_type_dict.get("func_arg_fix", {}))
|
2018-07-17 18:41:46 +08:00
|
|
|
namespaces_dict.update(gen_type_dict.get("namespaces_dict", {}))
|
2017-12-29 12:15:30 +08:00
|
|
|
if 'module_j_code' in gen_type_dict:
|
|
|
|
module_j_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_j_code'])))
|
|
|
|
if 'module_jn_code' in gen_type_dict:
|
|
|
|
module_jn_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_jn_code'])))
|
|
|
|
module_imports += gen_type_dict.get("module_imports", [])
|
|
|
|
|
|
|
|
java_files_dir = os.path.join(misc_location, 'src/java')
|
|
|
|
if os.path.exists(java_files_dir):
|
2018-02-28 21:23:42 +08:00
|
|
|
copy_java_files(java_files_dir, java_base_path, 'org/opencv/' + module)
|
2017-12-29 12:15:30 +08:00
|
|
|
|
|
|
|
java_test_files_dir = os.path.join(misc_location, 'test')
|
|
|
|
if os.path.exists(java_test_files_dir):
|
2018-02-28 21:23:42 +08:00
|
|
|
copy_java_files(java_test_files_dir, java_test_base_path, 'org/opencv/test/' + module)
|
2017-12-29 12:15:30 +08:00
|
|
|
|
2018-01-03 23:16:35 +08:00
|
|
|
if len(srcfiles) > 0:
|
|
|
|
generator.gen(srcfiles, module, dstdir, jni_path, java_path, common_headers)
|
|
|
|
else:
|
|
|
|
logging.info("No generated code for module: %s", module)
|
2017-12-29 12:15:30 +08:00
|
|
|
generator.finalize(jni_path)
|
|
|
|
|
|
|
|
print('Generated files: %d (updated %d)' % (total_files, updated_files))
|