getcsound 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
getcsound/__init__.py ADDED
@@ -0,0 +1,87 @@
1
+ """Install Csound 7 from Python.
2
+
3
+ ``getcsound`` lets a Python package declare Csound as a dependency and make it
4
+ available on the user's machine without asking them to install it manually::
5
+
6
+ from getcsound import ensure_csound
7
+
8
+ installation = ensure_csound()
9
+ # LIBCSOUNDPATH and OPCODE7DIR64 now point at a usable Csound 7.
10
+ import libcsound # or any other Csound binding
11
+
12
+ # installation.libpath, installation.plugindir and installation.bindir
13
+ # describe the installation without loading it.
14
+
15
+ The package is pure Python and has no runtime dependencies. It deliberately
16
+ does **not** import :mod:`ctypes` or depend on ``libcsound``, so it can be used
17
+ even by projects that must remain free of binary dependencies.
18
+
19
+ Importing ``getcsound`` does not install anything. Installation happens only
20
+ when :func:`ensure_csound` (or one of the ``install_csound_*`` functions) is
21
+ called.
22
+
23
+ The official installers are bundled with the package and are run with bash or
24
+ PowerShell:
25
+
26
+ * Linux: installs the portable Csound 7 build to ``~/.local/csound`` when no
27
+ terminal is available, or interactively otherwise.
28
+ * macOS: installs the official Csound 7 ``.pkg`` (needs sudo, either an
29
+ interactive terminal or password-less sudo).
30
+ * Windows: installs the machine-wide x86_64 package (needs Administrator
31
+ rights; an interactive or already-elevated session is required).
32
+
33
+ Environment variables
34
+ ---------------------
35
+
36
+ ``LIBCSOUNDPATH``
37
+ If set, absolute path to the Csound shared library to use. When set to a
38
+ file that does not exist, :func:`ensure_csound` refuses to install another
39
+ Csound and raises instead.
40
+
41
+ ``OPCODE7DIR64``
42
+ Plugin directory. Set or updated by the installation functions when it is
43
+ known.
44
+
45
+ ``GETCSOUND_INSTALL``
46
+ Set to ``0``, ``false``, ``no`` or ``off`` to disable automatic
47
+ installation. ``LIBCSOUND_INSTALL`` is accepted as a compatibility alias.
48
+
49
+ If automatic installation is disabled or unsupported, the official one-line
50
+ installers can still be used manually::
51
+
52
+ # Linux / macOS
53
+ curl -fsSL https://csound-plugins.github.io/getcsound.sh | bash
54
+
55
+ # Windows (PowerShell)
56
+ irm https://csound-plugins.github.io/getcsound.ps1 | iex
57
+ """
58
+
59
+ from __future__ import annotations
60
+
61
+ from ._errors import CsoundInstallError, CsoundNotFoundError, GetCsoundError
62
+ from ._install import (
63
+ ensure_csound,
64
+ install_csound,
65
+ install_csound_linux,
66
+ install_csound_macos,
67
+ install_csound_windows,
68
+ install_disabled,
69
+ )
70
+ from ._locate import CsoundInstallation, find_csound
71
+ from ._util import run_installer, stdin_is_tty
72
+
73
+ __all__ = [
74
+ "CsoundInstallError",
75
+ "CsoundInstallation",
76
+ "CsoundNotFoundError",
77
+ "GetCsoundError",
78
+ "ensure_csound",
79
+ "find_csound",
80
+ "install_csound",
81
+ "install_csound_linux",
82
+ "install_csound_macos",
83
+ "install_csound_windows",
84
+ "install_disabled",
85
+ "run_installer",
86
+ "stdin_is_tty",
87
+ ]
getcsound/_errors.py ADDED
@@ -0,0 +1,15 @@
1
+ """Exceptions raised by :mod:`getcsound`."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class GetCsoundError(RuntimeError):
7
+ """Base class for errors raised by :mod:`getcsound`."""
8
+
9
+
10
+ class CsoundNotFoundError(GetCsoundError):
11
+ """Csound could not be found and automatic installation is disabled."""
12
+
13
+
14
+ class CsoundInstallError(GetCsoundError):
15
+ """Csound could not be installed."""
getcsound/_install.py ADDED
@@ -0,0 +1,400 @@
1
+ """Install Csound 7 by running the official bundled installers.
2
+
3
+ The development version of these installers lives at
4
+ https://github.com/csound-plugins/csound-plugins.github.io and is published at
5
+ https://csound-plugins.github.io/. Copies are bundled under
6
+ ``getcsound/data/`` so that installing Csound does not depend on any external
7
+ Python package.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib.resources
13
+ import os
14
+ import platform
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+
20
+ from ._errors import CsoundInstallError, CsoundNotFoundError
21
+ from ._locate import (
22
+ CsoundInstallation,
23
+ _linux_candidates,
24
+ _macos_candidates,
25
+ _windows_candidates,
26
+ find_csound,
27
+ )
28
+ from ._util import logger, run_installer, stdin_is_tty
29
+
30
+ _CSOUND_SH_URL = "https://csound-plugins.github.io/getcsound.sh"
31
+ _CSOUND_PS1_URL = "https://csound-plugins.github.io/getcsound.ps1"
32
+
33
+ _DISABLED_VALUES = {"0", "false", "no", "off"}
34
+
35
+ _ADMIN_CHECK = (
36
+ "$p = New-Object Security.Principal.WindowsPrincipal("
37
+ "[Security.Principal.WindowsIdentity]::GetCurrent()); "
38
+ "if ($p.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) "
39
+ "{ exit 0 } else { exit 1 }"
40
+ )
41
+
42
+
43
+ def _bundled_installer(name: str):
44
+ installer = importlib.resources.files(__package__).joinpath("data", name)
45
+ if not installer.is_file():
46
+ raise CsoundInstallError(f"The bundled installer was not found: {installer}")
47
+ return installer
48
+
49
+
50
+ def _manual_install_hint() -> str:
51
+ if sys.platform.startswith("win"):
52
+ return ("Csound 7 can be installed from a PowerShell session with:\n"
53
+ f" irm {_CSOUND_PS1_URL} | iex")
54
+ if sys.platform in ("linux", "darwin"):
55
+ return ("Csound 7 can be installed with:\n"
56
+ f" curl -fsSL {_CSOUND_SH_URL} | bash")
57
+ return "See https://github.com/csound/csound/releases for Csound 7 packages."
58
+
59
+
60
+ def install_disabled() -> bool:
61
+ """Return True if automatic installation has been disabled by the user.
62
+
63
+ ``GETCSOUND_INSTALL`` is checked first; ``LIBCSOUND_INSTALL`` is accepted as
64
+ a compatibility alias. A value of ``0``, ``false``, ``no`` or ``off``
65
+ disables installation.
66
+ """
67
+ for name in ("GETCSOUND_INSTALL", "LIBCSOUND_INSTALL"):
68
+ value = os.environ.get(name)
69
+ if value is not None:
70
+ return value.strip().lower() in _DISABLED_VALUES
71
+ return False
72
+
73
+
74
+ def install_csound_linux(quiet: bool = True) -> CsoundInstallation:
75
+ """Install Csound 7 on Linux by running the bundled installer.
76
+
77
+ This runs the bundled copy of the official installer at
78
+ https://csound-plugins.github.io/getcsound.sh with bash. The installer
79
+ downloads the portable Csound 7 release from the
80
+ ``csound-plugins/csound-plugins`` GitHub repository, verifies its SHA-256
81
+ checksum and installs it. ``--no-risset`` is always passed so that risset is
82
+ never installed.
83
+
84
+ When running inside a terminal the installer is run interactively;
85
+ otherwise it is run with ``--user -y`` so that Csound is installed to
86
+ ``~/.local/csound`` without prompting.
87
+
88
+ After a successful installation, the environment variables
89
+ ``LIBCSOUNDPATH`` and ``OPCODE7DIR64`` point to the installed library and
90
+ plugin directory, so that the current process can find Csound without
91
+ opening a new terminal.
92
+
93
+ Args:
94
+ quiet: only print essential installer output.
95
+
96
+ Returns:
97
+ the newly installed Csound installation.
98
+
99
+ Raises:
100
+ CsoundInstallError: if the bundled installer could not be found or
101
+ failed, or if Csound could not be located after installation.
102
+ """
103
+ installer = _bundled_installer("getcsound.sh")
104
+ hint = ("Csound can also be installed manually:\n"
105
+ f" curl -fsSL {_CSOUND_SH_URL} | bash")
106
+
107
+ # as_file() yields a real filesystem path, extracting to a temporary file
108
+ # first when the package is loaded from an archive (e.g. a zip).
109
+ with importlib.resources.as_file(installer) as script:
110
+ options = ["bash", str(script), "--no-risset"]
111
+ if not stdin_is_tty():
112
+ # No terminal (e.g. on CI): install for the current user and answer
113
+ # yes to any prompt, so that no password is needed and the
114
+ # installer does not block waiting for input.
115
+ options.extend(["--user", "-y"])
116
+ if quiet:
117
+ options.append("--quiet")
118
+ run_installer(options, failure_hint=hint)
119
+
120
+ # Make the freshly installed Csound available to the current process.
121
+ for candidate in _linux_candidates():
122
+ if not candidate.libpath.exists():
123
+ continue
124
+ if candidate.plugindir is None or not candidate.plugindir.is_dir():
125
+ raise CsoundInstallError(
126
+ f"Csound 7 installation failed: plugin directory "
127
+ f"'{candidate.plugindir}' was not found")
128
+ installation = CsoundInstallation(candidate.libpath.resolve(),
129
+ candidate.plugindir.resolve())
130
+ installation.update_environ()
131
+ logger.info("Csound installed successfully to %s", candidate.libpath.parent)
132
+ return installation
133
+
134
+ raise CsoundInstallError(
135
+ "Csound 7 installation failed: libcsound64.so was not found in any of "
136
+ "the standard locations")
137
+
138
+
139
+ def install_csound_macos(quiet: bool = True) -> CsoundInstallation:
140
+ """Install the latest Csound 7 .pkg for macOS by running the installer.
141
+
142
+ The official Csound 7 macOS package is produced by the ``csound_builds``
143
+ workflow of the csound/csound repository on the ``develop`` branch and is
144
+ installed with the system ``installer`` under sudo. An interactive terminal
145
+ session is used when available (so sudo can prompt for the password). When
146
+ there is no terminal (e.g. on CI) the install still succeeds if sudo is
147
+ configured to run password-less.
148
+
149
+ This runs the bundled copy of the one-line installer used at
150
+ https://csound-plugins.github.io/getcsound.sh, which resolves the latest
151
+ successful workflow run, downloads its ``csound-7.*-macos*`` artifact
152
+ through the anonymous nightly.link mirror and installs the extracted .pkg.
153
+ ``--no-risset`` is always passed so that risset is never installed.
154
+
155
+ After installation the environment variables ``LIBCSOUNDPATH`` and
156
+ ``OPCODE7DIR64`` point to the installed library and plugin directory, so
157
+ that the current process can find Csound immediately without opening a new
158
+ session.
159
+
160
+ Args:
161
+ quiet: only print essential installer output.
162
+
163
+ Returns:
164
+ the newly installed Csound installation.
165
+
166
+ Raises:
167
+ CsoundInstallError: if the bundled installer could not be found or
168
+ failed, or if no Csound installation could be located afterwards.
169
+ """
170
+ installer = _bundled_installer("getcsound.sh")
171
+ hint = ("The Csound macOS .pkg is installed with sudo and needs an "
172
+ "interactive terminal (or passwordless sudo).\n"
173
+ "Alternatively, Csound can be installed manually:\n"
174
+ f" curl -fsSL {_CSOUND_SH_URL} | bash")
175
+ with importlib.resources.as_file(installer) as script:
176
+ args = ["bash", str(script), "--no-risset"]
177
+ if quiet:
178
+ args.append("--quiet")
179
+ run_installer(args, failure_hint=hint)
180
+
181
+ for candidate in _macos_candidates():
182
+ if not candidate.libpath.exists():
183
+ continue
184
+ installation = CsoundInstallation(
185
+ candidate.libpath.resolve(),
186
+ candidate.plugindir.resolve()
187
+ if candidate.plugindir is not None and candidate.plugindir.is_dir()
188
+ else None)
189
+ installation.update_environ()
190
+ logger.info("Csound installed successfully to %s",
191
+ candidate.libpath.parents[1])
192
+ return installation
193
+
194
+ raise CsoundInstallError(
195
+ "Csound 7 installation failed: CsoundLib64 was not found in "
196
+ "/Applications/Csound")
197
+
198
+
199
+ def _find_powershell() -> str:
200
+ # Prefer PowerShell 7. Windows PowerShell 5.1's Expand-Archive -Force can
201
+ # fail with "Cannot find an overload for ExtractToDirectory ... argument
202
+ # count: 3" on .NET Framework, so use pwsh when it is available and fall
203
+ # back to the built-in powershell otherwise.
204
+ powershell = shutil.which("pwsh") or shutil.which("powershell")
205
+ if not powershell:
206
+ raise CsoundInstallError(
207
+ "PowerShell was not found. It is needed to install Csound on "
208
+ "Windows.\nAlternatively, Csound can be installed manually:\n"
209
+ f" irm {_CSOUND_PS1_URL} | iex")
210
+ return powershell
211
+
212
+
213
+ def _windows_is_admin(powershell: str | None = None) -> bool:
214
+ """Return True if the current Windows session is elevated.
215
+
216
+ This asks PowerShell directly, so it works without :mod:`ctypes` (which
217
+ ``getcsound`` deliberately does not use). Returns False when the check
218
+ cannot confirm elevation, so callers fail with a helpful message rather
219
+ than assuming admin rights.
220
+ """
221
+ if powershell is None:
222
+ powershell = shutil.which("pwsh") or shutil.which("powershell")
223
+ if not powershell:
224
+ logger.debug("Could not determine Windows elevation status: "
225
+ "PowerShell was not found")
226
+ return False
227
+ try:
228
+ result = subprocess.run(
229
+ [powershell, "-NoProfile", "-NonInteractive", "-Command", _ADMIN_CHECK],
230
+ stdout=subprocess.DEVNULL,
231
+ stderr=subprocess.DEVNULL,
232
+ timeout=30,
233
+ check=False,
234
+ )
235
+ except (OSError, subprocess.SubprocessError) as e:
236
+ logger.debug("Could not determine Windows elevation status: %s", e)
237
+ return False
238
+ return result.returncode == 0
239
+
240
+
241
+ def install_csound_windows(quiet: bool = True) -> CsoundInstallation:
242
+ """Install the latest Csound 7 for Windows by running the installer.
243
+
244
+ This runs the bundled copy of the official installer at
245
+ https://csound-plugins.github.io/getcsound.ps1 with Windows PowerShell. The
246
+ installer resolves the latest successful ``csound_builds`` workflow run of
247
+ the ``csound/csound`` repository on the ``develop`` branch, downloads the
248
+ Windows x86_64 Inno Setup package and installs it silently to
249
+ ``%ProgramFiles%\\Csound7``. Windows on ARM64 is not supported yet.
250
+
251
+ The package is installed machine-wide and needs admin rights: when the
252
+ current session is not elevated the installer triggers a UAC prompt, so an
253
+ interactive (or pre-elevated) session is required. On CI runners the
254
+ session is usually already elevated. ``--no-risset`` is always passed so
255
+ that risset is never installed.
256
+
257
+ After a successful installation the environment variables
258
+ ``LIBCSOUNDPATH`` and ``OPCODE7DIR64`` point to the installed library and
259
+ plugin folder, and the Csound ``bin`` directory is prepended to ``PATH``,
260
+ so that the current process can find Csound immediately without opening a
261
+ new terminal.
262
+
263
+ Args:
264
+ quiet: pass ``--quiet`` to the installer to only print essential
265
+ output.
266
+
267
+ Returns:
268
+ the newly installed Csound installation.
269
+
270
+ Raises:
271
+ CsoundInstallError: if the architecture is unsupported, PowerShell or
272
+ the bundled installer could not be found, the session is not
273
+ elevated, the installer failed, or no Csound installation could be
274
+ located afterwards.
275
+ """
276
+ machine = platform.machine().lower()
277
+ if machine in ("arm64", "aarch64"):
278
+ raise CsoundInstallError(
279
+ f"Windows on ARM64 (detected: '{platform.machine()}') is not "
280
+ "supported by the automatic Csound installer, which provides an "
281
+ "x86_64 package only.\n"
282
+ "Install Csound manually (e.g. from "
283
+ "https://github.com/csound/csound/releases) and point "
284
+ "LIBCSOUNDPATH at the installed csound7_64.dll.")
285
+
286
+ powershell = _find_powershell()
287
+
288
+ if not _windows_is_admin(powershell):
289
+ if stdin_is_tty():
290
+ logger.warning("The Csound Windows installer installs machine-wide "
291
+ "and needs admin rights; the installer will request "
292
+ "elevation (UAC prompt).")
293
+ else:
294
+ raise CsoundInstallError(
295
+ "The Csound Windows installer installs machine-wide and needs "
296
+ "admin rights, but the current session is not elevated and "
297
+ "there is no interactive terminal to show the UAC prompt.\n"
298
+ "Run from an interactive (or already elevated) PowerShell "
299
+ "session, or install Csound manually:\n"
300
+ f" irm {_CSOUND_PS1_URL} | iex")
301
+
302
+ installer = _bundled_installer("getcsound.ps1")
303
+ hint = ("The Csound Windows installer installs machine-wide and needs "
304
+ "admin rights: run it from an interactive (or elevated) "
305
+ "PowerShell session.\n"
306
+ "Alternatively, Csound can be installed manually:\n"
307
+ f" irm {_CSOUND_PS1_URL} | iex")
308
+ with importlib.resources.as_file(installer) as script:
309
+ args = [powershell, "-NoProfile", "-ExecutionPolicy", "Bypass",
310
+ "-File", str(script), "--no-risset"]
311
+ if quiet:
312
+ args.append("--quiet")
313
+ run_installer(args, failure_hint=hint)
314
+
315
+ for candidate in _windows_candidates():
316
+ if not candidate.libpath.is_file():
317
+ continue
318
+ installation = CsoundInstallation(
319
+ candidate.libpath.resolve(),
320
+ candidate.plugindir.resolve()
321
+ if candidate.plugindir is not None and candidate.plugindir.is_dir()
322
+ else None,
323
+ candidate.bindir.resolve()
324
+ if candidate.bindir is not None and candidate.bindir.is_dir()
325
+ else None)
326
+ installation.update_environ()
327
+ logger.info("Csound installed successfully to %s",
328
+ candidate.libpath.parent.parent)
329
+ return installation
330
+
331
+ first = _windows_candidates()[0]
332
+ raise CsoundInstallError(
333
+ f"Csound 7 installation failed: csound7_64.dll (or csound64.dll) was "
334
+ f"not found in '{first.bindir}'")
335
+
336
+
337
+ def install_csound(quiet: bool = True) -> CsoundInstallation:
338
+ """Install Csound 7 for the current platform.
339
+
340
+ Dispatches to :func:`install_csound_linux`, :func:`install_csound_macos`
341
+ or :func:`install_csound_windows`. The newly installed installation is
342
+ returned and the environment of the current process is updated so that
343
+ ``LIBCSOUNDPATH`` and ``OPCODE7DIR64`` point at it.
344
+ """
345
+ if sys.platform == "linux":
346
+ return install_csound_linux(quiet=quiet)
347
+ if sys.platform == "darwin":
348
+ return install_csound_macos(quiet=quiet)
349
+ if sys.platform.startswith("win"):
350
+ return install_csound_windows(quiet=quiet)
351
+ raise CsoundInstallError(
352
+ f"Automatic Csound installation is not supported on {sys.platform!r}.\n"
353
+ + _manual_install_hint())
354
+
355
+
356
+ def ensure_csound(quiet: bool = True,
357
+ install: bool | None = None) -> CsoundInstallation:
358
+ """Return a usable Csound 7 installation, installing it if necessary.
359
+
360
+ This is the main entry point for packages that want Csound to be available
361
+ without asking the user to install it manually. If Csound is already
362
+ installed, its environment variables are applied to the current process.
363
+ Otherwise the official installer is run and the result is returned.
364
+
365
+ Args:
366
+ quiet: only print essential installer output.
367
+ install: whether to install Csound when it cannot be found. If None,
368
+ automatic installation is enabled unless ``GETCSOUND_INSTALL`` (or
369
+ the compatibility alias ``LIBCSOUND_INSTALL``) is set to ``0``,
370
+ ``false``, ``no`` or ``off``.
371
+
372
+ Returns:
373
+ the Csound installation. ``LIBCSOUNDPATH`` and, when known,
374
+ ``OPCODE7DIR64`` are set in :data:`os.environ`.
375
+
376
+ Raises:
377
+ CsoundNotFoundError: if Csound was not found, ``LIBCSOUNDPATH`` points
378
+ to a missing file, or installation is disabled.
379
+ CsoundInstallError: if automatic installation was attempted and
380
+ failed.
381
+ """
382
+ libcsoundpath = os.environ.get("LIBCSOUNDPATH")
383
+ if libcsoundpath and not Path(libcsoundpath).expanduser().is_file():
384
+ raise CsoundNotFoundError(
385
+ f"The environment variable LIBCSOUNDPATH '{libcsoundpath}' does "
386
+ "not point to an existing file")
387
+
388
+ found = find_csound()
389
+ if found is not None:
390
+ found.update_environ()
391
+ return found
392
+
393
+ if install is None:
394
+ install = not install_disabled()
395
+ if not install:
396
+ raise CsoundNotFoundError(
397
+ "Csound 7 was not found and automatic installation is disabled.\n"
398
+ + _manual_install_hint())
399
+
400
+ return install_csound(quiet=quiet)
getcsound/_locate.py ADDED
@@ -0,0 +1,191 @@
1
+ """Locate an existing Csound 7 installation without importing libcsound.
2
+
3
+ The locations listed here are the ones used by the official Csound 7
4
+ installers on Linux, macOS and Windows. Set ``LIBCSOUNDPATH`` (and optionally
5
+ ``OPCODE7DIR64``) to point at an installation in a non-standard location.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import os
11
+ import sys
12
+ from collections.abc import MutableMapping
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ _LINUX_USER_LIB = Path(".local/csound/libcsound64.so")
17
+ _LINUX_USER_PLUGINS = Path(".local/lib/csound/7.0/plugins64")
18
+ _LINUX_SYSTEM_LIB = Path("/usr/local/lib/libcsound64.so")
19
+ _LINUX_SYSTEM_PLUGINS = Path("/usr/local/lib/csound/plugins64-7.0")
20
+
21
+ _MACOS_CSOUND_DIR = Path("/Applications/Csound")
22
+ _MACOS_LIB = (_MACOS_CSOUND_DIR / "CsoundLib64.framework" / "CsoundLib64")
23
+ _MACOS_PLUGINS = (_MACOS_CSOUND_DIR / "CsoundLib64.framework" / "Resources"
24
+ / "Opcodes64")
25
+
26
+ _WINDOWS_CSOUND_DIR = "Csound7"
27
+ # Csound 7 uses csound7_64.dll (double precision); csound64.dll is the
28
+ # Csound 6 name and is kept as a fallback for older Csound 7 builds.
29
+ _WINDOWS_LIB_NAMES = ("csound7_64.dll", "csound64.dll")
30
+ _WINDOWS_PLUGINS = Path("plugins64")
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class CsoundInstallation:
35
+ """A Csound 7 installation found on this system.
36
+
37
+ Attributes:
38
+ libpath: absolute path to the Csound shared library.
39
+ plugindir: directory containing the Csound plugins, if known.
40
+ bindir: directory containing the Csound DLLs on Windows, if known. It
41
+ is added to ``PATH`` so that dependencies such as libsndfile can be
42
+ resolved when the library is loaded.
43
+ """
44
+
45
+ libpath: Path
46
+ plugindir: Path | None = None
47
+ bindir: Path | None = None
48
+
49
+ def as_env(self) -> dict[str, str]:
50
+ """Return the environment variables needed to use this installation.
51
+
52
+ The keys are the ones understood by ``libcsound`` (and by other
53
+ packages using Csound):
54
+
55
+ * ``LIBCSOUNDPATH``: absolute path to the Csound shared library.
56
+ * ``OPCODE7DIR64``: plugin directory, if known.
57
+ """
58
+ env = {"LIBCSOUNDPATH": str(self.libpath)}
59
+ if self.plugindir is not None:
60
+ env["OPCODE7DIR64"] = str(self.plugindir)
61
+ return env
62
+
63
+ def update_environ(self,
64
+ environ: MutableMapping[str, str] | None = None) -> None:
65
+ """Make this installation available to the current process.
66
+
67
+ Sets ``LIBCSOUNDPATH`` and, when known, ``OPCODE7DIR64``. On Windows
68
+ the ``bin`` directory is also prepended to ``PATH`` (without creating
69
+ duplicates), because dependent DLLs are resolved through it.
70
+
71
+ Args:
72
+ environ: mapping to update. Defaults to :data:`os.environ`.
73
+ """
74
+ environ = os.environ if environ is None else environ
75
+ environ.update(self.as_env())
76
+ if self.bindir is None:
77
+ return
78
+
79
+ bindir = str(self.bindir)
80
+ current = environ.get("PATH", "")
81
+ entries = current.split(os.pathsep) if current else []
82
+ if bindir not in entries:
83
+ entries.insert(0, bindir)
84
+ environ["PATH"] = os.pathsep.join(entries)
85
+
86
+
87
+ def _normalize(installation: CsoundInstallation) -> CsoundInstallation | None:
88
+ """Return an installation with only existing paths, or None."""
89
+ libpath = installation.libpath
90
+ if not libpath.is_file():
91
+ return None
92
+ plugindir = installation.plugindir
93
+ if plugindir is not None and not plugindir.is_dir():
94
+ plugindir = None
95
+ bindir = installation.bindir
96
+ if bindir is not None and not bindir.is_dir():
97
+ bindir = None
98
+ return CsoundInstallation(libpath.resolve(),
99
+ plugindir.resolve() if plugindir is not None else None,
100
+ bindir.resolve() if bindir is not None else None)
101
+
102
+
103
+ def _linux_candidates() -> list[CsoundInstallation]:
104
+ home = Path.home()
105
+ return [
106
+ CsoundInstallation(home / _LINUX_USER_LIB, home / _LINUX_USER_PLUGINS),
107
+ CsoundInstallation(_LINUX_SYSTEM_LIB, _LINUX_SYSTEM_PLUGINS),
108
+ ]
109
+
110
+
111
+ def _macos_candidates() -> list[CsoundInstallation]:
112
+ return [CsoundInstallation(_MACOS_LIB, _MACOS_PLUGINS)]
113
+
114
+
115
+ def _windows_candidates() -> list[CsoundInstallation]:
116
+ candidates: list[CsoundInstallation] = []
117
+ seen: set[str] = set()
118
+ for var in ("ProgramW6432", "ProgramFiles"):
119
+ value = os.environ.get(var)
120
+ if value and value not in seen:
121
+ seen.add(value)
122
+ candidates.extend(_windows_candidates_for(Path(value)))
123
+ # This mirrors the fallback used by the installers when the environment
124
+ # variable is not set.
125
+ if r"C:\Program Files" not in seen:
126
+ candidates.extend(_windows_candidates_for(Path(r"C:\Program Files")))
127
+ return candidates
128
+
129
+
130
+ def _windows_candidates_for(program_files: Path) -> list[CsoundInstallation]:
131
+ csound_dir = program_files / _WINDOWS_CSOUND_DIR
132
+ return [
133
+ CsoundInstallation(csound_dir / "bin" / libname,
134
+ csound_dir / _WINDOWS_PLUGINS,
135
+ csound_dir / "bin")
136
+ for libname in _WINDOWS_LIB_NAMES
137
+ ]
138
+
139
+
140
+ def _from_environment() -> CsoundInstallation | None:
141
+ value = os.environ.get("LIBCSOUNDPATH")
142
+ if not value:
143
+ return None
144
+ libpath = Path(value).expanduser()
145
+ if not libpath.is_file():
146
+ return None
147
+
148
+ plugindir: Path | None = None
149
+ plugins = os.environ.get("OPCODE7DIR64")
150
+ if plugins:
151
+ candidate = Path(plugins).expanduser()
152
+ if candidate.is_dir():
153
+ plugindir = candidate
154
+
155
+ bindir: Path | None = None
156
+ if sys.platform.startswith("win"):
157
+ candidate = libpath.parent
158
+ if candidate.is_dir():
159
+ bindir = candidate
160
+ return _normalize(CsoundInstallation(libpath, plugindir, bindir))
161
+
162
+
163
+ def find_csound() -> CsoundInstallation | None:
164
+ """Find an existing Csound 7 installation.
165
+
166
+ ``LIBCSOUNDPATH`` is checked first. If it is unset or does not point to an
167
+ existing file, the standard installation locations for the current
168
+ platform are searched. No installation is attempted and the environment is
169
+ not modified.
170
+
171
+ Returns:
172
+ the installation, or None if no Csound library was found.
173
+ """
174
+ from_env = _from_environment()
175
+ if from_env is not None:
176
+ return from_env
177
+
178
+ if sys.platform == "linux":
179
+ candidates = _linux_candidates()
180
+ elif sys.platform == "darwin":
181
+ candidates = _macos_candidates()
182
+ elif sys.platform.startswith("win"):
183
+ candidates = _windows_candidates()
184
+ else:
185
+ return None
186
+
187
+ for candidate in candidates:
188
+ installation = _normalize(candidate)
189
+ if installation is not None:
190
+ return installation
191
+ return None