gen_java.py 58.5 KB
Newer Older
1 2 3 4 5 6 7 8
import sys, re, os.path
from string import Template

try:
    from cStringIO import StringIO
except:
    from StringIO import StringIO

9 10
class_ignore_list = (
    #core
11
    "FileNode", "FileStorage", "KDTree",
12
    #highgui
13
    "VideoWriter", "VideoCapture",
14
    #features2d
15
    #"KeyPoint", "MSER", "StarDetector", "SURF", "DMatch",
16 17
    #ml
    "EM",
18 19
)

20
const_ignore_list = (
Leonid Beynenson's avatar
Leonid Beynenson committed
21 22 23 24 25 26 27 28 29 30 31
    "CV_CAP_OPENNI",
    "CV_CAP_PROP_OPENNI_",
    "WINDOW_AUTOSIZE",
    "CV_WND_PROP_",
    "CV_WINDOW_",
    "CV_EVENT_",
    "CV_GUI_",
    "CV_PUSH_BUTTON",
    "CV_CHECKBOX",
    "CV_RADIOBOX",

32 33 34
    #attention!
    #the following constants are added to this list using code automatic generation
    #TODO: should be checked
Leonid Beynenson's avatar
Leonid Beynenson committed
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
    "CV_CAP_ANY",
    "CV_CAP_MIL",
    "CV_CAP_VFW",
    "CV_CAP_V4L",
    "CV_CAP_V4L2",
    "CV_CAP_FIREWARE",
    "CV_CAP_FIREWIRE",
    "CV_CAP_IEEE1394",
    "CV_CAP_DC1394",
    "CV_CAP_CMU1394",
    "CV_CAP_STEREO",
    "CV_CAP_TYZX",
    "CV_TYZX_LEFT",
    "CV_TYZX_RIGHT",
    "CV_TYZX_COLOR",
    "CV_TYZX_Z",
    "CV_CAP_QT",
    "CV_CAP_UNICAP",
    "CV_CAP_DSHOW",
    "CV_CAP_PVAPI",
    "CV_CAP_PROP_DC1394_OFF",
    "CV_CAP_PROP_DC1394_MODE_MANUAL",
    "CV_CAP_PROP_DC1394_MODE_AUTO",
    "CV_CAP_PROP_DC1394_MODE_ONE_PUSH_AUTO",
    "CV_CAP_PROP_POS_MSEC",
    "CV_CAP_PROP_POS_FRAMES",
    "CV_CAP_PROP_POS_AVI_RATIO",
    "CV_CAP_PROP_FPS",
    "CV_CAP_PROP_FOURCC",
    "CV_CAP_PROP_FRAME_COUNT",
    "CV_CAP_PROP_FORMAT",
    "CV_CAP_PROP_MODE",
    "CV_CAP_PROP_BRIGHTNESS",
    "CV_CAP_PROP_CONTRAST",
    "CV_CAP_PROP_SATURATION",
    "CV_CAP_PROP_HUE",
    "CV_CAP_PROP_GAIN",
    "CV_CAP_PROP_EXPOSURE",
    "CV_CAP_PROP_CONVERT_RGB",
    "CV_CAP_PROP_WHITE_BALANCE_BLUE_U",
    "CV_CAP_PROP_RECTIFICATION",
    "CV_CAP_PROP_MONOCROME",
    "CV_CAP_PROP_SHARPNESS",
    "CV_CAP_PROP_AUTO_EXPOSURE",
    "CV_CAP_PROP_GAMMA",
    "CV_CAP_PROP_TEMPERATURE",
    "CV_CAP_PROP_TRIGGER",
    "CV_CAP_PROP_TRIGGER_DELAY",
    "CV_CAP_PROP_WHITE_BALANCE_RED_V",
    "CV_CAP_PROP_MAX_DC1394",
    "CV_CAP_GSTREAMER_QUEUE_LENGTH",
    "CV_CAP_PROP_PVAPI_MULTICASTIP",
87 88 89 90 91
    "CV_CAP_PROP_SUPPORTED_PREVIEW_SIZES_STRING",
    "EVENT_.*",
    "CV_L?(BGRA?|RGBA?|GRAY|XYZ|YCrCb|Luv|Lab|HLS|YUV|HSV)\d*2L?(BGRA?|RGBA?|GRAY|XYZ|YCrCb|Luv|Lab|HLS|YUV|HSV).*",
    "CV_COLORCVT_MAX",
    "CV_.*Bayer.*",
Andrey Kamaev's avatar
Andrey Kamaev committed
92
    "CV_YUV420(i|sp|p)2.+",
93 94
    "CV_TM_.+",
    "CV_FLOODFILL_.+",
95
    "CV_ADAPTIVE_THRESH_.+",
96 97
    "WINDOW_.+",
    "WND_PROP_.+",
98 99 100 101 102 103 104 105 106
)

const_private_list = (
    "CV_MOP_.+",
    "CV_INTER_.+",
    "CV_THRESH_.+",
    "CV_INPAINT_.+",
    "CV_RETR_.+",
    "CV_CHAIN_APPROX_.+",
107 108 109 110
    "OPPONENTEXTRACTOR",
    "GRIDRETECTOR",
    "PYRAMIDDETECTOR",
    "DYNAMICDETECTOR",
111 112
)

113 114 115 116 117 118 119 120 121 122 123 124
# { Module : { public : [[name, val],...], private : [[]...] } }
missing_consts = \
{
    'Core' :
    {
        'private' :
        (
            ('CV_8U',  0 ), ('CV_8S',  1 ),
            ('CV_16U', 2 ), ('CV_16S', 3 ),
            ('CV_32S', 4 ),
            ('CV_32F', 5 ), ('CV_64F', 6 ),
            ('CV_USRTYPE1', 7 ),
Andrey Kamaev's avatar
Andrey Kamaev committed
125 126 127
        ), # private
        'public' :
        (
128
            ('SVD_MODIFY_A', 1), ('SVD_NO_UV', 2), ('SVD_FULL_UV', 4),
Andrey Kamaev's avatar
Andrey Kamaev committed
129 130
            ('FILLED', -1),
            ('LINE_AA', 16), ('LINE_8', 8), ('LINE_4', 4),
131
            ('REDUCE_SUM', 0), ('REDUCE_AVG', 1), ('REDUCE_MAX', 2), ('REDUCE_MIN', 3),
Andrey Kamaev's avatar
Andrey Kamaev committed
132
        ) #public
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
    }, # Core

    "Imgproc":
    {
        'private' :
        (
            ('IPL_BORDER_CONSTANT',    0 ),
            ('IPL_BORDER_REPLICATE',   1 ),
            ('IPL_BORDER_REFLECT',     2 ),
            ('IPL_BORDER_WRAP',        3 ),
            ('IPL_BORDER_REFLECT_101', 4 ),
            ('IPL_BORDER_TRANSPARENT', 5 ),
        ) # private
    }, # Imgproc

    "Calib3d":
    {
150
        'private' :
151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
        (
            ('CV_LMEDS',  4),
            ('CV_RANSAC', 8),
            ('CV_FM_LMEDS', 'CV_LMEDS'),
            ('CV_FM_RANSAC','CV_RANSAC'),
            ('CV_FM_7POINT', 1),
            ('CV_FM_8POINT', 2),
            ('CV_CALIB_USE_INTRINSIC_GUESS', 1),
            ('CV_CALIB_FIX_ASPECT_RATIO',    2),
            ('CV_CALIB_FIX_PRINCIPAL_POINT', 4),
            ('CV_CALIB_ZERO_TANGENT_DIST',   8),
            ('CV_CALIB_FIX_FOCAL_LENGTH',   16),
            ('CV_CALIB_FIX_K1',             32),
            ('CV_CALIB_FIX_K2',             64),
            ('CV_CALIB_FIX_K3',            128),
            ('CV_CALIB_FIX_K4',           2048),
            ('CV_CALIB_FIX_K5',           4096),
            ('CV_CALIB_FIX_K6',           8192),
            ('CV_CALIB_RATIONAL_MODEL',  16384),
            ('CV_CALIB_FIX_INTRINSIC',     256),
            ('CV_CALIB_SAME_FOCAL_LENGTH', 512),
            ('CV_CALIB_ZERO_DISPARITY',   1024),
        ) # public
    }, # Calib3d

}

178

179 180 181 182 183 184 185 186
# c_type    : { java/jni correspondence }
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" },
187 188
    "int"     : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
    "long"    : { "j_type" : "int", "jn_type" : "int", "jni_type" : "jint", "suffix" : "I" },
189 190 191 192
    "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" },
193
    "int64"   : { "j_type" : "long", "jn_type" : "long", "jni_type" : "jlong", "suffix" : "J" },
194
    "double[]": { "j_type" : "double[]", "jn_type" : "double[]", "jni_type" : "jdoubleArray", "suffix" : "_3D" },
195 196 197

# "complex" : { j_type : "?", jn_args : (("", ""),), jn_name : "", jni_var : "", jni_name : "", "suffix" : "?" },

198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
    "vector_Point"    : { "j_type" : "MatOfPoint", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point> %(n)s", "suffix" : "J" },
    "vector_Point2f"  : { "j_type" : "MatOfPoint2f", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point2f> %(n)s", "suffix" : "J" },
    "vector_Point2d"  : { "j_type" : "MatOfPoint2f", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point2d> %(n)s", "suffix" : "J" },
    "vector_Point3i"  : { "j_type" : "MatOfPoint3", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point3i> %(n)s", "suffix" : "J" },
    "vector_Point3f"  : { "j_type" : "MatOfPoint3f", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point3f> %(n)s", "suffix" : "J" },
    "vector_Point3d"  : { "j_type" : "MatOfPoint3f", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Point3d> %(n)s", "suffix" : "J" },
    "vector_KeyPoint" : { "j_type" : "MatOfKeyPoint", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<KeyPoint> %(n)s", "suffix" : "J" },
    "vector_DMatch"   : { "j_type" : "MatOfDMatch", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<DMatch> %(n)s", "suffix" : "J" },
    "vector_Rect"     : { "j_type" : "MatOfRect", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Rect> %(n)s", "suffix" : "J" },
    "vector_uchar"    : { "j_type" : "MatOfByte", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<uchar> %(n)s", "suffix" : "J" },
    "vector_char"     : { "j_type" : "MatOfByte", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<char> %(n)s", "suffix" : "J" },
    "vector_int"      : { "j_type" : "MatOfInt", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<int> %(n)s", "suffix" : "J" },
    "vector_float"    : { "j_type" : "MatOfFloat", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<float> %(n)s", "suffix" : "J" },
    "vector_double"   : { "j_type" : "MatOfDouble", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<double> %(n)s", "suffix" : "J" },
    "vector_Vec4f"    : { "j_type" : "MatOfFloat", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Vec4f> %(n)s", "suffix" : "J" },
    "vector_Vec6f"    : { "j_type" : "MatOfFloat", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Vec6f> %(n)s", "suffix" : "J" },
214

Andrey Kamaev's avatar
Andrey Kamaev committed
215
    "vector_Mat"      : { "j_type" : "List<Mat>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector<Mat> %(n)s", "suffix" : "J" },
216

217 218 219 220 221
    "vector_vector_KeyPoint": { "j_type" : "List<MatOfKeyPoint>", "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<KeyPoint> > %(n)s" },
    "vector_vector_DMatch"  : { "j_type" : "List<MatOfDMatch>",   "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<DMatch> > %(n)s" },
    "vector_vector_char"    : { "j_type" : "List<MatOfByte>",     "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<char> > %(n)s" },
    "vector_vector_Point"   : { "j_type" : "List<MatOfPoint>",    "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<Point> > %(n)s" },
    "vector_vector_Point2f" : { "j_type" : "List<MatOfPoint2f>",    "jn_type" : "long", "jni_type" : "jlong", "jni_var" : "vector< vector<Point2f> > %(n)s" },
222

223
    "Mat"     : { "j_type" : "Mat", "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
224
                  "jni_var" : "Mat& %(n)s = *((Mat*)%(n)s_nativeObj)",
225
                  "jni_type" : "jlong", #"jni_name" : "*%(n)s",
226
                  "suffix" : "J" },
227

228
    "Point"   : { "j_type" : "Point", "jn_args" : (("double", ".x"), ("double", ".y")),
229
                  "jni_var" : "Point %(n)s((int)%(n)s_x, (int)%(n)s_y)", "jni_type" : "jdoubleArray",
230 231
                  "suffix" : "DD"},
    "Point2f" : { "j_type" : "Point", "jn_args" : (("double", ".x"), ("double", ".y")),
232
                  "jni_var" : "Point2f %(n)s((float)%(n)s_x, (float)%(n)s_y)", "jni_type" : "jdoubleArray",
233 234
                  "suffix" : "DD"},
    "Point2d" : { "j_type" : "Point", "jn_args" : (("double", ".x"), ("double", ".y")),
235
                  "jni_var" : "Point2d %(n)s(%(n)s_x, %(n)s_y)", "jni_type" : "jdoubleArray",
236
                  "suffix" : "DD"},
237
    "Point3i" : { "j_type" : "Point3", "jn_args" : (("double", ".x"), ("double", ".y"), ("double", ".z")),
238
                  "jni_var" : "Point3i %(n)s((int)%(n)s_x, (int)%(n)s_y, (int)%(n)s_z)", "jni_type" : "jdoubleArray",
239
                  "suffix" : "DDD"},
240
    "Point3f" : { "j_type" : "Point3", "jn_args" : (("double", ".x"), ("double", ".y"), ("double", ".z")),
241
                  "jni_var" : "Point3f %(n)s((float)%(n)s_x, (float)%(n)s_y, (float)%(n)s_z)", "jni_type" : "jdoubleArray",
242
                  "suffix" : "DDD"},
243
    "Point3d" : { "j_type" : "Point3", "jn_args" : (("double", ".x"), ("double", ".y"), ("double", ".z")),
244
                  "jni_var" : "Point3d %(n)s(%(n)s_x, %(n)s_y, %(n)s_z)", "jni_type" : "jdoubleArray",
245
                  "suffix" : "DDD"},
246 247 248 249 250
    "KeyPoint": { "j_type" : "KeyPoint", "jn_args" : (("float", ".x"), ("float", ".y"), ("float", ".size"),
                    ("float", ".angle"), ("float", ".response"), ("int", ".octave"), ("int", ".class_id")),
                  "jni_var" : "KeyPoint %(n)s(%(n)s_x, %(n)s_y, %(n)s_size, %(n)s_angle, %(n)s_response, %(n)s_octave, %(n)s_class_id)",
                  "jni_type" : "jdoubleArray",
                  "suffix" : "FFFFFII"},
251 252 253 254 255
    "DMatch" :  { "j_type" : "DMatch", "jn_args" : ( ('int', 'queryIdx'), ('int', 'trainIdx'),
                    ('int', 'imgIdx'), ('float', 'distance'), ),
                  "jni_var" : "DMatch %(n)s(%(n)s_queryIdx, %(n)s_trainIdx, %(n)s_imgIdx, %(n)s_distance)",
                  "jni_type" : "jdoubleArray",
                  "suffix" : "IIIF"},
256
    "Rect"    : { "j_type" : "Rect",  "jn_args" : (("int", ".x"), ("int", ".y"), ("int", ".width"), ("int", ".height")),
257
                  "jni_var" : "Rect %(n)s(%(n)s_x, %(n)s_y, %(n)s_width, %(n)s_height)", "jni_type" : "jdoubleArray",
258
                  "suffix" : "IIII"},
259
    "Size"    : { "j_type" : "Size",  "jn_args" : (("double", ".width"), ("double", ".height")),
260
                  "jni_var" : "Size %(n)s((int)%(n)s_width, (int)%(n)s_height)", "jni_type" : "jdoubleArray",
261 262
                  "suffix" : "DD"},
    "Size2f"  : { "j_type" : "Size",  "jn_args" : (("double", ".width"), ("double", ".height")),
263
                  "jni_var" : "Size2f %(n)s((float)%(n)s_width, (float)%(n)s_height)", "jni_type" : "jdoubleArray",
264 265
                  "suffix" : "DD"},
 "RotatedRect": { "j_type" : "RotatedRect",  "jn_args" : (("double", ".center.x"), ("double", ".center.y"), ("double", ".size.width"), ("double", ".size.height"), ("double", ".angle")),
266
                  "jni_var" : "RotatedRect %(n)s(cv::Point2f(%(n)s_center_x, %(n)s_center_y), cv::Size2f(%(n)s_size_width, %(n)s_size_height), %(n)s_angle)",
267
                  "jni_type" : "jdoubleArray", "suffix" : "DDDDD"},
268 269
    "Scalar"  : { "j_type" : "Scalar",  "jn_args" : (("double", ".val[0]"), ("double", ".val[1]"), ("double", ".val[2]"), ("double", ".val[3]")),
                  "jni_var" : "Scalar %(n)s(%(n)s_val0, %(n)s_val1, %(n)s_val2, %(n)s_val3)", "jni_type" : "jdoubleArray",
270
                  "suffix" : "DDDD"},
271
    "Range"   : { "j_type" : "Range",  "jn_args" : (("int", ".start"), ("int", ".end")),
272
                  "jni_var" : "Range %(n)s(%(n)s_start, %(n)s_end)", "jni_type" : "jdoubleArray",
273
                  "suffix" : "II"},
274
    "CvSlice" : { "j_type" : "Range",  "jn_args" : (("int", ".start"), ("int", ".end")),
275
                  "jni_var" : "Range %(n)s(%(n)s_start, %(n)s_end)", "jni_type" : "jdoubleArray",
276
                  "suffix" : "II"},
277
    "string"  : { "j_type" : "String",  "jn_type" : "String",
278
                  "jni_type" : "jstring", "jni_name" : "n_%(n)s",
279
                  "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)',
280
                  "suffix" : "Ljava_lang_String_2"},
281
    "String"  : { "j_type" : "String",  "jn_type" : "String",
282 283 284
                  "jni_type" : "jstring", "jni_name" : "n_%(n)s",
                  "jni_var" : 'const char* utf_%(n)s = env->GetStringUTFChars(%(n)s, 0); String n_%(n)s( utf_%(n)s ? utf_%(n)s : "" ); env->ReleaseStringUTFChars(%(n)s, utf_%(n)s)',
                  "suffix" : "Ljava_lang_String_2"},
285
    "c_string": { "j_type" : "String",  "jn_type" : "String",
286 287 288
                  "jni_type" : "jstring", "jni_name" : "n_%(n)s.c_str()",
                  "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"},
289 290 291
"TermCriteria": { "j_type" : "TermCriteria",  "jn_args" : (("int", ".type"), ("int", ".maxCount"), ("double", ".epsilon")),
                  "jni_var" : "TermCriteria %(n)s(%(n)s_type, %(n)s_maxCount, %(n)s_epsilon)",
                  "suffix" : "IID"},
292 293 294 295
    "Vec3d"   : { "j_type" : "double[]",  "jn_args" : (("double", ".val[0]"), ("double", ".val[1]"), ("double", ".val[2]")),
                  "jn_type" : "double[]",
                  "jni_var" : "Vec3d %(n)s(%(n)s_val0, %(n)s_val1, %(n)s_val2)", "jni_type" : "jdoubleArray",
                  "suffix" : "DDD"},
296 297 298

}

299
# { class : { func : {j_code, jn_code, cpp_code} } }
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
ManualFuncs = {
    'Core' :
    {
        'minMaxLoc' : {
            'j_code'   : """
    // manual port
    public static class MinMaxLocResult {
        public double minVal;
        public double maxVal;
        public Point minLoc;
        public Point maxLoc;

    	public MinMaxLocResult() {
    	    minVal=0; maxVal=0;
    	    minLoc=new Point();
    	    maxLoc=new Point();
    	}
    }

    // C++: minMaxLoc(Mat src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray())

    //javadoc: minMaxLoc(src, mask)
    public static MinMaxLocResult minMaxLoc(Mat src, Mat mask) {
        MinMaxLocResult res = new MinMaxLocResult();
        long maskNativeObj=0;
        if (mask != null) {
            maskNativeObj=mask.nativeObj;
        }
        double resarr[] = n_minMaxLocManual(src.nativeObj, maskNativeObj);
        res.minVal=resarr[0];
        res.maxVal=resarr[1];
        res.minLoc.x=resarr[2];
        res.minLoc.y=resarr[3];
        res.maxLoc.x=resarr[4];
        res.maxLoc.y=resarr[5];
        return res;
    }

    //javadoc: minMaxLoc(src)
    public static MinMaxLocResult minMaxLoc(Mat src) {
        return minMaxLoc(src, null);
    }

""",
            'jn_code'  :
"""    private static native double[] n_minMaxLocManual(long src_nativeObj, long mask_nativeObj);\n""",
            'cpp_code' :
"""
// C++: minMaxLoc(Mat src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArray mask=noArray())

JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Core_n_1minMaxLocManual
  (JNIEnv* env, jclass cls, jlong src_nativeObj, jlong mask_nativeObj)
{
    try {
        LOGD("Core::n_1minMaxLoc()");
        jdoubleArray result;
        result = env->NewDoubleArray(6);
        if (result == NULL) {
            return NULL; /* out of memory error thrown */
        }

        Mat& src = *((Mat*)src_nativeObj);

        double minVal, maxVal;
        Point minLoc, maxLoc;
        if (mask_nativeObj != 0) {
            Mat& mask = *((Mat*)mask_nativeObj);
            minMaxLoc(src, &minVal, &maxVal, &minLoc, &maxLoc, mask);
        } else {
            minMaxLoc(src, &minVal, &maxVal, &minLoc, &maxLoc);
        }

        jdouble fill[6];
        fill[0]=minVal;
        fill[1]=maxVal;
        fill[2]=minLoc.x;
        fill[3]=minLoc.y;
        fill[4]=maxLoc.x;
        fill[5]=maxLoc.y;

        env->SetDoubleArrayRegion(result, 0, 6, fill);

	return result;

    } catch(cv::Exception e) {
        LOGD("Core::n_1minMaxLoc() catched cv::Exception: %s", e.what());
        jclass je = env->FindClass("org/opencv/core/CvException");
        if(!je) je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, e.what());
        return NULL;
    } catch (...) {
        LOGD("Core::n_1minMaxLoc() catched unknown exception (...)");
        jclass je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, "Unknown exception in JNI code {core::minMaxLoc()}");
        return NULL;
    }
}

""",
        }, # minMaxLoc

        'getTextSize' :
        {
            'j_code'   :
"""
    // C++: Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine);
    //javadoc:getTextSize(text, fontFace, fontScale, thickness, baseLine)
    public static Size getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine) {
        if(baseLine != null && baseLine.length != 1)
            throw new java.lang.IllegalArgumentException("'baseLine' must be 'int[1]' or 'null'.");
        Size retVal = new Size(n_getTextSize(text, fontFace, fontScale, thickness, baseLine));
        return retVal;
    }
""",
            'jn_code'  :
"""    private static native double[] n_getTextSize(String text, int fontFace, double fontScale, int thickness, int[] baseLine);\n""",
            'cpp_code' :
"""
// C++: Size getTextSize(const string& text, int fontFace, double fontScale, int thickness, int* baseLine);

JNIEXPORT jdoubleArray JNICALL Java_org_opencv_core_Core_n_1getTextSize
  (JNIEnv* env, jclass cls, jstring text, jint fontFace, jdouble fontScale, jint thickness, jintArray baseLine)
{
    try {
        LOGD("Core::n_1getTextSize()");
        jdoubleArray result;
        result = env->NewDoubleArray(2);
        if (result == NULL) {
            return NULL; /* out of memory error thrown */
        }

        const char* utf_text = env->GetStringUTFChars(text, 0);
        std::string n_text( utf_text ? utf_text : "" );
        env->ReleaseStringUTFChars(text, utf_text);

        int _baseLine;
        int* pbaseLine = 0;

        if (baseLine != NULL)
            pbaseLine = &_baseLine;

        cv::Size rsize = cv::getTextSize(n_text, (int)fontFace, (double)fontScale, (int)thickness, pbaseLine);

        jdouble fill[2];
        fill[0]=rsize.width;
        fill[1]=rsize.height;

        env->SetDoubleArrayRegion(result, 0, 2, fill);

        if (baseLine != NULL)
            env->SetIntArrayRegion(baseLine, 0, 1, pbaseLine);

        return result;

    } catch(cv::Exception e) {
        LOGD("Core::n_1getTextSize() catched cv::Exception: %s", e.what());
        jclass je = env->FindClass("org/opencv/core/CvException");
        if(!je) je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, e.what());
        return NULL;
    } catch (...) {
        LOGD("Core::n_1getTextSize() catched unknown exception (...)");
        jclass je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, "Unknown exception in JNI code {core::getTextSize()}");
        return NULL;
    }
}

""",
        }, # getTextSize
470 471
##        "checkRange"           : #TBD
##            {'j_code' : '/* TBD: checkRange() */', 'jn_code' : '', 'cpp_code' : '' },
472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491

        "checkHardwareSupport" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "setUseOptimized"      : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "useOptimized"         : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },

    }, # Core

    'Highgui' :
    {
        "namedWindow"       : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "destroyWindow"     : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "destroyAllWindows" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "startWindowThread" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "setWindowProperty" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "getWindowProperty" : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "getTrackbarPos"    : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "setTrackbarPos"    : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "imshow"            : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
        "waitKey"           : {'j_code' : '', 'jn_code' : '', 'cpp_code' : '' },
    }, # Highgui
492

493
}
494

495 496 497
# { class : { func : {arg_name : ctype} } }
func_arg_fix = {
    '' : {
498 499
        'randu'    : { 'low'     : 'double', 'high'   : 'double', },
        'randn'    : { 'mean'    : 'double', 'stddev' : 'double', },
500
        'inRange'  : { 'lowerb'  : 'Scalar', 'upperb' : 'Scalar', },
501 502 503
        'goodFeaturesToTrack' : { 'corners' : 'vector_Point', },
        'findFundamentalMat' : { 'points1' : 'vector_Point2d', 'points2' : 'vector_Point2d', },
        'cornerSubPix' : { 'corners' : 'vector_Point2f', },
504
        'minEnclosingCircle' : { 'points' : 'vector_Point2f', },
505 506 507
        'findHomography' : { 'srcPoints' : 'vector_Point2f', 'dstPoints' : 'vector_Point2f', },
        'solvePnP' : { 'objectPoints' : 'vector_Point3f', 'imagePoints' : 'vector_Point2f', },
        'solvePnPRansac' : { 'objectPoints' : 'vector_Point3f', 'imagePoints' : 'vector_Point2f', },
508 509
        'calcOpticalFlowPyrLK' : { 'prevPts' : 'vector_Point2f', 'nextPts' : 'vector_Point2f',
                                   'status' : 'vector_uchar', 'err' : 'vector_float', },
510
        'fitEllipse' : { 'points' : 'vector_Point2f', },
Andrey Kamaev's avatar
Andrey Kamaev committed
511 512 513
        'fillPoly' : { 'pts' : 'vector_vector_Point', },
        'polylines' : { 'pts' : 'vector_vector_Point', },
        'fillConvexPoly' : { 'points' : 'vector_Point', },
514
        'boundingRect' : { 'points' : 'vector_Point', },
Andrey Pavlenko's avatar
Andrey Pavlenko committed
515
        'approxPolyDP' : { 'curve' : 'vector_Point2f', 'approxCurve' : 'vector_Point2f', },
516 517 518 519
        'arcLength' : { 'curve' : 'vector_Point2f', },
        'pointPolygonTest' : { 'contour' : 'vector_Point2f', },
        'minAreaRect' : { 'points' : 'vector_Point2f', },
        'getAffineTransform' : { 'src' : 'vector_Point2f', 'dst' : 'vector_Point2f', },
520 521
        'hconcat' : { 'src' : 'vector_Mat', },
        'vconcat' : { 'src' : 'vector_Mat', },
522 523
        'undistortPoints' : { 'src' : 'vector_Point2d', 'dst' : 'vector_Point2d' },
        'checkRange' : {'pos' : '*'},
Andrey Pavlenko's avatar
Andrey Pavlenko committed
524
        'meanStdDev' : {'mean' : 'vector_double', 'stddev' : 'vector_double'},
525 526 527 528
        'drawContours' : {'contours' : 'vector_vector_Point'},
        'findContours' : {'contours' : 'vector_vector_Point'},
        'convexityDefects' : {'contour' : 'vector_Point'},
        'isContourConvex' : { 'contour' : 'vector_Point2f', },
529
    }, # '', i.e. no class
530 531
} # func_arg_fix

532
class ConstInfo(object):
533
    def __init__(self, cname, name, val, addedManually=False):
534
        self.cname = cname
535
        self.name = re.sub(r"^Cv", "", name)
536
        self.value = val
537
        self.addedManually = addedManually
538 539


540 541 542 543 544 545
class ClassPropInfo(object):
    def __init__(self, decl): # [f_ctype, f_name, '', '/RW']
        self.ctype = decl[0]
        self.name = decl[1]
        self.rw = "/RW" in decl[3]

546
class ClassInfo(object):
547
    def __init__(self, decl): # [ 'class/struct cname', ': base', [modlist] ]
548 549 550
        name = decl[0]
        name = name[name.find(" ")+1:].strip()
        self.cname = self.name = self.jname = re.sub(r"^cv\.", "", name)
551
        self.cname = self.cname.replace(".", "::")
552
        self.methods = {}
553
        self.methods_suffixes = {}
554
        self.consts = [] # using a list to save the occurence order
555 556
        self.private_consts = []
        self.imports = set()
557
        self.props= []
558
        self.jname = self.name
559 560 561
        for m in decl[2]:
            if m.startswith("="):
                self.jname = m[1:]
562 563 564 565
        self.base = ''
        if decl[1]:
            self.base = re.sub(r"\b"+self.jname+r"\b", "", decl[1].replace(":", "")).strip()

566 567 568 569


class ArgInfo(object):
    def __init__(self, arg_tuple): # [ ctype, name, def val, [mod], argno ]
570 571 572 573 574 575
        self.pointer = False
        ctype = arg_tuple[0]
        if ctype.endswith("*"):
            ctype = ctype[:-1]
            self.pointer = True
        self.ctype = ctype
576 577
        self.name = arg_tuple[1]
        self.defval = arg_tuple[2]
578 579 580 581 582
        self.out = ""
        if "/O" in arg_tuple[3]:
            self.out = "O"
        if "/IO" in arg_tuple[3]:
            self.out = "IO"
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603


class FuncInfo(object):
    def __init__(self, decl): # [ funcname, return_ctype, [modifiers], [args] ]
        name = re.sub(r"^cv\.", "", decl[0])
        self.cname = name.replace(".", "::")
        classname = ""
        dpos = name.rfind(".")
        if dpos >= 0:
            classname = name[:dpos]
            name = name[dpos+1:]
        self.classname = classname
        self.jname = self.name = name
        if "[" in name:
            self.jname = "getelem"
        for m in decl[2]:
            if m.startswith("="):
                self.jname = m[1:]
        self.static = ["","static"][ "/S" in decl[2] ]
        self.ctype = decl[1] or ""
        self.args = []
604
        arg_fix_map = func_arg_fix.get(classname, {}).get(self.jname, {})
605
        for a in decl[3]:
606 607 608
            arg = a[:]
            arg[0] = arg_fix_map.get(arg[1], arg[0])
            ai = ArgInfo(arg)
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630
            self.args.append(ai)



class FuncFamilyInfo(object):
    def __init__(self, decl): # [ funcname, return_ctype, [modifiers], [args] ]
        self.funcs = []
        self.funcs.append( FuncInfo(decl) )
        self.jname = self.funcs[0].jname
        self.isconstructor = self.funcs[0].name == self.funcs[0].classname



    def add_func(self, fi):
        self.funcs.append( fi )


class JavaWrapperGenerator(object):
    def __init__(self):
        self.clear()

    def clear(self):
631
        self.classes = { "Mat" : ClassInfo([ 'class Mat', '', [], [] ]) }
632
        self.module = ""
633 634 635
        self.Module = ""
        self.java_code= {} # { class : {j_code, jn_code} }
        self.cpp_code = None
636 637
        self.ported_func_list = []
        self.skipped_func_list = []
638 639 640
        self.def_args_hist = {} # { def_args_cnt : funcs_cnt }
        self.classes_map = []
        self.classes_simple = []
641

642
    def add_class_code_stream(self, class_name, cls_base = ''):
643
        jname = self.classes[class_name].jname
644
        self.java_code[class_name] = { "j_code" : StringIO(), "jn_code" : StringIO(), }
645
        if class_name != self.Module:
646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
            if cls_base:
                self.java_code[class_name]["j_code"].write("""
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.%(m)s;

$imports

// C++: class %(c)s
//javadoc: %(c)s
public class %(jc)s extends %(base)s {

    protected %(jc)s(long addr) { super(addr); }

""" % { 'm' : self.module, 'c' : class_name, 'jc' : jname, 'base' :  cls_base })
            else: # not cls_base
                self.java_code[class_name]["j_code"].write("""
664 665 666
//
// This file is auto-generated. Please don't modify it!
//
667
package org.opencv.%(m)s;
668

669 670 671 672
$imports

// C++: class %(c)s
//javadoc: %(c)s
673
public class %(jc)s {
674 675

    protected final long nativeObj;
676
    protected %(jc)s(long addr) { nativeObj = addr; }
677

678
""" % { 'm' : self.module, 'c' : class_name, 'jc' : jname })
679 680 681 682 683 684 685 686 687
        else: # class_name == self.Module
            self.java_code[class_name]["j_code"].write("""
//
// This file is auto-generated. Please don't modify it!
//
package org.opencv.%(m)s;

$imports

688 689
public class %(jc)s {
""" % { 'm' : self.module, 'jc' : jname } )
690 691 692 693 694 695 696 697 698

        self.java_code[class_name]["jn_code"].write("""
    //
    // native stuff
    //
    static { System.loadLibrary("opencv_java"); }
""" )


699 700 701

    def add_class(self, decl):
        classinfo = ClassInfo(decl)
702 703
        if classinfo.name in class_ignore_list:
            return
704 705
        name = classinfo.name
        if name in self.classes:
706
            print "Generator error: class %s (%s) is duplicated" % \
707
                    (name, classinfo.cname)
708
            return
709 710 711
        self.classes[name] = classinfo
        if name in type_dict:
            print "Duplicated class: " + name
712
            return
713 714
        if '/Simple' in decl[2]:
            self.classes_simple.append(name)
715
        if ('/Map' in decl[2]):
716
            self.classes_map.append(name)
717 718 719
            #adding default c-tor
            ffi = FuncFamilyInfo(['cv.'+name+'.'+name, '', [], []])
            classinfo.methods[ffi.jname] = ffi
720 721
        type_dict[name] = \
            { "j_type" : classinfo.jname,
722
              "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
723 724 725 726 727 728
              "jni_name" : "(*("+name+"*)%(n)s_nativeObj)", "jni_type" : "jlong",
              "suffix" : "J" }
        type_dict[name+'*'] = \
            { "j_type" : classinfo.jname,
              "jn_type" : "long", "jn_args" : (("__int64", ".nativeObj"),),
              "jni_name" : "("+name+"*)%(n)s_nativeObj", "jni_type" : "jlong",
729
              "suffix" : "J" }
730

731
        # missing_consts { Module : { public : [[name, val],...], private : [[]...] } }
732 733 734 735 736 737 738
        if name in missing_consts:
            if 'private' in missing_consts[name]:
                for (n, val) in missing_consts[name]['private']:
                    classinfo.private_consts.append( ConstInfo(n, n, val, True) )
            if 'public' in missing_consts[name]:
                for (n, val) in missing_consts[name]['public']:
                    classinfo.consts.append( ConstInfo(n, n, val, True) )
739

740 741
        # class props
        for p in decl[3]:
742
            if True: #"vector" not in p[0]:
743 744
                classinfo.props.append( ClassPropInfo(p) )
            else:
745
                print "Skipped property: [%s]" % name, p
746

747
        self.add_class_code_stream(name, classinfo.base)
748 749 750 751 752 753


    def add_const(self, decl): # [ "const cname", val, [], [] ]
        name = decl[0].replace("const ", "").strip()
        name = re.sub(r"^cv\.", "", name)
        cname = name.replace(".", "::")
754 755 756
        for c in const_ignore_list:
            if re.match(c, name):
                return
757
        # class member?
758 759 760 761
        dpos = name.rfind(".")
        if dpos >= 0:
            classname = name[:dpos]
            name = name[dpos+1:]
762 763 764 765 766 767
        else:
            classname = self.Module
        if classname not in self.classes:
            # this class isn't wrapped
            # skipping this const
            return
768

769
        consts = self.classes[classname].consts
770 771 772 773
        for c in const_private_list:
            if re.match(c, name):
                consts = self.classes[classname].private_consts
                break
774

775 776
        constinfo = ConstInfo(cname, name, decl[1])
        # checking duplication
777 778 779 780 781 782 783 784 785
        for list in self.classes[classname].consts, self.classes[classname].private_consts:
            for c in list:
                if c.name == constinfo.name:
                    if c.addedManually:
                        return
                    print "Generator error: constant %s (%s) is duplicated" \
                            % (constinfo.name, constinfo.cname)
                    sys.exit(-1)

786 787 788 789
        consts.append(constinfo)

    def add_func(self, decl):
        ffi = FuncFamilyInfo(decl)
790 791
        classname = ffi.funcs[0].classname or self.Module
        if classname in class_ignore_list:
792
            return
793 794 795 796 797 798 799
        if classname in ManualFuncs and ffi.jname in ManualFuncs[classname]:
            return
        if classname not in self.classes:
            print "Generator error: the class %s for method %s is missing" % \
                    (classname, ffi.jname)
            sys.exit(-1)
        func_map = self.classes[classname].methods
800 801 802 803
        if ffi.jname in func_map:
            func_map[ffi.jname].add_func(ffi.funcs[0])
        else:
            func_map[ffi.jname] = ffi
804 805 806
        # calc args with def val
        cnt = len([a for a in ffi.funcs[0].args if a.defval])
        self.def_args_hist[cnt] = self.def_args_hist.get(cnt, 0) + 1
807

808 809
    def save(self, path, buf):
        f = open(path, "wt")
810
        f.write(buf)
811 812 813 814 815
        f.close()

    def gen(self, srcfiles, module, output_path):
        self.clear()
        self.module = module
816
        self.Module = module.capitalize()
817 818
        parser = hdr_parser.CppHeaderParser()

819
        self.add_class( ['class ' + self.Module, '', [], []] ) # [ 'class/struct cname', ':bases', [modlist] [props] ]
820 821

        # scan the headers and build more descriptive maps of classes, consts, functions
822 823 824 825 826 827 828 829 830 831
        for hdr in srcfiles:
            decls = parser.parse(hdr)
            for decl in decls:
                name = decl[0]
                if name.startswith("struct") or name.startswith("class"):
                    self.add_class(decl)
                elif name.startswith("const"):
                    self.add_const(decl)
                else: # function
                    self.add_func(decl)
832

833 834 835
        self.cpp_code = StringIO()
        self.cpp_code.write("""
//
836 837
// This file is auto-generated, please don't edit!
//
838 839

#include <jni.h>
840

841
#include "converters.h"
842

843
#ifdef DEBUG
844
#include <android/log.h>
845
#define MODULE_LOG_TAG "OpenCV.%(m)s"
846
#define LOGD(...) ((void)__android_log_print(ANDROID_LOG_DEBUG, MODULE_LOG_TAG, __VA_ARGS__))
847 848 849
#else //DEBUG
#define LOGD(...)
#endif //DEBUG
850

851
#include "opencv2/%(m)s/%(m)s.hpp"
852

853
using namespace cv;
Andrey Kamaev's avatar
Andrey Kamaev committed
854

855
extern "C" {
Andrey Kamaev's avatar
Andrey Kamaev committed
856

857
""" % {'m' : module} )
858

859 860
        # generate code for the classes
        for name in self.classes.keys():
861 862
            if name == "Mat":
                continue
863
            self.gen_class(name)
864
            # saving code streams
865
            imports = "\n".join([ "import %s;" % c for c in \
866 867 868
                sorted(self.classes[name].imports) if not c.startswith('org.opencv.'+self.module) ])
            self.java_code[name]["j_code"].write("\n\n%s\n}\n" % self.java_code[name]["jn_code"].getvalue())
            java_code = self.java_code[name]["j_code"].getvalue()
869
            java_code = Template(java_code).substitute(imports = imports)
870
            self.save("%s/%s+%s.java" % (output_path, module, self.classes[name].jname), java_code)
871

872
        self.cpp_code.write( '\n} // extern "C"\n' )
873
        self.save(output_path+"/"+module+".cpp",  self.cpp_code.getvalue())
874

875 876 877
        # report
        report = StringIO()
        report.write("PORTED FUNCs LIST (%i of %i):\n\n" % \
878
            (len(self.ported_func_list), len(self.ported_func_list)+ len(self.skipped_func_list))
879 880 881
        )
        report.write("\n".join(self.ported_func_list))
        report.write("\n\nSKIPPED FUNCs LIST (%i of %i):\n\n" % \
882
            (len(self.skipped_func_list), len(self.ported_func_list)+ len(self.skipped_func_list))
883 884
        )
        report.write("".join(self.skipped_func_list))
885 886 887 888 889 890 891

        for i in self.def_args_hist.keys():
            report.write("\n%i def args - %i funcs" % (i, self.def_args_hist[i]))

        report.write("\n\nclass as MAP:\n\t" + "\n\t".join(self.classes_map))
        report.write("\n\nclass SIMPLE:\n\t" + "\n\t".join(self.classes_simple))

892
        self.save(output_path+"/"+module+".txt", report.getvalue())
893

894
        print "Done %i of %i funcs." % (len(self.ported_func_list), len(self.ported_func_list)+ len(self.skipped_func_list))
895 896


897

898 899 900 901
    def get_imports(self, scope_classname, ctype):
        imports = self.classes[scope_classname or self.Module].imports
        if ctype.startswith('vector'):
            imports.add("org.opencv.core.Mat")
902
            if type_dict[ctype]['j_type'].startswith('MatOf'):
903 904 905 906 907
                imports.add("org.opencv.core." + type_dict[ctype]['j_type'])
                return #TMP
            else:
                imports.add("java.util.List")
                imports.add("org.opencv.utils.Converters")
908 909 910 911 912 913 914 915 916 917
            ctype = ctype.replace('vector_', '')
        j_type = ''
        if ctype in type_dict:
            j_type = type_dict[ctype]['j_type']
        if j_type in ( "CvType", "Mat", "Point", "Point3", "Range", "Rect", "RotatedRect", "Scalar", "Size", "TermCriteria" ):
            imports.add("org.opencv.core." + j_type)
        if j_type == 'String':
            imports.add("java.lang.String")


918

919
    def gen_func(self, fi, prop_name=''):
920 921
        j_code   = self.java_code[fi.classname or self.Module]["j_code"]
        jn_code  = self.java_code[fi.classname or self.Module]["jn_code"]
922
        cpp_code = self.cpp_code
923 924 925 926 927 928 929 930

        # 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:
931
                s = a.ctype or ' _hidden_ '
932 933 934 935 936 937 938 939 940
                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) )
941

942
        # java comment
943
        j_code.write( "\n    //\n    // C++: %s\n    //\n\n" % c_decl )
944
        # check if we 'know' all the types
945
        if fi.ctype not in type_dict: # unsupported ret type
946
            msg = "// Return type '%s' is not supported, skipping the function\n\n" % fi.ctype
947
            self.skipped_func_list.append(c_decl + "\n" + msg)
948
            j_code.write( " "*4 + msg )
949 950 951
            print "SKIP:", c_decl, "\n\tdue to RET type", fi.ctype
            return
        for a in fi.args:
952
            if a.ctype not in type_dict:
953
                msg = "// Unknown type '%s' (%s), skipping the function\n\n" % (a.ctype, a.out or "I")
954
                self.skipped_func_list.append(c_decl + "\n" + msg)
955
                j_code.write( " "*4 + msg )
956
                print "SKIP:", c_decl, "\n\tdue to ARG type", a.ctype, "/" + (a.out or "I")
957 958
                return

959
        self.ported_func_list.append(c_decl)
960

961
        # jn & cpp comment
962 963
        jn_code.write( "\n    // C++: %s\n" % c_decl )
        cpp_code.write( "\n//\n// %s\n//\n" % c_decl )
964

965
        # java args
966
        args = fi.args[:] # copy
967
        suffix_counter = int( self.classes[fi.classname or self.Module].methods_suffixes.get(fi.jname, -1) )
968
        while True:
969
            suffix_counter += 1
970
            self.classes[fi.classname or self.Module].methods_suffixes[fi.jname] = suffix_counter
971
             # java native method args
972 973 974
            jn_args = []
            # jni (cpp) function args
            jni_args = [ArgInfo([ "env", "env", "", [], "" ]), ArgInfo([ "cls", "cls", "", [], "" ])]
975 976 977 978 979
            j_prologue = []
            j_epilogue = []
            c_prologue = []
            c_epilogue = []
            if type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
980 981 982 983 984 985
                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_);") %
                    { "cnt" : len(fields), "args" : ", ".join(["_retval_" + f[1] for f in fields]) } )
986 987 988 989
            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", "", [], "" ]) )
990
            self.get_imports(fi.classname, fi.ctype)
991
            for a in args:
992 993
                if not a.ctype: # hidden
                    continue
994
                self.get_imports(fi.classname, a.ctype)
995 996 997 998
                if "vector" in a.ctype: # pass as 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} + ";" )
999
                    c_prologue.append( "Mat& %(n)s_mat = *((Mat*)%(n)s_mat_nativeObj)" % {"n" : a.name} + ";" )
1000
                    if "I" in a.out or not a.out:
1001 1002 1003 1004 1005
                        if a.ctype.startswith("vector_vector_"):
                            self.classes[fi.classname or self.Module].imports.add("java.util.ArrayList")
                            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:
1006
                            if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
1007 1008 1009
                                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) )
1010
                        c_prologue.append( "Mat_to_%(t)s( %(n)s_mat, %(n)s );" % {"n" : a.name, "t" : a.ctype} )
1011
                    else:
1012
                        if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
1013 1014 1015
                            j_prologue.append( "Mat %s_mat = new Mat();" % a.name )
                        else:
                            j_prologue.append( "Mat %s_mat = %s;" % (a.name, a.name) )
1016
                    if "O" in a.out:
1017
                        if not type_dict[a.ctype]["j_type"].startswith("MatOf"):
1018
                            j_epilogue.append("Converters.Mat_to_%(t)s(%(n)s_mat, %(n)s);" % {"t" : a.ctype, "n" : a.name})
1019
                        c_epilogue.append( "%(t)s_to_Mat( %(n)s, %(n)s_mat );" % {"n" : a.name, "t" : a.ctype} )
1020
                else:
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
                    fields = type_dict[a.ctype].get("jn_args", ((a.ctype, ""),))
                    if "I" in a.out or not a.out or a.ctype in self.classes: # input arg, pass by primitive fields
                        for f in fields:
                            jn_args.append ( ArgInfo([ f[0], a.name + f[1], "", [], "" ]) )
                            jni_args.append( ArgInfo([ f[0], a.name + f[1].replace(".","_").replace("[","").replace("]",""), "", [], "" ]) )
                    if a.out and a.ctype not in self.classes: # out arg, pass as double[]
                        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)) )
                        c_epilogue.append( \
                            "jdouble tmp_%(n)s[%(cnt)i] = {%(args)s}; env->SetDoubleArrayRegion(%(n)s_out, 0, %(cnt)i, tmp_%(n)s);" %
                            { "n" : a.name, "cnt" : len(fields), "args" : ", ".join([a.name + f[1] for f in fields]) } )
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043
                        if a.ctype 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':a.ctype})
                        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) + "; } ")
1044

1045 1046 1047 1048

            # java part:
            # private java NATIVE method decl
            # e.g.
1049
            # private static native void add_0(long src1, long src2, long dst, long mask, int dtype);
1050
            jn_code.write( Template(\
1051 1052
                "    private static native $type $name($args);\n").substitute(\
                type = type_dict[fi.ctype].get("jn_type", "double[]"), \
1053
                name = fi.jname + '_' + str(suffix_counter), \
1054
                args = ", ".join(["%s %s" % (type_dict[a.ctype]["jn_type"], a.name.replace(".","_").replace("[","").replace("]","")) for a in jn_args])
1055 1056 1057
            ) );

            # java part:
1058 1059

            #java doc comment
1060 1061 1062 1063
            f_name = fi.name
            if fi.classname:
                f_name = fi.classname + "::" + fi.name
            java_doc = "//javadoc: " + f_name + "(%s)" % ", ".join([a.name for a in args])
1064
            j_code.write(" "*4 + java_doc + "\n")
1065

1066 1067 1068
            # 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 )
1069
            # { add_0( src1.nativeObj, src2.nativeObj, dst.nativeObj, mask.nativeObj, dtype );  }
1070 1071 1072 1073
            ret_type = fi.ctype
            if fi.ctype.endswith('*'):
                ret_type = ret_type[:-1]
            ret_val = type_dict[ret_type]["j_type"] + " retVal = "
1074 1075
            tail = ""
            ret = "return retVal;"
1076 1077 1078
            if ret_type.startswith('vector'):
                tail = ")"
                j_type = type_dict[ret_type]["j_type"]
1079
                if j_type.startswith('MatOf'):
1080
                    ret_val += "new " + j_type + "("
1081 1082 1083 1084 1085 1086
                    m_t  = re.match('vector_(\w+)', ret_type)
                    m_ch = re.match('vector_Vec(\d+)', ret_type)
                    if m_ch:
                        ret_val += m_ch.group(1) +  ', '
                    elif m_t.group(1) in ('char', 'uchar', 'int', 'float', 'double'):
                        ret_val += '1, '
1087 1088 1089 1090 1091
                else:
                    ret_val = "Mat retValMat = new Mat("
                    j_prologue.append( j_type + ' retVal = new Array' + j_type+'();')
                    self.classes[fi.classname or self.Module].imports.add('java.util.ArrayList')
                    j_epilogue.append('Converters.Mat_to_' + ret_type + '(retValMat, retVal);')
1092
            elif ret_type == "void":
1093 1094
                ret_val = ""
                ret = "return;"
1095
            elif ret_type == "": # c-tor
1096 1097 1098 1099 1100
                if fi.classname and self.classes[fi.classname].base:
                    ret_val = "super( "
                    tail = " )"
                else:
                    ret_val = "nativeObj = "
1101
                ret = "return;"
1102 1103
            elif ret_type in self.classes: # wrapped class
                ret_val = type_dict[ret_type]["j_type"] + " retVal = new " + self.classes[ret_type].jname + "("
1104
                tail = ")"
1105 1106
            elif "jn_type" not in type_dict[ret_type]:
                ret_val = type_dict[fi.ctype]["j_type"] + " retVal = new " + type_dict[ret_type]["j_type"] + "("
1107
                tail = ")"
1108 1109 1110 1111 1112

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

1113 1114
            j_args = []
            for a in args:
1115 1116
                if not a.ctype: #hidden
                    continue
1117 1118 1119 1120 1121
                jt = type_dict[a.ctype]["j_type"]
                if a.out and a.ctype in ('bool', 'int', 'long', 'float', 'double'):
                    jt += '[]'
                j_args.append( jt + ' ' + a.name )

1122 1123 1124 1125 1126 1127 1128 1129
            j_code.write( Template(\
"""    public $static $j_type $j_name($j_args)
    {
        $prologue
        $ret_val$jn_name($jn_args_call)$tail;
        $epilogue
        $ret
    }
1130

1131 1132 1133 1134 1135
"""
                ).substitute(\
                    ret = ret, \
                    ret_val = ret_val, \
                    tail = tail, \
1136 1137
                    prologue = "\n        ".join(j_prologue), \
                    epilogue = "\n        ".join(j_epilogue), \
1138 1139 1140
                    static=static, \
                    j_type=type_dict[fi.ctype]["j_type"], \
                    j_name=fi.jname, \
1141
                    j_args=", ".join(j_args), \
1142
                    jn_name=fi.jname + '_' + str(suffix_counter), \
1143 1144 1145
                    jn_args_call=", ".join( [a.name for a in jn_args] ),\
                )
            )
1146

1147

1148
            # cpp part:
1149 1150
            # jni_func(..) { _retval_ = cv_func(..); return _retval_; }
            ret = "return _retval_;"
1151
            default = "return 0;"
1152
            if fi.ctype == "void":
1153 1154 1155 1156
                ret = "return;"
                default = "return;"
            elif not fi.ctype: # c-tor
                ret = "return (jlong) _retval_;"
1157 1158
            elif fi.ctype.startswith('vector'): # c-tor
                ret = "return (jlong) _retval_;"
1159
            elif fi.ctype == "string":
1160
                ret = "return env->NewStringUTF(_retval_.c_str());"
1161
                default = 'return env->NewStringUTF("");'
1162
            elif fi.ctype in self.classes: # wrapped class:
1163
                ret = "return (jlong) new %s(_retval_);" % fi.ctype
1164 1165
            elif ret_type in self.classes: # pointer to wrapped class:
                ret = "return (jlong) _retval_;"
1166
            elif type_dict[fi.ctype]["jni_type"] == "jdoubleArray":
1167
                ret = "return _da_retval_;"
1168

1169 1170 1171 1172 1173 1174 1175 1176 1177
            # hack: replacing func call with property set/get
            name = fi.name
            if prop_name:
                if args:
                    name = prop_name + " = "
                else:
                    name = prop_name + ";//"

            cvname = "cv::" + name
1178 1179 1180
            retval = fi.ctype + " _retval_ = "
            if fi.ctype == "void":
                retval = ""
1181 1182 1183 1184
            elif fi.ctype.startswith('vector'):
                retval = type_dict[fi.ctype]['jni_var'] % {"n" : '_ret_val_vector_'} + " = "
                c_epilogue.append("Mat* _retval_ = new Mat();")
                c_epilogue.append(fi.ctype+"_to_Mat(_ret_val_vector_, *_retval_);")
1185 1186
            if fi.classname:
                if not fi.ctype: # c-tor
1187 1188
                    retval = fi.classname + "* _retval_ = "
                    cvname = "new " + fi.classname
1189
                elif fi.static:
1190
                    cvname = "%s::%s" % (fi.classname, name)
1191
                else:
1192
                    cvname = "me->" + name
1193
                    c_prologue.append(\
1194
                        "%(cls)s* me = (%(cls)s*) self; //TODO: check for NULL" \
1195
                            % { "cls" : fi.classname} \
1196 1197 1198
                    )
            cvargs = []
            for a in args:
1199 1200 1201 1202
                if a.pointer:
                    jni_name = "&%(n)s"
                else:
                    jni_name = "%(n)s"
1203 1204
                if not a.ctype: # hidden
                    jni_name = a.defval
1205 1206 1207 1208
                cvargs.append( type_dict[a.ctype].get("jni_name", jni_name) % {"n" : a.name})
                if "vector" not in a.ctype :
                    if ("I" in a.out or not a.out or a.ctype in self.classes) and "jni_var" in type_dict[a.ctype]: # complex type
                        c_prologue.append(type_dict[a.ctype]["jni_var"] % {"n" : a.name} + ";")
1209
                    if a.out and "I" not in a.out and a.ctype not in self.classes and a.ctype:
1210
                        c_prologue.append("%s %s;" % (a.ctype, a.name))
1211

1212
            rtype = type_dict[fi.ctype].get("jni_type", "jdoubleArray")
1213 1214 1215
            clazz = self.Module
            if fi.classname:
                clazz = self.classes[fi.classname].jname
1216
            cpp_code.write ( Template( \
1217 1218
"""

1219
JNIEXPORT $rtype JNICALL Java_org_opencv_${module}_${clazz}_$fname
1220 1221
  ($args)
{
1222
    try {
1223
        LOGD("$module::$fname()");
1224
        $prologue
1225
        $retval$cvname( $cvargs );
1226
        $epilogue
1227
        $ret
1228
    } catch(cv::Exception e) {
1229
        LOGD("$module::$fname() catched cv::Exception: %s", e.what());
1230
        jclass je = env->FindClass("org/opencv/core/CvException");
1231 1232
        if(!je) je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, e.what());
1233
        $default
1234
    } catch (...) {
1235
        LOGD("$module::$fname() catched unknown exception (...)");
1236 1237
        jclass je = env->FindClass("java/lang/Exception");
        env->ThrowNew(je, "Unknown exception in JNI code {$module::$fname()}");
1238
        $default
1239
    }
1240 1241
}

1242

1243 1244 1245
""" ).substitute( \
        rtype = rtype, \
        module = self.module, \
1246
        clazz = clazz.replace('_', '_1'), \
1247
        fname = (fi.jname + '_' + str(suffix_counter)).replace('_', '_1'), \
1248
        args = ", ".join(["%s %s" % (type_dict[a.ctype].get("jni_type"), a.name) for a in jni_args]), \
1249 1250
        prologue = "\n        ".join(c_prologue), \
        epilogue = "  ".join(c_epilogue), \
1251 1252
        ret = ret, \
        cvname = cvname, \
1253
        cvargs = ", ".join(cvargs), \
1254 1255
        default = default, \
        retval = retval, \
1256 1257 1258
    ) )

            # processing args with default values
1259
            if not args or not args[-1].defval:
1260
                break
1261 1262 1263 1264 1265
            while args and args[-1].defval:
                # 'smart' overloads filtering
                a = args.pop()
                if a.name in ('mask', 'dtype', 'ddepth', 'lineType', 'borderType', 'borderMode', 'criteria'):
                    break
1266 1267 1268



1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
    def gen_class(self, name):
        # generate code for the class
        ci = self.classes[name]
        # constants
        if ci.private_consts:
            self.java_code[name]['j_code'].write("""
    private static final int
            %s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in ci.private_consts])
            )
        if ci.consts:
            self.java_code[name]['j_code'].write("""
    public static final int
            %s;\n\n""" % (",\n"+" "*12).join(["%s = %s" % (c.name, c.value) for c in ci.consts])
            )
        # c-tors
        fflist = ci.methods.items()
1285
        fflist.sort()
1286 1287 1288
        for n, ffi in fflist:
            if ffi.isconstructor:
                for fi in ffi.funcs:
1289
                    fi.jname = ci.jname
1290
                    self.gen_func(fi)
1291 1292 1293 1294
        # other methods
        for n, ffi in fflist:
            if not ffi.isconstructor:
                for fi in ffi.funcs:
1295
                    self.gen_func(fi)
1296 1297 1298 1299 1300 1301
        # props
        for pi in ci.props:
            # getter
            getter_name = name + ".get_" + pi.name
            #print getter_name
            fi = FuncInfo( [getter_name, pi.ctype, [], []] ) # [ funcname, return_ctype, [modifiers], [args] ]
1302
            self.gen_func(fi, pi.name)
1303 1304 1305 1306 1307
            if pi.rw:
                #setter
                setter_name = name + ".set_" + pi.name
                #print setter_name
                fi = FuncInfo( [ setter_name, "void", [], [ [pi.ctype, pi.name, "", [], ""] ] ] )
1308
                self.gen_func(fi, pi.name)
1309 1310 1311 1312 1313 1314 1315 1316 1317

        # manual ports
        if name in ManualFuncs:
            for func in ManualFuncs[name].keys():
                self.java_code[name]["j_code"].write ( ManualFuncs[name][func]["j_code"] )
                self.java_code[name]["jn_code"].write( ManualFuncs[name][func]["jn_code"] )
                self.cpp_code.write( ManualFuncs[name][func]["cpp_code"] )

        if name != self.Module:
1318
            # finalize()
1319
            self.java_code[name]["j_code"].write(
1320
"""
1321 1322
    @Override
    protected void finalize() throws Throwable {
1323
        delete(nativeObj);
1324
    }
1325
""" )
1326

1327
            self.java_code[name]["jn_code"].write(
1328
"""
1329
    // native support for java finalize()
1330
    private static native void delete(long nativeObj);
1331
""" )
1332 1333 1334 1335 1336 1337

            # native support for java finalize()
            self.cpp_code.write( \
"""
//
//  native support for java finalize()
1338
//  static void %(cls)s::delete( __int64 self )
1339 1340
//

1341
JNIEXPORT void JNICALL Java_org_opencv_%(module)s_%(j_cls)s_delete
1342 1343 1344 1345 1346
  (JNIEnv* env, jclass cls, jlong self)
{
    delete (%(cls)s*) self;
}

1347
""" % {"module" : module, "cls" : name, "j_cls" : ci.jname}
1348
            )
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370


if __name__ == "__main__":
    if len(sys.argv) < 4:
        print "Usage:\n", \
            os.path.basename(sys.argv[0]), \
            "<full path to hdr_parser.py> <module name> <C++ header> [<C++ header>...]"
        print "Current args are: ", ", ".join(["'"+a+"'" for a in sys.argv])
        exit(0)

    dstdir = "."
    hdr_parser_path = os.path.abspath(sys.argv[1])
    if hdr_parser_path.endswith(".py"):
        hdr_parser_path = os.path.dirname(hdr_parser_path)
    sys.path.append(hdr_parser_path)
    import hdr_parser
    module = sys.argv[2]
    srcfiles = sys.argv[3:]
    print "Generating module '" + module + "' from headers:\n\t" + "\n\t".join(srcfiles)
    generator = JavaWrapperGenerator()
    generator.gen(srcfiles, module, dstdir)