gen_java.py 65.4 KB
Newer Older
1
#!/usr/bin/env python
2

3
import sys, re, os.path, errno, fnmatch
A
abratchik 已提交
4
import json
5
import logging
6
import codecs
7
from shutil import copyfile
8
from pprint import pformat
9 10
from string import Template

11 12 13
if sys.version_info[0] >= 3:
    from io import StringIO
else:
14 15 16 17 18 19
    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)
20

21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
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

A
abratchik 已提交
41 42 43
# 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 = []
44

A
abratchik 已提交
45 46 47
# list of constant names, which should be skipped by wrapper generator
# ignored constants can be defined using regular expressions
const_ignore_list = []
48

A
abratchik 已提交
49 50
# list of private constants
const_private_list = []
51

A
abratchik 已提交
52 53
# { Module : { public : [[name, val],...], private : [[]...] } }
missing_consts = {}
54 55

# c_type    : { java/jni correspondence }
A
abratchik 已提交
56 57
# Complex data types are configured for each module using misc/java/gen_dict.json

58 59 60 61 62 63 64
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" },
B
berak 已提交
65
    "char"    : { "j_type" : "char", "jn_type" : "char", "jni_type" : "jchar", "suffix" : "C" },
66 67 68 69 70 71 72
    "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" },
73 74 75 76 77 78 79 80 81 82
    "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'
    },
83 84 85 86 87 88 89 90 91
    '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'
    },
92 93
}

94 95 96 97
# 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 = {}

98
# { class : { func : {j_code, jn_code, cpp_code} } }
A
abratchik 已提交
99
ManualFuncs = {}
100

101
# { class : { func : { arg_name : {"ctype" : ctype, "attrib" : [attrib]} } } }
A
abratchik 已提交
102
func_arg_fix = {}
103

104 105 106 107 108 109 110 111 112 113 114 115 116 117
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
118

119 120 121 122
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')))
123 124

class GeneralInfo():
125
    def __init__(self, type, decl, namespaces):
126 127
        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)
128 129 130 131 132

        # parse doxygen comments
        self.params={}
        self.annotation=[]
        if type == "class":
133
            docstring="// C++: class " + self.name + "\n"
134 135
        else:
            docstring=""
136

137
        if len(decl)>5 and decl[5]:
138 139 140 141
            doc = decl[5]

            #logging.info('docstring: %s', doc)
            if re.search("(@|\\\\)deprecated", doc):
142 143
                self.annotation.append("@Deprecated")

144 145
            docstring += sanitize_java_documentation_string(doc, type)

146
        self.docstring = docstring
147 148 149 150 151 152 153

    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
154 155 156
        parent = name[:name.rfind('.')].strip()
        if len(parent) == 0:
            parent = None
157 158 159 160 161 162 163 164 165
        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>
166
            return name, parent, spaceName, ".".join(pieces[:-1]), pieces[-2], pieces[-1]
167
        elif len(pieces) == 2: # <class>.<name>
168
            return name, parent, spaceName, pieces[0], pieces[0], pieces[1]
169
        elif len(pieces) == 1: # <name>
170
            return name, parent, spaceName, "", "", pieces[0]
171
        else:
172
            return name, parent, spaceName, "", "" # error?!
173

174 175 176 177 178 179 180
    def fullNameOrigin(self):
        result = self.symbol_id
        return result

    def fullNameJAVA(self):
        result = '.'.join([self.fullParentNameJAVA(), self.jname])
        return result
181

182 183 184 185 186
    def fullNameCPP(self):
        result = self.cname
        return result

    def fullParentNameJAVA(self):
187
        result = ".".join([f for f in [self.namespace] + self.classpath.split(".") if len(f)>0])
188 189 190 191 192
        return result

    def fullParentNameCPP(self):
        result = get_cname(self.parent_id)
        return result
193

194
class ConstInfo(GeneralInfo):
195
    def __init__(self, decl, addedManually=False, namespaces=[], enumType=None):
196
        GeneralInfo.__init__(self, "const", decl, namespaces)
197
        self.value = decl[1]
198
        self.enumType = enumType
199
        self.addedManually = addedManually
200
        if self.namespace in namespaces_dict:
201 202 203
            prefix = namespaces_dict[self.namespace]
            if prefix:
                self.name = '%s_%s' % (prefix, self.name)
204

205 206 207 208 209 210 211 212 213 214 215
    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

216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
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

235
class ClassPropInfo():
236 237 238 239 240
    def __init__(self, decl): # [f_ctype, f_name, '', '/RW']
        self.ctype = decl[0]
        self.name = decl[1]
        self.rw = "/RW" in decl[3]

241 242 243
    def __repr__(self):
        return Template("PROP $ctype $name").substitute(ctype=self.ctype, name=self.name)

244 245
class ClassInfo(GeneralInfo):
    def __init__(self, decl, namespaces=[]): # [ 'class/struct cname', ': base', [modlist] ]
246
        GeneralInfo.__init__(self, "class", decl, namespaces)
247
        self.methods = []
248
        self.methods_suffixes = {}
L
luz.paz 已提交
249
        self.consts = [] # using a list to save the occurrence order
250 251 252 253
        self.private_consts = []
        self.imports = set()
        self.props= []
        self.jname = self.name
A
abratchik 已提交
254
        self.smart = None # True if class stores Ptr<T>* instead of T* in nativeObj field
255 256 257
        self.j_code = None # java code stream
        self.jn_code = None # jni code stream
        self.cpp_code = None # cpp code stream
258 259 260
        for m in decl[2]:
            if m.startswith("="):
                self.jname = m[1:]
261 262
            if m == '/Simple':
                self.smart = False
263 264 265 266 267 268 269 270 271 272 273 274

        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)

275 276
        self.base = ''
        if decl[1]:
277 278 279 280 281 282 283 284 285 286
            # 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)
287

288
    def __repr__(self):
289
        return Template("CLASS $namespace::$classpath.$name : $base").substitute(**self.__dict__)
290 291

    def getAllImports(self, module):
292 293
        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)]
294 295

    def addImports(self, ctype):
A
abratchik 已提交
296 297 298 299
        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]:
300
                self.imports.add("java.util.List")
A
abratchik 已提交
301
                self.imports.add("java.util.ArrayList")
302
                self.imports.add("org.opencv.utils.Converters")
A
abratchik 已提交
303 304
                if type_dict[ctype]["v_type"] in ("Mat", "vector_Mat"):
                    self.imports.add("org.opencv.core.Mat")
305 306 307

    def getAllMethods(self):
        result = []
A
Alexander Alekhin 已提交
308 309
        result += [fi for fi in self.methods if fi.isconstructor]
        result += [fi for fi in self.methods if not fi.isconstructor]
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        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()
333
        self.cpp_code = StringIO()
334 335
        if self.base:
            self.j_code.write(T_JAVA_START_INHERITED)
336
        else:
337 338 339 340
            if self.name != Module:
                self.j_code.write(T_JAVA_START_ORPHAN)
            else:
                self.j_code.write(T_JAVA_START_MODULE)
341
        # misc handling
342 343 344 345 346 347 348
        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)
349 350 351 352 353 354 355

    def cleanupCodeStreams(self):
        self.j_code.close()
        self.jn_code.close()
        self.cpp_code.close()

    def generateJavaCode(self, m, M):
356 357
        return Template(self.j_code.getvalue() + "\n\n" +
                         self.jn_code.getvalue() + "\n}\n").substitute(
358 359 360 361
                            module = m,
                            name = self.name,
                            jname = self.jname,
                            imports = "\n".join(self.getAllImports(M)),
362
                            docs = self.docstring,
363
                            annotation = "\n" + "\n".join(self.annotation) if self.annotation else "",
364 365 366 367 368 369
                            base = self.base)

    def generateCppCode(self):
        return self.cpp_code.getvalue()

class ArgInfo():
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    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"

385 386 387 388 389
    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)
390

391 392
class FuncInfo(GeneralInfo):
    def __init__(self, decl, namespaces=[]): # [ funcname, return_ctype, [modifiers], [args] ]
393
        GeneralInfo.__init__(self, "func", decl, namespaces)
394
        self.cname = get_cname(decl[0])
395
        self.jname = self.name
396
        self.isconstructor = self.name == self.classname
397
        if "[" in self.name:
398 399
            self.jname = "getelem"
        for m in decl[2]:
400
            if m.startswith("="):  # alias from WRAP_AS
401
                self.jname = m[1:]
402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
        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)

419 420 421
        self.static = ["","static"][ "/S" in decl[2] ]
        self.ctype = re.sub(r"^CvTermCriteria", "TermCriteria", decl[1] or "")
        self.args = []
A
abratchik 已提交
422
        func_fix_map = func_arg_fix.get(self.jname, {})
423 424
        for a in decl[3]:
            arg = a[:]
425 426 427
            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
428
            self.args.append(ArgInfo(arg))
429

430 431 432 433 434 435
    def fullClassJAVA(self):
        return self.fullParentNameJAVA()

    def fullClassCPP(self):
        return self.fullParentNameCPP()

436 437
    def __repr__(self):
        return Template("FUNC <$ctype $namespace.$classpath.$name $args>").substitute(**self.__dict__)
438

A
Alexander Alekhin 已提交
439 440 441 442
    def __lt__(self, other):
        return self.__repr__() < other.__repr__()


443 444
class JavaWrapperGenerator(object):
    def __init__(self):
445
        self.cpp_files = []
446 447 448
        self.clear()

    def clear(self):
A
Alexander Alekhin 已提交
449
        self.namespaces = ["cv"]
450
        classinfo_Mat = ClassInfo([ 'class cv.Mat', '', ['/Simple'], [] ], self.namespaces)
451
        self.classes = { "Mat" : classinfo_Mat }
452 453 454 455 456 457 458
        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):
459
        classinfo = ClassInfo(decl, namespaces=self.namespaces)
460
        if classinfo.name in class_ignore_list:
461
            logging.info('ignored: %s', classinfo)
462 463
            return
        name = classinfo.name
464
        if self.isWrapped(name) and not classinfo.base:
465
            logging.warning('duplicated: %s', classinfo)
466 467
            return
        self.classes[name] = classinfo
468
        if name in type_dict and not classinfo.base:
469
            logging.warning('duplicated: %s', classinfo)
470
            return
471 472 473 474
        if self.isSmartClass(classinfo):
            jni_name = "*((*(Ptr<"+classinfo.fullNameCPP()+">*)%(n)s_nativeObj).get())"
        else:
            jni_name = "(*("+classinfo.fullNameCPP()+"*)%(n)s_nativeObj)"
A
Alexander Alekhin 已提交
475
        type_dict.setdefault(name, {}).update(
476 477
            { "j_type" : classinfo.jname,
              "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
478 479
              "jni_name" : jni_name,
              "jni_type" : "jlong",
A
Alexander Alekhin 已提交
480 481 482 483 484
              "suffix" : "J",
              "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
            }
        )
        type_dict.setdefault(name+'*', {}).update(
485 486
            { "j_type" : classinfo.jname,
              "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
487 488
              "jni_name" : "&("+jni_name+")",
              "jni_type" : "jlong",
A
Alexander Alekhin 已提交
489 490 491 492
              "suffix" : "J",
              "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
            }
        )
493 494 495 496 497

        # 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']:
498
                    classinfo.private_consts.append( ConstInfo([n, val], addedManually=True) )
499 500
            if 'public' in missing_consts[name]:
                for (n, val) in missing_consts[name]['public']:
501
                    classinfo.consts.append( ConstInfo([n, val], addedManually=True) )
502 503 504 505 506 507

        # class props
        for p in decl[3]:
            if True: #"vector" not in p[0]:
                classinfo.props.append( ClassPropInfo(p) )
            else:
508
                logging.warning("Skipped property: [%s]" % name, p)
509 510

        if classinfo.base:
511
            classinfo.addImports(classinfo.base)
A
Alexander Alekhin 已提交
512
        type_dict.setdefault("Ptr_"+name, {}).update(
513
            { "j_type" : classinfo.jname,
514
              "jn_type" : "long", "jn_args" : (("__int64", ".getNativeObjAddr()"),),
515
              "jni_name" : "*((Ptr<"+classinfo.fullNameCPP()+">*)%(n)s_nativeObj)", "jni_type" : "jlong",
A
Alexander Alekhin 已提交
516 517 518 519
              "suffix" : "J",
              "j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
            }
        )
520
        logging.info('ok: class %s, name: %s, base: %s', classinfo, name, classinfo.base)
521

522 523
    def add_const(self, decl, enumType=None): # [ "const cname", val, [], [] ]
        constinfo = ConstInfo(decl, namespaces=self.namespaces, enumType=enumType)
524 525 526
        if constinfo.isIgnored():
            logging.info('ignored: %s', constinfo)
        else:
527 528 529 530 531
            if not self.isWrapped(constinfo.classname):
                logging.info('class not found: %s', constinfo)
                constinfo.name = constinfo.classname + '_' + constinfo.name
                constinfo.classname = ''

532 533 534 535 536 537 538 539 540 541
            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)
542

543
    def add_enum(self, decl): # [ "enum cname", "", [], [] ]
544 545 546 547 548 549
        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" }
550 551 552
        const_decls = decl[3]

        for decl in const_decls:
553
            self.add_const(decl, enumType)
554

555
    def add_func(self, decl):
556 557
        fi = FuncInfo(decl, namespaces=self.namespaces)
        classname = fi.classname or self.Module
558
        class_symbol_id = classname if self.isWrapped(classname) else fi.classpath.replace('.', '_') #('.'.join([fi.namespace, fi.classpath])[3:])
559
        if classname in class_ignore_list:
560 561 562
            logging.info('ignored: %s', fi)
        elif classname in ManualFuncs and fi.jname in ManualFuncs[classname]:
            logging.info('manual: %s', fi)
563
        elif not self.isWrapped(class_symbol_id):
564
            logging.warning('not found: %s', fi)
565
        else:
566
            self.getClass(class_symbol_id).addMethod(fi)
567 568 569 570
            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
571 572

    def save(self, path, buf):
573 574 575 576 577 578 579
        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
580
        with codecs.open(path, "w", "utf-8") as f:
581 582 583 584
            f.write(buf)
        updated_files += 1

    def gen(self, srcfiles, module, output_path, output_jni_path, output_java_path, common_headers):
585 586 587
        self.clear()
        self.module = module
        self.Module = module.capitalize()
588 589
        # TODO: support UMat versions of declarations (implement UMat-wrapper for Java)
        parser = hdr_parser.CppHeaderParser(generate_umat_decls=False)
590

591
        self.add_class( ['class cv.' + self.Module, '', [], []] ) # [ 'class/struct cname', ':bases', [modlist] [props] ]
592 593

        # scan the headers and build more descriptive maps of classes, consts, functions
594
        includes = []
595 596 597
        for hdr in common_headers:
            logging.info("\n===== Common header : %s =====", hdr)
            includes.append('#include "' + hdr + '"')
598 599
        for hdr in srcfiles:
            decls = parser.parse(hdr)
A
Alexander Alekhin 已提交
600
            self.namespaces = sorted(parser.namespaces)
601
            logging.info("\n\n===== Header: %s =====", hdr)
A
Alexander Alekhin 已提交
602
            logging.info("Namespaces: %s", sorted(parser.namespaces))
603 604
            if decls:
                includes.append('#include "' + hdr + '"')
605 606
            else:
                logging.info("Ignore header: %s", hdr)
607
            for decl in decls:
608
                logging.info("\n--- Incoming ---\n%s", pformat(decl[:5], 4)) # without docstring
609 610 611 612 613
                name = decl[0]
                if name.startswith("struct") or name.startswith("class"):
                    self.add_class(decl)
                elif name.startswith("const"):
                    self.add_const(decl)
614 615 616
                elif name.startswith("enum"):
                    # enum
                    self.add_enum(decl)
617 618 619
                else: # function
                    self.add_func(decl)

620 621
        logging.info("\n\n===== Generating... =====")
        moduleCppCode = StringIO()
622 623
        package_path = os.path.join(output_java_path, module)
        mkdir_p(package_path)
A
Alexander Alekhin 已提交
624
        for ci in sorted(self.classes.values(), key=lambda x: x.symbol_id):
625
            if ci.name == "Mat":
626
                continue
627 628 629
            ci.initCodeStreams(self.Module)
            self.gen_class(ci)
            classJavaCode = ci.generateJavaCode(self.module, self.Module)
630
            self.save("%s/%s/%s.java" % (output_java_path, module, ci.jname), classJavaCode)
631 632
            moduleCppCode.write(ci.generateCppCode())
            ci.cleanupCodeStreams()
633 634 635 636
        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())
637 638 639 640 641

    def makeReport(self):
        '''
        Returns string with generator report
        '''
642
        report = StringIO()
643 644
        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))
645
        report.write("\n".join(self.ported_func_list))
646
        report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % (len(self.skipped_func_list), total_count))
647
        report.write("".join(self.skipped_func_list))
A
Alexander Alekhin 已提交
648
        for i in sorted(self.def_args_hist.keys()):
649
            report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i]))
650
        return report.getvalue()
651

652
    def fullTypeNameCPP(self, t):
653
        if self.isWrapped(t):
654
            return self.getClass(t).fullNameCPP()
655
        else:
656
            return cast_from(t)
657

658 659 660 661 662
    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
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688

        # 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 )
689
            logging.info("SKIP:" + c_decl.strip() + "\t due to RET type " + fi.ctype)
690 691 692
            return
        for a in fi.args:
            if a.ctype not in type_dict:
A
Andrey Kamaev 已提交
693 694 695 696 697
                if not a.defval and a.ctype.endswith("*"):
                    a.defval = 0
                if a.defval:
                    a.ctype = ''
                    continue
698 699 700
                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 )
701
                logging.info("SKIP:" + c_decl.strip() + "\t due to ARG type " + a.ctype + "/" + (a.out or "I"))
702 703 704 705 706 707 708 709 710 711
                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
712
        j_signatures=[]
713
        suffix_counter = int(ci.methods_suffixes.get(fi.jname, -1))
714 715
        while True:
            suffix_counter += 1
716
            ci.methods_suffixes[fi.jname] = suffix_counter
717 718 719 720 721 722 723 724 725 726 727 728 729 730
             # 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_);") %
731
                    { "cnt" : len(fields), "args" : ", ".join(["(jdouble)_retval_" + f[1] for f in fields]) } )
732 733 734 735
            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", "", [], "" ]) )
736
            ci.addImports(fi.ctype)
737 738 739
            for a in args:
                if not a.ctype: # hidden
                    continue
740
                ci.addImports(a.ctype)
A
abratchik 已提交
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756
                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} )
757 758
                        else:
                            if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
A
abratchik 已提交
759
                                j_prologue.append( "Mat %s_mat = new Mat();" % a.name )
760 761
                            else:
                                j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
A
abratchik 已提交
762 763 764 765 766 767 768 769 770 771 772 773 774
                        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))
775 776
                else:
                    fields = type_dict[a.ctype].get("jn_args", ((a.ctype, ""),))
777
                    if "I" in a.out or not a.out or self.isWrapped(a.ctype): # input arg, pass by primitive fields
778 779
                        for f in fields:
                            jn_args.append ( ArgInfo([ f[0], a.name + f[1], "", [], "" ]) )
780
                            jni_args.append( ArgInfo([ f[0], a.name + normalize_field_name(f[1]), "", [], "" ]) )
A
abratchik 已提交
781
                    if "O" in a.out and not self.isWrapped(a.ctype): # out arg, pass as double[]
782 783 784
                        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)) )
785
                        c_epilogue.append(
786
                            "jdouble tmp_%(n)s[%(cnt)i] = {%(args)s}; env->SetDoubleArrayRegion(%(n)s_out, 0, %(cnt)i, tmp_%(n)s);" %
787
                            { "n" : a.name, "cnt" : len(fields), "args" : ", ".join(["(jdouble)" + a.name + f[1] for f in fields]) } )
A
abratchik 已提交
788 789
                        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"]})
790 791 792 793 794 795 796 797 798 799
                        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) + "; } ")

800 801 802 803 804 805
            # 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"]
A
abratchik 已提交
806
                if a.out and jt in ('bool', 'int', 'long', 'float', 'double'):
807 808 809 810 811 812
                    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)

813
            if j_signature in j_signatures:
814
                if args:
815
                    args.pop()
816 817 818
                    continue
                else:
                    break
819 820 821 822 823

            # 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);
824 825 826 827
            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),
828
                args = ", ".join(["%s %s" % (type_dict[a.ctype]["jn_type"], normalize_field_name(a.name)) for a in jn_args])
829
            ) )
830 831 832 833

            # java part:

            #java doc comment
834
            if fi.docstring:
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
                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
A
Alexander Alekhin 已提交
857
                        line = line.replace('@result ', '@return ')  # @result is valid in Doxygen, but invalid in Javadoc
858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874
                        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:
875 876 877 878
                    j_code.write(" "*4 + line + "\n")
            if fi.annotation:
                j_code.write(" "*4 + "\n".join(fi.annotation) + "\n")

879 880 881 882 883 884 885
            # 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]
886
            ret_val = type_dict[ret_type]["j_type"] + " retVal = " if j_epilogue else "return "
887
            tail = ""
888
            ret = "return retVal;" if j_epilogue else ""
A
abratchik 已提交
889
            if "v_type" in type_dict[ret_type]:
890
                j_type = type_dict[ret_type]["j_type"]
A
abratchik 已提交
891 892 893 894 895 896 897 898
                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);')
899
                        ret = "return retVal;"
900
            elif ret_type.startswith("Ptr_"):
901
                constructor = type_dict[ret_type]["j_type"] + ".__fromPtr__("
902 903 904 905
                if j_epilogue:
                    ret_val = type_dict[fi.ctype]["j_type"] + " retVal = " + constructor
                else:
                    ret_val = "return " + constructor
906
                tail = ")"
907 908
            elif ret_type == "void":
                ret_val = ""
909
                ret = ""
910
            elif ret_type == "": # c-tor
911
                if fi.classname and ci.base:
912 913
                    ret_val = "super("
                    tail = ")"
914 915
                else:
                    ret_val = "nativeObj = "
916
                ret = ""
917
            elif self.isWrapped(ret_type): # wrapped class
918
                constructor = self.getClass(ret_type).jname + "("
919 920 921 922
                if j_epilogue:
                    ret_val = type_dict[ret_type]["j_type"] + " retVal = new " + constructor
                else:
                    ret_val = "return new " + constructor
923 924
                tail = ")"
            elif "jn_type" not in type_dict[ret_type]:
925
                constructor = type_dict[ret_type]["j_type"] + "("
926 927 928 929
                if j_epilogue:
                    ret_val = type_dict[fi.ctype]["j_type"] + " retVal = new " + constructor
                else:
                    ret_val = "return new " + constructor
930 931 932 933 934 935
                tail = ")"

            static = "static"
            if fi.classname:
                static = fi.static

936
            j_code.write( Template(
937
"""    public $static$j_type$j_name($j_args) {$prologue
938
        $ret_val$jn_name($jn_args_call)$tail;$epilogue$ret
939 940 941
    }

"""
942 943 944 945 946 947 948
                ).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 "",
949
                    j_type=type_dict[fi.ctype]["j_type"] + " " if type_dict[fi.ctype]["j_type"] else "",
950 951 952 953
                    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] ),
954 955 956 957 958 959
                )
            )


            # cpp part:
            # jni_func(..) { _retval_ = cv_func(..); return _retval_; }
960
            ret = "return _retval_;" if c_epilogue else ""
961 962
            default = "return 0;"
            if fi.ctype == "void":
963 964
                ret = ""
                default = ""
965
            elif not fi.ctype: # c-tor
966
                if self.isSmartClass(ci):
967
                    ret = "return (jlong)(new Ptr<%(ctype)s>(_retval_));" % { 'ctype': fi.fullClassCPP() }
968 969
                else:
                    ret = "return (jlong) _retval_;"
A
abratchik 已提交
970 971 972
            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_;"
973
            elif fi.ctype in ['String', 'string']:
974 975
                ret = "return env->NewStringUTF(_retval_.c_str());"
                default = 'return env->NewStringUTF("");'
976
            elif self.isWrapped(fi.ctype): # wrapped class:
977 978 979 980 981 982 983
                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)
984
            elif fi.ctype.startswith('Ptr_'):
985
                c_prologue.append("typedef Ptr<%s> %s;" % (self.fullTypeNameCPP(fi.ctype[4:]), fi.ctype))
M
mshabunin 已提交
986
                ret = "return (jlong)(new %(ctype)s(_retval_));" % { 'ctype':fi.ctype }
987
            elif self.isWrapped(ret_type): # pointer to wrapped class:
988 989 990 991 992 993 994 995 996 997 998 999
                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 + ";//"

1000 1001
            cvname = fi.fullNameCPP()
            retval = self.fullTypeNameCPP(fi.ctype) + " _retval_ = " if ret else "return "
1002 1003
            if fi.ctype == "void":
                retval = ""
1004
            elif fi.ctype == "String":
1005
                retval = "cv::" + self.fullTypeNameCPP(fi.ctype) + " _retval_ = "
1006
            elif fi.ctype == "string":
1007
                retval = "std::string _retval_ = "
A
abratchik 已提交
1008
            elif "v_type" in type_dict[fi.ctype]: # vector is returned
1009
                retval = type_dict[fi.ctype]['jni_var'] % {"n" : '_ret_val_vector_'} + " = "
A
abratchik 已提交
1010 1011 1012 1013
                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:
1014 1015 1016 1017
                    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_);")
1018
            if fi.classname:
1019
                if not fi.ctype: # c-tor
1020
                    if self.isSmartClass(ci):
1021 1022
                        retval = self.smartWrap(ci, fi.fullClassCPP()) + " _retval_ = "
                        cvname = "makePtr<" + fi.fullClassCPP() +">"
1023
                    else:
1024 1025
                        retval = fi.fullClassCPP() + "* _retval_ = "
                        cvname = "new " + fi.fullClassCPP()
1026
                elif fi.static:
1027
                    cvname = fi.fullNameCPP()
1028
                else:
A
abratchik 已提交
1029
                    cvname = ("me->" if  not self.isSmartClass(ci) else "(*me)->") + name
1030 1031
                    c_prologue.append(
                        "%(cls)s* me = (%(cls)s*) self; //TODO: check for NULL"
1032
                            % { "cls" : self.smartWrap(ci, fi.fullClassCPP())}
1033 1034 1035 1036 1037 1038 1039
                    )
            cvargs = []
            for a in args:
                if a.pointer:
                    jni_name = "&%(n)s"
                else:
                    jni_name = "%(n)s"
1040 1041 1042
                    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)
1043
                        jni_name  = "(%s)%s" % (cast_to(a.ctype), jni_name)
1044 1045 1046
                if not a.ctype: # hidden
                    jni_name = a.defval
                cvargs.append( type_dict[a.ctype].get("jni_name", jni_name) % {"n" : a.name})
A
abratchik 已提交
1047
                if "v_type" not in type_dict[a.ctype]:
1048
                    if ("I" in a.out or not a.out or self.isWrapped(a.ctype)) and "jni_var" in type_dict[a.ctype]: # complex type
1049
                        c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")
1050
                    if a.out and "I" not in a.out and not self.isWrapped(a.ctype) and a.ctype:
1051 1052 1053
                        c_prologue.append("%s %s;" % (a.ctype, a.name))

            rtype = type_dict[fi.ctype].get("jni_type", "jdoubleArray")
1054
            clazz = ci.jname
1055
            cpp_code.write ( Template(
1056 1057 1058 1059 1060 1061
"""
JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname ($argst);

JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname
  ($args)
{
1062
    ${namespace}
1063
    static const char method_name[] = "$module::$fname()";
1064
    try {
1065 1066
        LOGD("%s", method_name);$prologue
        $retval$cvname($cvargs);$epilogue$ret
1067 1068
    } catch(const std::exception &e) {
        throwJavaException(env, &e, method_name);
1069
    } catch (...) {
1070
        throwJavaException(env, 0, method_name);
1071
    }$default
1072 1073 1074
}


1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
""" ).substitute(
        rtype = rtype,
        module = self.module.replace('_', '_1'),
        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,
1089
        namespace = ('using namespace ' + ci.namespace.replace('.', '::') + ';') if ci.namespace and ci.namespace != 'cv' else ''
1090 1091
    ) )

1092
            # adding method signature to dictionary
1093 1094
            j_signatures.append(j_signature)

1095
            # processing args with default values
1096 1097 1098
            if args and args[-1].defval:
                args.pop()
            else:
1099 1100 1101 1102
                break



1103 1104
    def gen_class(self, ci):
        logging.info("%s", ci)
1105
        # constants
1106 1107 1108 1109 1110 1111 1112 1113
        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
1114
        if ci.private_consts:
1115 1116
            logging.info("%s", ci.private_consts)
            ci.j_code.write("""
1117
    private static final int
1118
            %s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, const_value(c.value)) for c in ci.private_consts])
1119 1120
            )
        if ci.consts:
1121 1122
            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}
A
Alexander Alekhin 已提交
1123 1124
            for typeName in sorted(grouped_consts.keys(), key=lambda x: str(x) if x is not None else ""):
                consts = grouped_consts[typeName]
1125 1126
                logging.info("%s", consts)
                if typeName:
A
Alexander Alekhin 已提交
1127
                    typeNameShort = typeName.rsplit(".", 1)[-1]
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
###################### 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("""
A
Alexander Alekhin 已提交
1141
    // C++: enum {1} ({2})
1142
    public static final int
1143
            {0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]), typeNameShort, typeName)
1144 1145 1146 1147 1148 1149 1150
                    )
                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]))
                    )
1151 1152 1153
        # methods
        for fi in ci.getAllMethods():
            self.gen_func(ci, fi)
1154 1155
        # props
        for pi in ci.props:
1156
            basename = ci.fullNameOrigin()
1157
            # getter
1158
            getter_name = basename + ".get_" + pi.name
1159
            fi = FuncInfo( [getter_name, pi.ctype, [], []], self.namespaces ) # [ funcname, return_ctype, [modifiers], [args] ]
1160
            self.gen_func(ci, fi, pi.name)
1161 1162
            if pi.rw:
                #setter
1163
                setter_name = basename + ".set_" + pi.name
1164
                fi = FuncInfo( [ setter_name, "void", [], [ [pi.ctype, pi.name, "", [], ""] ] ], self.namespaces)
1165
                self.gen_func(ci, fi, pi.name)
1166 1167

        # manual ports
1168
        if ci.name in ManualFuncs:
A
Alexander Alekhin 已提交
1169 1170 1171 1172 1173 1174
            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"]))
1175

1176
        if ci.name != self.Module or ci.base:
1177
            # finalize()
1178
            ci.j_code.write(
1179
"""
1180 1181
    @Override
    protected void finalize() throws Throwable {
1182 1183 1184 1185
        delete(nativeObj);
    }
""" )

1186
            ci.jn_code.write(
1187 1188 1189 1190 1191 1192
"""
    // native support for java finalize()
    private static native void delete(long nativeObj);
""" )

            # native support for java finalize()
1193
            ci.cpp_code.write(
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
"""
//
//  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;
}

1207
""" % {"module" : module.replace('_', '_1'), "cls" : self.smartWrap(ci, ci.fullNameCPP()), "j_cls" : ci.jname.replace('_', '_1')}
1208 1209
            )

1210 1211 1212 1213 1214 1215 1216
    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

A
abratchik 已提交
1217
    def isSmartClass(self, ci):
1218 1219 1220
        '''
        Check if class stores Ptr<T>* instead of T* in nativeObj field
        '''
A
abratchik 已提交
1221 1222 1223
        if ci.smart != None:
            return ci.smart

1224
        ci.smart = True  # smart class is not properly handled in case of base/derived classes
A
abratchik 已提交
1225
        return ci.smart
1226

A
abratchik 已提交
1227
    def smartWrap(self, ci, fullname):
1228
        '''
1229
        Wraps fullname with Ptr<> if needed
1230
        '''
A
abratchik 已提交
1231
        if self.isSmartClass(ci):
1232 1233
            return "Ptr<" + fullname + ">"
        return fullname
1234

1235 1236 1237 1238 1239
    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]))


1240
def copy_java_files(java_files_dir, java_base_path, default_package_path='org/opencv/'):
1241 1242
    global total_files, updated_files
    java_files = []
G
Giles Payne 已提交
1243
    re_filter = re.compile(r'^.+\.(java|aidl|kt)(.in)?$')
1244 1245 1246 1247
    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]

1248
    re_package = re.compile(r'^package +(.+);')
G
Giles Payne 已提交
1249
    re_prefix = re.compile(r'^.+[\+/]([^\+]+).(java|aidl|kt)(.in)?$')
1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260
    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:
1261
            package_path = default_package_path
1262 1263 1264 1265 1266 1267 1268 1269 1270
        #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

1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355
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("&", "&amp;") \
        .replace("\\<", "&lt;") \
        .replace("\\>", "&gt;") \
        .replace("<", "&lt;") \
        .replace(">", "&gt;") \
        .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:
1356
            if listInd and (not line or line == "*" or line.strip().startswith("@note") or line.strip().startswith("@param")):
1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
                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 ""
1387 1388

if __name__ == "__main__":
1389 1390 1391
    # initialize logger
    logging.basicConfig(filename='gen_java.log', format=None, filemode='w', level=logging.INFO)
    handler = logging.StreamHandler()
A
Alexander Alekhin 已提交
1392
    handler.setLevel(os.environ.get('LOG_LEVEL', logging.WARNING))
1393
    logging.getLogger().addHandler(handler)
1394

A
abratchik 已提交
1395 1396 1397 1398
    # 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')
1399
    arg_parser.add_argument('-c', '--config', required=True, help='OpenCV modules config')
A
abratchik 已提交
1400 1401 1402 1403 1404

    args=arg_parser.parse_args()

    # import header parser
    hdr_parser_path = os.path.abspath(args.parser)
1405 1406 1407 1408
    if hdr_parser_path.endswith(".py"):
        hdr_parser_path = os.path.dirname(hdr_parser_path)
    sys.path.append(hdr_parser_path)
    import hdr_parser
A
abratchik 已提交
1409

1410 1411
    with open(args.config) as f:
        config = json.load(f)
A
abratchik 已提交
1412

1413 1414 1415
    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))
A
abratchik 已提交
1416

1417 1418 1419 1420
    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)
A
abratchik 已提交
1421

1422 1423 1424 1425 1426 1427 1428
    for (subdir, target_subdir) in [('src/java', 'java'), ('android/java', None), ('android-21/java', None)]:
        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)
A
abratchik 已提交
1429 1430

    # launch Java Wrapper generator
1431
    generator = JavaWrapperGenerator()
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455

    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:
1456
            re_bad = re.compile(r'(private|.inl.hpp$|_inl.hpp$|.details.hpp$|_winrt.hpp$|/cuda/|/legacy/)')
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483
            # .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", {}))
1484
            namespaces_dict.update(gen_type_dict.get("namespaces_dict", {}))
1485 1486 1487 1488 1489 1490 1491 1492
            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):
1493
            copy_java_files(java_files_dir, java_base_path, 'org/opencv/' + module)
1494 1495 1496

        java_test_files_dir = os.path.join(misc_location, 'test')
        if os.path.exists(java_test_files_dir):
1497
            copy_java_files(java_test_files_dir, java_test_base_path, 'org/opencv/test/' + module)
1498

1499 1500 1501 1502
        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)
1503 1504 1505
    generator.finalize(jni_path)

    print('Generated files: %d (updated %d)' % (total_files, updated_files))