forked from hartror/python-libvlc-bindings
-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.py
executable file
·1203 lines (1026 loc) · 40.1 KB
/
generate.py
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
#! /usr/bin/python
# Code generator for python ctypes bindings for VLC
#
# Copyright (C) 2009-2010 the VideoLAN team
# $Id: $
#
# Authors: Olivier Aubert <olivier.aubert at liris.cnrs.fr>
# Jean Brouwers <MrJean1 at gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
"""This module parses VLC public API include files and generates
corresponding Python/ctypes bindingsB{**} code. Moreover, it
generates Python class and method wrappers from the VLC functions
and enum types.
There are 3 dependencies. Files C{header.py} and C{footer.py}
contain the pre- and postamble of the generated code. Module
C{override.py} defines a number of classes and methods overriding
the ones to be generated.
This module and the generated Python bindings have been verified
with PyChecker 0.8.18, see U{http://pychecker.sourceforge.net}
and PyFlakes 0.4.0, see U{http://pypi.python.org/pypi/pyflakes}.
The C{#PYCHOK ...} comments direct the PyChecker/-Flakes post-
processor, see U{http://code.activestate.com/recipes/546532}.
This module and the generated Python bindings have been tested with
32-bit Python 2.6, 2.7 and 3.1 on Linux, Windows XP SP3 and MacOS X 10.4.11
(Intel) using the VLC 1.1.4.1 and 1.1.5 public API include files.
B{**)} The Java/JNA bindings for the VLC public API can be created
in a similar manner and depend on 3 Java files: C{boilerplate.java},
C{LibVlc-footer.java} and C{LibVlc-header.java}.
"""
__all__ = ('Parser',
'PythonGenerator', 'JavaGenerator',
'process')
__version__ = '20.11.05.15'
_debug = False
import sys
import os
import re
import time
import operator
# Opener for text files
if sys.hexversion < 0x3000000:
def opener(name, mode='r'):
return open(name, mode)
else: # Python 3+
def opener(name, mode='r'): #PYCHOK expected
return open(name, mode, encoding='utf8')
# Functions not wrapped/not referenced
_blacklist = {
'libvlc_set_exit_handler': '', # not in 1.1.5?
'libvlc_video_set_callbacks': '',
'libvlc_video_set_format_callbacks': '',
'libvlc_audio_set_callbacks': '',
'libvlc_audio_set_format_callbacks': '',
'libvlc_audio_set_volume_callback': '',
'libvlc_vprinterr': '',
'libvlc_printerr': '',
}
# Set of functions that return a string that the caller is
# expected to free.
free_string_funcs = set((
'libvlc_media_discoverer_localized_name',
'libvlc_media_get_mrl',
'libvlc_media_get_meta',
'libvlc_video_get_aspect_ratio',
'libvlc_video_get_crop_geometry',
'libvlc_video_get_marquee_string',
'libvlc_audio_output_device_longname',
'libvlc_audio_output_device_id',
'libvlc_vlm_show_media',
))
# some constants
_NA_ = 'N/A'
_NL_ = '\n' # os.linesep
_OUT_ = '[OUT]'
_PNTR_ = 'pointer to get the ' # KLUDGE: see @param ... [OUT]
_INDENT_ = ' '
# special keywords in header.py
_BUILD_DATE_ = 'build_date = '
_GENERATED_ENUMS_ = '# GENERATED_ENUMS'
# keywords in header files
_VLC_FORWARD_ = 'VLC_FORWARD'
_VLC_PUBLIC_API_ = 'LIBVLC_API'
# Precompiled regexps
api_re = re.compile(_VLC_PUBLIC_API_ + '\s+(\S+\s+.+?)\s*\(\s*(.+?)\s*\)')
at_param_re = re.compile('(@param\s+\S+)(.+)')
bs_param_re = re.compile('\\param\s+(\S+)')
class_re = re.compile('class\s+(\S+):')
def_re = re.compile('^\s+def\s+(\w+)', re.MULTILINE)
enum_re = re.compile('(?:typedef\s+)?(enum)\s*(\S+)\s*\{\s*(.+)\s*\}\s*(?:\S+)?;')
enum_pair_re = re.compile('\s*=\s*')
enum_type_re = re.compile('^(?:typedef\s+)?enum')
forward_re = re.compile('.+\(\s*(.+?)\s*\)(\s*\S+)')
libvlc_re = re.compile('\slibvlc_[a-z_]+')
param_re = re.compile('\s*(const\s*|unsigned\s*|struct\s*)?(\S+\s*\**)\s+(.+)')
paramlist_re = re.compile('\s*,\s*')
version_re = re.compile('vlc[\-]\d+[.]\d+[.]\d+.*')
def endot(text):
"""Terminate string with a period.
"""
if text and text[-1] not in '.,:;?!':
text += '.'
return text
def errorf(fmt, *args):
"""Print error.
"""
global _nerrors
_nerrors += 1
sys.stderr.write('Error: ' + (fmt % args) + "\n")
_nerrors = 0
def errors(fmt, e=0):
"""Report total number of errors.
"""
if _nerrors > e:
n = _nerrors - e
x = min(n, 9)
errorf(fmt + '... exit(%s)', n, x)
sys.exit(x)
elif _debug:
sys.stderr.write(fmt % (_NL_ + 'No') + "\n")
class _Source(object):
"""Base class for elements parsed from source.
"""
source = ''
def __init__(self, file_='', line=0):
self.source = '%s:%s' % (file_, line)
self.dump() #PYCHOK expected
class Enum(_Source):
"""Enum type.
"""
type = 'enum'
def __init__(self, name, type='enum', vals=(), docs='', **kwds):
if type != self.type:
raise TypeError('expected enum type: %s %s' % (type, name))
self.docs = docs
self.name = name
self.vals = vals # list/tuple of Val instances
if _debug:
_Source.__init__(self, **kwds)
def check(self):
"""Perform some consistency checks.
"""
if not self.docs:
errorf('no comment for typedef %s %s', self.type, self.name)
if self.type != 'enum':
errorf('expected enum type: %s %s', self.type, self.name)
def dump(self): # for debug
sys.stderr.write('%s (%s): %s\n' % (self.name, self.type, self.source))
for v in self.vals:
v.dump()
def epydocs(self):
"""Return epydoc string.
"""
return self.docs.replace('@see', 'See').replace('\\see', 'See')
class Flag(object):
"""Enum-like, ctypes parameter direction flag constants.
"""
In = 1 # input only
Out = 2 # output only
InOut = 3 # in- and output
InZero = 4 # input, default int 0
def __init__(self):
raise TypeError('constants only')
class Func(_Source):
"""C function.
"""
heads = () # docs lines without most @tags
out = () # [OUT] parameter names
params = () # @param lines, except [OUT]
tails = () # @return, @version, @bug lines
wrapped = 0 # number of times wrapped
def __init__(self, name, type, pars=(), docs='', **kwds):
self.docs = docs
self.name = name
self.pars = pars # list/tuple of Par instances
self.type = type
if _debug:
_Source.__init__(self, **kwds)
def args(self, first=0):
"""Return the parameter names, excluding output parameters.
Ctypes returns all output parameter values as part of
the returned tuple.
"""
return [p.name for p in self.pars[first:] if
p.flags(self.out)[0] != Flag.Out]
def check(self):
"""Perform some consistency checks.
"""
if not self.docs:
errorf('no comment for function %s', self.name)
elif len(self.pars) != self.nparams:
errorf('doc parameters (%d) mismatch for function %s (%d)',
self.nparams, self.name, len(self.pars))
if _debug:
self.dump()
sys.stderr.write(self.docs + "\n")
def dump(self): # for debug
sys.stderr.write('%s (%s): %s\n' % (self.name, self.type, self.source))
for p in self.pars:
p.dump(self.out)
def epydocs(self, first=0, indent=0):
"""Return epydoc doc string with/out first parameter.
"""
# "out-of-bounds" slices are OK, e.g. ()[1:] == ()
t = _NL_ + (' ' * indent)
return t.join(self.heads + self.params[first:] + self.tails)
def __nparams_(self):
return (len(self.params) + len(self.out)) or len(bs_param_re.findall(self.docs))
nparams = property(__nparams_, doc='number of \\param lines in doc string')
def xform(self):
"""Transform Doxygen to epydoc syntax.
"""
b, c, h, o, p, r, v = [], None, [], [], [], [], []
# see <http://epydoc.sourceforge.net/manual-fields.html>
# (or ...replace('{', 'E{lb}').replace('}', 'E{rb}') ?)
for t in self.docs.replace('@{', '').replace('@}', '').replace('\\ingroup', '') \
.replace('{', '').replace('}', '') \
.replace('<b>', 'B{').replace('</b>', '}') \
.replace('@see', 'See').replace('\\see', 'See') \
.replace('\\bug', '@bug').replace('\\version', '@version') \
.replace('\\note', '@note').replace('\\warning', '@warning') \
.replace('\\param', '@param').replace('\\return', '@return') \
.splitlines():
if '@param' in t:
if _OUT_ in t:
# KLUDGE: remove @param, some comment and [OUT]
t = t.replace('@param', '').replace(_PNTR_, '').replace(_OUT_, '')
# keep parameter name and doc string
o.append(' '.join(t.split()))
c = [''] # drop continuation line(s)
else:
p.append(at_param_re.sub('\\1:\\2', t))
c = p
elif '@return' in t:
r.append(t.replace('@return ', '@return: '))
c = r
elif '@bug' in t:
b.append(t.replace('@bug ', '@bug: '))
c = b
elif '@version' in t:
v.append(t.replace('@version ', '@version: '))
c = v
elif c is None:
h.append(t.replace('@note ', '@note: ').replace('@warning ', '@warning: '))
else: # continuation, concatenate to previous @tag line
c[-1] = '%s %s' % (c[-1], t.strip())
if h:
h[-1] = endot(h[-1])
self.heads = tuple(h)
if o: # just the [OUT] parameter names
self.out = tuple(t.split()[0] for t in o)
# ctypes returns [OUT] parameters as tuple
r = ['@return: %s' % ', '.join(o)]
if p:
self.params = tuple(map(endot, p))
t = r + v + b
if t:
self.tails = tuple(map(endot, t))
class Par(object):
"""C function parameter.
"""
def __init__(self, name, type):
self.name = name
self.type = type # C type
def dump(self, out=()): # for debug
if self.name in out:
t = _OUT_ # @param [OUT]
else:
t = {Flag.In: '', # default
Flag.Out: 'Out',
Flag.InOut: 'InOut',
Flag.InZero: 'InZero',
}.get(self.flags()[0], 'FIXME_Flag')
sys.stderr.write('%s%s (%s) %s\n' % (_INDENT_, self.name, self.type, t))
# Parameter passing flags for types. This shouldn't
# be hardcoded this way, but works all right for now.
def flags(self, out=(), default=None):
"""Return parameter flags tuple.
Return the parameter flags tuple for the given parameter
type and name and a list of parameter names documented as
[OUT].
"""
if self.name in out:
f = Flag.Out # @param [OUT]
else:
f = {'int*': Flag.Out,
'unsigned*': Flag.Out,
'libvlc_media_track_info_t**': Flag.Out,
}.get(self.type, Flag.In) # default
if default is None:
return f, # 1-tuple
else: # see ctypes 15.16.2.4 Function prototypes
return f, self.name, default #PYCHOK expected
class Val(object):
"""Enum name and value.
"""
def __init__(self, enum, value):
self.enum = enum # C name
# convert name
t = enum.split('_')
n = t[-1]
if len(n) <= 1: # single char name
n = '_'.join( t[-2:] ) # some use 1_1, 5_1, etc.
if n[0].isdigit(): # can't start with a number
n = '_' + n
self.name = n
self.value = value
def dump(self): # for debug
sys.stderr.write('%s%s = %s\n' % (_INDENT_, self.name, self.value))
class Parser(object):
"""Parser of C header files.
"""
h_file = ''
def __init__(self, h_files, version=''):
self.enums = []
self.funcs = []
self.version = version
for h in h_files:
if not self.version: # find vlc-... version
for v in h.replace('\\', '/').split('/'):
if version_re.match(v):
self.version = v
break
self.h_file = h
self.enums.extend(self.parse_enums())
self.funcs.extend(self.parse_funcs())
def check(self):
"""Perform some consistency checks.
"""
for e in self.enums:
e.check()
for f in self.funcs:
f.check()
def __dump(self, attr):
sys.stderr.write('%s==== %s ==== %s\n' % (_NL_, attr, self.version))
for a in getattr(self, attr, ()):
a.dump()
def dump_enums(self): # for debug
self.__dump('enums')
def dump_funcs(self): # for debug
self.__dump('funcs')
def parse_enums(self):
"""Parse header file for enum type definitions.
@return: yield an Enum instance for each enum.
"""
for typ, name, enum, docs, line in self.parse_groups(enum_type_re.match, enum_re.match):
vals, v = [], -1 # enum value(s)
for t in paramlist_re.split(enum):
t = t.strip()
if not t.startswith('/*'):
if '=' in t: # has value
n, v = enum_pair_re.split(t)
vals.append(Val(n, v))
if v.startswith('0x'): # '0X'?
v = int(v, 16)
else:
v = int(v)
elif t: # only name
v += 1
vals.append(Val(t, str(v)))
name = name.strip()
if not name: # anonymous
name = 'libvlc_enum_t'
# more doc string cleanup
docs = endot(docs).capitalize()
yield Enum(name, typ, vals, docs,
file_=self.h_file, line=line)
def parse_funcs(self):
"""Parse header file for public function definitions.
@return: yield a Func instance for each function, unless blacklisted.
"""
def match_t(t):
return t.startswith(_VLC_PUBLIC_API_)
for name, pars, docs, line in self.parse_groups(match_t, api_re.match, ');'):
f = self.parse_param(name)
if f.name in _blacklist:
_blacklist[f.name] = f.type
continue
pars = [self.parse_param(p) for p in paramlist_re.split(pars)]
if len(pars) == 1 and pars[0].type == 'void':
pars = [] # no parameters
elif any(p for p in pars if not p.name): # list(...)
# no or missing parameter names, peek in doc string
n = bs_param_re.findall(docs)
if len(n) < len(pars):
errorf('%d parameter(s) missing in function %s comment: %s',
(len(pars) - len(n)), f.name, docs.replace(_NL_, ' ') or _NA_)
n.extend('param%d' % i for i in range(len(n), len(pars))) #PYCHOK false?
# FIXME: this assumes that the order of the parameters is
# the same in the parameter list and in the doc string
for i, p in enumerate(pars):
p.name = n[i]
yield Func(f.name, f.type, pars, docs,
file_=self.h_file, line=line)
def parse_groups(self, match_t, match_re, ends=';'):
"""Parse header file for matching lines, re and ends.
@return: yield a tuple of re groups extended with the
doc string and the line number in the header file.
"""
a = [] # multi-lines
d = [] # doc lines
n = 0 # line number
s = False # skip comments except doc
f = opener(self.h_file)
for t in f:
n += 1
# collect doc lines
if t.startswith('/**'):
d = [t[3:].rstrip()]
elif t.startswith(' * '): # FIXME: keep empty lines
d.append(t[3:].rstrip())
else: # parse line
t, m = t.strip(), None
if s or t.startswith('/*'): # in comment
s = not t.endswith('*/')
elif a: # accumulate multi-line
t = t.split('/*', 1)[0].rstrip() # //?
a.append(t)
if t.endswith(ends): # end
t = ' '.join(a)
m = match_re(t)
a = []
elif match_t(t):
if t.endswith(ends):
m = match_re(t) # single line
else: # new multi-line
a = [t]
if m:
# clean up doc string
d = _NL_.join(d).strip()
if d.endswith('*/'):
d = d[:-2].rstrip()
if _debug:
sys.stderr.write('%s==== source ==== %s:%d\n' % (_NL_, self.h_file, n))
sys.stderr.write(t + "\n")
sys.stderr.write('"""%s%s"""\n' % (d, _NL_))
yield m.groups() + (d, n)
d = []
f.close()
def parse_param(self, param):
"""Parse a C parameter expression.
It is used to parse the type/name of functions
and type/name of the function parameters.
@return: a Par instance.
"""
t = param.replace('const', '').strip()
if _VLC_FORWARD_ in t:
m = forward_re.match(t)
t = m.group(1) + m.group(2)
m = param_re.search(t)
if m:
_, t, n = m.groups()
while n.startswith('*'):
n = n[1:].lstrip()
t += '*'
## if n == 'const*':
## # K&R: [const] char* const*
## n = ''
else: # K&R: only [const] type
n = ''
return Par(n, t.replace(' ', ''))
class _Generator(object):
"""Base class.
"""
comment_line = '#' # Python
file = None
links = {} # must be overloaded
outdir = ''
outpath = ''
type_re = None # must be overloaded
type2class = {} # must be overloaded
def __init__(self, parser=None):
##self.type2class = self.type2class.copy()
self.parser = parser
self.convert_enums()
def check_types(self):
"""Make sure that all types are properly translated.
@note: This method must be called B{after} C{convert_enums},
since the latter populates C{type2class} with enum class names.
"""
e = _nerrors
for f in self.parser.funcs:
if f.type not in self.type2class:
errorf('no type conversion for %s %s', f.type, f.name)
for p in f.pars:
if p.type not in self.type2class:
errorf('no type conversion for %s %s in %s', p.type, p.name, f.name)
errors('%s type conversion(s) missing', e)
def class4(self, type):
"""Return the class name for a type or enum.
"""
return self.type2class.get(type, '') or ('FIXME_%s' % (type,))
def convert_enums(self):
"""Convert enum names to class names.
"""
for e in self.parser.enums:
if e.type != 'enum':
raise TypeError('expected enum: %s %s' % (e.type, e.name))
c = self.type_re.findall(e.name)[0][0]
if '_' in c:
c = c.title().replace('_', '')
elif c[0].islower():
c = c.capitalize()
self.type2class[e.name] = c
def dump_dicts(self): # for debug
s = _NL_ + _INDENT_
for n in ('type2class', 'prefixes', 'links'):
d = getattr(self, n, None)
if d:
n = ['%s==== %s ==== %s' % (_NL_, n, self.parser.version)]
sys.stderr.write(s.join(n + sorted('%s: %s\n' % t for t in d.items())))
def epylink(self, docs, striprefix=None):
"""Link function, method and type names in doc string.
"""
def _L(m): # re.sub callback
t = m.group(0)
n = t.strip()
k = self.links.get(n, '')
if k:
if striprefix:
k = striprefix(k)
t = t.replace(n, 'L{%s}' % (k,))
return t
if self.links:
return libvlc_re.sub(_L, docs)
else:
return docs
def generate_enums(self):
raise TypeError('must be overloaded')
def insert_code(self, source, genums=False):
"""Include code from source file.
"""
f = opener(source)
for t in f:
if genums and t.startswith(_GENERATED_ENUMS_):
self.generate_enums()
elif t.startswith(_BUILD_DATE_):
v, t = _NA_, self.parser.version
if t:
v, t = t, ' ' + t
self.output('__version__ = "%s"' % (v,))
self.output('%s"%s%s"' % (_BUILD_DATE_, time.ctime(), t))
else:
self.output(t, nt=0)
f.close()
def outclose(self):
"""Close the output file.
"""
if self.file not in (None, sys.stdout):
self.file.close()
self.file = None
def outopen(self, name):
"""Open an output file.
"""
if self.file:
self.outclose()
raise IOError('file left open: %s' % (self.outpath,))
if name in ('-', 'stdout'):
self.outpath = 'stdout'
self.file = sys.stdout
else:
self.outpath = os.path.join(self.outdir, name)
self.file = opener(self.outpath, 'w')
def output(self, text, nl=0, nt=1):
"""Write to current output file.
"""
if nl: # leading newlines
self.file.write(_NL_ * nl)
self.file.write(text)
if nt: # trailing newlines
self.file.write(_NL_ * nt)
def unwrapped(self):
"""Report the unwrapped and blacklisted functions.
"""
b = [f for f, t in _blacklist.items() if t]
u = [f.name for f in self.parser.funcs if not f.wrapped]
c = self.comment_line
for f, t in ((b, 'blacklisted'),
(u, 'not wrapped as methods')):
if f:
self.output('%s %d function(s) %s:' % (c, len(f), t), nl=1)
self.output(_NL_.join('%s %s' % (c, f) for f in sorted(f))) #PYCHOK false?
class PythonGenerator(_Generator):
"""Generate Python bindings.
"""
type_re = re.compile('libvlc_(.+?)(_t)?$') # Python
# C-type to Python/ctypes type conversion. Note, enum
# type conversions are generated (cf convert_enums).
type2class = {
'libvlc_audio_output_t*': 'ctypes.POINTER(AudioOutput)',
'libvlc_callback_t': 'ctypes.c_void_p',
'libvlc_drawable_t': 'ctypes.c_uint', # FIXME?
'libvlc_event_type_t': 'ctypes.c_uint',
'libvlc_event_manager_t*': 'EventManager',
'libvlc_instance_t*': 'Instance',
'libvlc_log_t*': 'Log',
'libvlc_log_iterator_t*': 'LogIterator',
'libvlc_log_message_t*': 'ctypes.POINTER(LogMessage)',
'libvlc_media_t*': 'Media',
'libvlc_media_discoverer_t*': 'MediaDiscoverer',
'libvlc_media_library_t*': 'MediaLibrary',
'libvlc_media_list_t*': 'MediaList',
'libvlc_media_list_player_t*': 'MediaListPlayer',
'libvlc_media_list_view_t*': 'MediaListView',
'libvlc_media_player_t*': 'MediaPlayer',
'libvlc_media_stats_t*': 'ctypes.POINTER(MediaStats)',
'libvlc_media_track_info_t**': 'ctypes.POINTER(ctypes.c_void_p)',
'libvlc_rectangle_t*': 'ctypes.POINTER(Rectangle)',
'libvlc_time_t': 'ctypes.c_longlong',
'libvlc_track_description_t*': 'ctypes.POINTER(TrackDescription)',
'libvlc_module_description_t*': 'ctypes.POINTER(ModuleDescription)',
'...': 'FIXME_va_list',
'va_list': 'FIXME_va_list',
'char*': 'ctypes.c_char_p',
'char**': 'ListPOINTER(ctypes.c_char_p)',
'float': 'ctypes.c_float',
'int': 'ctypes.c_int',
'int*': 'ctypes.POINTER(ctypes.c_int)', # _video_get_cursor
'int64_t': 'ctypes.c_int64',
'short': 'ctypes.c_short',
'uint32_t': 'ctypes.c_uint32',
'unsigned': 'ctypes.c_uint',
'unsigned*': 'ctypes.POINTER(ctypes.c_uint)', # _video_get_size
'void': 'None',
'void*': 'ctypes.c_void_p',
'void**': 'ListPOINTER(ctypes.c_void_p)',
'WINDOWHANDLE': 'ctypes.c_ulong',
}
# Python classes, i.e. classes for which we want to
# generate class wrappers around libvlc functions
defined_classes = (
'EventManager',
'Instance',
'Log',
'LogIterator',
'Media',
'MediaDiscoverer',
'MediaLibrary',
'MediaList',
'MediaListPlayer',
'MediaListView',
'MediaPlayer',
)
def __init__(self, parser=None):
"""New instance.
@param parser: a L{Parser} instance.
"""
_Generator.__init__(self, parser)
# one special enum type class
self.type2class['libvlc_event_e'] = 'EventType'
# doc links to functions, methods and types
self.links = {'libvlc_event_e': 'EventType'}
# link enum value names to enum type/class
## for t in self.parser.enums:
## for v in t.vals:
## self.links[v.enum] = t.name
# prefixes to strip from method names
# when wrapping them into class methods
self.prefixes = {}
for t, c in self.type2class.items():
t = t.rstrip('*')
if c in self.defined_classes:
self.links[t] = c
self.prefixes[c] = t[:-1]
elif c.startswith('ctypes.POINTER('):
c = c.replace('ctypes.POINTER(', '') \
.rstrip(')')
if c[:1].isupper():
self.links[t] = c
# xform docs to epydoc lines
for f in self.parser.funcs:
f.xform()
self.links[f.name] = f.name
self.check_types()
def generate_ctypes(self):
"""Generate a ctypes decorator for all functions.
"""
self.output("""
# LibVLC __version__ functions #
""")
for f in self.parser.funcs:
name = f.name #PYCHOK flake
# arg names, excluding output args
args = ', '.join(f.args()) #PYCHOK flake
# tuples of arg flags
flags = ', '.join(str(p.flags(f.out)) for p in f.pars) #PYCHOK false?
if flags:
flags += ','
# arg classes
types = [self.class4(p.type) for p in f.pars]
# result type
rtype = self.class4(f.type)
if name in free_string_funcs:
# some functions that return strings need special treatment
if rtype != 'ctypes.c_char_p':
raise TypeError('Function %s expected to return char* not %s' % (name, f.type))
errcheck = 'string_result'
types = ['ctypes.c_void_p'] + types
elif rtype in self.defined_classes:
# if the result is a pointer to one of the defined
# classes then we tell ctypes that the return type is
# ctypes.c_void_p so that 64-bit pointers are handled
# correctly, and then create a Python object of the
# result
errcheck = 'class_result(%s)' % rtype
types = [ 'ctypes.c_void_p'] + types
else:
errcheck = 'None'
types.insert(0, rtype)
types = ', '.join(types)
# xformed doc string with first @param
docs = self.epylink(f.epydocs(0, 4)) #PYCHOK flake
self.output("""def %(name)s(%(args)s):
'''%(docs)s
'''
f = _Cfunctions.get('%(name)s', None) or \\
_Cfunction('%(name)s', (%(flags)s), %(errcheck)s,
%(types)s)
return f(%(args)s)
""" % locals())
def generate_enums(self):
"""Generate classes for all enum types.
"""
self.output("""
class _Enum(ctypes.c_uint):
'''(INTERNAL) Base class
'''
_enum_names_ = {}
def __str__(self):
n = self._enum_names_.get(self.value, '') or ('FIXME_(%r)' % (self.value,))
return '.'.join((self.__class__.__name__, n))
def __repr__(self):
return '.'.join((self.__class__.__module__, self.__str__()))
def __eq__(self, other):
return ( (isinstance(other, _Enum) and self.value == other.value)
or (isinstance(other, _Ints) and self.value == other) )
def __ne__(self, other):
return not self.__eq__(other)
""")
for e in self.parser.enums:
cls = self.class4(e.name)
self.output("""class %s(_Enum):
'''%s
'''
_enum_names_ = {""" % (cls, e.epydocs() or _NA_))
for v in e.vals:
self.output(" %s: '%s'," % (v.value, v.name))
self.output(' }')
# align on '=' signs
w = -max(len(v.name) for v in e.vals)
t = ['%s.%*s = %s(%s)' % (cls, w,v.name, cls, v.value) for v in e.vals]
self.output(_NL_.join(sorted(t)), nt=2)
def generate_wrappers(self):
"""Generate class wrappers for all appropriate functions.
"""
def striprefix(name):
return name.replace(x, '').replace('libvlc_', '')
codes, methods, docstrs = self.parse_override('override.py')
# sort functions on the type/class
# of their first parameter
t = []
for f in self.parser.funcs:
if f.pars:
p = f.pars[0]
c = self.class4(p.type)
if c in self.defined_classes:
t.append((c, f))
cls = x = '' # wrap functions in class methods
for c, f in sorted(t, key=operator.itemgetter(0)):
if cls != c:
cls = c
self.output("""class %s(_Ctype):
'''%s
'''""" % (cls, docstrs.get(cls, '') or _NA_))
c = codes.get(cls, '')
if not 'def __new__' in c:
self.output("""
def __new__(cls, ptr=_internal_guard):
'''(INTERNAL) ctypes wrapper constructor.
'''
return _Constructor(cls, ptr)""")
if c:
self.output(c)
x = self.prefixes.get(cls, 'libvlc_')
f.wrapped += 1
name = f.name
# method name is function name less prefix
meth = striprefix(name)
if meth in methods.get(cls, []):
continue # overridden
# arg names, excluding output args
# and rename first arg to 'self'
args = ', '.join(['self'] + f.args(1)) #PYCHOK flake
# xformed doc string without first @param
docs = self.epylink(f.epydocs(1, 8), striprefix) #PYCHOK flake
self.output(""" def %(meth)s(%(args)s):
'''%(docs)s
'''
return %(name)s(%(args)s)
""" % locals())
# check for some standard methods
if meth == 'count':
# has a count method, generate __len__
self.output(""" def __len__(self):
return %s(self)
""" % (name,))
elif meth.endswith('item_at_index'):
# indexable (and thus iterable)
self.output(""" def __getitem__(self, i):
return %s(self, i)
def __iter__(self):
for i in range(len(self)):
yield self[i]
""" % (name,))
def parse_override(self, override):
"""Parse the override definitions file.
It is possible to override methods definitions in classes.
@param override: the C{override.py} file name.
@return: a tuple (codes, methods, docstrs) of 3 dicts
containing the source code, the method names and the
class-level doc strings for each of the classes defined
in the B{override} file.
"""
codes = {}
k, v = None, []
f = opener(override)
for t in f:
m = class_re.match(t)
if m: # new class
if k is not None:
codes[k] = ''.join(v)
k, v = m.group(1), []
else:
v.append(t)
if k is not None:
codes[k] = ''.join(v)
f.close()
docstrs, methods = {}, {}
for k, v in codes.items():
q = v.lstrip()[:3]
if q in ('"""', "'''"):
# use class comment as doc string
_, docstrs[k], v = v.split(q, 2)
codes[k] = v
# FIXME: not robust wrt. internal methods
methods[k] = def_re.findall(v)
return codes, methods, docstrs
def save(self, path=None):
"""Write Python bindings to a file or C{stdout}.
"""
self.outopen(path or '-')
self.insert_code('header.py', genums=True)