-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsetupApp.py
More file actions
272 lines (249 loc) · 10.8 KB
/
Copy pathsetupApp.py
File metadata and controls
272 lines (249 loc) · 10.8 KB
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
#!/usr/bin/env python
################
# see notes at bottom for requirements
import os
import sys
import platform
import setuptools # noqa: setuptools complains if it isn't explicitly imported before distutils
from distutils.core import setup
from packaging.version import Version
import py2app # noqa: needed to build app bundle, even though not explicitly used here
from ctypes import util
import importlib
from building import compile_po
from building import semanticVersion
from pathlib import Path
import psychopy
root = Path(__file__).parent # root of the repo
version = psychopy.__version__
def glob_to_list(path, glob_pattern='*'):
"""Convert a glob pattern to a list of files."""
return [str(p.absolute()) for p in Path(path).glob(glob_pattern)]
compile_po.compilePoFiles()
# semanticVersion.updateVersionFile()
# semanticVersion.updateGitShaFile()
def find_library(libName):
"""Search for the specified library in system paths and homebrew directories."""
# libPath = util.find_library(libName)
# if libPath:
# print(f"Found {libName} library in system paths: {libPath}")
# return libPath
# search homebrew
if platform.machine() == 'arm64':
homebrewLibs = Path('/opt/homebrew') # default homebrew location on Apple Silicon
else:
homebrewLibs = Path('/usr/local/lib') # default homebrew location on Intel Macs
libPath = list(homebrewLibs.glob(f'**/{libName}.dylib'))
if len(libPath) > 0:
print(f"Found multiple {libName} libraries: {libPath}")
libPath = libPath[0] # take the first match
if libPath:
print(f"Using {libName} library: {libPath}")
return str(libPath)
#define the extensions to compile if necess
packageData = []
requires = []
if sys.platform != 'darwin':
raise RuntimeError("setupApp.py is only for building Mac Standalone bundle")
if sys.platform == 'darwin' and platform.machine() == 'arm64':
homebrewLibs = Path('/opt/homebrew') # default homebrew location on Apple Silicon
else:
homebrewLibs = Path('/usr/local/libs') # default homebrew location on Intel Macs
frameworks = []
# check dylibs
homebrewNames = {
'libevent': 'libevent',
'libglfw': 'glfw',
'libffi': 'libffi',
'libmp3lame': 'lame'
}
for libName in ["libevent", "libglfw", "libffi", "libmp3lame"]:
libPath = find_library(libName)
if not libPath:
brewName = homebrewNames.get(libName, libName)
raise ImportError(f"Couldn't find {libName} library. Try installing it using homebrew like this?: brew install {brewName}")
frameworks.append(libPath)
opencvLibs = glob_to_list(Path(sys.exec_prefix, 'lib'), 'libopencv*.2.4.dylib')
frameworks.extend(opencvLibs)
resources = glob_to_list(root / 'src/psychopy_app/Resources', '*')
import macholib
#print("~"*60 + "macholib version: "+macholib.__version__)
if Version(macholib.__version__) <= Version('1.7'):
print("Applying macholib patch...")
import macholib.dyld
import macholib.MachOGraph
dyld_find_1_7 = macholib.dyld.dyld_find
def dyld_find(name, loader=None, **kwargs):
#print("~"*60 + "calling alternate dyld_find")
if loader is not None:
kwargs['loader_path'] = loader
return dyld_find_1_7(name, **kwargs)
macholib.MachOGraph.dyld_find = dyld_find
# excludes are often because of codesign difficulties on macos
excludes=['torch', 'mediapipe',
'bsddb', 'jinja2', 'IPython','ipython_genutils','nbconvert',
'tkinter', 'Tkinter', 'tcl',
'libsz.2.dylib', 'pygame',
# 'stringprep',
'functools32',
'sympy',
'/usr/lib/libffi.dylib',
'libwebp.7.dylib',
'google',
]
includes = ['_sitebuiltins', # needed for help()
'imp', 'subprocess', 'shlex',
'shelve', # for scipy.io
'_elementtree', 'pyexpat', # for openpyxl
'greenlet', 'zmq', 'tornado',
'psutil', # for iohub
'soundfile', 'sounddevice', 'readline',
'xlwt', # writes excel files for pandas
'msgpack_numpy',
'configparser',
'ntplib', # for egi-pynetstation
]
packages = ['pydoc', # needed for help()
'setuptools', 'wheel', # for plugin installing
'wx', 'psychopy',
'PyQt6',
'pyglet', 'pytz',
'scipy', 'matplotlib', 'openpyxl', 'pandas',
'xml', 'xmlschema',
'ffpyplayer', 'cython', 'AVFoundation',
'imageio', 'imageio_ffmpeg',
'_sounddevice_data', '_soundfile_data',
'cffi', 'pycparser',
'PIL', # 'Image',
'freetype',
'objc', 'Quartz', 'AppKit', 'Cocoa',
'Foundation', 'CoreFoundation',
'requests', 'certifi', 'cryptography',
'json_tricks', # allows saving arrays/dates in json
'git', 'gitlab',
'msgpack', 'yaml', 'gevent', # for ioHub
'astunparse', 'esprima', # for translating/adapting py/JS
'metapensiero.pj', 'dukpy',
'jedi', 'parso',
'bidi', 'arabic_reshaper', 'charset_normalizer', # for (natural) language conversions
'ujson', # faster than built-in json
'six', # needed by configobj
# hardware
'serial',
# handy science tools
'tables', # 'cython',
# these aren't needed, but liked
'pylsl',
#'smite', # https://github.com/marcus-nystrom/SMITE (not pypi!)
'cv2',
'questplus',
'psychtoolbox',
'h5py',
'markdown_it',
'zeroconf', 'ifaddr', # for pupillabs plugin (fail to build)
'websocket', # dependency for emotiv that doesn't install nicely from plugins
'moviepy', # used for a range of of movie-based backends
'egi_pynetstation', # to be removed in future
]
# Add packages that older PsychoPy (<=2023.1.x) shipped, for useVersion() compatibility
# In PsychoPy 2023.2.0 these packages were removed from Standalone Py3.10+ builds
if sys.version_info < (3, 9):
packages.extend(
[
'OpenGL', 'glfw',
'badapted', #'darc_toolbox', # adaptive methods from Ben Vincent
'pylink', 'tobiiresearch',
'pyxid2', 'ftd2xx', # ftd2xx is used by cedrus
'Phidget22',
'hid',
'macropy',
]
)
packages.append('PyQt5')
packages.remove('PyQt6') # PyQt6 is not compatible with earlier PsychoPy versions
excludes.append('PyQt6') # and explicitly exclude it
# check the includes and packages are all available
missingPkgs = []
pipInstallLines = ''
packagePipNames = { # packages that are imported as one thing but installed as another
'OpenGL': 'pyopengl',
'opencv': 'opencv-python',
'googleapiclient': 'google-api-python-client',
'google': 'google-api-python-client',
'macropy': 'macropy3',
}
for pkg in includes+packages:
try:
importlib.import_module(pkg)
except ModuleNotFoundError:
if pkg in packagePipNames:
missingPkgs.append(packagePipNames[pkg])
elif pkg == 'pylink':
pipInstallLines += 'pip install --index-url=https://pypi.sr-support.com sr-research-pylink\n'
else:
missingPkgs.append(pkg)
except OSError as err:
if 'libftd2xx.dylib' in str(err):
raise ImportError(f"Missing package: ftd2xx. Please install the FTDI D2XX drivers from "
"https://www.ftdichip.com/Drivers/D2XX.htm")
except ImportError as err:
if 'eyelink' in str(err):
raise ImportError(f"It looks like the Eyelink dev kit is not installed "
"https://www.sr-research.com/support/thread-13.html")
if missingPkgs or pipInstallLines:
helpStr = f"You're missing some packages to include in standalone. Fix with:\n"
if missingPkgs:
helpStr += f"pip install {' '.join(missingPkgs)}\n"
helpStr += pipInstallLines
raise ImportError(helpStr)
else:
print("All packages appear to be present. Proceeding to build...")
setup(
app=[str(root / 'src/psychopy_app/psychopyApp.py')],
options=dict(py2app=dict(
includes=includes,
packages=packages,
excludes=excludes,
resources=resources,
argv_emulation=False, # must be False or app bundle pauses (py2app 0.21 and 0.24 tested)
site_packages=True,
frameworks=frameworks,
iconfile= str(root / 'src/psychopy_app/Resources/psychopy.icns'),
plist=dict(
CFBundleIconFile='psychopy.icns',
CFBundleName = "PsychoPy",
CFBundleShortVersionString = version, # must be in X.X.X format
CFBundleVersion = version,
CFBundleExecutable = "PsychoPy",
CFBundleIdentifier = "org.opensciencetools.psychopy",
CFBundleLicense = "GNU GPLv3+",
NSHumanReadableCopyright = "Open Science Tools Limited",
CFBundleDocumentTypes=[dict(CFBundleTypeExtensions=['*'],
CFBundleTypeRole='Editor')],
CFBundleURLTypes=[dict(CFBundleURLName='psychopy', # respond to psychopy://
CFBundleURLSchemes='psychopy',
CFBundleTypeRole='Editor')],
LSEnvironment=dict(PATH="/usr/local/git/bin:/usr/local/bin:"
"/usr/local:/usr/bin:/usr/sbin"),
NSMicrophoneUsageDescription="This app may require access to the microphone to record audio for experiments.",
NSCameraUsageDescription="This app may require access to the camera to record video for experiments.",
),
)), # end of the options dict
install_requires=[],
)
# ugly hack for opencv2:
# As of opencv 2.4.5 the cv2.so binary used rpath to a fixed
# location to find libs and even more annoyingly it then appended
# 'lib' to the rpath as well. These were fine for the packaged
# framework python but the libs in an app bundle are different.
# So, create symlinks so they appear in the same place as in framework python
rpath = root / "dist/PsychoPy.app/Contents/Resources/"
for libPath in opencvLibs:
libname = os.path.split(libPath)[-1]
realPath = "../../Frameworks/"+libname # relative path (w.r.t. the fake)
fakePath = os.path.join(rpath, "lib", libname)
os.symlink(realPath, fakePath)
# they even did this for Python lib itself, which is in diff location
realPath = "../Frameworks/Python.framework/Python" # relative to the fake path
fakePath = os.path.join(rpath, "Python")
os.symlink(realPath, fakePath)