Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Tetragramm
GitHub Repository: Tetragramm/opencv
Path: blob/master/modules/java/generator/gen_java.py
16337 views
1
#!/usr/bin/env python
2
3
import sys, re, os.path, errno, fnmatch
4
import json
5
import logging
6
from shutil import copyfile
7
from pprint import pformat
8
from string import Template
9
10
if sys.version_info[0] >= 3:
11
from io import StringIO
12
else:
13
from cStringIO import StringIO
14
15
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
16
17
# list of modules + files remap
18
config = None
19
ROOT_DIR = None
20
FILES_REMAP = {}
21
def checkFileRemap(path):
22
path = os.path.realpath(path)
23
if path in FILES_REMAP:
24
return FILES_REMAP[path]
25
assert path[-3:] != '.in', path
26
return path
27
28
total_files = 0
29
updated_files = 0
30
31
module_imports = []
32
module_j_code = None
33
module_jn_code = None
34
35
# list of class names, which should be skipped by wrapper generator
36
# the list is loaded from misc/java/gen_dict.json defined for the module and its dependencies
37
class_ignore_list = []
38
39
# list of constant names, which should be skipped by wrapper generator
40
# ignored constants can be defined using regular expressions
41
const_ignore_list = []
42
43
# list of private constants
44
const_private_list = []
45
46
# { Module : { public : [[name, val],...], private : [[]...] } }
47
missing_consts = {}
48
49
# c_type : { java/jni correspondence }
50
# Complex data types are configured for each module using misc/java/gen_dict.json
51
52
type_dict = {
53
# "simple" : { j_type : "?", jn_type : "?", jni_type : "?", suffix : "?" },
54
"" : { "j_type" : "", "jn_type" : "long", "jni_type" : "jlong" }, # c-tor ret_type
55
"void" : { "j_type" : "void", "jn_type" : "void", "jni_type" : "void" },
56
"env" : { "j_type" : "", "jn_type" : "", "jni_type" : "JNIEnv*"},
57
"cls" : { "j_type" : "", "jn_type" : "", "jni_type" : "jclass"},
58
"bool" : { "j_type" : "boolean", "jn_type" : "boolean", "jni_type" : "jboolean", "suffix" : "Z" },
59
"char" : { "j_type" : "char", "jn_type" : "char", "jni_type" : "jchar", "suffix" : "C" },
60
"int" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
61
"long" : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
62
"float" : { "j_type" : "float", "jn_type" : "float", "jni_type" : "jfloat", "suffix" : "F" },
63
"double" : { "j_type" : "double", "jn_type" : "double", "jni_type" : "jdouble", "suffix" : "D" },
64
"size_t" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
65
"__int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
66
"int64" : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
67
"double[]": { "j_type" : "double[]", "jn_type" : "double[]", "jni_type" : "jdoubleArray", "suffix" : "_3D" }
68
}
69
70
# Defines a rule to add extra prefixes for names from specific namespaces.
71
# In example, cv::fisheye::stereoRectify from namespace fisheye is wrapped as fisheye_stereoRectify
72
namespaces_dict = {}
73
74
# { class : { func : {j_code, jn_code, cpp_code} } }
75
ManualFuncs = {}
76
77
# { class : { func : { arg_name : {"ctype" : ctype, "attrib" : [attrib]} } } }
78
func_arg_fix = {}
79
80
def read_contents(fname):
81
with open(fname, 'r') as f:
82
data = f.read()
83
return data
84
85
def mkdir_p(path):
86
''' mkdir -p '''
87
try:
88
os.makedirs(path)
89
except OSError as exc:
90
if exc.errno == errno.EEXIST and os.path.isdir(path):
91
pass
92
else:
93
raise
94
95
T_JAVA_START_INHERITED = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class_inherited.prolog'))
96
T_JAVA_START_ORPHAN = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_class.prolog'))
97
T_JAVA_START_MODULE = read_contents(os.path.join(SCRIPT_DIR, 'templates/java_module.prolog'))
98
T_CPP_MODULE = Template(read_contents(os.path.join(SCRIPT_DIR, 'templates/cpp_module.template')))
99
100
class GeneralInfo():
101
def __init__(self, type, decl, namespaces):
102
self.namespace, self.classpath, self.classname, self.name = self.parseName(decl[0], namespaces)
103
104
# parse doxygen comments
105
self.params={}
106
self.annotation=[]
107
if type == "class":
108
docstring="// C++: class " + self.name + "\n//javadoc: " + self.name
109
else:
110
docstring=""
111
if len(decl)>5 and decl[5]:
112
#logging.info('docstring: %s', decl[5])
113
if re.search("(@|\\\\)deprecated", decl[5]):
114
self.annotation.append("@Deprecated")
115
116
self.docstring = docstring
117
118
def parseName(self, name, namespaces):
119
'''
120
input: full name and available namespaces
121
returns: (namespace, classpath, classname, name)
122
'''
123
name = name[name.find(" ")+1:].strip() # remove struct/class/const prefix
124
spaceName = ""
125
localName = name # <classes>.<name>
126
for namespace in sorted(namespaces, key=len, reverse=True):
127
if name.startswith(namespace + "."):
128
spaceName = namespace
129
localName = name.replace(namespace + ".", "")
130
break
131
pieces = localName.split(".")
132
if len(pieces) > 2: # <class>.<class>.<class>.<name>
133
return spaceName, ".".join(pieces[:-1]), pieces[-2], pieces[-1]
134
elif len(pieces) == 2: # <class>.<name>
135
return spaceName, pieces[0], pieces[0], pieces[1]
136
elif len(pieces) == 1: # <name>
137
return spaceName, "", "", pieces[0]
138
else:
139
return spaceName, "", "" # error?!
140
141
def fullName(self, isCPP=False):
142
result = ".".join([self.fullClass(), self.name])
143
return result if not isCPP else get_cname(result)
144
145
def fullClass(self, isCPP=False):
146
result = ".".join([f for f in [self.namespace] + self.classpath.split(".") if len(f)>0])
147
return result if not isCPP else get_cname(result)
148
149
class ConstInfo(GeneralInfo):
150
def __init__(self, decl, addedManually=False, namespaces=[], enumType=None):
151
GeneralInfo.__init__(self, "const", decl, namespaces)
152
self.cname = get_cname(self.name)
153
self.value = decl[1]
154
self.enumType = enumType
155
self.addedManually = addedManually
156
if self.namespace in namespaces_dict:
157
self.name = '%s_%s' % (namespaces_dict[self.namespace], self.name)
158
159
def __repr__(self):
160
return Template("CONST $name=$value$manual").substitute(name=self.name,
161
value=self.value,
162
manual="(manual)" if self.addedManually else "")
163
164
def isIgnored(self):
165
for c in const_ignore_list:
166
if re.match(c, self.name):
167
return True
168
return False
169
170
def normalize_field_name(name):
171
return name.replace(".","_").replace("[","").replace("]","").replace("_getNativeObjAddr()","_nativeObj")
172
173
def normalize_class_name(name):
174
return re.sub(r"^cv\.", "", name).replace(".", "_")
175
176
def get_cname(name):
177
return name.replace(".", "::")
178
179
def cast_from(t):
180
if t in type_dict and "cast_from" in type_dict[t]:
181
return type_dict[t]["cast_from"]
182
return t
183
184
def cast_to(t):
185
if t in type_dict and "cast_to" in type_dict[t]:
186
return type_dict[t]["cast_to"]
187
return t
188
189
class ClassPropInfo():
190
def __init__(self, decl): # [f_ctype, f_name, '', '/RW']
191
self.ctype = decl[0]
192
self.name = decl[1]
193
self.rw = "/RW" in decl[3]
194
195
def __repr__(self):
196
return Template("PROP $ctype $name").substitute(ctype=self.ctype, name=self.name)
197
198
class ClassInfo(GeneralInfo):
199
def __init__(self, decl, namespaces=[]): # [ 'class/struct cname', ': base', [modlist] ]
200
GeneralInfo.__init__(self, "class", decl, namespaces)
201
self.cname = get_cname(self.name)
202
self.methods = []
203
self.methods_suffixes = {}
204
self.consts = [] # using a list to save the occurrence order
205
self.private_consts = []
206
self.imports = set()
207
self.props= []
208
self.jname = self.name
209
self.smart = None # True if class stores Ptr<T>* instead of T* in nativeObj field
210
self.j_code = None # java code stream
211
self.jn_code = None # jni code stream
212
self.cpp_code = None # cpp code stream
213
for m in decl[2]:
214
if m.startswith("="):
215
self.jname = m[1:]
216
self.base = ''
217
if decl[1]:
218
#self.base = re.sub(r"\b"+self.jname+r"\b", "", decl[1].replace(":", "")).strip()
219
self.base = re.sub(r"^.*:", "", decl[1].split(",")[0]).strip().replace(self.jname, "")
220
221
def __repr__(self):
222
return Template("CLASS $namespace::$classpath.$name : $base").substitute(**self.__dict__)
223
224
def getAllImports(self, module):
225
return ["import %s;" % c for c in sorted(self.imports) if not c.startswith('org.opencv.'+module)]
226
227
def addImports(self, ctype):
228
if ctype in type_dict:
229
if "j_import" in type_dict[ctype]:
230
self.imports.add(type_dict[ctype]["j_import"])
231
if "v_type" in type_dict[ctype]:
232
self.imports.add("java.util.List")
233
self.imports.add("java.util.ArrayList")
234
self.imports.add("org.opencv.utils.Converters")
235
if type_dict[ctype]["v_type"] in ("Mat", "vector_Mat"):
236
self.imports.add("org.opencv.core.Mat")
237
238
def getAllMethods(self):
239
result = []
240
result.extend([fi for fi in sorted(self.methods) if fi.isconstructor])
241
result.extend([fi for fi in sorted(self.methods) if not fi.isconstructor])
242
return result
243
244
def addMethod(self, fi):
245
self.methods.append(fi)
246
247
def getConst(self, name):
248
for cand in self.consts + self.private_consts:
249
if cand.name == name:
250
return cand
251
return None
252
253
def addConst(self, constinfo):
254
# choose right list (public or private)
255
consts = self.consts
256
for c in const_private_list:
257
if re.match(c, constinfo.name):
258
consts = self.private_consts
259
break
260
consts.append(constinfo)
261
262
def initCodeStreams(self, Module):
263
self.j_code = StringIO()
264
self.jn_code = StringIO()
265
self.cpp_code = StringIO();
266
if self.base:
267
self.j_code.write(T_JAVA_START_INHERITED)
268
else:
269
if self.name != Module:
270
self.j_code.write(T_JAVA_START_ORPHAN)
271
else:
272
self.j_code.write(T_JAVA_START_MODULE)
273
# misc handling
274
if self.name == Module:
275
for i in module_imports or []:
276
self.imports.add(i)
277
if module_j_code:
278
self.j_code.write(module_j_code)
279
if module_jn_code:
280
self.jn_code.write(module_jn_code)
281
282
def cleanupCodeStreams(self):
283
self.j_code.close()
284
self.jn_code.close()
285
self.cpp_code.close()
286
287
def generateJavaCode(self, m, M):
288
return Template(self.j_code.getvalue() + "\n\n" + \
289
self.jn_code.getvalue() + "\n}\n").substitute(\
290
module = m,
291
name = self.name,
292
jname = self.jname,
293
imports = "\n".join(self.getAllImports(M)),
294
docs = self.docstring,
295
annotation = "\n".join(self.annotation),
296
base = self.base)
297
298
def generateCppCode(self):
299
return self.cpp_code.getvalue()
300
301
class ArgInfo():
302
def __init__(self, arg_tuple): # [ ctype, name, def val, [mod], argno ]
303
self.pointer = False
304
ctype = arg_tuple[0]
305
if ctype.endswith("*"):
306
ctype = ctype[:-1]
307
self.pointer = True
308
self.ctype = ctype
309
self.name = arg_tuple[1]
310
self.defval = arg_tuple[2]
311
self.out = ""
312
if "/O" in arg_tuple[3]:
313
self.out = "O"
314
if "/IO" in arg_tuple[3]:
315
self.out = "IO"
316
317
def __repr__(self):
318
return Template("ARG $ctype$p $name=$defval").substitute(ctype=self.ctype,
319
p=" *" if self.pointer else "",
320
name=self.name,
321
defval=self.defval)
322
323
class FuncInfo(GeneralInfo):
324
def __init__(self, decl, namespaces=[]): # [ funcname, return_ctype, [modifiers], [args] ]
325
GeneralInfo.__init__(self, "func", decl, namespaces)
326
self.cname = get_cname(decl[0])
327
self.jname = self.name
328
self.isconstructor = self.name == self.classname
329
if "[" in self.name:
330
self.jname = "getelem"
331
if self.namespace in namespaces_dict:
332
self.jname = '%s_%s' % (namespaces_dict[self.namespace], self.jname)
333
for m in decl[2]:
334
if m.startswith("="):
335
self.jname = m[1:]
336
self.static = ["","static"][ "/S" in decl[2] ]
337
self.ctype = re.sub(r"^CvTermCriteria", "TermCriteria", decl[1] or "")
338
self.args = []
339
func_fix_map = func_arg_fix.get(self.jname, {})
340
for a in decl[3]:
341
arg = a[:]
342
arg_fix_map = func_fix_map.get(arg[1], {})
343
arg[0] = arg_fix_map.get('ctype', arg[0]) #fixing arg type
344
arg[3] = arg_fix_map.get('attrib', arg[3]) #fixing arg attrib
345
self.args.append(ArgInfo(arg))
346
347
def __repr__(self):
348
return Template("FUNC <$ctype $namespace.$classpath.$name $args>").substitute(**self.__dict__)
349
350
def __lt__(self, other):
351
return self.__repr__() < other.__repr__()
352
353
354
class JavaWrapperGenerator(object):
355
def __init__(self):
356
self.cpp_files = []
357
self.clear()
358
359
def clear(self):
360
self.namespaces = set(["cv"])
361
self.classes = { "Mat" : ClassInfo([ 'class Mat', '', [], [] ], self.namespaces) }
362
self.module = ""
363
self.Module = ""
364
self.ported_func_list = []
365
self.skipped_func_list = []
366
self.def_args_hist = {} # { def_args_cnt : funcs_cnt }
367
368
def add_class(self, decl):
369
classinfo = ClassInfo(decl, namespaces=self.namespaces)
370
if classinfo.name in class_ignore_list:
371
logging.info('ignored: %s', classinfo)
372
return
373
name = classinfo.name
374
if self.isWrapped(name) and not classinfo.base:
375
logging.warning('duplicated: %s', classinfo)
376
return
377
self.classes[name] = classinfo
378
if name in type_dict and not classinfo.base:
379
logging.warning('duplicated: %s', classinfo)
380
return
381
type_dict.setdefault(name, {}).update(
382
{ "j_type" : classinfo.jname,
383
"jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
384
"jni_name" : "(*("+classinfo.fullName(isCPP=True)+"*)%(n)s_nativeObj)", "jni_type" : "jlong",
385
"suffix" : "J",
386
"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
387
}
388
)
389
type_dict.setdefault(name+'*', {}).update(
390
{ "j_type" : classinfo.jname,
391
"jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
392
"jni_name" : "("+classinfo.fullName(isCPP=True)+"*)%(n)s_nativeObj", "jni_type" : "jlong",
393
"suffix" : "J",
394
"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
395
}
396
)
397
398
# missing_consts { Module : { public : [[name, val],...], private : [[]...] } }
399
if name in missing_consts:
400
if 'private' in missing_consts[name]:
401
for (n, val) in missing_consts[name]['private']:
402
classinfo.private_consts.append( ConstInfo([n, val], addedManually=True) )
403
if 'public' in missing_consts[name]:
404
for (n, val) in missing_consts[name]['public']:
405
classinfo.consts.append( ConstInfo([n, val], addedManually=True) )
406
407
# class props
408
for p in decl[3]:
409
if True: #"vector" not in p[0]:
410
classinfo.props.append( ClassPropInfo(p) )
411
else:
412
logging.warning("Skipped property: [%s]" % name, p)
413
414
if classinfo.base:
415
classinfo.addImports(classinfo.base)
416
type_dict.setdefault("Ptr_"+name, {}).update(
417
{ "j_type" : classinfo.jname,
418
"jn_type" : "long", "jn_args" : (("__int64", ".getNativeObjAddr()"),),
419
"jni_name" : "*((Ptr<"+classinfo.fullName(isCPP=True)+">*)%(n)s_nativeObj)", "jni_type" : "jlong",
420
"suffix" : "J",
421
"j_import" : "org.opencv.%s.%s" % (self.module, classinfo.jname)
422
}
423
)
424
logging.info('ok: class %s, name: %s, base: %s', classinfo, name, classinfo.base)
425
426
def add_const(self, decl, enumType=None): # [ "const cname", val, [], [] ]
427
constinfo = ConstInfo(decl, namespaces=self.namespaces, enumType=enumType)
428
if constinfo.isIgnored():
429
logging.info('ignored: %s', constinfo)
430
elif not self.isWrapped(constinfo.classname):
431
logging.info('class not found: %s', constinfo)
432
else:
433
ci = self.getClass(constinfo.classname)
434
duplicate = ci.getConst(constinfo.name)
435
if duplicate:
436
if duplicate.addedManually:
437
logging.info('manual: %s', constinfo)
438
else:
439
logging.warning('duplicated: %s', constinfo)
440
else:
441
ci.addConst(constinfo)
442
logging.info('ok: %s', constinfo)
443
444
def add_enum(self, decl): # [ "enum cname", "", [], [] ]
445
enumType = decl[0].rsplit(" ", 1)[1]
446
if enumType.endswith("<unnamed>"):
447
enumType = None
448
else:
449
ctype = normalize_class_name(enumType)
450
type_dict[ctype] = { "cast_from" : "int", "cast_to" : get_cname(enumType), "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" }
451
const_decls = decl[3]
452
453
for decl in const_decls:
454
self.add_const(decl, enumType)
455
456
def add_func(self, decl):
457
fi = FuncInfo(decl, namespaces=self.namespaces)
458
classname = fi.classname or self.Module
459
if classname in class_ignore_list:
460
logging.info('ignored: %s', fi)
461
elif classname in ManualFuncs and fi.jname in ManualFuncs[classname]:
462
logging.info('manual: %s', fi)
463
elif not self.isWrapped(classname):
464
logging.warning('not found: %s', fi)
465
else:
466
self.getClass(classname).addMethod(fi)
467
logging.info('ok: %s', fi)
468
# calc args with def val
469
cnt = len([a for a in fi.args if a.defval])
470
self.def_args_hist[cnt] = self.def_args_hist.get(cnt, 0) + 1
471
472
def save(self, path, buf):
473
global total_files, updated_files
474
total_files += 1
475
if os.path.exists(path):
476
with open(path, "rt") as f:
477
content = f.read()
478
if content == buf:
479
return
480
with open(path, "wt") as f:
481
f.write(buf)
482
updated_files += 1
483
484
def gen(self, srcfiles, module, output_path, output_jni_path, output_java_path, common_headers):
485
self.clear()
486
self.module = module
487
self.Module = module.capitalize()
488
# TODO: support UMat versions of declarations (implement UMat-wrapper for Java)
489
parser = hdr_parser.CppHeaderParser(generate_umat_decls=False)
490
491
self.add_class( ['class ' + self.Module, '', [], []] ) # [ 'class/struct cname', ':bases', [modlist] [props] ]
492
493
# scan the headers and build more descriptive maps of classes, consts, functions
494
includes = [];
495
for hdr in common_headers:
496
logging.info("\n===== Common header : %s =====", hdr)
497
includes.append('#include "' + hdr + '"')
498
for hdr in srcfiles:
499
decls = parser.parse(hdr)
500
self.namespaces = parser.namespaces
501
logging.info("\n\n===== Header: %s =====", hdr)
502
logging.info("Namespaces: %s", parser.namespaces)
503
if decls:
504
includes.append('#include "' + hdr + '"')
505
else:
506
logging.info("Ignore header: %s", hdr)
507
for decl in decls:
508
logging.info("\n--- Incoming ---\n%s", pformat(decl[:5], 4)) # without docstring
509
name = decl[0]
510
if name.startswith("struct") or name.startswith("class"):
511
self.add_class(decl)
512
elif name.startswith("const"):
513
self.add_const(decl)
514
elif name.startswith("enum"):
515
# enum
516
self.add_enum(decl)
517
else: # function
518
self.add_func(decl)
519
520
logging.info("\n\n===== Generating... =====")
521
moduleCppCode = StringIO()
522
package_path = os.path.join(output_java_path, module)
523
mkdir_p(package_path)
524
for ci in self.classes.values():
525
if ci.name == "Mat":
526
continue
527
ci.initCodeStreams(self.Module)
528
self.gen_class(ci)
529
classJavaCode = ci.generateJavaCode(self.module, self.Module)
530
self.save("%s/%s/%s.java" % (output_java_path, module, ci.jname), classJavaCode)
531
moduleCppCode.write(ci.generateCppCode())
532
ci.cleanupCodeStreams()
533
cpp_file = os.path.abspath(os.path.join(output_jni_path, module + ".inl.hpp"))
534
self.cpp_files.append(cpp_file)
535
self.save(cpp_file, T_CPP_MODULE.substitute(m = module, M = module.upper(), code = moduleCppCode.getvalue(), includes = "\n".join(includes)))
536
self.save(os.path.join(output_path, module+".txt"), self.makeReport())
537
538
def makeReport(self):
539
'''
540
Returns string with generator report
541
'''
542
report = StringIO()
543
total_count = len(self.ported_func_list)+ len(self.skipped_func_list)
544
report.write("PORTED FUNCs LIST (%i of %i):\n\n" % (len(self.ported_func_list), total_count))
545
report.write("\n".join(self.ported_func_list))
546
report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % (len(self.skipped_func_list), total_count))
547
report.write("".join(self.skipped_func_list))
548
for i in self.def_args_hist.keys():
549
report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i]))
550
return report.getvalue()
551
552
def fullTypeName(self, t):
553
if self.isWrapped(t):
554
return self.getClass(t).fullName(isCPP=True)
555
else:
556
return cast_from(t)
557
558
def gen_func(self, ci, fi, prop_name=''):
559
logging.info("%s", fi)
560
j_code = ci.j_code
561
jn_code = ci.jn_code
562
cpp_code = ci.cpp_code
563
564
# c_decl
565
# e.g: void add(Mat src1, Mat src2, Mat dst, Mat mask = Mat(), int dtype = -1)
566
if prop_name:
567
c_decl = "%s %s::%s" % (fi.ctype, fi.classname, prop_name)
568
else:
569
decl_args = []
570
for a in fi.args:
571
s = a.ctype or ' _hidden_ '
572
if a.pointer:
573
s += "*"
574
elif a.out:
575
s += "&"
576
s += " " + a.name
577
if a.defval:
578
s += " = "+a.defval
579
decl_args.append(s)
580
c_decl = "%s %s %s(%s)" % ( fi.static, fi.ctype, fi.cname, ", ".join(decl_args) )
581
582
# java comment
583
j_code.write( "\n //\n // C++: %s\n //\n\n" % c_decl )
584
# check if we 'know' all the types
585
if fi.ctype not in type_dict: # unsupported ret type
586
msg = "// Return type '%s' is not supported, skipping the function\n\n" % fi.ctype
587
self.skipped_func_list.append(c_decl + "\n" + msg)
588
j_code.write( " "*4 + msg )
589
logging.warning("SKIP:" + c_decl.strip() + "\t due to RET type " + fi.ctype)
590
return
591
for a in fi.args:
592
if a.ctype not in type_dict:
593
if not a.defval and a.ctype.endswith("*"):
594
a.defval = 0
595
if a.defval:
596
a.ctype = ''
597
continue
598
msg = "// Unknown type '%s' (%s), skipping the function\n\n" % (a.ctype, a.out or "I")
599
self.skipped_func_list.append(c_decl + "\n" + msg)
600
j_code.write( " "*4 + msg )
601
logging.warning("SKIP:" + c_decl.strip() + "\t due to ARG type " + a.ctype + "/" + (a.out or "I"))
602
return
603
604
self.ported_func_list.append(c_decl)
605
606
# jn & cpp comment
607
jn_code.write( "\n // C++: %s\n" % c_decl )
608
cpp_code.write( "\n//\n// %s\n//\n" % c_decl )
609
610
# java args
611
args = fi.args[:] # copy
612
j_signatures=[]
613
suffix_counter = int(ci.methods_suffixes.get(fi.jname, -1))
614
while True:
615
suffix_counter += 1
616
ci.methods_suffixes[fi.jname] = suffix_counter
617
# java native method args
618
jn_args = []
619
# jni (cpp) function args
620
jni_args = [ArgInfo([ "env", "env", "", [], "" ]), ArgInfo([ "cls", "", "", [], "" ])]
621
j_prologue = []
622
j_epilogue = []
623
c_prologue = []
624
c_epilogue = []
625
if type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
626
fields = type_dict[fi.ctype]["jn_args"]
627
c_epilogue.append( \
628
("jdoubleArray _da_retval_ = env->NewDoubleArray(%(cnt)i); " +
629
"jdouble _tmp_retval_[%(cnt)i] = {%(args)s}; " +
630
"env->SetDoubleArrayRegion(_da_retval_, 0, %(cnt)i, _tmp_retval_);") %
631
{ "cnt" : len(fields), "args" : ", ".join(["(jdouble)_retval_" + f[1] for f in fields]) } )
632
if fi.classname and fi.ctype and not fi.static: # non-static class method except c-tor
633
# adding 'self'
634
jn_args.append ( ArgInfo([ "__int64", "nativeObj", "", [], "" ]) )
635
jni_args.append( ArgInfo([ "__int64", "self", "", [], "" ]) )
636
ci.addImports(fi.ctype)
637
for a in args:
638
if not a.ctype: # hidden
639
continue
640
ci.addImports(a.ctype)
641
if "v_type" in type_dict[a.ctype]: # pass as vector
642
if type_dict[a.ctype]["v_type"] in ("Mat", "vector_Mat"): #pass as Mat or vector_Mat
643
jn_args.append ( ArgInfo([ "__int64", "%s_mat.nativeObj" % a.name, "", [], "" ]) )
644
jni_args.append ( ArgInfo([ "__int64", "%s_mat_nativeObj" % a.name, "", [], "" ]) )
645
c_prologue.append( type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";" )
646
c_prologue.append( "Mat& %(n)s_mat = *((Mat*)%(n)s_mat_nativeObj)" % {"n" : a.name} + ";" )
647
if "I" in a.out or not a.out:
648
if type_dict[a.ctype]["v_type"] == "vector_Mat":
649
j_prologue.append( "List<Mat> %(n)s_tmplm = new ArrayList<Mat>((%(n)s != null) ? %(n)s.size() : 0);" % {"n" : a.name } )
650
j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s, %(n)s_tmplm);" % {"n" : a.name, "t" : a.ctype} )
651
else:
652
if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
653
j_prologue.append( "Mat %(n)s_mat = Converters.%(t)s_to_Mat(%(n)s);" % {"n" : a.name, "t" : a.ctype} )
654
else:
655
j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
656
c_prologue.append( "Mat_to_%(t)s( %(n)s_mat, %(n)s );" % {"n" : a.name, "t" : a.ctype} )
657
else:
658
if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
659
j_prologue.append( "Mat %s_mat = new Mat();" % a.name )
660
else:
661
j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
662
if "O" in a.out:
663
if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
664
j_epilogue.append("Converters.Mat_to_%(t)s(%(n)s_mat, %(n)s);" % {"t" : a.ctype, "n" : a.name})
665
j_epilogue.append( "%s_mat.release();" % a.name )
666
c_epilogue.append( "%(t)s_to_Mat( %(n)s, %(n)s_mat );" % {"n" : a.name, "t" : a.ctype} )
667
else: #pass as list
668
jn_args.append ( ArgInfo([ a.ctype, a.name, "", [], "" ]) )
669
jni_args.append ( ArgInfo([ a.ctype, "%s_list" % a.name , "", [], "" ]) )
670
c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")
671
if "I" in a.out or not a.out:
672
c_prologue.append("%(n)s = List_to_%(t)s(env, %(n)s_list);" % {"n" : a.name, "t" : a.ctype})
673
if "O" in a.out:
674
c_epilogue.append("Copy_%s_to_List(env,%s,%s_list);" % (a.ctype, a.name, a.name))
675
else:
676
fields = type_dict[a.ctype].get("jn_args", ((a.ctype, ""),))
677
if "I" in a.out or not a.out or self.isWrapped(a.ctype): # input arg, pass by primitive fields
678
for f in fields:
679
jn_args.append ( ArgInfo([ f[0], a.name + f[1], "", [], "" ]) )
680
jni_args.append( ArgInfo([ f[0], a.name + normalize_field_name(f[1]), "", [], "" ]) )
681
if "O" in a.out and not self.isWrapped(a.ctype): # out arg, pass as double[]
682
jn_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )
683
jni_args.append ( ArgInfo([ "double[]", "%s_out" % a.name, "", [], "" ]) )
684
j_prologue.append( "double[] %s_out = new double[%i];" % (a.name, len(fields)) )
685
c_epilogue.append( \
686
"jdouble tmp_%(n)s[%(cnt)i] = {%(args)s}; env->SetDoubleArrayRegion(%(n)s_out, 0, %(cnt)i, tmp_%(n)s);" %
687
{ "n" : a.name, "cnt" : len(fields), "args" : ", ".join(["(jdouble)" + a.name + f[1] for f in fields]) } )
688
if type_dict[a.ctype]["j_type"] in ('bool', 'int', 'long', 'float', 'double'):
689
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"]})
690
else:
691
set_vals = []
692
i = 0
693
for f in fields:
694
set_vals.append( "%(n)s%(f)s = %(t)s%(n)s_out[%(i)i]" %
695
{"n" : a.name, "t": ("("+type_dict[f[0]]["j_type"]+")", "")[f[0]=="double"], "f" : f[1], "i" : i}
696
)
697
i += 1
698
j_epilogue.append( "if("+a.name+"!=null){ " + "; ".join(set_vals) + "; } ")
699
700
# calculate java method signature to check for uniqueness
701
j_args = []
702
for a in args:
703
if not a.ctype: #hidden
704
continue
705
jt = type_dict[a.ctype]["j_type"]
706
if a.out and jt in ('bool', 'int', 'long', 'float', 'double'):
707
jt += '[]'
708
j_args.append( jt + ' ' + a.name )
709
j_signature = type_dict[fi.ctype]["j_type"] + " " + \
710
fi.jname + "(" + ", ".join(j_args) + ")"
711
logging.info("java: " + j_signature)
712
713
if(j_signature in j_signatures):
714
if args:
715
args.pop()
716
continue
717
else:
718
break
719
720
# java part:
721
# private java NATIVE method decl
722
# e.g.
723
# private static native void add_0(long src1, long src2, long dst, long mask, int dtype);
724
jn_code.write( Template(\
725
" private static native $type $name($args);\n").substitute(\
726
type = type_dict[fi.ctype].get("jn_type", "double[]"), \
727
name = fi.jname + '_' + str(suffix_counter), \
728
args = ", ".join(["%s %s" % (type_dict[a.ctype]["jn_type"], normalize_field_name(a.name)) for a in jn_args])
729
) );
730
731
# java part:
732
733
#java doc comment
734
f_name = fi.jname
735
if fi.classname:
736
f_name = fi.classname + "::" + fi.jname
737
java_doc = "//javadoc: " + f_name + "(%s)" % ", ".join([a.name for a in args if a.ctype])
738
j_code.write(" "*4 + java_doc + "\n")
739
740
if fi.docstring:
741
lines = StringIO(fi.docstring)
742
for line in lines:
743
j_code.write(" "*4 + line + "\n")
744
if fi.annotation:
745
j_code.write(" "*4 + "\n".join(fi.annotation) + "\n")
746
747
# public java wrapper method impl (calling native one above)
748
# e.g.
749
# public static void add( Mat src1, Mat src2, Mat dst, Mat mask, int dtype )
750
# { add_0( src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype ); }
751
ret_type = fi.ctype
752
if fi.ctype.endswith('*'):
753
ret_type = ret_type[:-1]
754
ret_val = type_dict[ret_type]["j_type"] + " retVal = "
755
tail = ""
756
ret = "return retVal;"
757
if "v_type" in type_dict[ret_type]:
758
j_type = type_dict[ret_type]["j_type"]
759
if type_dict[ret_type]["v_type"] in ("Mat", "vector_Mat"):
760
tail = ")"
761
if j_type.startswith('MatOf'):
762
ret_val += j_type + ".fromNativeAddr("
763
else:
764
ret_val = "Mat retValMat = new Mat("
765
j_prologue.append( j_type + ' retVal = new Array' + j_type+'();')
766
j_epilogue.append('Converters.Mat_to_' + ret_type + '(retValMat, retVal);')
767
elif ret_type.startswith("Ptr_"):
768
ret_val = type_dict[fi.ctype]["j_type"] + " retVal = " + type_dict[ret_type]["j_type"] + ".__fromPtr__("
769
tail = ")"
770
elif ret_type == "void":
771
ret_val = ""
772
ret = "return;"
773
elif ret_type == "": # c-tor
774
if fi.classname and ci.base:
775
ret_val = "super( "
776
tail = " )"
777
else:
778
ret_val = "nativeObj = "
779
ret = "return;"
780
elif self.isWrapped(ret_type): # wrapped class
781
ret_val = type_dict[ret_type]["j_type"] + " retVal = new " + self.getClass(ret_type).jname + "("
782
tail = ")"
783
elif "jn_type" not in type_dict[ret_type]:
784
ret_val = type_dict[fi.ctype]["j_type"] + " retVal = new " + type_dict[ret_type]["j_type"] + "("
785
tail = ")"
786
787
static = "static"
788
if fi.classname:
789
static = fi.static
790
791
j_code.write( Template(\
792
""" public $static $j_type $j_name($j_args)
793
{
794
$prologue
795
$ret_val$jn_name($jn_args_call)$tail;
796
$epilogue
797
$ret
798
}
799
800
"""
801
).substitute(\
802
ret = ret, \
803
ret_val = ret_val, \
804
tail = tail, \
805
prologue = "\n ".join(j_prologue), \
806
epilogue = "\n ".join(j_epilogue), \
807
static=static, \
808
j_type=type_dict[fi.ctype]["j_type"], \
809
j_name=fi.jname, \
810
j_args=", ".join(j_args), \
811
jn_name=fi.jname + '_' + str(suffix_counter), \
812
jn_args_call=", ".join( [a.name for a in jn_args] ),\
813
)
814
)
815
816
817
# cpp part:
818
# jni_func(..) { _retval_ = cv_func(..); return _retval_; }
819
ret = "return _retval_;"
820
default = "return 0;"
821
if fi.ctype == "void":
822
ret = "return;"
823
default = "return;"
824
elif not fi.ctype: # c-tor
825
ret = "return (jlong) _retval_;"
826
elif "v_type" in type_dict[fi.ctype]: # c-tor
827
if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"):
828
ret = "return (jlong) _retval_;"
829
else: # returned as jobject
830
ret = "return _retval_;"
831
elif fi.ctype == "String":
832
ret = "return env->NewStringUTF(_retval_.c_str());"
833
default = 'return env->NewStringUTF("");'
834
elif self.isWrapped(fi.ctype): # wrapped class:
835
ret = "return (jlong) new %s(_retval_);" % self.fullTypeName(fi.ctype)
836
elif fi.ctype.startswith('Ptr_'):
837
c_prologue.append("typedef Ptr<%s> %s;" % (self.fullTypeName(fi.ctype[4:]), fi.ctype))
838
ret = "return (jlong)(new %(ctype)s(_retval_));" % { 'ctype':fi.ctype }
839
elif self.isWrapped(ret_type): # pointer to wrapped class:
840
ret = "return (jlong) _retval_;"
841
elif type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
842
ret = "return _da_retval_;"
843
844
# hack: replacing func call with property set/get
845
name = fi.name
846
if prop_name:
847
if args:
848
name = prop_name + " = "
849
else:
850
name = prop_name + ";//"
851
852
cvname = fi.fullName(isCPP=True)
853
retval = self.fullTypeName(fi.ctype) + " _retval_ = "
854
if fi.ctype == "void":
855
retval = ""
856
elif fi.ctype == "String":
857
retval = "cv::" + retval
858
elif "v_type" in type_dict[fi.ctype]: # vector is returned
859
retval = type_dict[fi.ctype]['jni_var'] % {"n" : '_ret_val_vector_'} + " = "
860
if type_dict[fi.ctype]["v_type"] in ("Mat", "vector_Mat"):
861
c_epilogue.append("Mat* _retval_ = new Mat();")
862
c_epilogue.append(fi.ctype+"_to_Mat(_ret_val_vector_, *_retval_);")
863
else:
864
c_epilogue.append("jobject _retval_ = " + fi.ctype + "_to_List(env, _ret_val_vector_);")
865
if len(fi.classname)>0:
866
if not fi.ctype: # c-tor
867
retval = fi.fullClass(isCPP=True) + "* _retval_ = "
868
cvname = "new " + fi.fullClass(isCPP=True)
869
elif fi.static:
870
cvname = fi.fullName(isCPP=True)
871
else:
872
cvname = ("me->" if not self.isSmartClass(ci) else "(*me)->") + name
873
c_prologue.append(\
874
"%(cls)s* me = (%(cls)s*) self; //TODO: check for NULL" \
875
% { "cls" : self.smartWrap(ci, fi.fullClass(isCPP=True))} \
876
)
877
cvargs = []
878
for a in args:
879
if a.pointer:
880
jni_name = "&%(n)s"
881
else:
882
jni_name = "%(n)s"
883
if not a.out and not "jni_var" in type_dict[a.ctype]:
884
# explicit cast to C type to avoid ambiguous call error on platforms (mingw)
885
# where jni types are different from native types (e.g. jint is not the same as int)
886
jni_name = "(%s)%s" % (cast_to(a.ctype), jni_name)
887
if not a.ctype: # hidden
888
jni_name = a.defval
889
cvargs.append( type_dict[a.ctype].get("jni_name", jni_name) % {"n" : a.name})
890
if "v_type" not in type_dict[a.ctype]:
891
if ("I" in a.out or not a.out or self.isWrapped(a.ctype)) and "jni_var" in type_dict[a.ctype]: # complex type
892
c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")
893
if a.out and "I" not in a.out and not self.isWrapped(a.ctype) and a.ctype:
894
c_prologue.append("%s %s;" % (a.ctype, a.name))
895
896
rtype = type_dict[fi.ctype].get("jni_type", "jdoubleArray")
897
clazz = ci.jname
898
cpp_code.write ( Template( \
899
"""
900
${namespace}
901
902
JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname ($argst);
903
904
JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname
905
($args)
906
{
907
static const char method_name[] = "$module::$fname()";
908
try {
909
LOGD("%s", method_name);
910
$prologue
911
$retval$cvname( $cvargs );
912
$epilogue$ret
913
} catch(const std::exception &e) {
914
throwJavaException(env, &e, method_name);
915
} catch (...) {
916
throwJavaException(env, 0, method_name);
917
}
918
$default
919
}
920
921
922
""" ).substitute( \
923
rtype = rtype, \
924
module = self.module.replace('_', '_1'), \
925
clazz = clazz.replace('_', '_1'), \
926
fname = (fi.jname + '_' + str(suffix_counter)).replace('_', '_1'), \
927
args = ", ".join(["%s %s" % (type_dict[a.ctype].get("jni_type"), a.name) for a in jni_args]), \
928
argst = ", ".join([type_dict[a.ctype].get("jni_type") for a in jni_args]), \
929
prologue = "\n ".join(c_prologue), \
930
epilogue = " ".join(c_epilogue) + ("\n " if c_epilogue else ""), \
931
ret = ret, \
932
cvname = cvname, \
933
cvargs = ", ".join(cvargs), \
934
default = default, \
935
retval = retval, \
936
namespace = ('using namespace ' + ci.namespace.replace('.', '::') + ';') if ci.namespace else ''
937
) )
938
939
# adding method signature to dictionarry
940
j_signatures.append(j_signature)
941
942
# processing args with default values
943
if args and args[-1].defval:
944
args.pop()
945
else:
946
break
947
948
949
950
def gen_class(self, ci):
951
logging.info("%s", ci)
952
# constants
953
if ci.private_consts:
954
logging.info("%s", ci.private_consts)
955
ci.j_code.write("""
956
private static final int
957
%s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in ci.private_consts])
958
)
959
if ci.consts:
960
enumTypes = set(map(lambda c: c.enumType, ci.consts))
961
grouped_consts = {enumType: [c for c in ci.consts if c.enumType == enumType] for enumType in enumTypes}
962
for typeName, consts in grouped_consts.items():
963
logging.info("%s", consts)
964
if typeName:
965
typeName = typeName.rsplit(".", 1)[-1]
966
###################### Utilize Java enums ######################
967
# ci.j_code.write("""
968
# public enum {1} {{
969
# {0};
970
#
971
# private final int id;
972
# {1}(int id) {{ this.id = id; }}
973
# {1}({1} _this) {{ this.id = _this.id; }}
974
# public int getValue() {{ return id; }}
975
# }}\n\n""".format((",\n"+" "*8).join(["%s(%s)" % (c.name, c.value) for c in consts]), typeName)
976
# )
977
################################################################
978
ci.j_code.write("""
979
// C++: enum {1}
980
public static final int
981
{0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]), typeName)
982
)
983
else:
984
ci.j_code.write("""
985
// C++: enum <unnamed>
986
public static final int
987
{0};\n\n""".format((",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in consts]))
988
)
989
# methods
990
for fi in ci.getAllMethods():
991
self.gen_func(ci, fi)
992
# props
993
for pi in ci.props:
994
# getter
995
getter_name = ci.fullName() + ".get_" + pi.name
996
fi = FuncInfo( [getter_name, pi.ctype, [], []], self.namespaces ) # [ funcname, return_ctype, [modifiers], [args] ]
997
self.gen_func(ci, fi, pi.name)
998
if pi.rw:
999
#setter
1000
setter_name = ci.fullName() + ".set_" + pi.name
1001
fi = FuncInfo( [ setter_name, "void", [], [ [pi.ctype, pi.name, "", [], ""] ] ], self.namespaces)
1002
self.gen_func(ci, fi, pi.name)
1003
1004
# manual ports
1005
if ci.name in ManualFuncs:
1006
for func in ManualFuncs[ci.name].keys():
1007
ci.j_code.write ( "\n".join(ManualFuncs[ci.name][func]["j_code"]) )
1008
ci.jn_code.write( "\n".join(ManualFuncs[ci.name][func]["jn_code"]) )
1009
ci.cpp_code.write( "\n".join(ManualFuncs[ci.name][func]["cpp_code"]) )
1010
1011
if ci.name != self.Module or ci.base:
1012
# finalize()
1013
ci.j_code.write(
1014
"""
1015
@Override
1016
protected void finalize() throws Throwable {
1017
delete(nativeObj);
1018
}
1019
""" )
1020
1021
ci.jn_code.write(
1022
"""
1023
// native support for java finalize()
1024
private static native void delete(long nativeObj);
1025
""" )
1026
1027
# native support for java finalize()
1028
ci.cpp_code.write( \
1029
"""
1030
//
1031
// native support for java finalize()
1032
// static void %(cls)s::delete( __int64 self )
1033
//
1034
JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete(JNIEnv*, jclass, jlong);
1035
1036
JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete
1037
(JNIEnv*, jclass, jlong self)
1038
{
1039
delete (%(cls)s*) self;
1040
}
1041
1042
""" % {"module" : module.replace('_', '_1'), "cls" : self.smartWrap(ci, ci.fullName(isCPP=True)), "j_cls" : ci.jname.replace('_', '_1')}
1043
)
1044
1045
def getClass(self, classname):
1046
return self.classes[classname or self.Module]
1047
1048
def isWrapped(self, classname):
1049
name = classname or self.Module
1050
return name in self.classes
1051
1052
def isSmartClass(self, ci):
1053
'''
1054
Check if class stores Ptr<T>* instead of T* in nativeObj field
1055
'''
1056
if ci.smart != None:
1057
return ci.smart
1058
1059
# if parents are smart (we hope) then children are!
1060
# if not we believe the class is smart if it has "create" method
1061
ci.smart = False
1062
if ci.base or ci.name == 'Algorithm':
1063
ci.smart = True
1064
else:
1065
for fi in ci.methods:
1066
if fi.name == "create":
1067
ci.smart = True
1068
break
1069
1070
return ci.smart
1071
1072
def smartWrap(self, ci, fullname):
1073
'''
1074
Wraps fullname with Ptr<> if needed
1075
'''
1076
if self.isSmartClass(ci):
1077
return "Ptr<" + fullname + ">"
1078
return fullname
1079
1080
def finalize(self, output_jni_path):
1081
list_file = os.path.join(output_jni_path, "opencv_jni.hpp")
1082
self.save(list_file, '\n'.join(['#include "%s"' % f for f in self.cpp_files]))
1083
1084
1085
def copy_java_files(java_files_dir, java_base_path, default_package_path='org/opencv/'):
1086
global total_files, updated_files
1087
java_files = []
1088
re_filter = re.compile(r'^.+\.(java|aidl)(.in)?$')
1089
for root, dirnames, filenames in os.walk(java_files_dir):
1090
java_files += [os.path.join(root, filename) for filename in filenames if re_filter.match(filename)]
1091
java_files = [f.replace('\\', '/') for f in java_files]
1092
1093
re_package = re.compile(r'^package +(.+);')
1094
re_prefix = re.compile(r'^.+[\+/]([^\+]+).(java|aidl)(.in)?$')
1095
for java_file in java_files:
1096
src = checkFileRemap(java_file)
1097
with open(src, 'r') as f:
1098
package_line = f.readline()
1099
m = re_prefix.match(java_file)
1100
target_fname = (m.group(1) + '.' + m.group(2)) if m else os.path.basename(java_file)
1101
m = re_package.match(package_line)
1102
if m:
1103
package = m.group(1)
1104
package_path = package.replace('.', '/')
1105
else:
1106
package_path = default_package_path
1107
#print(java_file, package_path, target_fname)
1108
dest = os.path.join(java_base_path, os.path.join(package_path, target_fname))
1109
assert dest[-3:] != '.in', dest + ' | ' + target_fname
1110
mkdir_p(os.path.dirname(dest))
1111
total_files += 1
1112
if (not os.path.exists(dest)) or (os.stat(src).st_mtime - os.stat(dest).st_mtime > 1):
1113
copyfile(src, dest)
1114
updated_files += 1
1115
1116
1117
if __name__ == "__main__":
1118
# initialize logger
1119
logging.basicConfig(filename='gen_java.log', format=None, filemode='w', level=logging.INFO)
1120
handler = logging.StreamHandler()
1121
handler.setLevel(logging.WARNING)
1122
logging.getLogger().addHandler(handler)
1123
1124
# parse command line parameters
1125
import argparse
1126
arg_parser = argparse.ArgumentParser(description='OpenCV Java Wrapper Generator')
1127
arg_parser.add_argument('-p', '--parser', required=True, help='OpenCV header parser')
1128
arg_parser.add_argument('-c', '--config', required=True, help='OpenCV modules config')
1129
1130
args=arg_parser.parse_args()
1131
1132
# import header parser
1133
hdr_parser_path = os.path.abspath(args.parser)
1134
if hdr_parser_path.endswith(".py"):
1135
hdr_parser_path = os.path.dirname(hdr_parser_path)
1136
sys.path.append(hdr_parser_path)
1137
import hdr_parser
1138
1139
with open(args.config) as f:
1140
config = json.load(f)
1141
1142
ROOT_DIR = config['rootdir']; assert os.path.exists(ROOT_DIR)
1143
FILES_REMAP = { os.path.realpath(os.path.join(ROOT_DIR, f['src'])): f['target'] for f in config['files_remap'] }
1144
logging.info("\nRemapped configured files (%d):\n%s", len(FILES_REMAP), pformat(FILES_REMAP))
1145
1146
dstdir = "./gen"
1147
jni_path = os.path.join(dstdir, 'cpp'); mkdir_p(jni_path)
1148
java_base_path = os.path.join(dstdir, 'java'); mkdir_p(java_base_path)
1149
java_test_base_path = os.path.join(dstdir, 'test'); mkdir_p(java_test_base_path)
1150
1151
for (subdir, target_subdir) in [('src/java', 'java'), ('android/java', None), ('android-21/java', None)]:
1152
if target_subdir is None:
1153
target_subdir = subdir
1154
java_files_dir = os.path.join(SCRIPT_DIR, subdir)
1155
if os.path.exists(java_files_dir):
1156
target_path = os.path.join(dstdir, target_subdir); mkdir_p(target_path)
1157
copy_java_files(java_files_dir, target_path)
1158
1159
# launch Java Wrapper generator
1160
generator = JavaWrapperGenerator()
1161
1162
gen_dict_files = []
1163
1164
print("JAVA: Processing OpenCV modules: %d" % len(config['modules']))
1165
for e in config['modules']:
1166
(module, module_location) = (e['name'], os.path.join(ROOT_DIR, e['location']))
1167
logging.info("\n=== MODULE: %s (%s) ===\n" % (module, module_location))
1168
1169
java_path = os.path.join(java_base_path, 'org/opencv')
1170
mkdir_p(java_path)
1171
1172
module_imports = []
1173
module_j_code = None
1174
module_jn_code = None
1175
srcfiles = []
1176
common_headers = []
1177
1178
misc_location = os.path.join(module_location, 'misc/java')
1179
1180
srcfiles_fname = os.path.join(misc_location, 'filelist')
1181
if os.path.exists(srcfiles_fname):
1182
with open(srcfiles_fname) as f:
1183
srcfiles = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()]
1184
else:
1185
re_bad = re.compile(r'(private|.inl.hpp$|_inl.hpp$|.details.hpp$|_winrt.hpp$|/cuda/)')
1186
# .h files before .hpp
1187
h_files = []
1188
hpp_files = []
1189
for root, dirnames, filenames in os.walk(os.path.join(module_location, 'include')):
1190
h_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.h')]
1191
hpp_files += [os.path.join(root, filename) for filename in fnmatch.filter(filenames, '*.hpp')]
1192
srcfiles = h_files + hpp_files
1193
srcfiles = [f for f in srcfiles if not re_bad.search(f.replace('\\', '/'))]
1194
logging.info("\nFiles (%d):\n%s", len(srcfiles), pformat(srcfiles))
1195
1196
common_headers_fname = os.path.join(misc_location, 'filelist_common')
1197
if os.path.exists(common_headers_fname):
1198
with open(common_headers_fname) as f:
1199
common_headers = [os.path.join(module_location, str(l).strip()) for l in f.readlines() if str(l).strip()]
1200
logging.info("\nCommon headers (%d):\n%s", len(common_headers), pformat(common_headers))
1201
1202
gendict_fname = os.path.join(misc_location, 'gen_dict.json')
1203
if os.path.exists(gendict_fname):
1204
with open(gendict_fname) as f:
1205
gen_type_dict = json.load(f)
1206
class_ignore_list += gen_type_dict.get("class_ignore_list", [])
1207
const_ignore_list += gen_type_dict.get("const_ignore_list", [])
1208
const_private_list += gen_type_dict.get("const_private_list", [])
1209
missing_consts.update(gen_type_dict.get("missing_consts", {}))
1210
type_dict.update(gen_type_dict.get("type_dict", {}))
1211
ManualFuncs.update(gen_type_dict.get("ManualFuncs", {}))
1212
func_arg_fix.update(gen_type_dict.get("func_arg_fix", {}))
1213
namespaces_dict.update(gen_type_dict.get("namespaces_dict", {}))
1214
if 'module_j_code' in gen_type_dict:
1215
module_j_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_j_code'])))
1216
if 'module_jn_code' in gen_type_dict:
1217
module_jn_code = read_contents(checkFileRemap(os.path.join(misc_location, gen_type_dict['module_jn_code'])))
1218
module_imports += gen_type_dict.get("module_imports", [])
1219
1220
java_files_dir = os.path.join(misc_location, 'src/java')
1221
if os.path.exists(java_files_dir):
1222
copy_java_files(java_files_dir, java_base_path, 'org/opencv/' + module)
1223
1224
java_test_files_dir = os.path.join(misc_location, 'test')
1225
if os.path.exists(java_test_files_dir):
1226
copy_java_files(java_test_files_dir, java_test_base_path, 'org/opencv/test/' + module)
1227
1228
if len(srcfiles) > 0:
1229
generator.gen(srcfiles, module, dstdir, jni_path, java_path, common_headers)
1230
else:
1231
logging.info("No generated code for module: %s", module)
1232
generator.finalize(jni_path)
1233
1234
print('Generated files: %d (updated %d)' % (total_files, updated_files))
1235
1236