forked from matplotlib/matplotlib
-
Notifications
You must be signed in to change notification settings - Fork 1
/
setupext.py
1246 lines (1026 loc) · 40.2 KB
/
setupext.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
import builtins
import configparser
from distutils import sysconfig, version
from distutils.core import Extension
import glob
import hashlib
import importlib
import logging
import os
import pathlib
import platform
import shutil
import subprocess
import sys
import tarfile
import textwrap
import urllib.request
import setuptools
import versioneer
_log = logging.getLogger(__name__)
def _get_xdg_cache_dir():
"""
Return the XDG cache directory.
See https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
"""
cache_dir = os.environ.get('XDG_CACHE_HOME')
if not cache_dir:
cache_dir = os.path.expanduser('~/.cache')
if cache_dir.startswith('~/'): # Expansion failed.
return None
return os.path.join(cache_dir, 'matplotlib')
# SHA256 hashes of the FreeType tarballs
_freetype_hashes = {
'2.6.1': '0a3c7dfbda6da1e8fce29232e8e96d987ababbbf71ebc8c75659e4132c367014',
'2.6.2': '8da42fc4904e600be4b692555ae1dcbf532897da9c5b9fb5ebd3758c77e5c2d4',
'2.6.3': '7942096c40ee6fea882bd4207667ad3f24bff568b96b10fd3885e11a7baad9a3',
'2.6.4': '27f0e38347a1850ad57f84fc4dfed68ba0bc30c96a6fa6138ef84d485dd9a8d7',
'2.6.5': '3bb24add9b9ec53636a63ea8e867ed978c4f8fdd8f1fa5ccfd41171163d4249a',
'2.7': '7b657d5f872b0ab56461f3bd310bd1c5ec64619bd15f0d8e08282d494d9cfea4',
'2.7.1': '162ef25aa64480b1189cdb261228e6c5c44f212aac4b4621e28cf2157efb59f5',
'2.8': '33a28fabac471891d0523033e99c0005b95e5618dc8ffa7fa47f9dadcacb1c9b',
'2.8.1': '876711d064a6a1bd74beb18dd37f219af26100f72daaebd2d86cb493d7cd7ec6',
}
# This is the version of FreeType to use when building a local
# version. It must match the value in
# lib/matplotlib.__init__.py and also needs to be changed below in the
# embedded windows build script (grep for "REMINDER" in this file)
LOCAL_FREETYPE_VERSION = '2.6.1'
LOCAL_FREETYPE_HASH = _freetype_hashes.get(LOCAL_FREETYPE_VERSION, 'unknown')
# matplotlib build options, which can be altered using setup.cfg
options = {
'display_status': True,
'backend': None,
'basedirlist': None
}
setup_cfg = os.environ.get('MPLSETUPCFG', 'setup.cfg')
if os.path.exists(setup_cfg):
config = configparser.ConfigParser()
config.read(setup_cfg)
if config.has_option('status', 'suppress'):
options['display_status'] = not config.getboolean("status", "suppress")
if config.has_option('rc_options', 'backend'):
options['backend'] = config.get("rc_options", "backend")
if config.has_option('directories', 'basedirlist'):
options['basedirlist'] = [
x.strip() for x in
config.get("directories", "basedirlist").split(',')]
if config.has_option('test', 'local_freetype'):
options['local_freetype'] = config.getboolean("test", "local_freetype")
else:
config = None
lft = bool(os.environ.get('MPLLOCALFREETYPE', False))
options['local_freetype'] = lft or options.get('local_freetype', False)
def has_include_file(include_dirs, filename):
"""
Returns `True` if *filename* can be found in one of the
directories in *include_dirs*.
"""
if sys.platform == 'win32':
include_dirs = [*include_dirs, # Don't modify it in-place.
*os.environ.get('INCLUDE', '.').split(os.pathsep)]
return any(pathlib.Path(dir, filename).exists() for dir in include_dirs)
def check_include_file(include_dirs, filename, package):
"""
Raises an exception if the given include file can not be found.
"""
if not has_include_file(include_dirs, filename):
raise CheckFailed(
"The C/C++ header for %s (%s) could not be found. You "
"may need to install the development package." %
(package, filename))
def get_base_dirs():
"""
Returns a list of standard base directories on this platform.
"""
if options['basedirlist']:
return options['basedirlist']
if os.environ.get('MPLBASEDIRLIST'):
return os.environ.get('MPLBASEDIRLIST').split(os.pathsep)
win_bases = ['win32_static']
# on conda windows, we also add the <conda_env_dir>\Library,
# as conda installs libs/includes there
# env var names mess: https://github.com/conda/conda/issues/2312
conda_env_path = os.getenv('CONDA_PREFIX') # conda >= 4.1
if not conda_env_path:
conda_env_path = os.getenv('CONDA_DEFAULT_ENV') # conda < 4.1
if conda_env_path and os.path.isdir(conda_env_path):
win_bases.append(os.path.join(conda_env_path, "Library"))
basedir_map = {
'win32': win_bases,
'darwin': ['/usr/local/', '/usr', '/usr/X11',
'/opt/X11', '/opt/local'],
'sunos5': [os.getenv('MPLIB_BASE') or '/usr/local', ],
'gnu0': ['/usr'],
'aix5': ['/usr/local'],
}
return basedir_map.get(sys.platform, ['/usr/local', '/usr'])
def get_include_dirs():
"""
Returns a list of standard include directories on this platform.
"""
include_dirs = [os.path.join(d, 'include') for d in get_base_dirs()]
if sys.platform != 'win32':
# gcc includes these dirs automatically, so also look for headers in
# these dirs
include_dirs.extend(
os.environ.get('CPATH', '').split(os.pathsep))
include_dirs.extend(
os.environ.get('CPLUS_INCLUDE_PATH', '').split(os.pathsep))
return include_dirs
def is_min_version(found, minversion):
"""
Returns whether *found* is a version at least as high as *minversion*.
"""
return version.LooseVersion(found) >= version.LooseVersion(minversion)
# Define the display functions only if display_status is True.
if options['display_status']:
def print_line(char='='):
print(char * 79)
def print_status(package, status):
initial_indent = "%18s: " % package
indent = ' ' * 24
print(textwrap.fill(str(status), width=79,
initial_indent=initial_indent,
subsequent_indent=indent))
def print_message(message):
indent = ' ' * 24 + "* "
print(textwrap.fill(str(message), width=79,
initial_indent=indent,
subsequent_indent=indent))
def print_raw(section):
print(section)
else:
def print_line(*args, **kwargs):
pass
print_status = print_message = print_raw = print_line
def make_extension(name, files, *args, **kwargs):
"""
Make a new extension. Automatically sets include_dirs and
library_dirs to the base directories appropriate for this
platform.
`name` is the name of the extension.
`files` is a list of source files.
Any additional arguments are passed to the
`distutils.core.Extension` constructor.
"""
ext = DelayedExtension(name, files, *args, **kwargs)
for dir in get_base_dirs():
include_dir = os.path.join(dir, 'include')
if os.path.exists(include_dir):
ext.include_dirs.append(include_dir)
for lib in ('lib', 'lib64'):
lib_dir = os.path.join(dir, lib)
if os.path.exists(lib_dir):
ext.library_dirs.append(lib_dir)
ext.include_dirs.append('.')
return ext
def get_file_hash(filename):
"""
Get the SHA256 hash of a given filename.
"""
BLOCKSIZE = 1 << 16
hasher = hashlib.sha256()
with open(filename, 'rb') as fd:
buf = fd.read(BLOCKSIZE)
while buf:
hasher.update(buf)
buf = fd.read(BLOCKSIZE)
return hasher.hexdigest()
class PkgConfig(object):
"""
This is a class for communicating with pkg-config.
"""
def __init__(self):
"""
Determines whether pkg-config exists on this machine.
"""
if sys.platform == 'win32':
self.has_pkgconfig = False
else:
self.pkg_config = os.environ.get('PKG_CONFIG', 'pkg-config')
self.set_pkgconfig_path()
self.has_pkgconfig = shutil.which(self.pkg_config) is not None
if not self.has_pkgconfig:
print("IMPORTANT WARNING:\n"
" pkg-config is not installed.\n"
" matplotlib may not be able to find some of its dependencies")
def set_pkgconfig_path(self):
pkgconfig_path = sysconfig.get_config_var('LIBDIR')
if pkgconfig_path is None:
return
pkgconfig_path = os.path.join(pkgconfig_path, 'pkgconfig')
if not os.path.isdir(pkgconfig_path):
return
try:
os.environ['PKG_CONFIG_PATH'] += ':' + pkgconfig_path
except KeyError:
os.environ['PKG_CONFIG_PATH'] = pkgconfig_path
def setup_extension(self, ext, package, default_include_dirs=[],
default_library_dirs=[], default_libraries=[],
alt_exec=None):
"""
Add parameters to the given `ext` for the given `package`.
"""
flag_map = {
'-I': 'include_dirs', '-L': 'library_dirs', '-l': 'libraries'}
executable = alt_exec
if self.has_pkgconfig:
executable = (self.pkg_config + ' {0}').format(package)
use_defaults = True
if executable is not None:
command = "{0} --libs --cflags ".format(executable)
try:
output = subprocess.check_output(
command, shell=True, stderr=subprocess.STDOUT)
except subprocess.CalledProcessError:
pass
else:
output = output.decode(sys.getfilesystemencoding())
use_defaults = False
for token in output.split():
attr = flag_map.get(token[:2])
if attr is not None:
getattr(ext, attr).insert(0, token[2:])
if use_defaults:
basedirs = get_base_dirs()
for base in basedirs:
for include in default_include_dirs:
dir = os.path.join(base, include)
if os.path.exists(dir):
ext.include_dirs.append(dir)
for lib in default_library_dirs:
dir = os.path.join(base, lib)
if os.path.exists(dir):
ext.library_dirs.append(dir)
ext.libraries.extend(default_libraries)
return True
return False
def get_version(self, package):
"""
Get the version of the package from pkg-config.
"""
if not self.has_pkgconfig:
return None
status, output = subprocess.getstatusoutput(
self.pkg_config + " %s --modversion" % (package))
if status == 0:
return output
return None
# The PkgConfig class should be used through this singleton
pkg_config = PkgConfig()
class CheckFailed(Exception):
"""
Exception thrown when a `SetupPackage.check` method fails.
"""
pass
class SetupPackage(object):
optional = False
pkg_names = {
"apt-get": None,
"yum": None,
"dnf": None,
"brew": None,
"port": None,
"windows_url": None
}
def check(self):
"""
Checks whether the build dependencies are met. Should raise a
`CheckFailed` exception if the dependency could not be met, otherwise
return a string indicating a version number or some other message
indicating what was found.
"""
pass
def get_packages(self):
"""
Get a list of package names to add to the configuration.
These are added to the `packages` list passed to
`distutils.setup`.
"""
return []
def get_namespace_packages(self):
"""
Get a list of namespace package names to add to the configuration.
These are added to the `namespace_packages` list passed to
`distutils.setup`.
"""
return []
def get_py_modules(self):
"""
Get a list of top-level modules to add to the configuration.
These are added to the `py_modules` list passed to
`distutils.setup`.
"""
return []
def get_package_data(self):
"""
Get a package data dictionary to add to the configuration.
These are merged into to the `package_data` list passed to
`distutils.setup`.
"""
return {}
def get_extension(self):
"""
Get a list of C extensions (`distutils.core.Extension`
objects) to add to the configuration. These are added to the
`extensions` list passed to `distutils.setup`.
"""
return None
def get_install_requires(self):
"""
Get a list of Python packages that we require.
pip/easy_install will attempt to download and install this
package if it is not installed.
"""
return []
def get_setup_requires(self):
"""
Get a list of Python packages that we require at build time.
pip/easy_install will attempt to download and install this
package if it is not installed.
"""
return []
def _check_for_pkg_config(self, package, include_file, min_version=None,
version=None):
"""
A convenience function for writing checks for a
pkg_config-defined dependency.
`package` is the pkg_config package name.
`include_file` is a top-level include file we expect to find.
`min_version` is the minimum version required.
`version` will override the found version if this package
requires an alternate method for that. Set version='unknown'
if the version is not known but you still want to disabled
pkg_config version check.
"""
if version is None:
version = pkg_config.get_version(package)
if version is None:
raise CheckFailed(
"pkg-config information for '%s' could not be found." %
package)
if min_version and version != 'unknown':
if not is_min_version(version, min_version):
raise CheckFailed(
"Requires %s %s or later. Found %s." %
(package, min_version, version))
ext = self.get_extension()
if ext is None:
ext = make_extension('test', [])
pkg_config.setup_extension(ext, package)
check_include_file(
ext.include_dirs + get_include_dirs(), include_file, package)
return 'version %s' % version
def do_custom_build(self):
"""
If a package needs to do extra custom things, such as building a
third-party library, before building an extension, it should
override this method.
"""
pass
def install_help_msg(self):
"""
Do not override this method !
Generate the help message to show if the package is not installed.
To use this in subclasses, simply add the dictionary `pkg_names` as
a class variable:
pkg_names = {
"apt-get": <Name of the apt-get package>,
"yum": <Name of the yum package>,
"dnf": <Name of the dnf package>,
"brew": <Name of the brew package>,
"port": <Name of the port package>,
"windows_url": <The url which has installation instructions>
}
All the dictionary keys are optional. If a key is not present or has
the value `None` no message is provided for that platform.
"""
def _try_managers(*managers):
for manager in managers:
pkg_name = self.pkg_names.get(manager, None)
if pkg_name:
if shutil.which(manager) is not None:
if manager == 'port':
pkgconfig = 'pkgconfig'
else:
pkgconfig = 'pkg-config'
return ('Try installing {0} with `{1} install {2}` '
'and pkg-config with `{1} install {3}`'
.format(self.name, manager, pkg_name,
pkgconfig))
message = None
if sys.platform == "win32":
url = self.pkg_names.get("windows_url", None)
if url:
message = ('Please check {0} for instructions to install {1}'
.format(url, self.name))
elif sys.platform == "darwin":
message = _try_managers("brew", "port")
elif sys.platform == "linux":
release = platform.linux_distribution()[0].lower()
if release in ('debian', 'ubuntu'):
message = _try_managers('apt-get')
elif release in ('centos', 'redhat', 'fedora'):
message = _try_managers('dnf', 'yum')
return message
class OptionalPackage(SetupPackage):
optional = True
force = False
config_category = "packages"
default_config = "auto"
@classmethod
def get_config(cls):
"""
Look at `setup.cfg` and return one of ["auto", True, False] indicating
if the package is at default state ("auto"), forced by the user (case
insensitively defined as 1, true, yes, on for True) or opted-out (case
insensitively defined as 0, false, no, off for False).
"""
conf = cls.default_config
if config is not None and config.has_option(cls.config_category, cls.name):
try:
conf = config.getboolean(cls.config_category, cls.name)
except ValueError:
conf = config.get(cls.config_category, cls.name)
return conf
def check(self):
"""
Do not override this method!
For custom dependency checks override self.check_requirements().
Two things are checked: Configuration file and requirements.
"""
# Check configuration file
conf = self.get_config()
# Default "auto" state or install forced by user
if conf in [True, 'auto']:
message = "installing"
# Set non-optional if user sets `True` in config
if conf is True:
self.optional = False
# Configuration opt-out by user
else:
# Some backend extensions (e.g. Agg) need to be built for certain
# other GUI backends (e.g. TkAgg) even when manually disabled
if self.force is True:
message = "installing forced (config override)"
else:
raise CheckFailed("skipping due to configuration")
# Check requirements and add extra information (if any) to message.
# If requirements are not met a CheckFailed should be raised in there.
additional_info = self.check_requirements()
if additional_info:
message += ", " + additional_info
# No CheckFailed raised until now, return install message.
return message
def check_requirements(self):
"""
Override this method to do custom dependency checks.
- Raise CheckFailed() if requirements are not met.
- Return message with additional information, or an empty string
(or None) for no additional information.
"""
return ""
class OptionalBackendPackage(OptionalPackage):
config_category = "gui_support"
class Platform(SetupPackage):
name = "platform"
def check(self):
return sys.platform
class Python(SetupPackage):
name = "python"
def check(self):
if sys.version_info < (3, 5):
error = """
Matplotlib 3.0+ does not support Python 2.x, 3.0, 3.1, 3.2, 3.3, or 3.4.
Beginning with Matplotlib 3.0, Python 3.5 and above is required.
This may be due to an out of date pip.
Make sure you have pip >= 9.0.1.
"""
raise CheckFailed(error)
return sys.version
def _pkg_data_helper(pkg, subdir):
"""Glob "lib/$pkg/$subdir/**/*", returning paths relative to "lib/$pkg"."""
base = pathlib.Path("lib", pkg)
return [str(path.relative_to(base)) for path in (base / subdir).rglob("*")]
class Matplotlib(SetupPackage):
name = "matplotlib"
def check(self):
return versioneer.get_version()
def get_packages(self):
return setuptools.find_packages("lib", exclude=["*.tests"])
def get_namespace_packages(self):
return ['mpl_toolkits']
def get_py_modules(self):
return ['pylab']
def get_package_data(self):
return {
'matplotlib': [
'mpl-data/matplotlibrc',
*_pkg_data_helper('matplotlib', 'mpl-data/fonts'),
*_pkg_data_helper('matplotlib', 'mpl-data/images'),
*_pkg_data_helper('matplotlib', 'mpl-data/stylelib'),
*_pkg_data_helper('matplotlib', 'backends/web_backend'),
],
}
class SampleData(OptionalPackage):
"""
This handles the sample data that ships with matplotlib. It is
technically optional, though most often will be desired.
"""
name = "sample_data"
def get_package_data(self):
return {
'matplotlib': [
*_pkg_data_helper('matplotlib', 'mpl-data/sample_data'),
],
}
class Tests(OptionalPackage):
name = "tests"
default_config = True
def get_packages(self):
return setuptools.find_packages("lib", include=["*.tests"])
def get_package_data(self):
return {
'matplotlib': [
*_pkg_data_helper('matplotlib', 'tests/baseline_images'),
'tests/cmr10.pfb',
'tests/mpltest.ttf',
'tests/test_rcparams.rc',
'tests/test_utf32_be_rcparams.rc',
'sphinxext/tests/tinypages/*.rst',
'sphinxext/tests/tinypages/*.py',
'sphinxext/tests/tinypages/_static/*',
],
'mpl_toolkits': [
*_pkg_data_helper('mpl_toolkits', 'tests/baseline_images'),
]
}
class DelayedExtension(Extension, object):
"""
A distutils Extension subclass where some of its members
may have delayed computation until reaching the build phase.
This is so we can, for example, get the Numpy include dirs
after pip has installed Numpy for us if it wasn't already
on the system.
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._finalized = False
self._hooks = {}
def add_hook(self, member, func):
"""
Add a hook to dynamically compute a member.
Parameters
----------
member : string
The name of the member
func : callable
The function to call to get dynamically-computed values
for the member.
"""
self._hooks[member] = func
def finalize(self):
self._finalized = True
class DelayedMember(property):
def __init__(self, name):
self._name = name
def __get__(self, obj, objtype=None):
result = getattr(obj, '_' + self._name, [])
if obj._finalized:
if self._name in obj._hooks:
result = obj._hooks[self._name]() + result
return result
def __set__(self, obj, value):
setattr(obj, '_' + self._name, value)
include_dirs = DelayedMember('include_dirs')
class Numpy(SetupPackage):
name = "numpy"
@staticmethod
def include_dirs_hook():
if hasattr(builtins, '__NUMPY_SETUP__'):
del builtins.__NUMPY_SETUP__
import numpy
importlib.reload(numpy)
ext = Extension('test', [])
ext.include_dirs.append(numpy.get_include())
if not has_include_file(
ext.include_dirs, os.path.join("numpy", "arrayobject.h")):
_log.warning(
"The C headers for numpy could not be found. "
"You may need to install the development package")
return [numpy.get_include()]
def add_flags(self, ext):
ext.add_hook('include_dirs', self.include_dirs_hook)
ext.define_macros.extend([
# Ensure that PY_ARRAY_UNIQUE_SYMBOL is uniquely defined for each
# extension.
('PY_ARRAY_UNIQUE_SYMBOL',
'MPL_' + ext.name.replace('.', '_') + '_ARRAY_API'),
('NPY_NO_DEPRECATED_API', 'NPY_1_7_API_VERSION'),
# Allow NumPy's printf format specifiers in C++.
('__STDC_FORMAT_MACROS', 1),
])
def get_setup_requires(self):
return ['numpy>=1.11']
def get_install_requires(self):
return ['numpy>=1.11']
class LibAgg(SetupPackage):
name = 'libagg'
def add_flags(self, ext, add_sources=True):
# We need a patched Agg not available elsewhere, so always use the
# vendored version.
ext.include_dirs.insert(0, 'extern/agg24-svn/include')
if add_sources:
agg_sources = [
'agg_bezier_arc.cpp',
'agg_curves.cpp',
'agg_image_filters.cpp',
'agg_trans_affine.cpp',
'agg_vcgen_contour.cpp',
'agg_vcgen_dash.cpp',
'agg_vcgen_stroke.cpp',
'agg_vpgen_segmentator.cpp'
]
ext.sources.extend(os.path.join('extern', 'agg24-svn', 'src', x)
for x in agg_sources)
# For FreeType2 and libpng, we add a separate checkdep_foo.c source to at the
# top of the extension sources. This file is compiled first and immediately
# aborts the compilation either with "foo.h: No such file or directory" if the
# header is not found, or an appropriate error message if the header indicates
# a too-old version.
class FreeType(SetupPackage):
name = "freetype"
pkg_names = {
"apt-get": "libfreetype6-dev",
"yum": "freetype-devel",
"dnf": "freetype-devel",
"brew": "freetype",
"port": "freetype",
"windows_url": "http://gnuwin32.sourceforge.net/packages/freetype.htm"
}
def add_flags(self, ext):
ext.sources.insert(0, 'src/checkdep_freetype2.c')
if options.get('local_freetype'):
src_path = os.path.join(
'build', 'freetype-{0}'.format(LOCAL_FREETYPE_VERSION))
# Statically link to the locally-built freetype.
# This is certainly broken on Windows.
ext.include_dirs.insert(0, os.path.join(src_path, 'include'))
if sys.platform == 'win32':
libfreetype = 'libfreetype.lib'
else:
libfreetype = 'libfreetype.a'
ext.extra_objects.insert(
0, os.path.join(src_path, 'objs', '.libs', libfreetype))
ext.define_macros.append(('FREETYPE_BUILD_TYPE', 'local'))
else:
pkg_config.setup_extension(
ext, 'freetype2',
default_include_dirs=[
'include/freetype2', 'freetype2',
'lib/freetype2/include',
'lib/freetype2/include/freetype2'],
default_library_dirs=[
'freetype2/lib'],
default_libraries=['freetype', 'z'])
ext.define_macros.append(('FREETYPE_BUILD_TYPE', 'system'))
def do_custom_build(self):
# We're using a system freetype
if not options.get('local_freetype'):
return
src_path = os.path.join(
'build', 'freetype-{0}'.format(LOCAL_FREETYPE_VERSION))
# We've already built freetype
if sys.platform == 'win32':
libfreetype = 'libfreetype.lib'
else:
libfreetype = 'libfreetype.a'
if os.path.isfile(os.path.join(src_path, 'objs', '.libs', libfreetype)):
return
tarball = 'freetype-{0}.tar.gz'.format(LOCAL_FREETYPE_VERSION)
tarball_path = os.path.join('build', tarball)
try:
tarball_cache_dir = _get_xdg_cache_dir()
tarball_cache_path = os.path.join(tarball_cache_dir, tarball)
except Exception:
# again, do not really care if this fails
tarball_cache_dir = None
tarball_cache_path = None
if not os.path.isfile(tarball_path):
if (tarball_cache_path is not None and
os.path.isfile(tarball_cache_path)):
if get_file_hash(tarball_cache_path) == LOCAL_FREETYPE_HASH:
os.makedirs('build', exist_ok=True)
try:
shutil.copy(tarball_cache_path, tarball_path)
print('Using cached tarball: {}'
.format(tarball_cache_path))
except OSError:
# If this fails, oh well just re-download
pass
if not os.path.isfile(tarball_path):
if not os.path.exists('build'):
os.makedirs('build')
url_fmts = [
'https://downloads.sourceforge.net/project/freetype'
'/freetype2/{version}/{tarball}',
'https://download.savannah.gnu.org/releases/freetype'
'/{tarball}'
]
for url_fmt in url_fmts:
tarball_url = url_fmt.format(
version=LOCAL_FREETYPE_VERSION, tarball=tarball)
print("Downloading {}".format(tarball_url))
try:
urllib.request.urlretrieve(tarball_url, tarball_path)
except IOError: # URLError (a subclass) on Py3.
print("Failed to download {}".format(tarball_url))
else:
if get_file_hash(tarball_path) != LOCAL_FREETYPE_HASH:
print("Invalid hash.")
else:
break
else:
raise IOError("Failed to download FreeType. You can "
"download the file by alternative means and "
"copy it to {}".format(tarball_path))
os.makedirs(tarball_cache_dir, exist_ok=True)
try:
shutil.copy(tarball_path, tarball_cache_path)
print('Cached tarball at {}'.format(tarball_cache_path))
except OSError:
# If this fails, we can always re-download.
pass
if get_file_hash(tarball_path) != LOCAL_FREETYPE_HASH:
raise IOError(
"{} does not match expected hash.".format(tarball))
print("Building {}".format(tarball))
with tarfile.open(tarball_path, "r:gz") as tgz:
tgz.extractall("build")
if sys.platform != 'win32':
# compilation on all other platforms than windows
env = {**os.environ,
"CFLAGS": "{} -fPIC".format(os.environ.get("CFLAGS", ""))}
subprocess.check_call(
["./configure", "--with-zlib=no", "--with-bzip2=no",
"--with-png=no", "--with-harfbuzz=no"],
env=env, cwd=src_path)
subprocess.check_call(["make"], env=env, cwd=src_path)
else:
# compilation on windows
shutil.rmtree(str(pathlib.Path(src_path, "objs")),
ignore_errors=True)
FREETYPE_BUILD_CMD = r"""
call "%ProgramFiles%\Microsoft SDKs\Windows\v7.0\Bin\SetEnv.Cmd" ^
/Release /{xXX} /xp
call "{vcvarsall}" {xXX}
set MSBUILD=C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe
%MSBUILD% "builds\windows\{vc20xx}\freetype.sln" ^
/t:Clean;Build /p:Configuration="Release";Platform={WinXX}
"""
import distutils.msvc9compiler as msvc
# Note: freetype has no build profile for 2014, so we don't bother...
vc = 'vc2010'
WinXX = 'x64' if platform.architecture()[0] == '64bit' else 'Win32'
xXX = 'x64' if platform.architecture()[0] == '64bit' else 'x86'
vcvarsall = msvc.find_vcvarsall(10.0)
if vcvarsall is None:
raise RuntimeError('Microsoft VS 2010 required')
cmdfile = pathlib.Path("build/build_freetype.cmd")
cmdfile.write_text(FREETYPE_BUILD_CMD.format(
vc20xx=vc, WinXX=WinXX, xXX=xXX, vcvarsall=vcvarsall))
subprocess.check_call([str(cmdfile.resolve())],
shell=True, cwd=src_path)
# Move to the corresponding Unix build path.
pathlib.Path(src_path, "objs/.libs").mkdir()
# Be robust against change of FreeType version.
lib_path, = (pathlib.Path(src_path, "objs", vc, xXX)
.glob("freetype*.lib"))
shutil.copy2(
str(lib_path),
str(pathlib.Path(src_path, "objs/.libs/libfreetype.lib")))
class FT2Font(SetupPackage):
name = 'ft2font'
def get_extension(self):
sources = [
'src/ft2font.cpp',
'src/ft2font_wrapper.cpp',
'src/mplutils.cpp',
'src/py_converters.cpp',
]
ext = make_extension('matplotlib.ft2font', sources)
FreeType().add_flags(ext)
Numpy().add_flags(ext)
LibAgg().add_flags(ext, add_sources=False)
return ext
class Png(SetupPackage):
name = "png"
pkg_names = {
"apt-get": "libpng12-dev",
"yum": "libpng-devel",
"dnf": "libpng-devel",
"brew": "libpng",
"port": "libpng",
"windows_url": "http://gnuwin32.sourceforge.net/packages/libpng.htm"
}
def get_extension(self):
sources = [
'src/checkdep_libpng.c',
'src/_png.cpp',
'src/mplutils.cpp',
]
ext = make_extension('matplotlib._png', sources)