Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add matplotlib #4

Open
dalcacer opened this issue Jan 24, 2019 · 3 comments
Open

Add matplotlib #4

dalcacer opened this issue Jan 24, 2019 · 3 comments

Comments

@dalcacer
Copy link

Similar to the numpy module, we try to add matplotlib with python bindings as a module, so that it can be used in iOS.

This is an experiment.

@dalcacer
Copy link
Author

dalcacer commented Jun 24, 2019

Step A Build Freetype

#!/bin/sh

# based on https://gist.github.com/ayansg/066f3ad7c84f9fd5f61651fc0d099bc3

PROJECT_DIR=$(pwd)
APP_PKGS=$PROJECT_DIR/dist/iOS/app_packages
PYTHON_VERSION=3.7.0
PYTHON_VER=3.7

CFLAGS_iOS=-mios-version-min=8.2
CFLAGS_iphoneos_arm64=-fembed-bitcode
CFLAGS_iphonesimulator_x86_64=-fembed-bitcode

FREETYPE_VERSION=2.9.1

BUILD_DIR=$PROJECT_DIR/build/iOS/freetype-$FREETYPE_VERSION
mkdir -p ${BUILD_DIR}
cd $BUILD_DIR

# Download original freetype source code archive.
if [ ! -e $PROJECT_DIR/downloads/freetype-$FREETYPE_VERSION.tgz ]; then curl --fail -L http://savannah.spinellicreations.com/freetype/freetype-$FREETYPE_VERSION.tar.gz -o $PROJECT_DIR/downloads/freetype-$FREETYPE_VERSION.tgz; fi
# unpack
mkdir -p $BUILD_DIR
tar zxf $PROJECT_DIR/downloads/freetype-$FREETYPE_VERSION.tgz --strip-components 1 -C $BUILD_DIR

cd $BUILD_DIR
echo $(pwd)

XCODE_ROOT=$(xcode-select -print-path)


red=$'\e[1;31m'
grn=$'\e[1;32m'
yel=$'\e[1;33m'
blu=$'\e[1;34m'
mag=$'\e[1;35m'
cyn=$'\e[1;36m'
end=$'\e[0m'


set -e

# do not increase this version number.
iphoneos="8.2"
# do not increase this version number.

ARCH="arm64"
printf "%s\n" "${blu}building iphoneos arm64${end}"
export CC=$(xcrun -sdk iphoneos -find clang)
export CFLAGS="-arch ${ARCH} -pipe -fembed-bitcode -Wno-trigraphs -fpascal-strings -O2 -Wreturn-type -Wunused-variable -fmessage-length=0 -fvisibility=hidden -miphoneos-version-min=$iphoneos -I/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk/usr/include/libxml2 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk"
export AR="/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar"
export LDFLAGS="-arch ${ARCH} -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS.sdk -miphoneos-version-min=$iphoneos"
./configure  --without-harfbuzz --host="aarch64-apple-darwin" --enable-static=yes --enable-shared=no
make clean
make
cp objs/.libs/libfreetype.a "${BUILD_DIR}/libfreetype-${ARCH}.a"

ARCH="x86_64"
printf "%s\n" "${blu}building iphonesimulator x86_64${end}"
export CC=$(xcrun -sdk iphonesimulator -find clang)
export CFLAGS="-arch ${ARCH} -pipe -fembed-bitcode=marker -Wno-trigraphs -fpascal-strings -O2 -Wreturn-type -Wunused-variable -fmessage-length=0 -fvisibility=hidden -miphoneos-version-min=$iphoneos -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk"
export LDFLAGS="-arch ${ARCH} -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk -miphoneos-version-min=$iphoneos"
./configure  --without-harfbuzz --disable-shared --enable-static --host="${ARCH}-apple-darwin"
make clean
make
cp objs/.libs/libfreetype.a "${BUILD_DIR}/libfreetype-${ARCH}.a"

printf "%s\n" "${blu}building fatlib${end}"
OUT_A=$PROJECT_DIR/dist/iOS/libfreetype.a
lipo -create "${BUILD_DIR}/libfreetype-arm64.a" "${BUILD_DIR}/libfreetype-x86_64.a" -output $OUT_A
printf "%s\n" "${grn}$(lipo -info $OUT_A)${end}"

Step B Build libpng

  • Based on insert link here
  • Builds libpng inside python-apple-support folder
#!/bin/sh

PROJECT_DIR=$(pwd)
APP_PKGS=$PROJECT_DIR/dist/iOS/app_packages
MACOSX_DEPLOYMENT_TARGET=10.14
PYTHON_VERSION=3.7.0
PYTHON_VER=3.7

CFLAGS_iOS=-mios-version-min=11.0
CFLAGS_iphoneos_arm64=-fembed-bitcode
CFLAGS_iphonesimulator_x86_64=-fembed-bitcode

PYTHON_DIR_macOS=build/macOS/Python-$PYTHON_VERSION-macosx.x86_64
PYTHON_HOST=$PYTHON_DIR_macOS/dist/lib/libpython$PYTHON_VERm.a

LPNG_VERSION=1.6.37
XCODE_ROOT=$(xcode-select -print-path)

mkdir -p $PROJECT_DIR/dist/iOS/

#### KIND OF RESET BUILD ENVIRONMENT, BY CHANGING DIR BACK TO ORIGIN
cd $PROJECT_DIR
#### KIND OF RESET BUILD ENVIRONMENT, BY CHANGING DIR BACK TO ORIGIN

# Download original libpng source code archive.
if [ ! -e downloads/libpng-$LPNG_VERSION.tgz ]; then curl --fail -L https://sourceforge.net/projects/libpng/files/libpng16/$LPNG_VERSION/libpng-$LPNG_VERSION.tar.gz/download -o downloads/libpng-$LPNG_VERSION.tgz; fi
# unpack
mkdir -p build/iOS/libpng-$LPNG_VERSION
tar zxf downloads/libpng-$LPNG_VERSION.tgz --strip-components 1 -C build/iOS/libpng-$LPNG_VERSION

# configure and build arm64 iphoneos
echo "building iphoneos arm64"
export CC=$(xcrun -sdk iphoneos -find clang)
export SDKROOT=$(xcrun --sdk iphoneos --show-sdk-path)
export CFLAGS="-O3 -Qunused-arguments -arch arm64 -pipe -no-cpp-precomp -isysroot $SDKROOT $CFLAGS_iOS $CFLAGS_iphoneos_arm64"
export CPPFLAGS=$CFLAGS
export CXXFLAGS="$CFLAGS -Wno-deprecated-register"
mkdir -p $PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos
cd $PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos
../configure --host=arm-apple-darwin64 --enable-shared=no --prefix=$PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos/ios-arm64
make -sj8 
make install
make distclean

# configure and build x86_64 iphonesimulator
echo "building iphonesimulator x86_64"
export CC=$(xcrun -sdk iphonesimulator -find clang)
export SDKROOT=$(xcrun --sdk iphonesimulator --show-sdk-path)
export CFLAGS="-O3 -Qunused-arguments -arch x86_64 -pipe -no-cpp-precomp -isysroot $SDKROOT $CFLAGS_iOS $CFLAGS_iphonesimulator_x86_64"
export CPPFLAGS=$CFLAGS
export CXXFLAGS="$CFLAGS -Wno-deprecated-register"
mkdir -p $PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos
cd $PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos
../configure --host x86_64-apple-darwin --enable-shared=no -prefix=$PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos/simulator-x86_64
make -sj8 
make install
make distclean

# make fatlib
OUT_A=$PROJECT_DIR/dist/iOS/libpng.a
xcrun lipo $PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos/ios-arm64/lib/libpng.a $PROJECT_DIR/build/iOS/libpng-$LPNG_VERSION/iphoneos/simulator-x86_64/lib/libpng.a  -create -output $OUT_A

Step C build kiwisolver

#!/bin/sh


PROJECT_DIR=$(pwd)
APP_PKGS=$PROJECT_DIR/dist/iOS/app_packages
MACOSX_DEPLOYMENT_TARGET=10.14
PYTHON_VERSION=3.7.0
PYTHON_VER=3.7

CFLAGS_iOS=-mios-version-min=12.2
CFLAGS_iphoneos_arm64=-fembed-bitcode
CFLAGS_iphonesimulator_x86_64=-fembed-bitcode
# override machine types for arm64
MACHINE_DETAILED_arm64=aarch64
MACHINE_SIMPLE_arm64=arm

PYTHON_DIR_macOS=$PROJECT_DIR/build/macOS/Python-$PYTHON_VERSION-macosx.x86_64
PYTHON_HOST=$PYTHON_DIR_macOS/dist/lib/libpython$PYTHON_VERm.a

KIWI_VERSION=1.1.0

XCODE_ROOT=$(xcode-select -print-path)

export CC=$XCODE_ROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang

HOST_PYTHON=$PROJECT_DIR/build/macOS/python/bin/python3
HOST_PIP=$PROJECT_DIR/build/macOS/python/bin/pip3

red=$'\e[1;31m'
grn=$'\e[1;32m'
yel=$'\e[1;33m'
blu=$'\e[1;34m'
mag=$'\e[1;35m'
cyn=$'\e[1;36m'
end=$'\e[0m'

BUILD_DIR=$PROJECT_DIR/build/iOS/kiwi-$KIWI_VERSION
# Download original kiwisikver source code archive.
if [ ! -e $PROJECT_DIR/downloads/kiwi-$KIWI_VERSION.tgz ]; then curl --fail -L https://github.com/nucleic/kiwi/archive/$KIWI_VERSION.tar.gz -o $PROJECT_DIR/downloads/kiwi-$KIWI_VERSION.tgz; fi
# unpack
mkdir -p $BUILD_DIR
tar zxf $PROJECT_DIR/downloads/kiwi-$KIWI_VERSION.tgz --strip-components 1 -C $BUILD_DIR

cd $BUILD_DIR
echo $(pwd)

# Now builds
# Help on compiler flags https://towardsdatascience.com/how-to-shrink-numpy-scipy-pandas-and-matplotlib-for-your-data-product-4ec8d7e86ee4
printf "%s\n" "${blu}building iphoneos arm64${end}"
export CC=$(xcrun -sdk iphoneos -find clang)
export AR=$(xcrun -sdk iphoneos -find ar)
export SDKROOT=$(xcrun --sdk iphoneos --show-sdk-path)

export CFLAGS="-arch arm64 -isysroot $SDKROOT $CFLAGS_iOS -g0 -O2 -I$SDKROOT -I$PROJECT_DIR/build/iOS/libpng-1.6.37/ -I$PROJECT_DIR/build/iOS/freetype-2.9.1/include -I$PROJECT_DIR/build/iOS/packages/numpy/numpy/core/inlcude/numpy -Wall"
export LDFLAGS="-arch arm64 -L$PROJECT_DIR/dist/iOS/ -isysroot $SDKROOT $CFLAGS_iOS -Wall -v -r"
cd $PROJECT_DIR/build/iOS/kiwi-$KIWI_VERSION
$HOST_PYTHON setup.py build_ext
find . -name "*.o" | xargs $AR -q libkiwisolver-arm64.a

# RESET THE BUILD OUTCOME FOR NEW BUILD
rm -rf  $BUILD_DIR/build/
# RESET THE BUILD OUTCOME FOR NEW BUILD

printf "%s\n" "${blu}building iphonesimulator x86_64${end}"
export CC=$(xcrun -sdk iphonesimulator -find clang)
export AR=$(xcrun -sdk iphonesimulator -find ar)
export SDKROOT=$(xcrun --sdk iphonesimulator --show-sdk-path)

export CFLAGS="-arch x86_64 -isysroot $SDKROOT $CFLAGS_iOS -g0 -O2 -I$SDKROOT -I$PROJECT_DIR/build/iOS/libpng-1.6.37/ -I$PROJECT_DIR/build/iOS/freetype-2.9.1/include -I$PROJECT_DIR/build/iOS/packages/numpy/numpy/core/inlcude/numpy -Wall"
export LDFLAGS="-arch x86_64 -L$PROJECT_DIR/dist/iOS/ -isysroot $SDKROOT $CFLAGS_iOS -Wall -v -r"
cd $PROJECT_DIR/build/iOS/kiwi-$KIWI_VERSION
$HOST_PYTHON setup.py build_ext
find . -name "*.o" | xargs $AR -q libkiwisolver-x86_64.a

cd $PROJECT_DIR/build/iOS/kiwi-$KIWI_VERSION
$HOST_PYTHON setup.py install
## copy from site-package folder

# make fatlib
echo "making fat lib"
OUT_A=$PROJECT_DIR/dist/iOS/libkiwisolver.a
xcrun lipo $PROJECT_DIR/dist/iOS/libkiwisolver-arm64.a $PROJECT_DIR/dist/iOS/libkiwisolver-x86_64.a -create -output $OUT_A

Step D build matplolib

  • for now simulator only
  • needs libpng and libfreetype in place
#!/bin/sh

###########################################################################
# Matplotlib
# Matplotlib requires the following dependencies:
# via Python-Apple-Support:
#   - `Python <https://www.python.org/downloads/>`_ (>= 3.5)
#   - `NumPy <http://www.numpy.org>`_ (>= |minimum_numpy_version|)
#   - `setuptools <https://setuptools.readthedocs.io/en/latest/>`_
# compile:
#   - `FreeType <https://www.freetype.org/>`_ (>= 2.3)
#   - `libpng <http://www.libpng.org>`_ (>= 1.2)
# pure-python:
# - `cycler <http://matplotlib.org/cycler/>`_ (>= 0.10.0)
# - `dateutil <https://pypi.python.org/pypi/python-dateutil>`_ (>= 2.1)
# - `kiwisolver <https://github.com/nucleic/kiwi>`_ (>= 1.0.0)
# - `pyparsing <https://pyparsing.wikispaces.com/>`_
##########################################################################

PROJECT_DIR=$(pwd)
APP_PKGS=$PROJECT_DIR/dist/iOS/app_packages
MACOSX_DEPLOYMENT_TARGET=10.14
PYTHON_VERSION=3.7.0
PYTHON_VER=3.7

CFLAGS_iOS=-mios-version-min=11.0
CFLAGS_iphoneos_arm64=-fembed-bitcode
CFLAGS_iphonesimulator_x86_64=-fembed-bitcode
# override machine types for arm64
MACHINE_DETAILED_arm64=aarch64
MACHINE_SIMPLE_arm64=arm

PYTHON_DIR_macOS=build/macOS/Python-$PYTHON_VERSION-macosx.x86_64
PYTHON_HOST=$PYTHON_DIR_macOS/dist/lib/libpython$PYTHON_VERm.a

MPL_VERSION=3.0.2
LPNG_VERSION=1.6.37
FREETYPE_VERSION=2.10.0
XCODE_ROOT=$(xcode-select -print-path)

export CC=$XCODE_ROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang
###########################################################################
# Compile all supporting libs that need to be provided.
###########################################################################

###########################################################################
# a) libpng
###########################################################################

#"$PROJECT_DIR/build_libpng.sh"


###########################################################################
# b) freetype
###########################################################################
# "$PROJECT_DIR/build_freetype.sh"
# skipped for now. results of https://gist.github.com/ayansg/066f3ad7c84f9fd5f61651fc0d099bc3
# were placed at PROJECT_DIR=$(pwd)/dist/iOS

###########################################################################
# Install all python dependencies.
###########################################################################
HOST_PYTHON=$PROJECT_DIR/build/macOS/python/bin/python3
HOST_PIP=$PROJECT_DIR/build/macOS/python/bin/pip3
$HOST_PIP install cycler python-dateutil kiwisolver pyparsing

# Download original matplotlib source code archive.
if [ ! -e downloads/matplotlib-$MPL_VERSION.tgz ]; then curl --fail -L https://github.com/matplotlib/matplotlib/archive/v$MPL_VERSION.tar.gz -o downloads/matplotlib-$MPL_VERSION.tgz; fi
# unpack
mkdir -p build/iOS/matplotlib-$MPL_VERSION
tar zxf downloads/matplotlib-$MPL_VERSION.tgz --strip-components 1 -C build/iOS/matplotlib-$MPL_VERSION

# Apply patch
cd $PROJECT_DIR/build/iOS/matplotlib-$MPL_VERSION && patch -p1 -i $PROJECT_DIR/patch/matplotlib/matplotlib.patch

# Now build
# Help on compiler flags https://towardsdatascience.com/how-to-shrink-numpy-scipy-pandas-and-matplotlib-for-your-data-product-4ec8d7e86ee4
export CC=$(xcrun -sdk iphonesimulator -find clang)
export AR=$XCODE_ROOT/Toolchains/XcodeDefault.xctoolchain/usr/bin/ar
export SDKROOT=$(xcrun --sdk iphonesimulator --show-sdk-path)
export CFLAGS="-arch x86_64 -isysroot $SDKROOT $CFLAGS_iOS -g0 -O2 -I$SDKROOT -I$PROJECT_DIR/build/iOS/libpng-1.6.37/ -I$PROJECT_DIR/build/iOS/freetype-2.9.1/include -I$PROJECT_DIR/build/iOS/packages/numpy/numpy/core/inlcude/numpy -Wall"
export LDFLAGS="-arch x86_64 -L$PROJECT_DIR/dist/iOS/ -isysroot $SDKROOT $CFLAGS_iOS -Wall -v -r"

BUILDDIR=$PROJECT_DIR/build/iOS/matplotlib-$MPL_VERSION/build
mkdir -p $BUILDDIR

DISTDIR=$PROJECT_DIR/dist/iOS/app_packages
mkdir -p $DISTDIR

cd $PROJECT_DIR/build/iOS/matplotlib-$MPL_VERSION
$HOST_PYTHON setup.py build_ext -I$BUILDDIR
cd $BUILDDIR
find . -name "*.o" | xargs $AR -q libmatplotlib.a
cd $PROJECT_DIR/build/iOS/matplotlib-$MPL_VERSION
$HOST_PYTHON setup.py install
## copy from site-package folder
  • The patch file writes out setup.cfg and removes backends
  • Patches unsupported calls to subprocess / popen (see pyto project).
diff -Nru matplotlib-3.0.2/lib/matplotlib/__init__.py matplotlib-3.0.2-modified/lib/matplotlib/__init__.py
--- matplotlib-3.0.2/lib/matplotlib/__init__.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/lib/matplotlib/__init__.py	2019-06-25 15:17:57.000000000 +0200
@@ -420,6 +420,7 @@
 
 def checkdep_dvipng():
     try:
+        """
         s = subprocess.Popen(['dvipng', '-version'],
                              stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
@@ -427,6 +428,9 @@
         line = stdout.decode('ascii').split('\n')[1]
         v = line.split()[-1]
         return v
+        """
+        # no supported on iOS
+        raise OSError
     except (IndexError, ValueError, OSError):
         return None
 
@@ -457,6 +461,7 @@
 
 def checkdep_pdftops():
     try:
+        """
         s = subprocess.Popen(['pdftops', '-v'], stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE)
         stdout, stderr = s.communicate()
@@ -465,6 +470,9 @@
             if 'version' in line:
                 v = line.split()[-1]
         return v
+        """
+        # not supported on iOS
+        raise OSError
     except (IndexError, ValueError, UnboundLocalError, OSError):
         return None
 
@@ -472,6 +480,7 @@
 def checkdep_inkscape():
     if checkdep_inkscape.version is None:
         try:
+            """
             s = subprocess.Popen(['inkscape', '-V'],
                                  stdout=subprocess.PIPE,
                                  stderr=subprocess.PIPE)
@@ -482,6 +491,9 @@
                     v = line.split()[1]
                     break
             checkdep_inkscape.version = v
+            """
+            #not supported on iOS
+            raise OSError
         except (IndexError, ValueError, UnboundLocalError, OSError):
             pass
     return checkdep_inkscape.version
@@ -732,7 +744,10 @@
     """
 
     def gen_candidates():
-        yield os.path.join(os.getcwd(), 'matplotlibrc')
+        try:
+            yield os.path.join(os.getcwd(), 'matplotlibrc')
+        except PermissionError:
+            pass
         try:
             matplotlibrc = os.environ['MATPLOTLIBRC']
         except KeyError:
diff -Nru matplotlib-3.0.2/lib/matplotlib/animation.py matplotlib-3.0.2-modified/lib/matplotlib/animation.py
--- matplotlib-3.0.2/lib/matplotlib/animation.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/lib/matplotlib/animation.py	2019-06-25 15:32:45.000000000 +0200
@@ -348,10 +348,13 @@
         command = self._args()
         output = subprocess.PIPE
         _log.info('MovieWriter.run: running command: %s', command)
+        """
         self._proc = subprocess.Popen(command, shell=False,
                                       stdout=output, stderr=output,
                                       stdin=subprocess.PIPE,
                                       creationflags=subprocess_creation_flags)
+        """
+        raise NotImplementedError("Not supported by iOS.")
 
     def finish(self):
         '''Finish any processing for writing the movie.'''
diff -Nru matplotlib-3.0.2/lib/matplotlib/cbook/__init__.py matplotlib-3.0.2-modified/lib/matplotlib/cbook/__init__.py
--- matplotlib-3.0.2/lib/matplotlib/cbook/__init__.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/lib/matplotlib/cbook/__init__.py	2019-06-25 18:16:39.000000000 +0200
@@ -728,8 +728,12 @@
     pid = os.getpid()
     if sys.platform == 'sunos5':
         try:
+            """
             a2 = Popen(['ps', '-p', '%d' % pid, '-o', 'osz'],
                        stdout=PIPE).stdout.readlines()
+            """
+            # not supported on iOS
+            raise OSError
         except OSError:
             raise NotImplementedError(
                 "report_memory works on Sun OS only if "
@@ -737,8 +741,12 @@
         mem = int(a2[-1].strip())
     elif sys.platform == 'linux':
         try:
+            """
             a2 = Popen(['ps', '-p', '%d' % pid, '-o', 'rss,sz'],
                        stdout=PIPE).stdout.readlines()
+            """
+            # not supported on iOS
+            raise OSError
         except OSError:
             raise NotImplementedError(
                 "report_memory works on Linux only if "
@@ -746,8 +754,12 @@
         mem = int(a2[1].split()[1])
     elif sys.platform == 'darwin':
         try:
+            """
             a2 = Popen(['ps', '-p', '%d' % pid, '-o', 'rss,vsz'],
                        stdout=PIPE).stdout.readlines()
+            """
+            # not supported on iOS
+            raise OSError
         except OSError:
             raise NotImplementedError(
                 "report_memory works on Mac OS only if "
@@ -755,8 +767,12 @@
         mem = int(a2[1].split()[0])
     elif sys.platform == 'win32':
         try:
+            """
             a2 = Popen(["tasklist", "/nh", "/fi", "pid eq %d" % pid],
                        stdout=PIPE).stdout.read()
+            """
+            # not supported on iOS
+            raise OSError
         except OSError:
             raise NotImplementedError(
                 "report_memory works on Windows only if "
diff -Nru matplotlib-3.0.2/lib/matplotlib/compat/subprocess.py matplotlib-3.0.2-modified/lib/matplotlib/compat/subprocess.py
--- matplotlib-3.0.2/lib/matplotlib/compat/subprocess.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/lib/matplotlib/compat/subprocess.py	2019-06-25 15:07:12.000000000 +0200
@@ -19,24 +19,15 @@
 
 __all__ = ['Popen', 'PIPE', 'STDOUT', 'check_output', 'CalledProcessError']
 
-
-if hasattr(subprocess, 'Popen'):
-    Popen = subprocess.Popen
-    # Assume that it also has the other constants.
-    PIPE = subprocess.PIPE
-    STDOUT = subprocess.STDOUT
-    CalledProcessError = subprocess.CalledProcessError
-    check_output = subprocess.check_output
-else:
-    # In restricted environments (such as Google App Engine), these are
-    # non-existent. Replace them with dummy versions that always raise OSError.
-    def Popen(*args, **kwargs):
-        raise OSError("subprocess.Popen is not supported")
-
-    def check_output(*args, **kwargs):
-        raise OSError("subprocess.check_output is not supported")
-    PIPE = -1
-    STDOUT = -2
-    # There is no need to catch CalledProcessError. These stubs cannot raise
-    # it. None in an except clause will simply not match any exceptions.
-    CalledProcessError = None
+# In restricted environments (such as Google App Engine), these are
+# non-existent. Replace them with dummy versions that always raise OSError.
+def Popen(*args, **kwargs):
+    raise OSError("subprocess.Popen is not supported")
+    
+def check_output(*args, **kwargs):
+    raise OSError("subprocess.check_output is not supported")
+PIPE = -1
+STDOUT = -2
+# There is no need to catch CalledProcessError. These stubs cannot raise
+# it. None in an except clause will simply not match any exceptions.
+CalledProcessError = None
\ No newline at end of file
diff -Nru matplotlib-3.0.2/lib/matplotlib/dviread.py matplotlib-3.0.2-modified/lib/matplotlib/dviread.py
--- matplotlib-3.0.2/lib/matplotlib/dviread.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/lib/matplotlib/dviread.py	2019-06-25 15:21:18.000000000 +0200
@@ -1018,9 +1018,12 @@
         cmd += ['--format=' + format]
     cmd += [filename]
     _log.debug('find_tex_file(%s): %s', filename, cmd)
+    '''
     pipe = subprocess.Popen(cmd, stdout=subprocess.PIPE)
     result = pipe.communicate()[0].rstrip()
     _log.debug('find_tex_file result: %s', result)
+    '''
+    raise NotImplementedError("Not supported on iOS")
     return result.decode('ascii')
 
 
diff -Nru matplotlib-3.0.2/lib/matplotlib/font_manager.py matplotlib-3.0.2-modified/lib/matplotlib/font_manager.py
--- matplotlib-3.0.2/lib/matplotlib/font_manager.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/lib/matplotlib/font_manager.py	2019-06-25 15:09:30.000000000 +0200
@@ -233,7 +233,11 @@
         'This may take a moment.'))
     timer.start()
     try:
+        """
         out = subprocess.check_output(['fc-list', '--format=%{file}\\n'])
+        """
+        # not supported on iOS
+        raise OSError
     except (OSError, subprocess.CalledProcessError):
         return []
     finally:
@@ -1298,11 +1302,15 @@
         fontexts = get_fontext_synonyms(fontext)
         ext = "." + fontext
         try:
+            """
             pipe = subprocess.Popen(
                 ['fc-match', '-s', '--format=%{file}\\n', pattern],
                 stdout=subprocess.PIPE,
                 stderr=subprocess.PIPE)
             output = pipe.communicate()[0]
+            """
+            # not supported on iOS
+            raise OSError
         except OSError:
             return None
 
diff -Nru matplotlib-3.0.2/lib/matplotlib/texmanager.py matplotlib-3.0.2-modified/lib/matplotlib/texmanager.py
--- matplotlib-3.0.2/lib/matplotlib/texmanager.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/lib/matplotlib/texmanager.py	2019-06-25 15:10:34.000000000 +0200
@@ -291,11 +291,13 @@
         return texfile
 
     def _run_checked_subprocess(self, command, tex):
+        raise NotImplementedError("Tex is not supported by iOS")
         _log.debug(command)
         try:
             report = subprocess.check_output(command,
                                              cwd=self.texcache,
                                              stderr=subprocess.STDOUT)
+            raise subprocess.CalledProcessError(1, command)
         except subprocess.CalledProcessError as exc:
             raise RuntimeError(
                 '{prog} was not able to process the following string:\n'
diff -Nru matplotlib-3.0.2/setup.cfg matplotlib-3.0.2-modified/setup.cfg
--- matplotlib-3.0.2/setup.cfg	1970-01-01 01:00:00.000000000 +0100
+++ matplotlib-3.0.2-modified/setup.cfg	2019-06-25 18:36:02.000000000 +0200
@@ -0,0 +1,14 @@
+[packages]
+tests = False
+sample_data = False
+toolkits = False
+toolkits_tests = False
+
+[gui_support]
+agg = True
+macosx = False
+tkagg = False
+windowing = False
+
+[rc_options]
+backend = Agg
\ No newline at end of file
diff -Nru matplotlib-3.0.2/setup.py matplotlib-3.0.2-modified/setup.py
--- matplotlib-3.0.2/setup.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/setup.py	2019-06-25 18:48:20.000000000 +0200
@@ -65,17 +65,17 @@
     setupext.QhullWrap(),
     setupext.Tri(),
     'Optional subpackages',
-    setupext.SampleData(),
+    #setupext.SampleData(),
     setupext.Toolkits(),
-    setupext.Tests(),
-    setupext.Toolkits_Tests(),
+    #setupext.Tests(),
+    #setupext.Toolkits_Tests(),
     'Optional backend extensions',
     setupext.BackendAgg(),
-    setupext.BackendTkAgg(),
-    setupext.BackendMacOSX(),
-    setupext.Windowing(),
+    #setupext.BackendTkAgg(),
+    #setupext.BackendMacOSX(),
+    #setupext.Windowing(),
     'Optional package data',
-    setupext.Dlls(),
+    #setupext.Dlls(),
     ]
 
 
diff -Nru matplotlib-3.0.2/setupext.py matplotlib-3.0.2-modified/setupext.py
--- matplotlib-3.0.2/setupext.py	2018-11-10 02:06:33.000000000 +0100
+++ matplotlib-3.0.2-modified/setupext.py	2019-06-25 18:24:07.000000000 +0200
@@ -667,7 +667,7 @@
                 *iter_dir('mpl-data/fonts'),
                 *iter_dir('mpl-data/images'),
                 *iter_dir('mpl-data/stylelib'),
-                *iter_dir('backends/web_backend'),
+            #   *iter_dir('backends/web_backend'),
             ]}
 
 

Step E include matplotlib

  • Add pure-python deps to app_packages/ folder
  • Copy matplotlib

Add libpng.a/libfreetype.a/libmatplotlib.a and libc++1.tbd to XCode-Project

// name all modules, that are a *.so-file within site-packes/matplotlib and subfolders.
// _contour.cpython.....so
// _image.cpython.....so
// _path.cpython.....so
// _png.cpython.....so
// _qhull.cpython.....so
// _tri.cpython.....so
// backends/_backend_agg.cpython.....so
// ft2font.cpython.....so
// ttconf.cpython.....so
// and kiwisolver
void matplotlib_importer() {
  PyRun_SimpleString(
                     "import sys, importlib\n" \
                     "class MatplotlibImporter(object):\n" \
                     "    def find_module(self, fullname, mpath=None):\n" \
                     "        if fullname in (" \
                     "                    'matplotlib._contour', " \
                     "                    'matplotlib._image', " \
                     "                    'matplotlib._path', " \
                     "                    'matplotlib._png', " \
                     "                    'matplotlib._qhull', " \
                     "                    'matplotlib._tri', " \
                     "                    'matplotlib.backends._backend_agg', " \
                     "                    'matplotlib.ft2font', " \
                     "                    'matplotlib.ttconv', " \
                     "                    'kiwisolver', " \
                     "                ):\n" \
                     "            return self\n" \
                     "        return\n" \
                     "    def load_module(self, fullname):\n" \
                     "        f = '__' + fullname.replace('.', '_')\n" \
                     "        mod = sys.modules.get(f)\n" \
                     "        if mod is None:\n" \
                     "            mod = importlib.__import__(f)\n" \
                     "            sys.modules[fullname] = mod\n" \
                     "            return mod\n" \
                     "        return mod\n" \
                     "sys.meta_path.append(MatplotlibImporter())"
                     );
}
// MATPLOTLIB
/*
 nm libmatplotlib.a | grep PyInit
 0000000000000000 T _PyInit__tri
 0000000000000000 T _PyInit_ft2font
 0000000000000560 T _PyInit__path
 0000000000000000 T _PyInit__png
 0000000000000000 T _PyInit__qhull
 0000000000000000 T _PyInit__contour
 0000000000000170 T _PyInit_ttconv
 0000000000000000 T _PyInit__image
 0000000000000370 T _PyInit__tkagg
 0000000000002a60 T _PyInit__backend_agg
 */
extern PyMODINIT_FUNC PyInit__tri(void);
extern PyMODINIT_FUNC PyInit_ft2font(void);
extern PyMODINIT_FUNC PyInit__path(void);
extern PyMODINIT_FUNC PyInit__png(void);
extern PyMODINIT_FUNC PyInit__qhull(void);
extern PyMODINIT_FUNC PyInit__contour(void);
extern PyMODINIT_FUNC PyInit_ttconv(void);
extern PyMODINIT_FUNC PyInit__image(void);
//extern PyMODINIT_FUNC PyInit__tkagg(void);
extern PyMODINIT_FUNC PyInit__backend_agg(void);
/*
 nm libkiwisolver.a | grep PyInit
 0000000000000000 T _PyInit_kiwisolver
 */
extern PyMODINIT_FUNC PyInit_kiwisolver(void);
  PyImport_AppendInittab("__matplotlib__tri", &PyInit__tri);
  PyImport_AppendInittab("__matplotlib_ft2font", &PyInit_ft2font);
  PyImport_AppendInittab("__matplotlib__path", &PyInit__path);
  PyImport_AppendInittab("__matplotlib__png", &PyInit__png);
  PyImport_AppendInittab("__matplotlib__qhull", &PyInit__qhull);
  PyImport_AppendInittab("__matplotlib__contour", &PyInit__contour);
  PyImport_AppendInittab("__matplotlib_ttconv", &PyInit_ttconv);
  PyImport_AppendInittab("__matplotlib__image", &PyInit__image);
  PyImport_AppendInittab("__matplotlib_backends__backend_agg", &PyInit__backend_agg);

  PyImport_AppendInittab("__kiwisolver", &PyInit_kiwisolver);
// If other modules are using threads, we need to initialize them.
  PyEval_InitThreads();
  numpy_importer();
  matplotlib_importer();

@siege098
Copy link

I was interested on working on this. Has anything else been done with it?

@dalcacer
Copy link
Author

Hi, no there is no off-the-shelve solution, yet.
I only managed to build it one time only and that binary is still in use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants