File: setup.py

package info (click to toggle)
python-reportlab 3.6.1-1
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 12,124 kB
  • sloc: python: 95,377; ansic: 19,096; xml: 1,494; makefile: 337; java: 193; sh: 100
file content (777 lines) | stat: -rw-r--r-- 28,681 bytes parent folder | download
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
#Copyright ReportLab Europe Ltd. 2000-2017
#see license.txt for license details
__version__='3.6.0'
import os, sys, glob, shutil, re, sysconfig, traceback, io, subprocess
platform = sys.platform
pjoin = os.path.join
abspath = os.path.abspath
isfile = os.path.isfile
isdir = os.path.isdir
dirname = os.path.dirname
basename = os.path.basename
splitext = os.path.splitext
archName = 'amd64' if sys.maxsize > 2**32 else 'x86'

try:
    from urllib.parse import quote as urlquote
except ImportError:
    from urllib import quote as urlquote

INFOLINES=[]
def infoline(t,
        pfx='#####',
        add=True,
        ):
    bn = splitext(basename(sys.argv[0]))[0]
    ver = '.'.join(map(str,sys.version_info[:3]))
    platform = sysconfig.get_platform()
    s = '%s %s-python-%s-%s: %s' % (pfx, bn, ver, platform, t)
    print(s)
    if add: INFOLINES.append(s)

def showTraceback(s):
    buf = io.StringIO()
    print(s,file=buf)
    if verbose:
        traceback.print_exc(file=buf)
    for l in buf.getvalue().split('\n'):
        infoline(l,pfx='!!!!!',add=False)

def os_system(cmd,*args,**kwds):
    r = os.system(cmd,*args,**kwds)
    if verbose:
        infoline('%r --> %s' % (cmd,r), pfx='!!!!!' if r else '#####', add=False)
    return r

def specialOption(n):
    v = False
    while n in sys.argv:
        v = True
        sys.argv.remove(n)
    return v

#defaults for these options may be configured in local-setup.cfg
#[OPTIONS]
#no-download-t1-files=yes
#ignore-system-libart=yes
# if used on command line the config values are not used
dlt1 = not specialOption('--no-download-t1-files')
usla = specialOption('--use-system-libart')
mdbg = specialOption('--memory-debug')
verbose = specialOption('--verbose')
nulldivert = '' if verbose else (" >%s 2>&1" % ('NUL' if sys.platform=='win32' else '/dev/null'))

try:
    import configparser
except ImportError:
    import ConfigParser as configparser
if __name__=='__main__':
    pkgDir=dirname(sys.argv[0])
else:
    pkgDir=dirname(__file__)
if not pkgDir:
    pkgDir=os.getcwd()
elif not os.path.isabs(pkgDir):
    pkgDir=abspath(pkgDir)
try:
    os.chdir(pkgDir)
except:
    showTraceback('warning could not change directory to %r' % pkgDir)
daily=int(os.environ.get('RL_EXE_DAILY','0'))

try:
    from setuptools import setup, Extension
except ImportError:
    from distutils.core import setup, Extension
try:
    import sysconfig
except ImportError:
    from distutils import sysconfig

def _packages_path(d):
    P = [_ for _ in sys.path if basename(_)==d]
    if P: return P[0]

package_path = _packages_path('dist-packages') or _packages_path('site-packages')
package_path = pjoin(package_path, 'reportlab')

def die(msg):
    raise ValueError(msg)

def make_libart_config(src):
    from struct import calcsize as sizeof
    L=["""/* Automatically generated by setup.py */
#ifndef _ART_CONFIG_H
#\tdefine _ART_CONFIG_H
#\tdefine ART_SIZEOF_CHAR %d
#\tdefine ART_SIZEOF_SHORT %d
#\tdefine ART_SIZEOF_INT %d
#\tdefine ART_SIZEOF_LONG %d""" % (sizeof('c'), sizeof('h'), sizeof('i'), sizeof('l'))
        ]
    aL = L.append

    if sizeof('c')==1:
        aL("typedef unsigned char art_u8;")
    else:
        die("sizeof(char) != 1")
    if sizeof('h')==2:
        aL("typedef unsigned short art_u16;")
    else:
        die("sizeof(short) != 2")

    if sizeof('i')==4:
        aL("typedef unsigned int art_u32;")
    elif sizeof('l')==4:
        aL("typedef unsigned long art_u32;")
    else:
        die("sizeof(int)!=4 and sizeof(long)!=4")
    aL('#endif\n')
    with open(pjoin(src,'art_config.h'),'w') as f:
        f.write('\n'.join(L))

def get_version():
    if daily: return 'daily'
    #determine Version
    HERE = pkgDir
    if os.getcwd()!=HERE:
        if __name__=='__main__':
            HERE=os.path.dirname(sys.argv[0])
        else:
            HERE=os.path.dirname(__file__)

    #first try source
    FN = pjoin(HERE,'src','reportlab','__init__')
    try:
        for l in open(pjoin(FN+'.py'),'r').readlines():
            if l.startswith('Version'):
                D = {}
                exec(l.strip(),D)
                return D['Version']
    except:
        pass

    #don't have source, try import
    import imp
    for desc in ('.pyc', 'rb', 2), ('.pyo', 'rb', 2):
        try:
            fn = FN+desc[0]
            f = open(fn,desc[1])
            m = imp.load_module('reportlab',f,fn,desc)
            return m.Version
        except:
            pass
    raise ValueError('Cannot determine ReportLab Version')

class config:
    def __init__(self):
        try:
            self.parser = configparser.RawConfigParser()
            self.parser.read([pjoin(pkgDir,'setup.cfg'),pjoin(pkgDir,'local-setup.cfg')])
        except:
            self.parser = None

    def __call__(self,sect,name,default=None):
        try:
            return self.parser.get(sect,name)
        except:
            return default
config = config()

if dlt1:
    #not set on command line so try for config value
    dlt1 = not config('OPTIONS','no-download-t1-files','0').lower() in ('1','true','yes')
if not usla:
    #not set on command line so try for config value
    usla = config('OPTIONS','use-system-libart','0').lower() in ('1','true','yes')
if not mdbg:
    mdbg = config('OPTIONS','memory-debug','0').lower() in ('1','true','yes')

#this code from /FBot's PIL setup.py
def aDir(P, d, x=None):
    if d and isdir(d) and d not in P:
        if x is None:
            P.append(d)
        else:
            P.insert(x, d)

class inc_lib_dirs:
    L = None
    I = None
    def __call__(self):
        if self.L is None:
            L = []
            I = []
            if platform == "cygwin":
                aDir(L, os.path.join("/usr/lib", "python%s" % sys.version[:3], "config"))
            elif platform == "darwin":
                # attempt to make sure we pick freetype2 over other versions
                aDir(I, "/sw/include/freetype2")
                aDir(I, "/sw/lib/freetype2/include")
                # fink installation directories
                aDir(L, "/sw/lib")
                aDir(I, "/sw/include")
                # darwin ports installation directories
                aDir(L, "/opt/local/lib")
                aDir(I, "/opt/local/include")
            aDir(I, "/usr/local/include")
            aDir(L, "/usr/local/lib")
            aDir(I, "/usr/include")
            aDir(L, "/usr/lib")
            aDir(I, "/usr/include/freetype2")
            if archName=='amd64':
                aDir(L, "/usr/lib/lib64")
                aDir(L, "/usr/lib/x86_64-linux-gnu")
            else:
                aDir(L, "/usr/lib/lib32")
            prefix = sysconfig.get_config_var("prefix")
            if prefix:
                aDir(L, pjoin(prefix, "lib"))
                aDir(I, pjoin(prefix, "include"))
            self.L=L
            self.I=I
        return self.I,self.L
inc_lib_dirs=inc_lib_dirs()

def getVersionFromCCode(fn):
    import re
    tag = re.search(r'^#define\s+VERSION\s+"([^"]*)"',open(fn,'r').read(),re.M)
    return tag and tag.group(1) or ''

class _rl_dir_info:
    def __init__(self,cn):
        self.cn=cn
    def __call__(self,dir):
        import stat
        fn = pjoin(dir,self.cn)
        try:
            return getVersionFromCCode(fn),os.stat(fn)[stat.ST_MTIME]
        except:
            return None

def _find_rl_ccode(dn='rl_accel',cn='_rl_accel.c'):
    '''locate where the accelerator code lives'''
    _ = []
    for x in [
            pjoin('src','rl_addons',dn),
            pjoin('rl_addons',dn),
            pjoin('..','rl_addons',dn),
            pjoin('..','..','rl_addons',dn),
            dn,
            pjoin('..',dn),
            pjoin('..','..',dn),
            ] \
            + glob.glob(pjoin(dn+'-*',dn))\
            + glob.glob(pjoin('..',dn+'-*',dn))\
            + glob.glob(pjoin('..','..',dn+'-*',dn))\
            :
        fn = pjoin(pkgDir,x,cn)
        if isfile(fn):
            _.append(x)
    if _:
        _ = list(filter(_rl_dir_info(cn),_))
        if len(_):
            _.sort(key=_rl_dir_info)
            _ = abspath(_[0])
            return _[_.index(os.sep.join(('','src','rl_addons')))+1:]

    return None


def BIGENDIAN(macname,value=None):
    'define a macro if bigendian'
    return sys.byteorder=='big' and [(macname,value)] or []

def pfxJoin(pfx,*N):
    R=[]
    for n in N:
        R.append(os.path.join(pfx,n))
    return R

reportlab_files= [
        'fonts/00readme.txt',
        'fonts/bitstream-vera-license.txt',
        'fonts/DarkGarden-changelog.txt',
        'fonts/DarkGarden-copying-gpl.txt',
        'fonts/DarkGarden-copying.txt',
        'fonts/DarkGarden-readme.txt',
        'fonts/DarkGarden.sfd',
        'fonts/DarkGardenMK.afm',
        'fonts/DarkGardenMK.pfb',
        'fonts/Vera.ttf',
        'fonts/VeraBd.ttf',
        'fonts/VeraBI.ttf',
        'fonts/VeraIt.ttf',
        'fonts/_abi____.pfb',
        'fonts/_ab_____.pfb',
        'fonts/_ai_____.pfb',
        'fonts/_a______.pfb',
        'fonts/cobo____.pfb',
        'fonts/cob_____.pfb',
        'fonts/com_____.pfb',
        'fonts/coo_____.pfb',
        'fonts/_ebi____.pfb',
        'fonts/_eb_____.pfb',
        'fonts/_ei_____.pfb',
        'fonts/_er_____.pfb',
        'fonts/sy______.pfb',
        'fonts/zd______.pfb',
        'fonts/zx______.pfb',
        'fonts/zy______.pfb',
        'fonts/callig15.pfb',
        'fonts/callig15.afm',
        'reportlab/graphics/barcode/README'
        'reportlab/graphics/barcode/TODO'
        'license.txt',
        ]

def url2data(url,returnRaw=False):
    import io
    import urllib.request as ureq
    remotehandle = ureq.urlopen(url)
    try:
        raw = remotehandle.read()
        return raw if returnRaw else io.BytesIO(raw)
    finally:
        remotehandle.close()

def ensureWinStuff(
                    url='https://www.reportlab.com/ftp/winstuff.zip',
                    target=pjoin(pkgDir,'build','winstuff'),
                ):
    done = pjoin(target,'.done')
    if not isfile(done):
        if not isdir(target):
            os.makedirs(target)
            import zipfile, time
            zipfile.ZipFile(url2data(url), 'r').extractall(path=target)
            with open(done,'w') as _:
                _.write(time.strftime('%Y%m%dU%H%M%S\n',time.gmtime()))
    return target

def get_fonts(PACKAGE_DIR, reportlab_files):
    import zipfile
    rl_dir = PACKAGE_DIR['reportlab']
    if not [x for x in reportlab_files if not isfile(pjoin(rl_dir,x))]:
        xitmsg = "Standard T1 font curves already downloaded"
    elif not dlt1:
        xitmsg = "not downloading T1 font curve files"
    else:
        try:
            infoline("Downloading standard T1 font curves")
            zipdata = url2data("http://www.reportlab.com/ftp/pfbfer-20180109.zip")
            archive = zipfile.ZipFile(zipdata)
            dst = pjoin(rl_dir, 'fonts')

            for name in archive.namelist():
                if not name.endswith('/'):
                    with open(pjoin(dst, name), 'wb') as outfile:
                        outfile.write(archive.read(name))
            xitmsg = "Finished download of standard T1 font curves"
        except:
            xitmsg = "Failed to download standard T1 font curves"
    infoline(xitmsg)

def get_glyphlist_module(PACKAGE_DIR):
    try:
        lfn = pjoin("pdfbase","_glyphlist.py")
        fn = pjoin(PACKAGE_DIR['reportlab'],lfn)
        if isfile(fn):
            xitmsg = "The _glyphlist module already exists"
        else:
            text = url2data("https://raw.githubusercontent.com/adobe-type-tools/agl-aglfn/master/glyphlist.txt",True)
            comments = ['#see https://github.com/adobe-type-tools/agl-aglfn\n'].append
            G2U = [].append
            G2Us = [].append
            if not isinstance(text,str):
                text = text.decode('latin1')
            for line in text.split('\n'):
                line = line.strip()
                if not line: continue
                if line.startswith('#'):
                    comments(line+'\n')
                else:
                    gu = line.split(';')
                    if len(gu)==2:
                        v = gu[1].split()
                        if len(v)==1:
                            G2U('\t%r: 0x%s,\n' % (gu[0],gu[1]))
                        else:
                            G2Us('\t%r: (%s),\n' % (gu[0],','.join('0x%s'%u for u in v)))
                    else:
                        infoline('bad glyphlist line %r' % line, '!!!!!')
            with open(fn,'w') as f:
                f.write(''.join(comments.__self__))
                f.write('_glyphname2unicode = {\n')
                f.write(''.join(G2U.__self__))
                f.write('\t}\n')
                f.write('_glyphname2unicodes = {\n')
                f.write(''.join(G2Us.__self__))
                f.write('\t}\n')
            xitmsg = "Finished creation of _glyphlist.py"
    except:
        xitmsg = "Failed to download glyphlist.txt"
    infoline(xitmsg)

def canImport(pkg):
    ns = [pkg.find(_) for _ in '<>=' if _ in pkg]
    if ns: pkg =pkg[:min(ns)]
    ns = {}
    try:
        exec('import %s as M' % pkg,{},ns)
    except:
        showTraceback("can't import %s" % pkg)
    return 'M' in ns

def pipInstall(pkg, ixu=None):
    if canImport(pkg): return True
    i = ['-i%s' % ixu] if ixu else []
    try:
        p = subprocess.Popen(
                [sys.executable, '-mpip', 'install']+i+[pkg],
                stdout=subprocess.PIPE,
                stderr=subprocess.STDOUT,
                )
        out = p.communicate(timeout=30)[0]
        if ixu and not nulldivert:
            for t in out.decode('utf8').replace('\r\n','\n').replace(ixu.u,'***').split('\n'):
                if t.strip():
                    infoline(t)
    except:
        showTraceback("pipInstall %s failed" % pkg)
    return canImport(pkg)

def pipUninstall(pkg):
    os_system('%s -mpip -q uninstall -y %s%s' % (sys.executable, pkg, nulldivert))

def pipInstallGroups(pkgs, ixu=None):
    '''install groups of packages; if any of a group fail we backout the group'''
    for g in pkgs:
        I = []  #thse are the installed in this group
        for pkg in g.split():
            if pipInstall(pkg,ixu):
                I.append(pkg)
            else:
                for pkg in I:
                    pipUninstall(pkg)
                break

def vopt(opt):
    opt = '--%s=' % opt
    v = [_ for _ in sys.argv if _.startswith(opt)]
    for _ in v: sys.argv.remove(_)
    n = len(opt)
    return list(filter(None,[_[n:] for _ in v]))

class QUPStr(str):
    def __new__(cls,s,u,p):
        self = str.__new__(cls,s)
        self.u = u
        self.p = p
        return self

def qup(url, pat=re.compile(r'(?P<scheme>https?://)(?P<up>[^@]*)(?P<rest>@.*)$')):
    '''urlquote the user name and password'''
    m = pat.match(url)
    if m:
        u, p = m.group('up').split(':',1)
        url = "%s%s:%s%s" % (m.group('scheme'),urlquote(u),urlquote(p),m.group('rest'))
    else:
        u = p = ''
    return QUPStr(url,u,p)

def performPipInstalls():
    pip_installs = vopt('pip-install')
    pipInstallGroups(pip_installs)
    rl_pip_installs = vopt('rl-pip-install')
    if rl_pip_installs:
        rl_ixu = vopt('rl-index-url')
        if len(rl_ixu)==1:
            pipInstallGroups(rl_pip_installs,qup(rl_ixu[0]))
        else:
            raise ValueError('rl-pip-install requires exactly 1 --rl-index-url not %d' % len(rl_ixu))

def main():
    performPipInstalls()
    #test to see if we've a special command
    if 'test' in sys.argv \
        or 'tests' in sys.argv \
        or 'tests-postinstall' in sys.argv \
        or 'tests-preinstall' in sys.argv:
        verboseTests = specialOption('--verbose-tests')
        if len(sys.argv)!=2:
            raise ValueError('tests commands may only be used alone sys.argv[1:]=%s' % repr(sys.argv[1:]))
        cmd = sys.argv[-1]
        PYTHONPATH = [pkgDir] if cmd!='test' else []
        if cmd=='tests-preinstall':
            PYTHONPATH.insert(0,pjoin(pkgDir,'src'))
        if PYTHONPATH: os.environ['PYTHONPATH']=os.pathsep.join(PYTHONPATH)
        os.chdir(pjoin(pkgDir,'tests'))
        cli = [sys.executable, 'runAll.py']
        if cmd=='tests-postinstall':
            cli.append('--post-install')
        if verboseTests:
            cli.append('--verbosity=2')
        cli = ' '.join(cli)
        r = os_system(cli)
        sys.exit(('!!!!! runAll.py --> %s should exit with error !!!!!' % r) if r else r)
    elif 'null-cmd' in sys.argv or 'null-command' in sys.argv:
        sys.exit(0)

    debug_compile_args = []
    debug_link_args = []
    debug_macros = []
    debug = int(os.environ.get('RL_DEBUG','0'))
    if debug:
        if sys.platform == 'win32':
            debug_compile_args=['/Zi']
            debug_link_args=['/DEBUG']
        if debug>1:
            debug_macros.extend([('RL_DEBUG',debug), ('ROBIN_DEBUG',None)])
    if mdbg:
        debug_macros.extend([('MEMORY_DEBUG',None)])

    SPECIAL_PACKAGE_DATA = {}
    RL_ACCEL = _find_rl_ccode('rl_accel','_rl_accel.c')
    LIBRARIES=[]
    EXT_MODULES = []

    if not RL_ACCEL:
        infoline( '===================================================')
        infoline( 'not attempting build of the _rl_accel extension')
        infoline( '===================================================')
    else:
        infoline( '================================================')
        infoline( 'Attempting build of _rl_accel')
        infoline( 'extensions from %r'%RL_ACCEL)
        infoline( '================================================')
        EXT_MODULES += [
                    Extension( 'reportlab.lib._rl_accel',
                                [pjoin(RL_ACCEL,'_rl_accel.c')],
                                include_dirs=[],
                            define_macros=[]+debug_macros,
                            library_dirs=[],
                            libraries=[], # libraries to link against
                            extra_compile_args=debug_compile_args,
                            extra_link_args=debug_link_args,
                            ),
                        ]
    RENDERPM = _find_rl_ccode('renderPM','_renderPM.c')
    if not RENDERPM:
        infoline( '===================================================')
        infoline( 'not attempting build of _renderPM')
        infoline( '===================================================')
    else:
        infoline( '===================================================')
        infoline( 'Attempting build of _renderPM')
        infoline( 'extensions from %r'%RENDERPM)
        infoline( '===================================================')
        GT1_DIR=pjoin(RENDERPM,'gt1')

        if not usla:
            LIBART_INC=None #don't use system libart
        else:
            #check for an installed libart
            LIBART_INC = list(sorted(glob.glob('/usr/include/libart-*/libart_lgpl/libart-features.h')))
        if LIBART_INC:
            def installed_libart_version(fn):
                for l in open(fn, 'r').readlines():
                    if l.startswith('#define LIBART_VERSION'):
                        v = l[:-1].split(' ')[-1]
                        return v
                return '"0.0.0"'
            LIBART_INC = LIBART_INC[-1]
            LIBART_VERSION = installed_libart_version(LIBART_INC)
            LIBART_INC = os.path.dirname(LIBART_INC)
            LIBART_SOURCES=[]
            LIBART_LIB = ['art_lgpl_2']
            infoline('will use installed libart %s' % LIBART_VERSION.replace('"',''))
        else:
            LIBART_DIR = LIBART_INC = pjoin(RENDERPM,'libart_lgpl')
            LIBART_LIB = []
            make_libart_config(LIBART_DIR)
            LIBART_SOURCES=[
                    pjoin(LIBART_DIR,'art_vpath_bpath.c'),
                    pjoin(LIBART_DIR,'art_rgb_pixbuf_affine.c'),
                    pjoin(LIBART_DIR,'art_rgb_svp.c'),
                    pjoin(LIBART_DIR,'art_svp.c'),
                    pjoin(LIBART_DIR,'art_svp_vpath.c'),
                    pjoin(LIBART_DIR,'art_svp_vpath_stroke.c'),
                    pjoin(LIBART_DIR,'art_svp_ops.c'),
                    pjoin(LIBART_DIR,'art_svp_wind.c'),
                    pjoin(LIBART_DIR,'art_vpath.c'),
                    pjoin(LIBART_DIR,'art_vpath_dash.c'),
                    pjoin(LIBART_DIR,'art_affine.c'),
                    pjoin(LIBART_DIR,'art_rect.c'),
                    pjoin(LIBART_DIR,'art_rgb_affine.c'),
                    pjoin(LIBART_DIR,'art_rgb_affine_private.c'),
                    pjoin(LIBART_DIR,'art_rgb.c'),
                    pjoin(LIBART_DIR,'art_rgb_rgba_affine.c'),
                    pjoin(LIBART_DIR,'art_svp_intersect.c'),
                    pjoin(LIBART_DIR,'art_svp_render_aa.c'),
                    pjoin(LIBART_DIR,'art_misc.c'),
                    ]
            def libart_version():
                pat0 = re.compile(r'^\s*LIBART_(MAJOR|MINOR|MICRO)_VERSION\s*=\s*(\d+)')
                pat1 = re.compile(r'^\s*m4_define\s*\(\s*\[\s*libart_(major|minor|micro)_version\s*\]\s*,\s*\[(\d+)\]\s*\)')
                def check_match(l):
                    for p in (pat0, pat1):
                        m = p.match(l)
                        if m: return m
                K = ('major','minor','micro')
                D = {}
                for l in open(pjoin(LIBART_DIR,'configure.in'),'r').readlines():
                    m = check_match(l)
                    if m:
                        D[m.group(1).lower()] = m.group(2)
                        if len(D)==3: break
                return '.'.join(map(lambda k,D=D: D.get(k,'?'),K))
            LIBART_VERSION = libart_version()
            infoline('will use package libart %s' % LIBART_VERSION.replace('"',''))

        SOURCES=[pjoin(RENDERPM,'_renderPM.c'),
                    pjoin(GT1_DIR,'gt1-parset1.c'),
                    pjoin(GT1_DIR,'gt1-dict.c'),
                    pjoin(GT1_DIR,'gt1-namecontext.c'),
                    pjoin(GT1_DIR,'gt1-region.c'),
                    ]+LIBART_SOURCES

        if platform=='win32':
            target = ensureWinStuff()
            FT_LIB = pjoin(target,'libs',archName,'freetype.lib')
            if not isfile(FT_LIB):
                infoline('freetype lib %r not found' % FT_LIB, pfx='!!!!')
                FT_LIB=[]
            if FT_LIB:
                FT_INC_DIR = pjoin(target,'include')
                if not isfile(pjoin(FT_INC_DIR,'ft2build.h')):
                    FT_INC_DIR = pjoin(FT_INC_DIR,'freetype2')
                    if not isfile(pjoin(FT_INC_DIR,'ft2build.h')):
                        infoline('freetype2 include folder %r not found' % FT_INC_DIR, pfx='!!!!!')
                        FT_LIB=FT_LIB_DIR=FT_INC_DIR=FT_MACROS=[]
                FT_MACROS = [('RENDERPM_FT',None)]
                FT_LIB_DIR = [dirname(FT_LIB)]
                FT_INC_DIR = [FT_INC_DIR]
                FT_LIB_PATH = FT_LIB
                FT_LIB = [splitext(basename(FT_LIB))[0]]
                if isdir(FT_INC_DIR[0]):
                    infoline('installing with freetype %r' % FT_LIB_PATH)
            else:
                FT_LIB=FT_LIB_DIR=FT_INC_DIR=FT_MACROS=[]
        else:
            if os.path.isdir('/usr/include/freetype2'):
                FT_LIB_DIR = []
                FT_INC_DIR = ['/usr/include/freetype2']
            else:
                FT_LIB_DIR=config('FREETYPE_PATHS','lib')
                FT_LIB_DIR=[FT_LIB_DIR] if FT_LIB_DIR else []
                FT_INC_DIR=config('FREETYPE_PATHS','inc')
                FT_INC_DIR=[FT_INC_DIR] if FT_INC_DIR else []
            I,L=inc_lib_dirs()
            ftv = None
            for d in I:
                if isfile(pjoin(d, "ft2build.h")):
                    ftv = 21
                    FT_INC_DIR=[d,pjoin(d, "freetype2")]
                    break
                d = pjoin(d, "freetype2")
                if isfile(pjoin(d, "ft2build.h")):
                    ftv = 21
                    FT_INC_DIR=[d]
                    break
                if isdir(pjoin(d, "freetype")):
                    ftv = 20
                    FT_INC_DIR=[d]
                    break
            if ftv:
                FT_LIB=['freetype']
                FT_LIB_DIR=L
                FT_MACROS = [('RENDERPM_FT',None)]
                infoline('# installing with freetype version %d' % ftv)
            else:
                FT_LIB=FT_LIB_DIR=FT_INC_DIR=FT_MACROS=[]
        if not FT_LIB:
            infoline('# installing without freetype no ttf, sorry!')
            infoline('# You need to install a static library version of the freetype2 software')
            infoline('# If you need truetype support in renderPM')
            infoline('# You may need to edit setup.cfg (win32)')
            infoline('# or edit this file to access the library if it is installed')

        EXT_MODULES +=  [Extension( 'reportlab.graphics._renderPM',
                                        SOURCES,
                                        include_dirs=[RENDERPM,LIBART_INC,GT1_DIR]+FT_INC_DIR,
                                        define_macros=FT_MACROS+[('LIBART_COMPILATION',None)]+debug_macros+[('LIBART_VERSION',LIBART_VERSION)],
                                        library_dirs=[]+FT_LIB_DIR,

                                        # libraries to link against
                                        libraries=FT_LIB+LIBART_LIB,
                                        extra_compile_args=debug_compile_args,
                                        extra_link_args=debug_link_args,
                                        ),
                            ]
        infoline('################################################')

    #copy some special case files into place so package_data will treat them properly
    PACKAGE_DIR = {'':'src','reportlab': pjoin('src','reportlab')}
    for fn,dst in SPECIAL_PACKAGE_DATA.items():
        shutil.copyfile(fn,pjoin(PACKAGE_DIR['reportlab'],dst))
        reportlab_files.append(dst)
    get_fonts(PACKAGE_DIR, reportlab_files)
    get_glyphlist_module(PACKAGE_DIR)
    try:
        setup(
            name="reportlab",
            version=get_version(),
            license="BSD license (see license.txt for details), Copyright (c) 2000-2018, ReportLab Inc.",
            description="The Reportlab Toolkit",
            long_description="""The ReportLab Toolkit. An Open Source Python library for generating PDFs and graphics.""",

            author="Andy Robinson, Robin Becker, the ReportLab team and the community",
            author_email="reportlab-users@lists2.reportlab.com",
            url="http://www.reportlab.com/",
            packages=[
                    'reportlab',
                    'reportlab.graphics.charts',
                    'reportlab.graphics.samples',
                    'reportlab.graphics.widgets',
                    'reportlab.graphics.barcode',
                    'reportlab.graphics',
                    'reportlab.lib',
                    'reportlab.pdfbase',
                    'reportlab.pdfgen',
                    'reportlab.platypus',
                    ],
            package_dir = PACKAGE_DIR,
            package_data = {'reportlab': reportlab_files},
            ext_modules =   EXT_MODULES,
            classifiers = [
                'Development Status :: 5 - Production/Stable',
                'Intended Audience :: Developers',
                'License :: OSI Approved :: BSD License',
                'Topic :: Printing',
                'Topic :: Text Processing :: Markup',
                'Programming Language :: Python :: 2',
                'Programming Language :: Python :: 2.7',
                'Programming Language :: Python :: 3',
                'Programming Language :: Python :: 3.6',
                'Programming Language :: Python :: 3.7',
                'Programming Language :: Python :: 3.8',
                'Programming Language :: Python :: 3.9',
                ],
            
            #this probably only works for setuptools, but distutils seems to ignore it
            install_requires=['pillow>=4.0.0'],
            python_requires='>=2.7, >=3.6, <4',
            extras_require={
                'RLPYCAIRO': ['rlPyCairo>=0.0.5'],
                },
            )
        print()
        print('########## SUMMARY INFO #########')
        print('\n'.join(INFOLINES))
    finally:
        for dst in SPECIAL_PACKAGE_DATA.values():
            os.remove(pjoin(PACKAGE_DIR['reportlab'],dst))
            reportlab_files.remove(dst)

if __name__=='__main__':
    main()