File: linphone.py

package info (click to toggle)
linphone 5.3.105-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 57,048 kB
  • sloc: cpp: 166,867; ansic: 102,939; python: 8,280; java: 4,406; sh: 1,040; xml: 1,023; makefile: 777; perl: 377; objc: 190; php: 88; javascript: 38; cs: 38
file content (1462 lines) | stat: -rw-r--r-- 64,490 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
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
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
# Copyright (c) 2010-2022 Belledonne Communications SARL.
#
# This file is part of Liblinphone 
# (see https://gitlab.linphone.org/BC/public/liblinphone).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.



import re
import six
import sys


def strip_leading_linphone(s):
	if s.lower().startswith('linphone'):
		return s[8:]
	else:
		return s

def remove_useless_enum_prefix(senum, svalue):
	lenum = re.findall('[A-Z][^A-Z]*', senum)
	lvalue = re.findall('[A-Z][^A-Z]*', svalue)
	if len(lenum) == 0 or len(lvalue) == 0:
		return svalue
	if lenum[0] == lvalue[0]:
		i = 0
		while i < len(lenum) and lenum[i] == lvalue[i]:
			i += 1
		svalue = ''.join(lvalue[i:])
	if svalue == "None":
		return "_None"
	return svalue

def is_callback(s):
	return s.startswith('Linphone') and s.endswith('Cb')

def compute_event_name(s, className):
	s = strip_leading_linphone(s)
	s = s[len(className):-2] # Remove leading class name and tailing 'Cb'
	event_name = ''
	first = True
	for l in s:
		if l.isupper() and not first:
			event_name += '_'
		event_name += l.lower()
		first = False
	return event_name

def is_const_from_complete_type(complete_type):
	splitted_type = complete_type.split(' ')
	return 'const' in splitted_type


class HandWrittenCode:
	def __init__(self, _class, name, func_list, doc = ''):
		self._class = _class
		self.name = name
		self.func_list = func_list
		self.doc = doc

class HandWrittenInstanceMethod(HandWrittenCode):
	def __init__(self, _class, name, cfunction, doc = ''):
		HandWrittenCode.__init__(self, _class, name, [cfunction], doc)

class HandWrittenClassMethod(HandWrittenCode):
	def __init__(self, _class, name, cfunction, doc = ''):
		HandWrittenCode.__init__(self, _class, name, [cfunction], doc)

class HandWrittenDeallocMethod(HandWrittenCode):
	def __init__(self, _class, cfunction):
		HandWrittenCode.__init__(self, _class, 'dealloc', [cfunction], '')

class HandWrittenProperty(HandWrittenCode):
	def __init__(self, _class, name, getter_cfunction = None, setter_cfunction = None, doc = ''):
		func_list = []
		if getter_cfunction is not None:
			func_list.append(getter_cfunction)
		if setter_cfunction is not None:
			func_list.append(setter_cfunction)
		HandWrittenCode.__init__(self, _class, name, func_list, doc)
		self.getter_cfunction = getter_cfunction
		self.setter_cfunction = setter_cfunction


class UnknownTypeException(Exception):
	def __init__(self, typename):
		self.typename = typename
	def __str__(self):
		return "Unknown type " + self.typename

class ArgumentType:
	def __init__(self, basic_type, complete_type, contained_type, linphone_module):
		if not basic_type in linphone_module.known_types:
			raise UnknownTypeException(basic_type)
		self.basic_type = basic_type
		self.complete_type = complete_type
		self.contained_type = contained_type
		self.linphone_module = linphone_module
		self.type_str = None
		self.check_condition = None
		self.convert_code = None
		self.convert_from_func = None
		self.free_convert_result_func = None
		self.fmt_str = 'O'
		self.cfmt_str = '%p'
		self.cnativefmt_str = '%p'
		self.use_native_pointer = False
		self.cast_convert_func_result = True
		self.is_linphone_object = False
		self.__compute()
		if (self.basic_type == 'MSList' or self.basic_type == 'bctbx_list_t') and self.contained_type is not None and self.contained_type != 'const char *':
			self.linphone_module.bctbxlist_types.add(self.contained_type)

	def __compute(self):
		splitted_type = self.complete_type.split(' ')
		if self.basic_type == 'char':
			if '*' in splitted_type:
				self.type_str = 'string'
				self.check_condition = "!PyString_Check({arg_name})"
				self.convert_code = "{result_name}{result_suffix} = {cast}PyString_AsString({arg_name});\n"
				self.fmt_str = 'z'
				self.cfmt_str = '\\"%s\\"'
			else:
				self.type_str = 'int'
				self.check_condition = "!PyInt_Check({arg_name}) && !PyLong_Check({arg_name})"
				self.convert_code = "{result_name}{result_suffix} = {cast}PyInt_AsLong({arg_name});\n"
				self.fmt_str = 'b'
				self.cfmt_str = '%08x'
		elif self.basic_type == 'int':
			if 'unsigned' in splitted_type:
				self.type_str = 'unsigned int'
				self.check_condition = "!PyInt_Check({arg_name})"
				self.convert_code = "{result_name}{result_suffix} = {cast}PyInt_AsUnsignedLongMask({arg_name});\n"
				self.fmt_str = 'I'
				self.cfmt_str = '%u'
			else:
				self.type_str = 'int'
				self.check_condition = "!PyInt_Check({arg_name})"
				self.convert_code = "{result_name}{result_suffix} = {cast}PyInt_AS_LONG({arg_name});\n"
				self.fmt_str = 'i'
				self.cfmt_str = '%d'
		elif self.basic_type in ['int8_t', 'int16_t' 'int32_t']:
			self.type_str = 'int'
			self.check_condition = "!PyInt_Check({arg_name})"
			self.convert_code = "{result_name}{result_suffix} = {cast}PyInt_AS_LONG({arg_name});\n"
			if self.basic_type == 'int8_t':
					self.fmt_str = 'c'
			elif self.basic_type == 'int16_t':
					self.fmt_str = 'h'
			elif self.basic_type == 'int32_t':
					self.fmt_str = 'l'
			self.cfmt_str = '%d'
		elif self.basic_type in ['uint8_t', 'uint16_t', 'uint32_t']:
			self.type_str = 'unsigned int'
			self.check_condition = "!PyInt_Check({arg_name})"
			self.convert_code = "{result_name}{result_suffix} = {cast}PyInt_AsUnsignedLongMask({arg_name});\n"
			if self.basic_type == 'uint8_t':
				self.fmt_str = 'b'
			elif self.basic_type == 'uint16_t':
				self.fmt_str = 'H'
			elif self.basic_type == 'uint32_t':
				self.fmt_str = 'k'
			self.cfmt_str = '%u'
		elif self.basic_type == 'int64_t':
			self.type_str = '64bits int'
			self.check_condition = "!PyInt_Check({arg_name}) && !PyLong_Check({arg_name})"
			self.convert_code = \
"""if (PyInt_Check({arg_name})) {result_name}{result_suffix} = {cast}(PY_LONG_LONG)PyInt_AsLong({arg_name});
	else if (PyLong_Check({arg_name})) {result_name}{result_suffix} = {cast}PyLong_AsLongLong({arg_name});
"""
			self.fmt_str = 'L'
			self.cfmt_str = '%ld'
		elif self.basic_type == 'uint64_t':
			self.type_str = '64bits unsigned int'
			self.check_condition = "!PyLong_Check({arg_name})"
			self.convert_code = "{result_name}{result_suffix} = {cast}PyLong_AsUnsignedLongLong({arg_name});\n"
			self.fmt_str = 'K'
			self.cfmt_str = '%lu'
		elif self.basic_type == 'size_t':
			self.type_str = 'int'
			self.check_condition = "!PyInt_Check({arg_name}) && !PyLong_Check({arg_name})"
			self.convert_code = \
"""if (PyInt_Check({arg_name})) {result_name}{result_suffix} = {cast}(size_t)PyInt_AsSsize_t({arg_name});
	else if (PyLong_Check({arg_name})) {result_name}{result_suffix} = {cast}(size_t)PyLong_AsSsize_t({arg_name});
"""
			self.fmt_str = 'n'
			self.cfmt_str = '%lu'
		elif self.basic_type == 'float':
			self.type_str = 'float'
			self.check_condition = "!PyFloat_Check({arg_name})"
			self.convert_code = \
"""if (PyInt_Check({arg_name})) {result_name}{result_suffix} = {cast}(float)PyInt_AsLong({arg_name});
	else if (PyLong_Check({arg_name})) {result_name}{result_suffix} = {cast}(float)PyLong_AsLong({arg_name});
	else if (PyFloat_Check({arg_name})) {result_name}{result_suffix} = {cast}(float)PyFloat_AsDouble({arg_name});
"""
			self.fmt_str = 'f'
			self.cfmt_str = '%f'
		elif self.basic_type == 'double':
			self.type_str = 'float'
			self.check_condition = "!PyFloat_Check({arg_name})"
			self.convert_code = \
"""if (PyInt_Check({arg_name})) {result_name}{result_suffix} = {cast}(double)PyInt_AsLong({arg_name});
	else if (PyLong_Check({arg_name})) {result_name}{result_suffix} = {cast}(double)PyLong_AsLong({arg_name});
	else if (PyFloat_Check({arg_name})) {result_name}{result_suffix} = {cast}(double)PyFloat_AsDouble({arg_name});
"""
			self.fmt_str = 'd'
			self.cfmt_str = '%f'
		elif self.basic_type == 'bool_t' or self.basic_type == 'LinphoneStatus':
			self.type_str = 'bool'
			self.check_condition = "!PyBool_Check({arg_name})"
			self.convert_code = "{result_name}{result_suffix} = {cast}PyObject_IsTrue({arg_name});\n"
			self.convert_from_func = 'PyBool_FromLong'
			self.fmt_str = 'O'
			self.cfmt_str = '%p'
			self.cnativefmt_str = '%u'
		elif self.basic_type == 'time_t':
			self.type_str = 'DateTime'
			self.check_condition = "!PyDateTime_Check({arg_name})"
			self.convert_code = "{result_name}{result_suffix} = {cast}PyDateTime_As_time_t({arg_name});\n"
			self.convert_from_func = 'PyDateTime_From_time_t'
			self.fmt_str = 'O'
			self.cfmt_str = '%p'
			self.cnativefmt_str = '%ld'
		elif self.basic_type == 'MSList' or self.basic_type == 'bctbx_list_t':
			if self.contained_type == 'const char *':
				self.type_str = 'list of string'
				self.convert_code = "{result_name}{result_suffix} = {cast}PyList_AsBctbxListOfString({arg_name});\n"
				self.convert_from_func = 'PyList_FromBctbxListOfString'
			else:
				self.type_str = 'list of linphone.' + self.contained_type
				self.convert_code = "{result_name}{result_suffix} = {cast}PyList_AsBctbxListOf" + self.contained_type + "({arg_name});\n"
				self.convert_from_func = 'PyList_FromBctbxListOf' + self.contained_type
			if not is_const_from_complete_type(self.complete_type):
				self.free_convert_result_func = "pylinphone_bctbx_list_free"
			self.check_condition = "!PyList_Check({arg_name})"
			self.fmt_str = 'O'
			self.cfmt_str = '%p'
		elif self.basic_type == 'MSVideoSize':
			self.type_str = 'linphone.VideoSize'
			self.check_condition = "!PyLinphoneVideoSize_Check({arg_name})"
			self.convert_code = "{result_name}{result_suffix} = {cast}PyLinphoneVideoSize_AsMSVideoSize({arg_name});\n"
			self.convert_from_func = 'PyLinphoneVideoSize_FromMSVideoSize'
			self.fmt_str = 'O'
			self.cfmt_str = '%p'
			self.cast_convert_func_result = False
		elif self.basic_type == 'LCSipTransports':
			self.type_str = 'linphone.SipTransports'
			self.check_condition = "!PyLinphoneSipTransports_Check({arg_name})"
			self.convert_code = "{result_name}{result_suffix} = {cast}PyLinphoneSipTransports_AsLCSipTransports({arg_name});\n"
			self.convert_from_func = 'PyLinphoneSipTransports_FromLCSipTransports'
			self.fmt_str = 'O'
			self.cfmt_str = '%p'
			self.cast_convert_func_result = False
		else:
			if strip_leading_linphone(self.basic_type) in self.linphone_module.enum_names:
				self.type_str = 'int'
				self.check_condition = "!PyInt_Check({arg_name})"
				self.convert_code = "{result_name}{result_suffix} = {cast}PyInt_AsLong({arg_name});\n"
				self.fmt_str = 'i'
				self.cfmt_str = '%d'
			elif is_callback(self.complete_type):
				self.type_str = 'callable'
				self.check_condition = "!PyCallable_Check({arg_name})"
				self.cnativefmt_str = None
			elif '*' in splitted_type:
				self.type_str = 'linphone.' + strip_leading_linphone(self.basic_type)
				self.use_native_pointer = True
				self.is_linphone_object = True
			else:
				self.type_str = 'linphone.' + strip_leading_linphone(self.basic_type)
				self.is_linphone_object = True


class MethodDefinition:
	def __init__(self, linphone_module, class_, method_name = "", method_node = None):
		self.body = ''
		self.arg_names = []
		self.parse_tuple_format = ''
		self.build_value_format = ''
		self.return_type = 'void'
		self.return_complete_type = 'void'
		self.return_contained_type = None
		self.method_name = method_name
		self.method_node = method_node
		self.class_ = class_
		self.linphone_module = linphone_module
		self.self_arg = None
		self.xml_method_return = None
		self.xml_method_args = []
		self.method_type = 'instancemethod'

	def format_local_variables_definition(self):
		body = self.format_local_return_variables_definition()
		if self.self_arg is not None:
			body += "\t" + self.self_arg.get('completetype') + "native_ptr;\n"
		for xml_method_arg in self.xml_method_args:
			arg_name = "_" + xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			self.parse_tuple_format += argument_type.fmt_str
			if is_callback(arg_complete_type):
				body += "\tPyObject * {arg_name};\n".format(arg_name=arg_name)
			elif argument_type.fmt_str == 'O' and argument_type.use_native_pointer:
				body += "\tPyObject * " + arg_name + ";\n"
				body += "\t" + arg_complete_type + " " + arg_name + "_native_ptr = NULL;\n"
			elif argument_type.fmt_str == 'O' and argument_type.convert_code is not None:
				body += "\tPyObject * " + arg_name + ";\n"
				body += "\t" + arg_complete_type + " " + arg_name + "_native_obj;\n"
			elif strip_leading_linphone(arg_complete_type) in self.linphone_module.enum_names:
				body += "\tint " + arg_name + ";\n"
			else:
				body += "\t" + arg_complete_type + " " + arg_name + ";\n"
			self.arg_names.append(arg_name)
		return body

	def format_deprecation_warning(self):
		if self.method_node is not None and self.method_node.get('deprecated') == 'true':
			print(self.class_['class_name'] + "." + self.method_name + " is deprecated")
			return "\tPyErr_WarnEx(PyExc_DeprecationWarning, \"{msg}\", 1);\n".format(msg="{class_name}.{method_name} is deprecated".format(class_name=self.class_['class_name'], method_name=self.method_name))
		return ""

	def format_arguments_parsing(self):
		class_native_ptr_check_code = ''
		if self.self_arg is not None:
			class_native_ptr_check_code = self.format_class_native_pointer_check(False)
		parse_tuple_code = ''
		if len(self.arg_names) > 0:
			parse_tuple_code = \
"""if (!PyArg_ParseTuple(args, "{fmt}", {args})) {{
		return NULL;
	}}
""".format(fmt=self.parse_tuple_format, args=', '.join(map(lambda a: '&' + a, self.arg_names)))
		args_conversion_code = ''
		for xml_method_arg in self.xml_method_args:
			arg_name = "_" + xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			if argument_type.fmt_str == 'O' and argument_type.convert_code is not None:
				args_conversion_code += argument_type.convert_code.format(result_name=arg_name, result_suffix='_native_obj', cast='', arg_name=arg_name)
		return \
"""	{class_native_ptr_check_code}
	{parse_tuple_code}
	{args_type_check_code}
	{args_native_ptr_check_code}
	{args_conversion_code}
""".format(class_native_ptr_check_code=class_native_ptr_check_code,
		parse_tuple_code=parse_tuple_code,
		args_type_check_code=self.format_args_type_check(),
		args_native_ptr_check_code=self.format_args_native_pointer_check(),
		args_conversion_code=args_conversion_code)

	def format_enter_trace(self):
		fmt = ''
		args = []
		if self.self_arg is not None:
			fmt += "%p [%p]"
			args += ["self", "native_ptr"]
		for xml_method_arg in self.xml_method_args:
			arg_name = "_" + xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			if fmt != '':
				fmt += ', '
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			fmt += argument_type.cfmt_str
			args.append(arg_name)
			if argument_type.fmt_str == 'O' and argument_type.cnativefmt_str is not None:
				fmt += ' [' + argument_type.cnativefmt_str + ']'
				if argument_type.use_native_pointer:
					args.append(arg_name + '_native_ptr')
				else:
					args.append(arg_name + '_native_obj')
		args = ', '.join(args)
		if args != '':
			args = ', ' + args
		return "\tpylinphone_trace(1, \"[PYLINPHONE] >>> %s({fmt})\", __FUNCTION__{args});\n".format(fmt=fmt, args=args)

	def format_c_function_call(self):
		arg_names = []
		c_function_call_code = ''
		cfree_argument_code = ''
		python_ref_code = ''
		for xml_method_arg in self.xml_method_args:
			arg_name = "_" + xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			if argument_type.fmt_str == 'O' and argument_type.use_native_pointer:
				arg_names.append(arg_name + "_native_ptr")
			elif argument_type.fmt_str == 'O' and argument_type.convert_code is not None:
				arg_names.append(arg_name + "_native_obj")
				if argument_type.free_convert_result_func is not None and not is_const_from_complete_type(arg_complete_type):
					cfree_argument_code = \
"""{free_func}({arg_name}_native_obj);
""".format(free_func=argument_type.free_convert_result_func, arg_name=arg_name)
			else:
				arg_names.append(arg_name)
		if is_callback(self.return_complete_type):
			c_function_call_code = "pyresult = ((pylinphone_{class_name}Object *)self)->{callback_name};".format(class_name=self.class_['class_name'], callback_name=compute_event_name(self.return_complete_type, self.class_['class_name']))
		else:
			if self.return_complete_type != 'void':
				c_function_call_code += "cresult = "
			c_function_call_code += self.method_node.get('name') + "("
			if self.self_arg is not None:
				c_function_call_code += "native_ptr"
				if len(arg_names) > 0:
					c_function_call_code += ', '
			c_function_call_code += ', '.join(arg_names) + ");"
		if self.method_name == 'add_callbacks':
			python_ref_code = "Py_INCREF(_cbs);"
		elif self.method_name == 'remove_callbacks':
			python_ref_code = "Py_XDECREF(_cbs);"
		from_native_pointer_code = ''
		convert_from_code = ''
		build_value_code = ''
		cfree_code = ''
		result_variable = ''
		take_native_ref = 'TRUE'
		if self.return_complete_type != 'void':
			if self.build_value_format == 'O':
				stripped_return_type = strip_leading_linphone(self.return_type)
				return_type_class = self.find_class_definition(self.return_type)
				if return_type_class is not None:
					if self.method_name.startswith('create'):
						take_native_ref = 'FALSE'
					from_native_pointer_code = "pyresult = pylinphone_{return_type}_from_native_ptr(&pylinphone_{return_type}Type, cresult, {take_native_ref});\n".format(return_type=stripped_return_type, take_native_ref=take_native_ref)
				else:
					return_argument_type = ArgumentType(self.return_type, self.return_complete_type, self.return_contained_type, self.linphone_module)
					if return_argument_type.convert_from_func is not None:
						convert_from_code = \
"""pyresult = {convert_func}(cresult);
""".format(convert_func=return_argument_type.convert_from_func)
					if return_argument_type.free_convert_result_func is not None:
						cfree_code = \
"""{free_func}(cresult);
""".format(free_func=return_argument_type.free_convert_result_func)
				result_variable = 'pyresult'
			else:
				result_variable = 'cresult'
		if result_variable != '':
			build_value_code = "pyret = Py_BuildValue(\"{fmt}\", {result_variable});".format(fmt=self.build_value_format, result_variable=result_variable)
			if take_native_ref == 'FALSE':
				build_value_code += """
	Py_XDECREF(pyresult);"""
		if self.return_complete_type == 'char *':
			cfree_code = 'ms_free(cresult);';
		body = \
"""	{c_function_call_code}
	{cfree_argument_code}
	{python_ref_code}
	pylinphone_dispatch_messages();
	{from_native_pointer_code}
	{convert_from_code}
	{build_value_code}
	{cfree_code}
""".format(c_function_call_code=c_function_call_code,
		cfree_argument_code=cfree_argument_code,
		python_ref_code=python_ref_code,
		from_native_pointer_code=from_native_pointer_code,
		convert_from_code=convert_from_code,
		build_value_code=build_value_code,
		cfree_code=cfree_code)
		return body

	def format_return_trace(self):
		if self.return_complete_type != 'void':
			return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s -> %p\", __FUNCTION__, pyret);\n"
		else:
			return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s -> None\", __FUNCTION__);\n"

	def format_return_result(self):
		if self.return_complete_type != 'void':
			return "\treturn pyret;"
		return "\tPy_RETURN_NONE;"

	def format_return_none_trace(self):
		return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s -> None\", __FUNCTION__);\n"

	def format_class_native_pointer_check(self, return_int):
		return_value = "NULL"
		if return_int:
			return_value = "-1"
		return \
"""native_ptr = pylinphone_{class_name}_get_native_ptr(self);
	if (native_ptr == NULL) {{
		PyErr_SetString(PyExc_TypeError, "Invalid linphone.{class_name} instance");
		return {return_value};
	}}
""".format(class_name=self.class_['class_name'], return_value=return_value)

	def format_args_type_check(self):
		body = ''
		for xml_method_arg in self.xml_method_args:
			arg_name = "_" + xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			if argument_type.fmt_str == 'O':
				if argument_type.use_native_pointer:
					body += \
"""	if (({arg_name} != Py_None) && !PyObject_IsInstance({arg_name}, (PyObject *)&pylinphone_{arg_type}Type)) {{
		PyErr_SetString(PyExc_TypeError, "The '{arg_name}' argument must be a {type_str} instance.");
		return NULL;
	}}
""".format(arg_name=arg_name, arg_type=strip_leading_linphone(arg_type), type_str=argument_type.type_str)
				else:
					body += \
"""	if ({check_condition}) {{
		PyErr_SetString(PyExc_TypeError, "The '{arg_name}' argument must be a {type_str} instance.");
		return NULL;
	}}
""".format(arg_name=arg_name, check_condition=argument_type.check_condition.format(arg_name=arg_name), type_str=argument_type.type_str)
		if body != '':
			body = body[1:] # Remove leading '\t'
		return body

	def format_args_native_pointer_check(self):
		body = ''
		for xml_method_arg in self.xml_method_args:
			arg_name = "_" + xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			if argument_type.fmt_str == 'O' and argument_type.use_native_pointer:
				body += \
"""	if (({arg_name} != NULL) && ({arg_name} != Py_None)) {{
		if (({arg_name}_native_ptr = pylinphone_{arg_type}_get_native_ptr({arg_name})) == NULL) {{
			return NULL;
		}}
	}}
""".format(arg_name=arg_name, arg_type=strip_leading_linphone(arg_type))
		if body != '':
			body = body[1:] # Remove leading '\t'
		return body

	def format_local_return_variables_definition(self):
		body = ''
		if self.xml_method_return is not None:
			self.return_type = self.xml_method_return.get('type')
			self.return_complete_type = self.xml_method_return.get('completetype')
			self.return_contained_type = self.xml_method_return.get('containedtype')
		if is_callback(self.return_complete_type):
			body += "\tPyObject * pyresult;\n"
			body += "\tPyObject * pyret;\n"
			argument_type = ArgumentType(self.return_type, self.return_complete_type, self.return_contained_type, self.linphone_module)
			self.build_value_format = argument_type.fmt_str
		elif self.return_complete_type != 'void':
			body += "\t" + self.return_complete_type + " cresult;\n"
			argument_type = ArgumentType(self.return_type, self.return_complete_type, self.return_contained_type, self.linphone_module)
			self.build_value_format = argument_type.fmt_str
			if self.build_value_format == 'O':
				body += "\tPyObject * pyresult;\n"
			body += "\tPyObject * pyret;\n"
		return body

	def parse_method_node(self):
		if self.method_node is not None:
			self.xml_method_return = self.method_node.find('./return')
			self.xml_method_args = self.method_node.findall('./arguments/argument')
			self.method_type = self.method_node.tag
		if self.method_type != 'classmethod' and len(self.xml_method_args) > 0:
			self.self_arg = self.xml_method_args[0]
			self.xml_method_args = self.xml_method_args[1:]

	def find_class_definition(self, basic_type):
		basic_type = strip_leading_linphone(basic_type)
		for c in self.linphone_module.classes:
			if c['class_name'] == basic_type:
				return c
		return None

	def find_property_definition(self, basic_type, property_name):
		class_definition = self.find_class_definition(basic_type)
		if class_definition is None:
			return None
		for p in class_definition['class_properties']:
			if p['property_name'] == property_name:
				return p
		return None

	def format(self):
		self.parse_method_node()
		body = self.format_local_variables_definition()
		body += self.format_deprecation_warning()
		body += self.format_arguments_parsing()
		body += self.format_enter_trace()
		body += self.format_c_function_call()
		body += self.format_return_trace()
		body += self.format_return_result()
		return body

class NewMethodDefinition(MethodDefinition):
	def __init__(self, linphone_module, class_, method_node = None):
		MethodDefinition.__init__(self, linphone_module, class_, "new", method_node)

	def format_local_variables_definition(self):
		return "\tpylinphone_{class_name}Object *self = (pylinphone_{class_name}Object *)type->tp_alloc(type, 0);\n".format(class_name=self.class_['class_name'])

	def format_arguments_parsing(self):
		return ''

	def format_enter_trace(self):
		return "\tpylinphone_trace(1, \"[PYLINPHONE] >>> %s()\", __FUNCTION__);\n"

	def format_c_function_call(self):
		return ''

	def format_return_trace(self):
		return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s -> %p\", __FUNCTION__, self);\n"

	def format_return_result(self):
		return "\treturn (PyObject *)self;"

class InitMethodDefinition(MethodDefinition):
	def __init__(self, linphone_module, class_, method_node = None):
		MethodDefinition.__init__(self, linphone_module, class_, "init", method_node)

	def format_local_variables_definition(self):
		return "\tpylinphone_{class_name}Object *self_obj = (pylinphone_{class_name}Object *)self;\n".format(class_name=self.class_['class_name'])

	def format_arguments_parsing(self):
		return ''

	def format_enter_trace(self):
		return "\tpylinphone_trace(1, \"[PYLINPHONE] >>> %s()\", __FUNCTION__);\n"

	def format_c_function_call(self):
		specific_member_initialization_code = ''
		for member in self.class_['class_object_members']:
			specific_member_initialization_code += "\tself_obj->{member} = NULL;\n".format(member=member)
		return \
"""	self_obj->native_ptr = NULL;
	self_obj->user_data = NULL;
{specific_member_initialization_code}
""".format(specific_member_initialization_code=specific_member_initialization_code)

	def format_return_trace(self):
		return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s -> %p\", __FUNCTION__, self);\n"

	def format_return_result(self):
		return "\treturn 0;"

class FromNativePointerMethodDefinition(MethodDefinition):
	def __init__(self, linphone_module, class_):
		MethodDefinition.__init__(self, linphone_module, class_, "from_native_pointer", None)

	def format_local_variables_definition(self):
		return "\tpylinphone_{class_name}Object *self = NULL;\n".format(class_name=self.class_['class_name'])

	def format_arguments_parsing(self):
		return ''

	def format_enter_trace(self):
		return "\tpylinphone_trace(1, \"[PYLINPHONE] >>> %s(%p)\", __FUNCTION__, native_ptr);\n"

	def format_c_function_call(self):
		get_user_data_func_call = ''
		set_user_data_func_call = ''
		if self.class_['class_has_user_data']:
			get_user_data_func_call = "self = (pylinphone_{class_name}Object *){function_prefix}get_user_data(native_ptr);".format(class_name=self.class_['class_name'], function_prefix=self.class_['class_c_function_prefix'])
			set_user_data_func_call = "{function_prefix}set_user_data(self->native_ptr, self);".format(function_prefix=self.class_['class_c_function_prefix'])
		ref_native_pointer_code = ''
		if self.class_['class_refcountable']:
			ref_native_pointer_code = "if (take_native_ref == TRUE) {func}(self->native_ptr);".format(func=self.class_['class_c_function_prefix'] + "ref")
		return \
"""	if (native_ptr == NULL) {{
	{none_trace}
		Py_RETURN_NONE;
	}}
	{get_user_data_func_call}
	if (self == NULL) {{
		self = (pylinphone_{class_name}Object *)PyObject_CallObject((PyObject *)&pylinphone_{class_name}Type, NULL);
		if (self == NULL) {{
		{none_trace}
			Py_RETURN_NONE;
		}}
		self->native_ptr = ({class_cname} *)native_ptr;
		{set_user_data_func_call}
		{ref_native_pointer_code}
	}}
""".format(class_name=self.class_['class_name'], class_cname=self.class_['class_cname'],
		none_trace=self.format_return_none_trace(),
		get_user_data_func_call=get_user_data_func_call, set_user_data_func_call=set_user_data_func_call,
		ref_native_pointer_code=ref_native_pointer_code)

	def format_return_trace(self):
		return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s -> %p\", __FUNCTION__, self);\n"

	def format_return_result(self):
		return "\treturn (PyObject *)self;"

class DeallocMethodDefinition(MethodDefinition):
	def __init__(self, linphone_module, class_, method_node = None):
		MethodDefinition.__init__(self, linphone_module, class_, "dealloc", method_node)

	def format_local_variables_definition(self):
		func = "pylinphone_{class_name}_get_native_ptr".format(class_name=self.class_['class_name'])
		return \
"""	{arg_type} * native_ptr = {func}(self);
""".format(arg_type=self.class_['class_cname'], func=func)

	def format_arguments_parsing(self):
		# Check that the dealloc is not called a second time because of reentrancy
		return "\tif (Py_REFCNT(self) < 0) return;\n"

	def format_enter_trace(self):
		return "\tpylinphone_trace(1, \"[PYLINPHONE] >>> %s(%p [%p])\", __FUNCTION__, self, native_ptr);\n"

	def format_c_function_call(self):
		reset_user_data_code = ''
		if self.class_['class_name'] != 'Core' and self.class_['class_has_user_data']:
			reset_user_data_code += \
"""if (native_ptr != NULL) {{
		{function_prefix}set_user_data(native_ptr, NULL);
	}}
""".format(function_prefix=self.class_['class_c_function_prefix'])
		native_ptr_dealloc_code = ''
		specific_member_decref_code = ''
		if self.class_['class_refcountable']:
			native_ptr_dealloc_code += \
"""	if (native_ptr != NULL) {{
		{function_prefix}unref(native_ptr);
	}}
""".format(function_prefix=self.class_['class_c_function_prefix'])
		elif self.class_['class_destroyable']:
			native_ptr_dealloc_code += \
"""	if (native_ptr != NULL) {{
		{function_prefix}destroy(native_ptr);
	}}
""".format(function_prefix=self.class_['class_c_function_prefix'])
		for member in self.class_['class_object_members']:
			specific_member_decref_code += "\tPy_XDECREF(((pylinphone_{class_name}Object *)self)->{member});\n".format(class_name=self.class_['class_name'], member=member)
		return \
"""	{reset_user_data_code}
	{native_ptr_dealloc_code}
	pylinphone_dispatch_messages();
	Py_XDECREF(((pylinphone_{class_name}Object *)self)->user_data);
{specific_member_decref_code}
	self->ob_type->tp_free(self);
""".format(class_name=self.class_['class_name'], reset_user_data_code=reset_user_data_code, native_ptr_dealloc_code=native_ptr_dealloc_code, specific_member_decref_code=specific_member_decref_code)

	def format_return_trace(self):
		return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s\", __FUNCTION__);"

	def format_return_result(self):
		return ''

	def format(self):
		return \
"""static void pylinphone_{class_name}_dealloc(PyObject *self) {{
{method_body}
}}""".format(class_name=self.class_['class_name'], method_body=MethodDefinition.format(self))

class GetterMethodDefinition(MethodDefinition):
	def __init__(self, linphone_module, class_, method_name = "", method_node = None):
		MethodDefinition.__init__(self, linphone_module, class_, method_name, method_node)

class SetterMethodDefinition(MethodDefinition):
	def __init__(self, linphone_module, class_, method_name = "", method_node = None):
		MethodDefinition.__init__(self, linphone_module, class_, method_name, method_node)

	def format_arguments_parsing(self):
		if self.first_argument_type.check_condition is None:
			attribute_type_check_code = \
"""if ((value != Py_None) && !PyObject_IsInstance(value, (PyObject *)&pylinphone_{class_name}Type)) {{
		PyErr_SetString(PyExc_TypeError, "The '{attribute_name}' attribute value must be a linphone.{class_name} instance.");
		return -1;
	}}
""".format(class_name=self.first_arg_class, attribute_name=self.attribute_name)
		else:
			checknotnone = ''
			if self.first_argument_type.type_str == 'string':
				checknotnone = "(value != Py_None) && "
			attribute_type_check_code = \
"""if ({checknotnone}{check_condition}) {{
		PyErr_SetString(PyExc_TypeError, "The '{attribute_name}' attribute value must be a {type_str}.");
		return -1;
	}}
""".format(checknotnone=checknotnone, check_condition=self.first_argument_type.check_condition.format(arg_name='value'), attribute_name=self.attribute_name, type_str=self.first_argument_type.type_str)
		attribute_conversion_code = ''
		callback_setting_code = ''
		if is_callback(self.first_argument_type.complete_type):
			callback_setting_code = \
"""Py_XDECREF(((pylinphone_{class_name}Object *)self)->{callback_name});
	Py_INCREF(value);
	((pylinphone_{class_name}Object *)self)->{callback_name} = value;
""".format(class_name=self.class_['class_name'], callback_name=compute_event_name(self.first_arg_complete_type, self.class_['class_name']))
		if (self.first_argument_type.convert_code is None) or \
			(self.first_argument_type.fmt_str == 'O' and self.first_argument_type.convert_code is not None):
			attribute_conversion_code += "{arg_name} = value;\n".format(arg_name="_" + self.first_arg_name)
		if self.first_argument_type.convert_code is not None:
			cast_code = ''
			suffix = ''
			if self.first_argument_type.cast_convert_func_result:
				cast_code = "({arg_type})".format(arg_type=self.first_arg_complete_type)
			if self.first_argument_type.fmt_str == 'O' and self.first_argument_type.convert_code is not None:
				suffix = '_native_obj'
			attribute_conversion_code += self.first_argument_type.convert_code.format(result_name="_" + self.first_arg_name, result_suffix=suffix, cast=cast_code, arg_name='value')
		attribute_native_ptr_check_code = ''
		if self.first_argument_type.use_native_pointer:
			attribute_native_ptr_check_code = \
"""if ({arg_name} != Py_None) {{
		if (({arg_name}_native_ptr = pylinphone_{arg_class}_get_native_ptr({arg_name})) == NULL) {{
			PyErr_SetString(PyExc_TypeError, "Invalid linphone.{arg_class} instance.");
			return -1;
		}}
	}}
""".format(arg_name="_" + self.first_arg_name, arg_class=self.first_arg_class)
		return \
"""	{native_ptr_check_code}
	if (value == NULL) {{
		PyErr_SetString(PyExc_TypeError, "Cannot delete the '{attribute_name}' attribute.");
		return -1;
	}}
	{attribute_type_check_code}
	{attribute_conversion_code}
	{callback_setting_code}
	{attribute_native_ptr_check_code}
""".format(attribute_name=self.attribute_name,
		native_ptr_check_code=self.format_class_native_pointer_check(True),
		attribute_type_check_code=attribute_type_check_code,
		attribute_conversion_code=attribute_conversion_code,
		callback_setting_code=callback_setting_code,
		attribute_native_ptr_check_code=attribute_native_ptr_check_code)

	def format_c_function_call(self):
		if is_callback(self.first_argument_type.complete_type):
			return \
"""	{method_name}(native_ptr, pylinphone_{class_name}_callback_{callback_name});
	pylinphone_dispatch_messages();
""".format(method_name=self.method_node.get('name'), class_name=self.class_['class_name'], callback_name=compute_event_name(self.first_argument_type.complete_type, self.class_['class_name']))
		cfree_argument_code = ''
		suffix = ''
		if self.first_argument_type.fmt_str == 'O' and self.first_argument_type.use_native_pointer:
			suffix = '_native_ptr'
		elif self.first_argument_type.fmt_str == 'O' and self.first_argument_type.convert_code is not None:
			suffix = '_native_obj'
			if self.first_argument_type.free_convert_result_func is not None and not is_const_from_complete_type(self.first_argument_type.complete_type):
					cfree_argument_code = \
"""{free_func}({arg_name}_native_obj);
""".format(free_func=self.first_argument_type.free_convert_result_func, arg_name="_" + self.first_arg_name)
		return \
"""	{method_name}(native_ptr, {arg_name}{suffix});
	{cfree_argument_code}
	pylinphone_dispatch_messages();
""".format(arg_name="_" + self.first_arg_name, method_name=self.method_node.get('name'), suffix=suffix, cfree_argument_code=cfree_argument_code)

	def format_return_trace(self):
		return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s -> 0\", __FUNCTION__);\n"

	def format_return_result(self):
		return "\treturn 0;"

	def parse_method_node(self):
		MethodDefinition.parse_method_node(self)
		# Force return value type of setter function to prevent declaring useless local variables
		# TODO: Investigate. Maybe we should decide that setters must always return an int value.
		self.xml_method_return = None
		self.attribute_name = self.method_node.get('property_name')
		self.first_arg_type = self.xml_method_args[0].get('type')
		self.first_arg_complete_type = self.xml_method_args[0].get('completetype')
		self.first_arg_contained_type = self.xml_method_args[0].get('containedtype')
		self.first_arg_name = self.xml_method_args[0].get('name')
		self.first_argument_type = ArgumentType(self.first_arg_type, self.first_arg_complete_type, self.first_arg_contained_type, self.linphone_module)
		self.first_arg_class = strip_leading_linphone(self.first_arg_type)

class EventCallbackMethodDefinition(MethodDefinition):
	def __init__(self, linphone_module, class_, method_name = "", method_node = None):
		MethodDefinition.__init__(self, linphone_module, class_, method_name, method_node)

	def format_local_variables_definition(self):
		class_name = self.class_['event_class']
		nocallbacks_class_name = class_name
		if class_name.endswith('Cbs'):
			nocallbacks_class_name = class_name[:-3]
		has_current_callbacks = self.find_property_definition(nocallbacks_class_name, 'current_callbacks')
		if has_current_callbacks is not None:
			get_callbacks_funcname = 'get_current_callbacks'
		else:
			get_callbacks_funcname = 'get_callbacks'
		returnvars = self.format_local_return_variables_definition()
		common = \
"""	pylinphone_{class_name}Object *pyself = (pylinphone_{class_name}Object *){function_prefix}get_user_data(self);
	PyObject *func;
	PyObject *args;
	PyGILState_STATE pygil_state;""".format(class_name=nocallbacks_class_name, function_prefix=self.find_class_definition(nocallbacks_class_name)['class_c_function_prefix'])
		if class_name.endswith('Cbs'):
			common += """
	pylinphone_{class_name}Object *pycbs = (pylinphone_{class_name}Object *){cbs_function_prefix}get_user_data({function_prefix}{get_callbacks_funcname}(self));
""".format(class_name=class_name, cbs_function_prefix=self.find_class_definition(class_name)['class_c_function_prefix'], function_prefix=self.find_class_definition(nocallbacks_class_name)['class_c_function_prefix'], get_callbacks_funcname=get_callbacks_funcname)
		specific = ''
		for xml_method_arg in self.xml_method_args:
			arg_name = xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			if argument_type.fmt_str == 'O':
				specific += "\tPyObject * py" + arg_name + " = NULL;\n"
		return "{returnvars}\n{common}\n{specific}".format(returnvars=returnvars, common=common, specific=specific)

	def format_arguments_parsing(self):
		return_str = ''
		if self.return_complete_type == 'int':
			return_str = '-1'
		elif self.return_complete_type == 'bool_t':
			return_str = 'FALSE'
		elif self.return_complete_type != 'void':
			argument_type = ArgumentType(self.return_type, self.return_complete_type, self.return_contained_type, self.linphone_module)
			if argument_type.fmt_str == 'O':
				return_str = 'NULL'
		return \
"""	if (Py_REFCNT(pyself) <= 0) return {return_str};
	func = pycbs->{event_name};
	pygil_state = PyGILState_Ensure();
""".format(event_name=self.class_['event_name'], return_str=return_str)

	def format_enter_trace(self):
		fmt = '%p'
		args = ['self']
		for xml_method_arg in self.xml_method_args:
			arg_name = xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			if fmt != '':
				fmt += ', '
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			fmt += argument_type.cfmt_str
			args.append(arg_name)
		args=', '.join(args)
		if args != '':
			args = ', ' + args
		return "\tpylinphone_trace(1, \"[PYLINPHONE] >>> %s({fmt})\", __FUNCTION__{args});\n".format(fmt=fmt, args=args)

	def format_c_function_call(self):
		create_python_objects_code = ''
		convert_python_result_code = ''
		fmt = 'O'
		args = ['pyself']
		for xml_method_arg in self.xml_method_args:
			arg_name = xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arg_contained_type = xml_method_arg.get('containedtype')
			argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self.linphone_module)
			fmt += argument_type.fmt_str
			if argument_type.fmt_str == 'O':
				args.append('py' + arg_name)
			else:
				args.append(arg_name)
			if argument_type.fmt_str == 'O':
				if argument_type.type_str == "bool":
					create_python_objects_code += "\t\tpy{name} = {convert_from_func}({name});\n".format(name=arg_name, convert_from_func=argument_type.convert_from_func)
				else:
					type_class = self.find_class_definition(arg_type)
					create_python_objects_code += "\t\tpy{name} = pylinphone_{arg_type}_from_native_ptr(&pylinphone_{arg_type}Type, {name}, TRUE);\n".format(name=arg_name, arg_type=strip_leading_linphone(arg_type))
		args=', '.join(args)
		if self.return_complete_type != 'void':
			argument_type = ArgumentType(self.return_type, self.return_complete_type, self.return_contained_type, self.linphone_module)
			if argument_type.is_linphone_object:
				convert_python_result_code = \
"""		if ((pyresult != Py_None) && !PyObject_IsInstance(pyresult, (PyObject *)&pylinphone_{class_name}Type)) {{
			PyErr_SetString(PyExc_TypeError, "The return value must be a linphone.{class_name} instance.");
			return NULL;
		}}
		if ((cresult = pylinphone_{class_name}_get_native_ptr(pyresult)) == NULL) {{
			return NULL;
		}}
""".format(class_name=strip_leading_linphone(self.return_type))

			else:
				convert_python_result_code = '\t\t' + argument_type.convert_code.format(result_name='cresult', result_suffix='', cast='', arg_name='pyresult')
		return \
"""	if ((func != NULL) && PyCallable_Check(func)) {{
{create_python_objects_code}
		args = Py_BuildValue("{fmt}", {args});
		pyresult = PyEval_CallObject(func, args);
		if (pyresult == NULL) {{
			PyErr_Print();
		}}
		Py_DECREF(args);
{convert_python_result_code}
	}}
""".format(fmt=fmt, args=args, create_python_objects_code=create_python_objects_code, convert_python_result_code=convert_python_result_code)

	def format_return_trace(self):
		return "\tpylinphone_trace(-1, \"[PYLINPHONE] <<< %s\", __FUNCTION__);\n"

	def format_return_result(self):
		s = '\tPyGILState_Release(pygil_state);'
		if self.return_complete_type != 'void':
			s += '\n\treturn cresult;'
		return s

	def format_local_return_variables_definition(self):
		body = "\tPyObject * pyresult;"
		if self.xml_method_return is not None:
			self.return_type = self.xml_method_return.get('type')
			self.return_complete_type = self.xml_method_return.get('completetype')
			self.return_contained_type = self.xml_method_return.get('containedtype')
		if self.return_complete_type != 'void':
			body += "\n\t" + self.return_complete_type + " cresult;"
		return body

	def format(self):
		body = MethodDefinition.format(self)
		class_name = self.class_['event_class']
		nocallbacks_class_name = class_name
		if class_name.endswith('Cbs'):
			nocallbacks_class_name = class_name[:-3]
		arguments = ['Linphone' + nocallbacks_class_name + ' * self']
		for xml_method_arg in self.xml_method_args:
			arg_name = xml_method_arg.get('name')
			arg_type = xml_method_arg.get('type')
			arg_complete_type = xml_method_arg.get('completetype')
			arguments.append(arg_complete_type + ' ' + arg_name)
		definition = \
"""static {returntype} pylinphone_{class_name}_callback_{event_name}({arguments}) {{
{body}
}}
""".format(returntype=self.return_complete_type, class_name=class_name, event_name=self.class_['event_name'], arguments=', '.join(arguments), body=body)
		return definition


class LinphoneModule:
	def __init__(self, tree, blacklisted_classes, blacklisted_events, blacklisted_functions, hand_written_codes):
		self.known_types = ['char', 'int', 'int8_t', 'int16_t', 'int32_t', 'int64_t', 'uint8_t', 'uint16_t', 'uint32_t', 'uint64_t', 'bool_t', 'float', 'double', 'size_t', 'time_t', 'MSList', 'bctbx_list_t', 'MSVideoSize', 'LCSipTransports', 'LinphoneStatus']
		self.internal_instance_method_names = ['destroy', 'ref', 'unref']
		self.internal_property_names = ['user_data']
		self.bctbxlist_types = set([])
		self.enums = []
		self.enum_names = []
		self.cfunction2methodmap = {}
		hand_written_functions = []
		for hand_written_code in hand_written_codes:
			hand_written_functions += hand_written_code.func_list
		xml_enums = tree.findall("./enums/enum")
		for xml_enum in xml_enums:
			e = {}
			e['enum_cname'] = xml_enum.get('name')
			e['enum_name'] = strip_leading_linphone(e['enum_cname'])
			e['enum_doc'] = self.__format_doc_content(xml_enum.find('briefdescription'), xml_enum.find('detaileddescription'))
			e['enum_doc'] = self.__replace_doc_special_chars(e['enum_doc'])
			e['enum_doc'] += """

.. csv-table::
   :delim: |
   :widths: 30, 70
   :header: Value,Description

"""
			e['enum_values'] = []
			e['enum_deprecated_values'] = []
			xml_enum_values = xml_enum.findall("./values/value")
			for xml_enum_value in xml_enum_values:
				v = {}
				v['enum_value_cname'] = xml_enum_value.get('name')
				valname = strip_leading_linphone(v['enum_value_cname'])
				v['enum_value_name'] = remove_useless_enum_prefix(e['enum_name'], valname)
				v['enum_value_doc'] = self.__format_doc(xml_enum_value.find('briefdescription'), xml_enum_value.find('detaileddescription'))
				e['enum_doc'] += '   ' + v['enum_value_name'] + '|' + v['enum_value_doc'] + '\n'
				e['enum_values'].append(v)
				if v['enum_value_name'] != valname:
					# TODO: To remove. Add deprecated value name.
					v = {}
					v['enum_value_cname'] = xml_enum_value.get('name')
					v['enum_value_name'] = strip_leading_linphone(v['enum_value_cname'])
					v['enum_value_doc'] = self.__format_doc(xml_enum_value.find('briefdescription'), xml_enum_value.find('detaileddescription'))
					e['enum_deprecated_values'].append(v)
			e['enum_doc'] = self.__replace_doc_special_chars(e['enum_doc'])
			e['enum_doc'] = e['enum_doc'].encode('unicode_escape')
			self.enums.append(e)
			self.enum_names.append(e['enum_name'])
			self.known_types.append(e['enum_cname'])
		self.core_events = []
		self.classes = []
		xml_classes = tree.findall("./classes/class")
		for xml_class in xml_classes:
			if xml_class.get('name') in blacklisted_classes:
				continue
			c = {}
			c['class_xml_node'] = xml_class
			c['class_cname'] = xml_class.get('name')
			c['class_name'] = strip_leading_linphone(c['class_cname'])
			c['class_c_function_prefix'] = xml_class.get('cfunctionprefix')
			c['class_doc'] = self.__format_doc(xml_class.find('briefdescription'), xml_class.find('detaileddescription'))
			c['class_doc'] = c['class_doc'].encode('unicode_escape')
			c['class_refcountable'] = (xml_class.get('refcountable') == 'true')
			c['class_destroyable'] = (xml_class.get('destroyable') == 'true')
			c['class_has_user_data'] = False
			c['class_type_methods'] = []
			c['class_type_hand_written_methods'] = []
			c['class_instance_hand_written_methods'] = []
			c['class_hand_written_properties'] = []
			c['class_object_members'] = []
			c['class_object_members_code'] = ''
			c['class_events'] = []
			xml_events = xml_class.findall("./events/event")
			for xml_event in xml_events:
				if xml_event.get('name') in blacklisted_events:
						continue
				ev = {}
				ev['event_class'] = c['class_name']
				ev['event_xml_node'] = xml_event
				ev['event_cname'] = xml_event.get('name')
				ev['event_name'] = compute_event_name(ev['event_cname'], c['class_name'])
				ev['event_doc'] = self.__format_doc(xml_event.find('briefdescription'), xml_event.find('detaileddescription'))
				ev['event_doc'] = ev['event_doc'].encode('unicode_escape')
				c['class_events'].append(ev)
				self.known_types.append(ev['event_cname'])
				c['class_object_members'].append(ev['event_name'])
				c['class_object_members_code'] += "\tPyObject *" + ev['event_name'] + ";\n"
			for hand_written_code in hand_written_codes:
				if hand_written_code._class == c['class_name']:
					if isinstance(hand_written_code, HandWrittenClassMethod):
						m = {}
						m['method_name'] = hand_written_code.name
						m['method_doc'] = self.__replace_doc_special_chars(hand_written_code.doc)
						m['method_doc'] = m['method_doc'].encode('unicode_escape')
						c['class_type_hand_written_methods'].append(m)
					elif isinstance(hand_written_code, HandWrittenInstanceMethod):
						m = {}
						m['method_name'] = hand_written_code.name
						m['method_doc'] = self.__replace_doc_special_chars(hand_written_code.doc)
						m['method_doc'] = m['method_doc'].encode('unicode_escape')
						c['class_instance_hand_written_methods'].append(m)
					elif isinstance(hand_written_code, HandWrittenDeallocMethod):
						c['class_has_hand_written_dealloc'] = True
					elif isinstance(hand_written_code, HandWrittenProperty):
						p = {}
						p['property_name'] = hand_written_code.name
						if hand_written_code.getter_cfunction is None:
							p['getter_reference'] = 'NULL'
						else:
							p['getter_reference'] = '(getter)pylinphone_' + c['class_name'] + '_get_' + p['property_name']
						if hand_written_code.setter_cfunction is None:
							p['setter_reference'] = 'NULL'
						else:
							p['setter_reference'] = '(setter)pylinphone_' + c['class_name'] + '_set_' + p['property_name']
						p['property_doc'] = self.__replace_doc_special_chars(hand_written_code.doc)
						p['property_doc'] = p['property_doc'].encode('unicode_escape')
						c['class_hand_written_properties'].append(p)
			xml_type_methods = xml_class.findall("./classmethods/classmethod")
			for xml_type_method in xml_type_methods:
				method_name = xml_type_method.get('name')
				if method_name in blacklisted_functions:
					continue
				m = {}
				m['method_name'] = method_name.replace(c['class_c_function_prefix'], '')
				if method_name not in hand_written_functions:
					m['method_xml_node'] = xml_type_method
					self.cfunction2methodmap[method_name] = ':py:meth:`linphone.' + c['class_name'] + '.' + m['method_name'] + '`'
					c['class_type_methods'].append(m)
			c['class_instance_methods'] = []
			xml_instance_methods = xml_class.findall("./instancemethods/instancemethod")
			for xml_instance_method in xml_instance_methods:
				method_name = xml_instance_method.get('name')
				if method_name in blacklisted_functions:
					continue
				if method_name.replace(c['class_c_function_prefix'], '') in self.internal_instance_method_names:
					continue
				m = {}
				m['method_name'] = method_name.replace(c['class_c_function_prefix'], '')
				if method_name not in hand_written_functions:
					m['method_xml_node'] = xml_instance_method
					self.cfunction2methodmap[method_name] = ':py:meth:`linphone.' + c['class_name'] + '.' + m['method_name'] + '`'
					c['class_instance_methods'].append(m)
			c['class_properties'] = []
			xml_properties = xml_class.findall("./properties/property")
			for xml_property in xml_properties:
				property_name = xml_property.get('name')
				if property_name == 'user_data':
					c['class_has_user_data'] = True
				if property_name in self.internal_property_names:
					continue
				p = {}
				p['property_name'] = property_name
				xml_property_getter = xml_property.find("./getter")
				xml_property_setter = xml_property.find("./setter")
				if xml_property_getter is not None:
					if xml_property_getter.get('name') in blacklisted_functions or xml_property_getter.get('name') in hand_written_functions:
						continue
				if xml_property_setter is not None:
					if xml_property_setter.get('name') in blacklisted_functions or xml_property_setter.get('name') in hand_written_functions:
						continue
				if xml_property_getter is not None:
					xml_property_getter.set('property_name', property_name)
					p['getter_name'] = xml_property_getter.get('name').replace(c['class_c_function_prefix'], '')
					p['getter_xml_node'] = xml_property_getter
					p['getter_reference'] = "(getter)pylinphone_" + c['class_name'] + "_" + p['getter_name']
					p['getter_definition_begin'] = "static PyObject * pylinphone_" + c['class_name'] + "_" + p['getter_name'] + "(PyObject *self, void *closure) {"
					p['getter_definition_end'] = "}"
					self.cfunction2methodmap[xml_property_getter.get('name')] = ':py:attr:`linphone.' + c['class_name'] + '.' + property_name + '`'
				else:
					p['getter_reference'] = "NULL"
				if xml_property_setter is not None:
					xml_property_setter.set('property_name', property_name)
					p['setter_name'] = xml_property_setter.get('name').replace(c['class_c_function_prefix'], '')
					p['setter_xml_node'] = xml_property_setter
					p['setter_reference'] = "(setter)pylinphone_" + c['class_name'] + "_" + p['setter_name']
					p['setter_definition_begin'] = "static int pylinphone_" + c['class_name'] + "_" + p['setter_name'] + "(PyObject *self, PyObject *value, void *closure) {"
					p['setter_definition_end'] = "}"
					self.cfunction2methodmap[xml_property_setter.get('name')] = ':py:attr:`linphone.' + c['class_name'] + '.' + property_name + '`'
				else:
					p['setter_reference'] = "NULL"
				c['class_properties'].append(p)
			self.classes.append(c)
			self.known_types.append(c['class_cname'])
		# Format events definitions
		for c in self.classes:
			for ev in c['class_events']:
				ev['event_callback_definition'] = EventCallbackMethodDefinition(self, ev, ev['event_name'], ev['event_xml_node']).format()
		# Format methods' bodies
		for c in self.classes:
			xml_new_method = c['class_xml_node'].find("./classmethods/classmethod[@name='" + c['class_c_function_prefix'] + "new']")
			try:
				c['new_body'] = NewMethodDefinition(self, c, xml_new_method).format()
			except (UnknownTypeException) as e:
				print(e)
				c['blacklisted'] = True
			except (Exception) as e:
				e.args += (c['class_name'], 'new_body')
				raise
			try:
				c['init_body'] = InitMethodDefinition(self, c, xml_new_method).format()
			except (UnknownTypeException) as e:
				print(e)
				c['blacklisted'] = True
			except (Exception) as e:
				e.args += (c['class_name'], 'init_body')
				raise
			try:
				c['from_native_pointer_body'] = FromNativePointerMethodDefinition(self, c).format()
			except (UnknownTypeException) as e:
				print(e)
				c['blacklisted'] = True
			except (Exception) as e:
				e.args += (c['class_name'], 'from_native_pointer_body')
				raise
			for m in c['class_type_methods']:
				try:
					m['method_body'] = MethodDefinition(self, c, m['method_name'], m['method_xml_node']).format()
					m['method_doc'] = self.__format_method_doc(m['method_xml_node'])
					m['method_doc'] = m['method_doc'].encode('unicode_escape')
				except (UnknownTypeException) as e:
					print(e)
					m['blacklisted'] = True
				except (Exception) as e:
					e.args += (c['class_name'], m['method_name'])
					raise
			for m in c['class_instance_methods']:
				try:
					m['method_body'] = MethodDefinition(self, c, m['method_name'], m['method_xml_node']).format()
					m['method_doc'] = self.__format_method_doc(m['method_xml_node'])
					m['method_doc'] = m['method_doc'].encode('unicode_escape')
				except (UnknownTypeException) as e:
					print(e)
					m['blacklisted'] = True
				except (Exception) as e:
					e.args += (c['class_name'], m['method_name'])
					raise
			for p in c['class_properties']:
				p['property_doc'] = ''
				if 'setter_xml_node' in p:
					try:
						p['setter_body'] = SetterMethodDefinition(self, c, p['property_name'], p['setter_xml_node']).format()
						p['property_doc'] = self.__format_setter_doc(p['setter_xml_node'])
					except (UnknownTypeException) as e:
						print(e)
						p['blacklisted'] = True
					except (Exception) as e:
						e.args += (c['class_name'], p['property_name'])
						raise
				if 'getter_xml_node' in p:
					try:
						p['getter_body'] = GetterMethodDefinition(self, c, p['property_name'], p['getter_xml_node']).format()
						if p['property_doc'] == '':
							p['property_doc'] = self.__format_getter_doc(p['getter_xml_node'])
					except (UnknownTypeException) as e:
						print(e)
						p['blacklisted'] = True
					except (Exception) as e:
						e.args += (c['class_name'], p['property_name'])
						raise
				p['property_doc'] = p['property_doc'].encode('unicode_escape')
			if not 'class_has_hand_written_dealloc' in c:
				try:
					if c['class_refcountable']:
						xml_instance_method = c['class_xml_node'].find("./instancemethods/instancemethod[@name='" + c['class_c_function_prefix'] + "unref']")
						c['dealloc_definition'] = DeallocMethodDefinition(self, c, xml_instance_method).format()
					elif c['class_destroyable']:
						xml_instance_method = c['class_xml_node'].find("./instancemethods/instancemethod[@name='" + c['class_c_function_prefix'] + "destroy']")
						c['dealloc_definition'] = DeallocMethodDefinition(self, c, xml_instance_method).format()
					else:
						c['dealloc_definition'] = DeallocMethodDefinition(self, c).format()
				except (UnknownTypeException) as e:
					print(e)
					c['blacklisted'] = True
				except (Exception) as e:
					e.args += (c['class_name'], 'dealloc_body')
					raise
		# Remove blacklisted classes and methods
		self.classes = [c for c in self.classes if not 'blacklisted' in c]
		for c in self.classes:
			c['class_type_methods'] = [m for m in c['class_type_methods'] if not 'blacklisted' in m]
			c['class_instance_methods'] = [m for m in c['class_instance_methods'] if not 'blacklisted' in m]
			c['class_properties'] = [m for m in c['class_properties'] if not 'blacklisted' in m]
		# Convert bctbxlist_types to a list of dictionaries for the template
		d = []
		for bctbxlist_type in self.bctbxlist_types:
			t = {}
			t['c_contained_type'] = bctbxlist_type
			t['python_contained_type'] = strip_leading_linphone(bctbxlist_type)
			d.append(t)
		self.bctbxlist_types = d

	def __format_doc_node(self, node):
		desc = ''
		if node.tag == 'para':
			if node.text is not None:
				desc += node.text.strip()
			for n in list(node):
				desc += self.__format_doc_node(n)
		elif node.tag == 'note':
			if node.text is not None:
				desc += node.text.strip()
			for n in list(node):
				desc += self.__format_doc_node(n)
		elif node.tag == 'ref':
			if node.text is not None:
				desc += ' ' + node.text.strip() + ' '
		tail = node.tail.strip()
		if tail != '':
			if node.tag != 'ref':
				desc += '\n'
			desc += tail
		if node.tag == 'para':
			desc += '\n'
		return desc

	def __format_doc_content(self, brief_description, detailed_description):
		doc = ''
		if brief_description is None:
			brief_description = ''
		else:
			brief_description = brief_description.text
			
		if detailed_description is None:
			detailed_description = ''
		else:
			desc = ''
			for node in list(detailed_description):
				desc += self.__format_doc_node(node) + '\n'
			detailed_description = desc.strip()
		brief_description = brief_description.strip()
		doc += brief_description
		if detailed_description != '':
			if doc != '':
				doc += '\n\n'
			doc += detailed_description
		return doc

	def __replace_doc_special_chars(self, doc):
		return doc.replace('"', '') #.encode('utf-8') #.encode('unicode_escape')

	def __replace_doc_cfunction_by_method(self, doc):
		for cfunction, method in six.iteritems(self.cfunction2methodmap):
			doc = doc.replace(cfunction + '()', method)
		for cfunction, method in six.iteritems(self.cfunction2methodmap):
			doc = doc.replace(cfunction, method)
		return doc

	def __replace_doc_keywords(self, doc):
		return doc.replace('NULL', 'None')

	def __format_doc(self, brief_description, detailed_description):
		doc = self.__format_doc_content(brief_description, detailed_description)
		doc = self.__replace_doc_cfunction_by_method(doc)
		doc = self.__replace_doc_keywords(doc)
		doc = self.__replace_doc_special_chars(doc)
		return doc

	def __format_method_doc(self, xml_node):
		doc = self.__format_doc_content(xml_node.find('briefdescription'), xml_node.find('detaileddescription'))
		xml_method_return = xml_node.find('./return')
		xml_method_args = xml_node.findall('./arguments/argument')
		method_type = xml_node.tag
		if method_type != 'classmethod' and len(xml_method_args) > 0:
			xml_method_args = xml_method_args[1:]
		doc += '\n'
		if len(xml_method_args) > 0:
			for xml_method_arg in xml_method_args:
				arg_name = xml_method_arg.get('name')
				arg_type = xml_method_arg.get('type')
				arg_complete_type = xml_method_arg.get('completetype')
				arg_contained_type = xml_method_arg.get('containedtype')
				argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self)
				arg_doc = self.__format_doc_content(None, xml_method_arg.find('description'))
				doc += '\n:param ' + arg_name + ':'
				if arg_doc != '':
					doc += ' ' + arg_doc
				doc += '\n:type ' + arg_name + ': ' + argument_type.type_str
		if xml_method_return is not None:
			return_type = xml_method_return.get('type')
			return_complete_type = xml_method_return.get('completetype')
			return_contained_type = xml_method_return.get('containedtype')
			if return_complete_type != 'void':
				return_doc = self.__format_doc_content(None, xml_method_return.find('description'))
				return_argument_type = ArgumentType(return_type, return_complete_type, return_contained_type, self)
				doc += '\n:returns: ' + return_doc
				doc += '\n:rtype: ' + return_argument_type.type_str
		doc = self.__replace_doc_cfunction_by_method(doc)
		doc = self.__replace_doc_keywords(doc)
		doc = self.__replace_doc_special_chars(doc)
		return doc

	def __format_setter_doc(self, xml_node):
		xml_method_arg = xml_node.findall('./arguments/argument')[1]
		arg_type = xml_method_arg.get('type')
		arg_complete_type = xml_method_arg.get('completetype')
		arg_contained_type = xml_method_arg.get('containedtype')
		argument_type = ArgumentType(arg_type, arg_complete_type, arg_contained_type, self)
		doc = self.__format_doc_content(xml_node.find('briefdescription'), xml_node.find('detaileddescription'))
		doc = '[' + argument_type.type_str + '] ' + doc
		doc = self.__replace_doc_cfunction_by_method(doc)
		doc = self.__replace_doc_keywords(doc)
		doc = self.__replace_doc_special_chars(doc)
		return doc

	def __format_getter_doc(self, xml_node):
		xml_method_return = xml_node.find('./return')
		return_type = xml_method_return.get('type')
		return_complete_type = xml_method_return.get('completetype')
		return_contained_type = xml_method_return.get('containedtype')
		return_argument_type = ArgumentType(return_type, return_complete_type, return_contained_type, self)
		doc = self.__format_doc_content(xml_node.find('briefdescription'), xml_node.find('detaileddescription'))
		doc = '[' + return_argument_type.type_str + '] ' + doc
		doc = self.__replace_doc_cfunction_by_method(doc)
		doc = self.__replace_doc_keywords(doc)
		doc = self.__replace_doc_special_chars(doc)
		return doc