diff --git a/.github/workflows/style.yml b/.github/workflows/style.yml index 0b8cb69..d760b22 100644 --- a/.github/workflows/style.yml +++ b/.github/workflows/style.yml @@ -62,7 +62,7 @@ jobs: # Scope diagnostics to this object's and the core's own headers: a path # filter over source/projects would also match the bundled CPython # headers, which are reached via …/tap.python_tilde/../../../support/… . - hf='.*/(tap\.python_tilde/tap\.python_tilde|core/(include|tests|bench)/).*' + hf='.*/(tap\.python_tilde/tap\.python|core/(include|tests|bench)/).*' fail=0 check() { # # a finding, a compile error, or clang-tidy itself failing (non-zero exit with or diff --git a/CLAUDE.md b/CLAUDE.md index c99ff7e..d30c1ad 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,9 +39,13 @@ built yet. interval). `scripts/update-perf-docs.py` builds it (Release), runs it, and rewrites the ReadMe's generated performance tables — with `--max`, Max's CPU meter too, through `runtime-tests/run.py --session perf`. Never hand-edit those tables; measure on an idle machine. -- **`source/projects/tap.python_tilde/`** — the Min external: package paths, the file watcher, atom - conversion, and mapping the core's descriptions onto `object_addattr`/`object_addmethod`. Its - `_test.cpp` drives the Max glue through min-api's mock kernel. +- **`source/projects/tap.python_tilde/`** — the Min external (`tap.python_tilde.h`) over the shared + glue (plan 9.2), which `tap.python` (9.3) will use too: `tap.python_glue.h` — starting the runtime, + atom conversion, the reserved names (`reserved_messages(audio)`) and the guard, and mapping the + core's descriptions onto `object_addattr`/`object_addmethod`, with the C trampolines instantiated + per host type (`python_glue`, through `Host::self()`) — plus the package paths + (`tap.python_package.h`) and the file watcher (`tap.python_filewatch.h`). Its `_test.cpp` drives + the Max glue through min-api's mock kernel. - **`python/`** — the user's script folder in the package (and the examples: `default.py`, `numpy_gain.py`, `allpass.py`, `numpy_allpass.py` — the same filter per vector, checked equal sample for sample by the core battery — `stereo_width.py`, two inputs and two outputs, and @@ -136,14 +140,14 @@ attaches all the zips + SHA256s to a release — a pre-release for 0.x, a draft - Max calls some methods directly with C arguments (`A_CANT`): the file watcher's `filechanged` is one. min registers a `message<>` whose name it does not special-case with its `A_GIMME` wrapper, which such a call crashes — so - the watcher is owned by a nobox helper with the SDK's signature (`tap.python_tilde_filewatch.h`). + the watcher is owned by a nobox helper with the SDK's signature (`tap.python_filewatch.h`). Check the SDK's calling convention before exposing a Max-called method as a `message<>`. And read the SDK's return contract before testing a Max call's result: `object_getmethod()` answers `method_false()`, a function, not null, for a name an object does not have — a null test reserved every Python name in 1.0.0. **Never compare a function pointer Max returns with the address of a function this module imports:** across a DLL boundary the module's `&method_false` is its own import thunk (the SDK declares it without `dllimport`), so 1.0.1's - comparison reserved every name again, on Windows only. The object asks Max what it answers for a + comparison reserved every name again, on Windows only. The glue asks Max what it answers for a name no class can have (`not_found_method()`) and compares with that (`found_method()`, 1.0.2). And what the object itself registers can answer its name too — its *attributes* do, and the guard must leave them out, or a reload reserves every field (1.0.1, found in Max); its messages, added diff --git a/docs/PRODUCTION-PLAN.md b/docs/PRODUCTION-PLAN.md index fc566f9..cebb5ee 100644 --- a/docs/PRODUCTION-PLAN.md +++ b/docs/PRODUCTION-PLAN.md @@ -815,7 +815,7 @@ row shipped what only a host platform could show. the release is 2.0.0, decided 2026-10-09); announce-once per (file, kind); the `Loaded` line per binding. `test_output.cpp`, the output table over its edges, the new examples on known inputs, and a bench row for a message call. `tap.python~` unchanged and green. -- [ ] **9.2 The shared glue:** the attribute, message, trampoline, file-watcher and package headers +- [x] **9.2 The shared glue** (#47)**:** the attribute, message, trampoline, file-watcher and package headers as `python_glue`; `reserved_messages()` parameterized by the audio names. A pure move. - [ ] **9.3 The object:** `tap.python.h` in the project, a plain SDK class registered by the project's `ext_main` — ports with the dumpout and the object's lock, the output mapping, the diff --git a/docs/TAP-PYTHON-PLAN.md b/docs/TAP-PYTHON-PLAN.md index 4e09b99..c37cb57 100644 --- a/docs/TAP-PYTHON-PLAN.md +++ b/docs/TAP-PYTHON-PLAN.md @@ -373,10 +373,18 @@ third was Windows-only. running, a message with 64 numbers in and out measured 5.6 µs for the bridge alone and 15 µs for `scale.py`, and `main` and the branch measured alike back to back.)* No Max code changes; `tap.python~`'s battery and glue test unchanged and green; the audio bench numbers unchanged (the audio path does not touch the new code). -- [ ] **9.2 The shared glue.** `tap.python_tilde_{attribute,message,cglue,filewatch,package}.h` +- [x] **9.2 The shared glue** (#47). `tap.python_tilde_{attribute,message,cglue,filewatch,package}.h` become `python_glue` (the trampolines instantiated per host through `Host::self()`), in `source/shared/tap/python_max/` or beside the object; `reserved_messages()` parameterized by the audio names. A pure move: `tap.python~`'s behavior, tests and the data-import check unchanged. + *(Done beside the object, as one binary builds both: `tap.python_glue.h` holds `python_attr`, + `python_message` and `python_members` (the attributes and messages made for a class, their + reconciliation, attribute access and the guard) on the host, the trampolines, `start_runtime()`, + `watch_source()` and `to_values()`; the file watcher and package paths are + `tap.python_{filewatch,package}.h`. The same 53 reserved names in the same order; the glue test + pins what an audio object reserves beyond every object's; every runtime test passes in Max 9.1.5. + For 9.3: `reserved_messages(false)` still has 8.2's `anything`, which `tap.python`, exposing a + class's `anything`, takes out — and adds `dumpout`.)* - [ ] **9.3 The object.** `tap.python.h` and its TU in the project, registered by the project's `ext_main` (replacing the 9.0 spike's TU and its CMake option); ports with the dumpout, its `dumpout` method and the lock; output mapping (a `str` as `symbol `); the `anything` forwarder @@ -579,7 +587,7 @@ own log (`Logs/Max.log`) has every console line with its thread, but not a `[pri And methods added with `object_addmethod()` are not found by `object_getmethod()` (4 above) — CLAUDE.md said an object's own messages answer their names, as its attributes do; only the attributes do, which the guard was right to leave out either way (CLAUDE.md now says so; the -comment on `answered_by_max()` says the same, for 9.2's move to correct). +comment on `answered_by_max()` said the same, and 9.2's move corrected it). **On Windows, learned on the way** (for 9.5 and 9.6, which run Windows by hand). A patcher opened together with Max (`Max.exe ""`, as Explorer opens one) had its scheduler held for diff --git a/scripts/assemble-package.py b/scripts/assemble-package.py index 05ecc29..f6b6f66 100644 --- a/scripts/assemble-package.py +++ b/scripts/assemble-package.py @@ -65,7 +65,7 @@ # Each platform's folder for its runtime in a package for every platform (plan 4.8); the external -# names its own (runtime_platform() in tap.python_tilde_package.h). +# names its own (runtime_platform() in tap.python_package.h). RUNTIME_PLATFORMS = ["macos-arm64", "macos-x86_64", "windows-x64"] # What differs between single-platform packages, and is merged rather than copied once. diff --git a/source/projects/tap.python_tilde/CMakeLists.txt b/source/projects/tap.python_tilde/CMakeLists.txt index d1de4bf..019d0dc 100644 --- a/source/projects/tap.python_tilde/CMakeLists.txt +++ b/source/projects/tap.python_tilde/CMakeLists.txt @@ -71,10 +71,9 @@ include_directories( set(SOURCE_FILES ${PROJECT_NAME}.h - ${PROJECT_NAME}_package.h - ${PROJECT_NAME}_cglue.h - ${PROJECT_NAME}_attribute.h - ${PROJECT_NAME}_message.h + tap.python_glue.h + tap.python_filewatch.h + tap.python_package.h ${PROJECT_NAME}.cpp ) diff --git a/source/projects/tap.python_tilde/tap.python_tilde_filewatch.h b/source/projects/tap.python_tilde/tap.python_filewatch.h similarity index 96% rename from source/projects/tap.python_tilde/tap.python_tilde_filewatch.h rename to source/projects/tap.python_tilde/tap.python_filewatch.h index 7ef5bea..a22866e 100644 --- a/source/projects/tap.python_tilde/tap.python_tilde_filewatch.h +++ b/source/projects/tap.python_tilde/tap.python_filewatch.h @@ -1,4 +1,4 @@ -/// @file tap.python_tilde_filewatch.h +/// @file tap.python_filewatch.h /// @brief Watches the class file, and delivers a save to the object as its filechanged message. // SPDX-License-Identifier: MIT // Copyright 2022-2026 Timothy Place. @@ -22,7 +22,7 @@ namespace tap::python { struct file_watch_object { c74::max::t_object header; - c74::max::t_object* target; // the tap.python~ object told of each save + c74::max::t_object* target; // the object told of each save }; /// Called by Max's file watcher, on the main thread. diff --git a/source/projects/tap.python_tilde/tap.python_glue.h b/source/projects/tap.python_tilde/tap.python_glue.h new file mode 100644 index 0000000..bd9faff --- /dev/null +++ b/source/projects/tap.python_tilde/tap.python_glue.h @@ -0,0 +1,596 @@ +/// @file tap.python_glue.h +/// @brief The Max side every object over the core shares: its runtime, its attributes and messages. +// SPDX-License-Identifier: MIT +// Copyright 2022-2026 Timothy Place. +// +// tap.python~ (a min object) and tap.python (a plain SDK class, plan 9.3) both map a Python class +// onto Max through the core (core/include/tap/python/), and what is the same for both lives here, +// once (plan 9.2): starting the interpreter against the package's runtime, with Python's output +// posted from Max's main thread; watching the class file; the names Max answers itself, and the +// guard that keeps a Python name from replacing one; and the Max attributes and messages made for +// the class's fields and methods, with the C trampolines Max calls for them. +// +// The trampolines are instantiated per host type (python_glue): each finds the object Max +// called through Host::self() and calls its attr_set(), attr_get() or message_gimme(). + +#pragma once + +// The core includes CPython, which insists on preceding system headers. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "c74_min_api.h" +#include "tap.python_filewatch.h" +#include "tap.python_package.h" +#include "tap/python/processor.h" +#include "tap/python/runtime.h" +#include "tap/python/value.h" + +namespace tap::python { + + // ---- the runtime --------------------------------------------------------------------------- + + namespace detail { + + /// Python's print() output and tracebacks, for every object. + inline void console_line(const log_level level, const std::string_view text) { + const std::string line{text}; + if (level == log_level::error) { + c74::max::object_error(nullptr, "python: %s", line.c_str()); + } + else { + c74::max::object_post(nullptr, "python: %s", line.c_str()); + } + } + + /// Whether this is Max's main thread: where Python's output may be posted at once. On any + /// other thread — the audio thread, a worker, the scheduler — the core queues the line (plan 8.4). + inline bool is_main_thread() { + return c74::max::systhread_ismainthread() != 0; + } + + /// Called on the printing thread when the core queued a line: sets the process-wide qelem that + /// has the lines posted from the main thread. Real-time safe (qelem_set). + inline void console_ready() { + static c74::max::t_qelem* s_flush = + c74::max::qelem_new(nullptr, reinterpret_cast(+[](void*) { flush_console(); })); + c74::max::qelem_set(s_flush); + } + + } // namespace detail + + /// What start_runtime() found: the package's script folder, or why Python cannot run. + struct runtime_start { + bool ok{}; + std::filesystem::path scripts_dir; ///< /python + std::string error; ///< what to tell the user, when not ok + }; + + /// Start the embedded interpreter against this package's runtime and python folder, with + /// Python's output posted from Max's main thread (plan 8.4). Once per process: an object after + /// the first finds it running. Main thread. + inline runtime_start start_runtime() { + runtime_start result; + const auto package = package_root(); + result.scripts_dir = package / "python"; +#ifdef TAP_PYTHON_HOME + // Linux development builds embed a system CPython instead of a support/ runtime + // (see this project's CMakeLists.txt) + const std::filesystem::path home{TAP_PYTHON_HOME}; +#else + const auto home = runtime_home(package); // support/, or support/ (plan 4.8) +#endif + + if (!std::filesystem::exists(home)) { + result.error = "No Python runtime found at " + detail::utf8(home) + + " — run scripts/install-runtime from the package root to install it."; + return result; + } + if (std::string error; !runtime_library_loadable(home, error)) { + result.error = error; + return result; + } + + runtime_options options; + options.home = home; + options.scripts_dir = result.scripts_dir; + options.console = detail::console_line; + options.is_main_thread = detail::is_main_thread; // Python's output posts from Max's main thread only (8.4) + options.console_ready = detail::console_ready; + if (const auto status = initialize(options); !status.ok) { + result.error = "failed to start Python from '" + detail::utf8(home) + "': " + status.error + + " (run scripts/install-runtime to install the runtime)"; + return result; + } + result.ok = true; + return result; + } + + /// Watch `/.py`, telling `owner` of each save by its filechanged message (see + /// tap.python_filewatch.h). Only a plain file name is watched: the core refuses anything else + /// (e.g. "../x"), and so must the watcher — null without `error`. Null with `error` set when Max + /// cannot find the file. Main thread. + inline std::unique_ptr watch_source(c74::max::t_object* owner, const std::filesystem::path& scripts_dir, + const std::string& name, std::string& error) { + if (name.find_first_of("/\\.:") != std::string::npos) { + return nullptr; + } + const auto watched_file = scripts_dir / (name + ".py"); + const auto watched_utf8 = detail::utf8(watched_file); // Max's paths are UTF-8 (8.7) + char filename[c74::max::MAX_PATH_CHARS]{}; + std::strncpy(filename, watched_utf8.c_str(), c74::max::MAX_PATH_CHARS - 1); + short path_id{}; + c74::max::t_fourcc filetype{}; + if (c74::max::locatefile_extended(filename, &path_id, &filetype, nullptr, 0) != 0) { + error = "Unable to watch " + watched_utf8 + " for changes."; + return nullptr; + } + return std::make_unique(owner, path_id, filename); + } + + // ---- the names Max answers --------------------------------------------------------------------- + + /// The names reserved_messages() adds for an audio object: Max's and min's audio messages, and + /// tap.python~'s own attributes (worker mode's, plan 2.5). + inline std::vector audio_messages() { + return {"dsp", + "dsp64", + "dspsetup", + "dspstate", + "inputchanged", + "latency", + "latencysamples", + "mode", + "multichanneloutputs", + "signal"}; + } + + /// Messages and attributes the Max object handles itself, which a Python method or field must + /// never replace: min's own class methods, the messages Max sends every object, the file + /// watcher's filechanged (a Python method named filechanged would silently disable hot reload), + /// and with `audio`, the audio_messages(). + /// + /// Above all, every message Max sends with C arguments (plan 8.2, audit A3): a Python method + /// of such a name would be registered with the A_GIMME trampoline, and Max calling it with a + /// long or a pointer reads them as a symbol and an atom list — the crash 6.1 found for + /// filechanged, in its general form. The names are those min treats as A_CANT + /// (c74_min_message.h, message_type::cant; the MIN_WRAPPER_ADDMETHOD table in + /// c74_min_object_wrapper.h) plus Max's own dspstate, inputchanged and multichanneloutputs. + /// Anything the Max class already answers is reserved as well: python_members::answered_by_max(). + inline std::vector reserved_messages(const bool audio) { + std::vector names{"anything", + "appendtodictionary", + "assist", + "dblclick", + "dictionary", + "edclose", + "filechanged", + "fileusage", + "focusgained", + "focuslost", + "getplaystate", + "getvalueof", + "inletinfo", + "jitclass_setup", + "key", + "loadbang", + "maxclass_setup", + "maxob_setup", + "mop_setup", + "mousedoubleclick", + "mousedown", + "mousedrag", + "mousedragdelta", + "mouseenter", + "mouseleave", + "mousemove", + "mouseup", + "mousewheel", + "mt_mousedown", + "mt_mousedrag", + "mt_mouseenter", + "mt_mouseleave", + "mt_mousemove", + "mt_mouseup", + "notify", + "okclose", + "oksize", + "paint", + "patchlineupdate", + "preset", + "savestate", + "setup", + "setvalueof"}; + if (audio) { + const auto more = audio_messages(); + names.insert(names.end(), more.begin(), more.end()); + std::sort(names.begin(), names.end()); + } + return names; + } + + /// Whether object_getmethod() found a method: neither null nor `not_found`, what it answers for a + /// name the object does not have — Max's method_false(), as the SDK documents. 1.0.0 tested for + /// null alone, and 1.0.1 compared with the address of method_false as this module sees it, which + /// on Windows is the external's own import thunk (the SDK declares it without dllimport), never + /// what Max returns: either way every field and method of a class was "answered by Max", and the + /// object had no attributes and no messages. So `not_found` comes from Max (not_found_method()). + inline bool found_method(const c74::max::method found, const c74::max::method not_found) { + return found != nullptr && found != not_found; + } + + /// What object_getmethod() answers for a name `object` does not have, asked of Max for one no + /// class can have (it has spaces): Max's method_false(), whatever its address looks like from + /// here — on a class with a class-level anything too (plan 9.0). Main thread. + inline c74::max::method not_found_method(c74::max::t_object* object) { + return c74::max::object_getmethod(object, c74::max::gensym("tap.python~ answers no such name")); + } + + // ---- atoms ---------------------------------------------------------------------------------- + + /// Max atoms as core values, keeping each atom's own type (the core coerces to the + /// hinted type with the same rules as atom_getlong/atom_getfloat/atom_getsym). + inline std::vector to_values(const long ac, const c74::max::t_atom* av) { + std::vector values; + values.reserve(static_cast(ac)); + for (long i = 0; i < ac; ++i) { + const auto* atom = av + i; + switch (c74::max::atom_gettype(atom)) { + case c74::max::A_LONG: + values.emplace_back(static_cast(c74::max::atom_getlong(atom))); + break; + case c74::max::A_FLOAT: + values.emplace_back(static_cast(c74::max::atom_getfloat(atom))); + break; + default: + values.emplace_back(std::string{c74::max::atom_getsym(atom)->s_name}); + break; + } + } + return values; + } + + // ---- the trampolines Max calls ------------------------------------------------------------------ + + /// Max calls the trampolines below from C, so no C++ exception may cross back into it. + template + c74::max::t_max_err guarded(c74::max::t_object* x, const char* object_name, Fn&& fn) noexcept { + try { + fn(); + } + catch (const std::exception& e) { + c74::max::object_error(x, "%s: %s", object_name, e.what()); + } + catch (...) { + c74::max::object_error(x, "%s: unknown error", object_name); + } + return c74::max::MAX_ERR_NONE; + } + + /// The C functions Max calls for the attributes and messages made for a Python class (by + /// python_attr and python_message), one set per host type. `Host` provides + /// - `static Host* self(c74::max::t_object* x)`: the object Max called; + /// - `static constexpr const char* k_max_name`: its Max class name, for an error; + /// - `attr_set(name, argc, argv)`, `attr_get(name, argc, argv)` and `message_gimme(name, ac, av)`, + /// the name a `c74::max::t_symbol*` (or anything made from one). + template + struct python_glue { + static c74::max::t_max_err attr_set(c74::max::t_object* x, c74::max::t_object* maxattr, const long argc, + const c74::max::t_atom* argv) { + return guarded(x, Host::k_max_name, [&] { Host::self(x)->attr_set(attribute_name(maxattr), argc, argv); }); + } + + static c74::max::t_max_err attr_get(c74::max::t_object* x, c74::max::t_object* maxattr, long* argc, + c74::max::t_atom** argv) { + return guarded(x, Host::k_max_name, [&] { Host::self(x)->attr_get(attribute_name(maxattr), argc, argv); }); + } + + static c74::max::t_max_err mess_int(c74::max::t_object* x, const long value) { + return guarded(x, Host::k_max_name, [&] { + c74::max::t_atom a; + c74::max::atom_setlong(&a, value); + Host::self(x)->message_gimme(c74::max::gensym("int"), 1, &a); + }); + } + + static c74::max::t_max_err mess_float(c74::max::t_object* x, const double value) { + return guarded(x, Host::k_max_name, [&] { + c74::max::t_atom a; + c74::max::atom_setfloat(&a, value); + Host::self(x)->message_gimme(c74::max::gensym("float"), 1, &a); + }); + } + + static c74::max::t_max_err mess_symbol(c74::max::t_object* x, c74::max::t_symbol* value) { + return guarded(x, Host::k_max_name, [&] { + c74::max::t_atom a; + c74::max::atom_setsym(&a, value); + Host::self(x)->message_gimme(c74::max::gensym("symbol"), 1, &a); + }); + } + + static c74::max::t_max_err mess_bang(c74::max::t_object* x) { + return guarded(x, Host::k_max_name, + [&] { Host::self(x)->message_gimme(c74::max::gensym("bang"), 0, nullptr); }); + } + + static c74::max::t_max_err mess_gimme(c74::max::t_object* x, c74::max::t_symbol* name, const long ac, + c74::max::t_atom* av) { + return guarded(x, Host::k_max_name, [&] { Host::self(x)->message_gimme(name, ac, av); }); + } + + private: + static const c74::max::t_symbol* attribute_name(c74::max::t_object* maxattr) { + return static_cast(c74::max::object_method(maxattr, c74::min::k_sym_getname)); + } + }; + + // ---- the attributes and messages made for a class --------------------------------------------- + + /// A Max attribute dynamically added to an object, mirroring an annotated attribute of the user's + /// Python class. Instances are owned via unique_ptr in python_members; one persists across reloads + /// while the class keeps the field with the same type, and is removed otherwise. + template + class python_attr { + public: + python_attr(c74::max::t_object* owner, const std::string& name, const tap::python::value_type type) + : m_owner{owner} + , m_name{name} + , m_value_type{type} { + switch (m_value_type) { + case value_type::integer: + case value_type::boolean: + m_type = c74::min::k_sym_long; + break; + case value_type::real: + m_type = c74::min::k_sym_float64; + break; + case value_type::symbol: + case value_type::any: + m_type = c74::min::k_sym_symbol; + break; + } + + m_attrobj = c74::max::attribute_new(m_name.c_str(), m_type, 0, + reinterpret_cast(python_glue::attr_get), + reinterpret_cast(python_glue::attr_set)); + auto err = c74::max::object_addattr(m_owner, m_attrobj); + if (err) { + c74::max::object_error(m_owner, "failed to add attribute for python member '%s'", m_name.c_str()); + return; + } + err = c74::max::object_attr_addattr_parse(m_owner, m_name.c_str(), "dynamicattr", c74::min::k_sym_long, 0, + "1"); + if (err) { + c74::max::object_error(m_owner, "failed to make dynamic attribute for %s", m_name.c_str()); + } + if (m_value_type == value_type::boolean) { + // a bool field shows as a toggle in the inspector and attrui + c74::max::object_attr_addattr_parse(m_owner, m_name.c_str(), "style", c74::min::k_sym_symbol, 0, + "onoff"); + } + } + + python_attr(const python_attr&) = delete; + python_attr& operator=(const python_attr&) = delete; + + /// Detach the attribute from the Max object and free it (the class no longer has the field, + /// or its type changed). Not called at object destruction: Max frees instance attributes then. + void remove() { + if (m_attrobj) { + c74::max::object_deleteattr(m_owner, c74::max::gensym(m_name.c_str())); + m_attrobj = nullptr; + } + } + + /// The Max attribute type (long, float64 or symbol). + c74::min::symbol type() const { return m_type; } + + /// The core value type the attribute was created with; fixed for the attribute's lifetime. + tap::python::value_type value_type() const { return m_value_type; } + + private: + c74::max::t_object* m_owner; + std::string m_name; + tap::python::value_type m_value_type; + c74::min::symbol m_type; + c74::max::t_object* m_attrobj{}; + }; + + /// A Max message dynamically added to an object for a method of the user's Python class. It only + /// registers the Max method; the Python side (the bound function and its signature) is owned by + /// the core's processor, which the host's message_gimme() dispatches to by name. Instances are + /// owned via unique_ptr in python_members and rebuilt on every reload. + template + class python_message { + public: + python_message(c74::max::t_object* owner, const std::string& name) + : m_owner{owner} + , m_name{name} { + if (m_owner == nullptr) { + return; // this occurs during dummy construction + } + + using glue = python_glue; + c74::max::t_max_err err{}; + + if (m_name == "int") { + err = c74::max::object_addmethod(m_owner, reinterpret_cast(glue::mess_int), + m_name.c_str(), c74::max::A_LONG, 0); + } + else if (m_name == "float") { + err = c74::max::object_addmethod(m_owner, reinterpret_cast(glue::mess_float), + m_name.c_str(), c74::max::A_FLOAT, 0); + } + else if (m_name == "symbol") { + err = c74::max::object_addmethod(m_owner, reinterpret_cast(glue::mess_symbol), + m_name.c_str(), c74::max::A_SYM, 0); + } + else if (m_name == "bang") { + err = c74::max::object_addmethod(m_owner, reinterpret_cast(glue::mess_bang), + m_name.c_str(), 0); + } + else { + err = c74::max::object_addmethod(m_owner, reinterpret_cast(glue::mess_gimme), + m_name.c_str(), c74::max::A_GIMME, 0); + } + + if (err) { + c74::max::object_error(m_owner, "failed to add message for python method '%s'", m_name.c_str()); + } + } + + python_message(const python_message&) = delete; + python_message& operator=(const python_message&) = delete; + + private: + c74::max::t_object* m_owner; + std::string m_name; + }; + + /// The Max attributes and messages one object made for its class's fields and methods, kept in + /// step with the class across reloads; the attribute access and the guard that go with them. + template + class python_members { + public: + /// Make the Max attributes match the class's annotated fields: remove the ones the class no + /// longer has, recreate the ones whose type changed, add the new ones. (The core has already + /// carried the values of those that stayed over to the new instance.) Main thread. + void create_attributes(c74::max::t_object* owner, const processor& p) { + const auto& current = p.attributes(); + for (auto it = m_attributes.begin(); it != m_attributes.end();) { + const auto found = std::find_if(current.begin(), current.end(), + [&](const attribute_info& a) { return a.name == it->first; }); + if (found == current.end() || found->type != it->second->value_type()) { + it->second->remove(); + it = m_attributes.erase(it); + } + else { + ++it; + } + } + for (const auto& attribute : current) { + if (m_attributes.find(attribute.name) == m_attributes.end()) { + m_attributes[attribute.name] = + std::make_unique>(owner, attribute.name, attribute.type); + } + } + } + + /// Replace the previous incarnation's Max messages with the class's current methods. Main thread. + void create_messages(c74::max::t_object* owner, const processor& p) { + for (auto& element : m_messages) { + c74::max::object_deletemethod(owner, c74::max::gensym(element.first.c_str())); + } + m_messages.clear(); + + for (const auto& message : p.messages()) { // never names an attribute + m_messages[message.name] = std::make_unique>(owner, message.name); + } + } + + /// The names of the Max messages made for the class's methods, sorted (for the tests). + std::vector message_names() const { + std::vector names; + names.reserve(m_messages.size()); + for (const auto& element : m_messages) { + names.push_back(element.first); + } + std::sort(names.begin(), names.end()); + return names; + } + + /// Whether `owner` already answers `name` itself — a method its class registered (min's + /// dsp64, assist, the reserved names), which Max would call before anything added for a + /// Python method, or with C arguments. The attributes and messages made here for the previous + /// incarnation's fields and methods are the object's own, not Max's, and must not make the + /// class's names reserved on a reload: still registered while load() runs, an attribute + /// answers its name — 1.0.1 took them for Max's, so a reload lost every field — and a message + /// added with object_addmethod() answers as unknown (plan 9.0), so is left out either way. + /// Main thread. + bool answered_by_max(c74::max::t_object* owner, const std::string& name) const { + if (m_messages.find(name) != m_messages.end() || m_attributes.find(name) != m_attributes.end()) { + return false; + } + return found_method(c74::max::object_getmethod(owner, c74::max::gensym(name.c_str())), + not_found_method(owner)); + } + + /// Set the attribute `name` from Max's atoms: the core converts to the field's hinted type (a + /// bool field gets a bool). `log` hears what is wrong. Main or scheduler thread. + void set_attribute(processor* p, const char* name, const long argc, const c74::max::t_atom* argv, + const log_function& log) const { + if (!p || !p->loaded()) { + return; + } + if (argc != 1) { + log(log_level::error, "Attributes with more than 1 arg not supported"); + return; + } + if (m_attributes.find(name) == m_attributes.end()) { + return; + } + p->set_attribute(name, to_values(argc, argv).front()); + } + + /// Read the attribute `name` into Max's atoms, allocating them as an attribute getter must + /// unless Max passed one: one atom of the attribute's type, the type's empty value when there + /// is nothing to read (None, or a value that does not convert). Main or scheduler thread. + void get_attribute(processor* p, const char* name, long* argc, c74::max::t_atom** argv) const { + if ((*argc) != 1 || !(*argv)) { // otherwise use memory passed in + if (*argc && *argv) { + c74::max::sysmem_freeptr(*argv); + *argv = nullptr; + } + *argc = 1; + *argv = + reinterpret_cast(c74::max::sysmem_newptr(sizeof(c74::max::t_atom) * (*argc))); + } + c74::max::atom_setfloat(*argv, 0.0); // default in case anything below fails + + if (!p || !p->loaded()) { + return; + } + const auto found = m_attributes.find(name); + if (found == m_attributes.end()) { + return; + } + + // nothing to read (None, or a value that does not convert): the type's empty value + const auto type = found->second->value_type(); + if (type == value_type::integer || type == value_type::boolean) { + c74::max::atom_setlong(*argv, 0); + } + else if (type == value_type::symbol) { + c74::max::atom_setsym(*argv, c74::max::gensym("")); + } + + const auto result = p->get_attribute(name, type); + if (!result) { + return; + } + if (const auto* i = std::get_if(&*result)) { + c74::max::atom_setlong(*argv, static_cast(*i)); + } + else if (const auto* d = std::get_if(&*result)) { + c74::max::atom_setfloat(*argv, *d); + } + else { + c74::max::atom_setsym(*argv, c74::max::gensym(std::get(*result).c_str())); + } + } + + private: + std::unordered_map>> m_messages; + std::unordered_map>> m_attributes; + }; + +} // namespace tap::python diff --git a/source/projects/tap.python_tilde/tap.python_tilde_package.h b/source/projects/tap.python_tilde/tap.python_package.h similarity index 100% rename from source/projects/tap.python_tilde/tap.python_tilde_package.h rename to source/projects/tap.python_tilde/tap.python_package.h diff --git a/source/projects/tap.python_tilde/tap.python_tilde.cpp b/source/projects/tap.python_tilde/tap.python_tilde.cpp index a5d144f..43d4b26 100644 --- a/source/projects/tap.python_tilde/tap.python_tilde.cpp +++ b/source/projects/tap.python_tilde/tap.python_tilde.cpp @@ -4,91 +4,8 @@ #include "tap.python_tilde.h" -using namespace c74::min; -using namespace c74::max; - -namespace { - - /// Max calls the trampolines below from C, so no C++ exception may cross back into it. - template - c74::max::t_max_err guarded(c74::max::t_object* x, Fn&& fn) noexcept { - try { - fn(); - } - catch (const std::exception& e) { - c74::max::object_error(x, "tap.python~: %s", e.what()); - } - catch (...) { - c74::max::object_error(x, "tap.python~: unknown error"); - } - return c74::max::MAX_ERR_NONE; - } - -} // namespace - -namespace tap::python { - - c74::max::t_max_err python_attr_set(c74::max::t_object* x, c74::max::t_object* maxattr, const long argc, - const c74::max::t_atom* argv) { - return guarded(x, [&] { - auto attr_name{static_cast(c74::max::object_method(maxattr, k_sym_getname))}; - auto self = &(wrapper_find_self<::python>(x))->m_min_object; - self->attr_set(attr_name, argc, argv); - }); - } - - c74::max::t_max_err python_attr_get(c74::max::t_object* x, c74::max::t_object* maxattr, long* argc, - c74::max::t_atom** argv) { - return guarded(x, [&] { - auto attr_name{static_cast(c74::max::object_method(maxattr, k_sym_getname))}; - auto self = &(wrapper_find_self<::python>(x))->m_min_object; - self->attr_get(attr_name, argc, argv); - }); - } - - c74::max::t_max_err python_mess_int(c74::max::t_object* x, long value) { - return guarded(x, [&] { - auto self = &(wrapper_find_self<::python>(x))->m_min_object; - c74::max::t_atom a; - c74::max::atom_setlong(&a, value); - self->message_gimme(gensym("int"), 1, &a); - }); - } - - c74::max::t_max_err python_mess_float(c74::max::t_object* x, double value) { - return guarded(x, [&] { - auto self = &(wrapper_find_self<::python>(x))->m_min_object; - c74::max::t_atom a; - c74::max::atom_setfloat(&a, value); - self->message_gimme(k_sym_float, 1, &a); - }); - } - - c74::max::t_max_err python_mess_symbol(c74::max::t_object* x, c74::max::t_symbol* value) { - return guarded(x, [&] { - auto self = &(wrapper_find_self<::python>(x))->m_min_object; - c74::max::t_atom a; - c74::max::atom_setsym(&a, value); - self->message_gimme(gensym("symbol"), 1, &a); - }); - } - - c74::max::t_max_err python_mess_bang(c74::max::t_object* x) { - return guarded(x, [&] { - auto self = &(wrapper_find_self<::python>(x))->m_min_object; - self->message_gimme(k_sym_bang, 0, nullptr); - }); - } - - c74::max::t_max_err python_mess_gimme(c74::max::t_object* x, c74::max::t_symbol* name, long ac, - c74::max::t_atom* av) { - return guarded(x, [&] { - auto self = &(wrapper_find_self<::python>(x))->m_min_object; - self->message_gimme(name, ac, av); - }); - } - -} // namespace tap::python +// The trampolines Max calls for the attributes and messages made for a Python class are +// python_glue's (tap.python_glue.h), instantiated by the object's members. #if defined(TAP_PYTHON_SPIKE) // Plan 9.0, the spike (throwaway; -DTAP_PYTHON_SPIKE=ON, off by default): this binary also diff --git a/source/projects/tap.python_tilde/tap.python_tilde.h b/source/projects/tap.python_tilde/tap.python_tilde.h index 4090f68..43f8343 100644 --- a/source/projects/tap.python_tilde/tap.python_tilde.h +++ b/source/projects/tap.python_tilde/tap.python_tilde.h @@ -16,10 +16,9 @@ // the include guards swallow those definitions and the external fails to link. #include #include -#include #include #include -#include +#include #include #include "c74_min.h" @@ -29,11 +28,7 @@ #include #include #endif -#include "tap.python_tilde_attribute.h" -#include "tap.python_tilde_cglue.h" -#include "tap.python_tilde_filewatch.h" -#include "tap.python_tilde_message.h" -#include "tap.python_tilde_package.h" +#include "tap.python_glue.h" // what tap.python~ shares with tap.python (plan 9.2) using namespace c74::min; namespace runtime = tap::python; @@ -74,7 +69,7 @@ class python : public object, public vector_operator<> { "identifier. Without an argument, python/default.py is loaded."}; // Sent on every save of the class file (by the watch the constructor starts — see - // tap.python_tilde_filewatch.h), and by a patcher to force a reload. + // tap.python_filewatch.h), and by a patcher to force a reload. message<> m_filechanged{this, "filechanged", "Reload the Python file. The object's file watcher sends it when the file is saved; " "send it yourself to force a reload.", @@ -165,39 +160,12 @@ class python : public object, public vector_operator<> { return; // this occurs during dummy construction } - const auto package = runtime::package_root(); - m_scripts_dir = package / "python"; -#ifdef TAP_PYTHON_HOME - // Linux development builds embed a system CPython instead of a support/ runtime - // (see this object's CMakeLists.txt) - const std::filesystem::path home{TAP_PYTHON_HOME}; -#else - const auto home = runtime::runtime_home(package); // support/, or support/ (plan 4.8) -#endif - - if (!std::filesystem::exists(home)) { - cerr << "No Python runtime found at " << runtime::detail::utf8(home) - << " — run scripts/install-runtime from the package root to install it." << endl; - return; - } - - if (std::string error; !runtime::runtime_library_loadable(home, error)) { - cerr << error << endl; - return; - } - - runtime::runtime_options options; - options.home = home; - options.scripts_dir = m_scripts_dir; - options.console = console_line; - options.is_main_thread = is_main_thread; // Python's output posts from Max's main thread only (8.4) - options.console_ready = console_ready; - const auto status = runtime::initialize(options); - if (!status.ok) { - cerr << "failed to start Python from '" << runtime::detail::utf8(home) << "': " << status.error - << " (run scripts/install-runtime to install the runtime)" << endl; + const auto start = runtime::start_runtime(); + if (!start.ok) { + cerr << start.error << endl; return; } + m_scripts_dir = start.scripts_dir; if (args.empty()) { m_python_source = "default"; @@ -210,43 +178,29 @@ class python : public object, public vector_operator<> { : to_string(args); } - const auto object_log = [this](const runtime::log_level level, const std::string_view text) { - if (level == runtime::log_level::error) { - cerr << std::string{text} << endl; - } - else { - cout << std::string{text} << endl; - } - }; m_processor = std::make_unique( - m_python_source, object_log, reserved_messages(), [this] { m_reports.set(); }, - [this](const std::string& name) { return answered_by_max(name); }); + m_python_source, m_log, runtime::reserved_messages(true), [this] { m_reports.set(); }, + [this](const std::string& name) { return m_members.answered_by_max(maxobj(), name); }); m_worker = std::make_unique( - *m_processor, object_log, [this] { m_reports.set(); }, audio_thread_scheduling); + *m_processor, m_log, [this] { m_reports.set(); }, audio_thread_scheduling); update_source(); create_ports(); // before min makes the Max inlets and outlets from its lists, after this - // watch the source file for changes (delivered as our 'filechanged' message) — only a plain - // file name: the core refuses anything else (e.g. "../x"), and so must the watcher - if (m_python_source.find_first_of("/\\.:") != std::string::npos) { - return; - } - const auto watched_file = m_scripts_dir / (m_python_source + ".py"); - const auto watched_utf8 = runtime::detail::utf8(watched_file); // Max's paths are UTF-8 (8.7) - char filename[c74::max::MAX_PATH_CHARS]{}; - std::strncpy(filename, watched_utf8.c_str(), c74::max::MAX_PATH_CHARS - 1); - short path_id{}; - c74::max::t_fourcc filetype{}; - if (c74::max::locatefile_extended(filename, &path_id, &filetype, nullptr, 0) == 0) { - // not maxobj() itself: see tap.python_tilde_filewatch.h - m_file_watch = std::make_unique(maxobj(), path_id, filename); - } - else { - cerr << "Unable to watch " << watched_utf8 << " for changes." << endl; + // watch the source file for changes, delivered as our 'filechanged' message + std::string watch_error; + m_file_watch = runtime::watch_source(maxobj(), m_scripts_dir, m_python_source, watch_error); + if (!watch_error.empty()) { + cerr << watch_error << endl; } } + /// The object Max calls a trampoline with (tap.python_glue.h). + static python* self(c74::max::t_object* x) { return &(wrapper_find_self(x))->m_min_object; } + + /// This object's Max class name, for an error in a trampoline. + static constexpr const char* k_max_name = "tap.python~"; + ~python() { m_file_watch.reset(); m_use_worker = false; @@ -275,8 +229,8 @@ class python : public object, public vector_operator<> { if (!m_processor || !m_processor->load()) { return; // the processor has reported why, and outputs silence until the next reload } - create_attributes(); - create_messages(); + m_members.create_attributes(maxobj(), *m_processor); + m_members.create_messages(maxobj(), *m_processor); adapt_ports(); } @@ -286,69 +240,15 @@ class python : public object, public vector_operator<> { if (!m_processor || !m_processor->loaded()) { return; } - m_processor->call(name.c_str(), to_values(ac, av)); + m_processor->call(name.c_str(), runtime::to_values(ac, av)); } void attr_set(const symbol& name, const long argc, const c74::max::t_atom* argv) { - if (!m_processor || !m_processor->loaded()) { - return; - } - if (argc != 1) { - cerr << "Attributes with more than 1 arg not supported" << endl; - return; - } - - auto found = m_python_attributes.find(name.c_str()); - if (found == m_python_attributes.end()) { - return; - } - - // the core converts to the field's hinted type (a bool field gets a bool) - m_processor->set_attribute(name.c_str(), to_values(argc, argv).front()); + m_members.set_attribute(m_processor.get(), name.c_str(), argc, argv, m_log); } void attr_get(const symbol& name, long* argc, c74::max::t_atom** argv) { - if ((*argc) != 1 || !(*argv)) { // otherwise use memory passed in - if (*argc && *argv) { - c74::max::sysmem_freeptr(*argv); - *argv = NULL; - } - *argc = 1; - *argv = reinterpret_cast(c74::max::sysmem_newptr(sizeof(c74::max::t_atom) * (*argc))); - } - c74::max::atom_setfloat(*argv, 0.0); // default in case anything below fails - - if (!m_processor || !m_processor->loaded()) { - return; - } - - auto found = m_python_attributes.find(name.c_str()); - if (found == m_python_attributes.end()) { - return; - } - - // nothing to read (None, or a value that does not convert): the type's empty value - const auto type = found->second->value_type(); - if (type == runtime::value_type::integer || type == runtime::value_type::boolean) { - c74::max::atom_setlong(*argv, 0); - } - else if (type == runtime::value_type::symbol) { - c74::max::atom_setsym(*argv, c74::max::gensym("")); - } - - const auto result = m_processor->get_attribute(name.c_str(), type); - if (!result) { - return; - } - if (const auto* i = std::get_if(&*result)) { - c74::max::atom_setlong(*argv, static_cast(*i)); - } - else if (const auto* d = std::get_if(&*result)) { - c74::max::atom_setfloat(*argv, *d); - } - else { - c74::max::atom_setsym(*argv, c74::max::gensym(std::get(*result).c_str())); - } + m_members.get_attribute(m_processor.get(), name.c_str(), argc, argv); } /// The audio perform routine: the core calls the Python process() once per sample or per @@ -376,32 +276,7 @@ class python : public object, public vector_operator<> { } /// The names of the Max messages made for the class's methods (for the tests). - std::vector python_message_names() const { - std::vector names; - names.reserve(m_python_messages.size()); - for (const auto& element : m_python_messages) { - names.push_back(element.first); - } - std::sort(names.begin(), names.end()); - return names; - } - - /// Whether object_getmethod() found a method: neither null nor `not_found`, what it answers for a - /// name the object does not have — Max's method_false(), as the SDK documents. 1.0.0 tested for - /// null alone, and 1.0.1 compared with the address of method_false as this module sees it, which - /// on Windows is the external's own import thunk (the SDK declares it without dllimport), never - /// what Max returns: either way every field and method of a class was "answered by Max", and the - /// object had no attributes and no messages. So `not_found` comes from Max (not_found_method()). - static bool found_method(const c74::max::method found, const c74::max::method not_found) { - return found != nullptr && found != not_found; - } - - /// What object_getmethod() answers for a name the object does not have, asked of Max for one - /// no class can have (it has spaces): Max's method_false(), whatever its address looks like from - /// here. Main thread. - c74::max::method not_found_method() { - return c74::max::object_getmethod(maxobj(), c74::max::gensym("tap.python~ answers no such name")); - } + std::vector python_message_names() const { return m_members.message_names(); } private: string m_python_source{}; @@ -414,90 +289,18 @@ class python : public object, public vector_operator<> { std::vector>> m_more_outlets; // after the first bool m_ports_made{}; bool m_ports_differ{}; - std::unordered_map> m_python_messages; - std::unordered_map> m_python_attributes; - - /// Messages and attributes the Max object handles itself, which a Python method or field must - /// never replace: min's own class methods, the messages Max sends every object, this object's - /// file watcher (a Python method named filechanged would silently disable hot reload), and its - /// own attributes (worker mode's, plan 2.5). - /// - /// Above all, every message Max sends with C arguments (plan 8.2, audit A3): a Python method - /// of such a name would be registered with the A_GIMME trampoline, and Max calling it with a - /// long or a pointer reads them as a symbol and an atom list — the crash 6.1 found for - /// filechanged, in its general form. The names are those min treats as A_CANT - /// (c74_min_message.h, message_type::cant; the MIN_WRAPPER_ADDMETHOD table in - /// c74_min_object_wrapper.h) plus Max's own dspstate, inputchanged and multichanneloutputs. - /// Anything the Max class already answers is reserved as well: answered_by_max(). - static std::vector reserved_messages() { - return {"anything", - "appendtodictionary", - "assist", - "dblclick", - "dictionary", - "dsp", - "dsp64", - "dspsetup", - "dspstate", - "edclose", - "filechanged", - "fileusage", - "focusgained", - "focuslost", - "getplaystate", - "getvalueof", - "inletinfo", - "inputchanged", - "jitclass_setup", - "key", - "latency", - "latencysamples", - "loadbang", - "maxclass_setup", - "maxob_setup", - "mode", - "mop_setup", - "mousedoubleclick", - "mousedown", - "mousedrag", - "mousedragdelta", - "mouseenter", - "mouseleave", - "mousemove", - "mouseup", - "mousewheel", - "mt_mousedown", - "mt_mousedrag", - "mt_mouseenter", - "mt_mouseleave", - "mt_mousemove", - "mt_mouseup", - "multichanneloutputs", - "notify", - "okclose", - "oksize", - "paint", - "patchlineupdate", - "preset", - "savestate", - "setup", - "setvalueof", - "signal"}; - } + runtime::python_members m_members; // the Max attributes and messages made for the class - /// Whether the Max object already answers `name` itself — a method its class registered (min's - /// dsp64, assist, the ones above), which Max would call before anything added for a Python - /// method, or with C arguments. The messages and attributes this object added for the previous - /// incarnation's methods and fields are its own, not Max's: still registered while load() runs - /// (an attribute answers its name, as a message does), they must not make the class's names - /// reserved on a reload — 1.0.1 left out the attributes, so a reload lost every field. Main thread. - bool answered_by_max(const std::string& name) { - if (m_python_messages.find(name) != m_python_messages.end() - || m_python_attributes.find(name) != m_python_attributes.end()) { - return false; + /// What concerns this object, for the processor, the worker and the attributes: errors through + /// min's cerr, the rest through its cout. + runtime::log_function m_log{[this](const runtime::log_level level, const std::string_view text) { + if (level == runtime::log_level::error) { + cerr << std::string{text} << endl; } - return found_method(c74::max::object_getmethod(maxobj(), c74::max::gensym(name.c_str())), not_found_method()); - } + else { + cout << std::string{text} << endl; + } + }}; /// The worker thread's scheduling (plan 2.5): the real-time class an audio thread has, so that a /// busy machine does not hold it off for longer than its latency (measured in Max: an ordinary @@ -529,75 +332,6 @@ class python : public object, public vector_operator<> { #endif } - /// Whether this is Max's main thread: where Python's output may be posted at once. On any other - /// thread — the audio thread, a worker, the scheduler — the core queues the line (plan 8.4). - static bool is_main_thread() { return c74::max::systhread_ismainthread() != 0; } - - /// Called on the printing thread when the core queued a line: sets the process-wide qelem that - /// has the lines posted from the main thread. Real-time safe (qelem_set). - static void console_ready() { - static c74::max::t_qelem* s_flush = - c74::max::qelem_new(nullptr, reinterpret_cast(+[](void*) { runtime::flush_console(); })); - c74::max::qelem_set(s_flush); - } - - /// Python's print() output and tracebacks, for every instance. - static void console_line(const runtime::log_level level, const std::string_view text) { - const std::string line{text}; - if (level == runtime::log_level::error) { - c74::max::object_error(nullptr, "python: %s", line.c_str()); - } - else { - c74::max::object_post(nullptr, "python: %s", line.c_str()); - } - } - - /// Max atoms as core values, keeping each atom's own type (the core coerces to the - /// hinted type with the same rules as atom_getlong/atom_getfloat/atom_getsym). - static std::vector to_values(const long ac, const c74::max::t_atom* av) { - std::vector values; - values.reserve(static_cast(ac)); - for (long i = 0; i < ac; ++i) { - const auto* atom = av + i; - switch (c74::max::atom_gettype(atom)) { - case c74::max::A_LONG: - values.emplace_back(static_cast(c74::max::atom_getlong(atom))); - break; - case c74::max::A_FLOAT: - values.emplace_back(static_cast(c74::max::atom_getfloat(atom))); - break; - default: - values.emplace_back(std::string{c74::max::atom_getsym(atom)->s_name}); - break; - } - } - return values; - } - - /// Make the Max attributes match the class's annotated fields: remove the ones the class no - /// longer has, recreate the ones whose type changed, add the new ones. (The core has already - /// carried the values of those that stayed over to the new instance.) - void create_attributes() { - const auto& current = m_processor->attributes(); - for (auto it = m_python_attributes.begin(); it != m_python_attributes.end();) { - const auto found = std::find_if(current.begin(), current.end(), - [&](const runtime::attribute_info& a) { return a.name == it->first; }); - if (found == current.end() || found->type != it->second->value_type()) { - it->second->remove(); - it = m_python_attributes.erase(it); - } - else { - ++it; - } - } - for (const auto& attribute : current) { - if (m_python_attributes.find(attribute.name) == m_python_attributes.end()) { - m_python_attributes[attribute.name] = - std::make_unique(maxobj(), attribute.name, attribute.type); - } - } - } - /// A signal inlet for each input the class's process() declares, named for its parameter, and /// an outlet for each output — at least one of each: the first inlet also takes messages. /// Constructor only: min makes the Max inlets and outlets from these when it returns. @@ -712,16 +446,4 @@ class python : public object, public vector_operator<> { this, "(signal) output " + number + " returned from the Python process() method", "signal")); } } - - /// Replace the previous incarnation's Max messages with the class's current methods. - void create_messages() { - for (auto& element : m_python_messages) { - c74::max::object_deletemethod(maxobj(), c74::max::gensym(element.first.c_str())); - } - m_python_messages.clear(); - - for (const auto& message : m_processor->messages()) { // never names an attribute - m_python_messages[message.name] = std::make_unique(maxobj(), message.name); - } - } }; diff --git a/source/projects/tap.python_tilde/tap.python_tilde_attribute.h b/source/projects/tap.python_tilde/tap.python_tilde_attribute.h deleted file mode 100644 index 92ced75..0000000 --- a/source/projects/tap.python_tilde/tap.python_tilde_attribute.h +++ /dev/null @@ -1,84 +0,0 @@ -/// @file -/// @copyright Copyright 2022-2026 Timothy Place. All rights reserved. -/// @license Use of this source code is governed by the MIT License found in the License.md file. - -#pragma once - -#include - -#include "c74_min_api.h" -#include "tap.python_tilde_cglue.h" -#include "tap/python/value.h" - -namespace tap::python { - - /// A Max attribute dynamically added to a tap.python~ instance, mirroring an - /// annotated attribute of the user's Python class. Instances are owned via - /// unique_ptr in the object's attribute map; one persists across reloads while the - /// class keeps the field with the same type, and is removed otherwise. - class python_attr { - public: - python_attr(c74::max::t_object* owner, const std::string& name, const value_type type) - : m_owner{owner} - , m_name{name} - , m_value_type{type} { - switch (m_value_type) { - case value_type::integer: - case value_type::boolean: - m_type = c74::min::k_sym_long; - break; - case value_type::real: - m_type = c74::min::k_sym_float64; - break; - case value_type::symbol: - case value_type::any: - m_type = c74::min::k_sym_symbol; - break; - } - - m_attrobj = c74::max::attribute_new(m_name.c_str(), m_type, 0, (c74::max::method)python_attr_get, - (c74::max::method)python_attr_set); - auto err = c74::max::object_addattr(m_owner, m_attrobj); - if (err) { - c74::max::object_error(m_owner, "failed to add attribute for python member '%s'", m_name.c_str()); - return; - } - err = c74::max::object_attr_addattr_parse(m_owner, m_name.c_str(), "dynamicattr", c74::min::k_sym_long, 0, - "1"); - if (err) { - c74::max::object_error(m_owner, "failed to make dynamic attribute for %s", m_name.c_str()); - } - if (m_value_type == value_type::boolean) { - // a bool field shows as a toggle in the inspector and attrui - c74::max::object_attr_addattr_parse(m_owner, m_name.c_str(), "style", c74::min::k_sym_symbol, 0, - "onoff"); - } - } - - python_attr(const python_attr&) = delete; - python_attr& operator=(const python_attr&) = delete; - - /// Detach the attribute from the Max object and free it (the class no longer has the field, - /// or its type changed). Not called at object destruction: Max frees instance attributes then. - void remove() { - if (m_attrobj) { - c74::max::object_deleteattr(m_owner, c74::max::gensym(m_name.c_str())); - m_attrobj = nullptr; - } - } - - /// The Max attribute type (long, float64 or symbol). - c74::min::symbol type() const { return m_type; } - - /// The core value type the attribute was created with; fixed for the attribute's lifetime. - tap::python::value_type value_type() const { return m_value_type; } - - private: - c74::max::t_object* m_owner; - std::string m_name; - tap::python::value_type m_value_type; - c74::min::symbol m_type; - c74::max::t_object* m_attrobj{}; - }; - -} // namespace tap::python diff --git a/source/projects/tap.python_tilde/tap.python_tilde_cglue.h b/source/projects/tap.python_tilde/tap.python_tilde_cglue.h deleted file mode 100644 index 51d12e9..0000000 --- a/source/projects/tap.python_tilde/tap.python_tilde_cglue.h +++ /dev/null @@ -1,27 +0,0 @@ -/// @file -/// @copyright Copyright 2022-2026 Timothy Place. All rights reserved. -/// @license Use of this source code is governed by the MIT License found in the License.md file. - -#pragma once - -#include "c74_min_api.h" - -// C-style trampolines registered on the Max object for the attributes and -// messages that are created dynamically from the user's Python class. -// Implementations are in tap.python_tilde.cpp. - -namespace tap::python { - - c74::max::t_max_err python_attr_set(c74::max::t_object* x, c74::max::t_object* maxattr, const long argc, - const c74::max::t_atom* argv); - c74::max::t_max_err python_attr_get(c74::max::t_object* x, c74::max::t_object* maxattr, long* argc, - c74::max::t_atom** argv); - - c74::max::t_max_err python_mess_int(c74::max::t_object* x, long value); - c74::max::t_max_err python_mess_float(c74::max::t_object* x, double value); - c74::max::t_max_err python_mess_symbol(c74::max::t_object* x, c74::max::t_symbol* value); - c74::max::t_max_err python_mess_bang(c74::max::t_object* x); - c74::max::t_max_err python_mess_gimme(c74::max::t_object* x, c74::max::t_symbol* name, long ac, - c74::max::t_atom* av); - -} // namespace tap::python diff --git a/source/projects/tap.python_tilde/tap.python_tilde_message.h b/source/projects/tap.python_tilde/tap.python_tilde_message.h deleted file mode 100644 index b7e16a6..0000000 --- a/source/projects/tap.python_tilde/tap.python_tilde_message.h +++ /dev/null @@ -1,63 +0,0 @@ -/// @file -/// @copyright Copyright 2022-2026 Timothy Place. All rights reserved. -/// @license Use of this source code is governed by the MIT License found in the License.md file. - -#pragma once - -#include - -#include "c74_min_api.h" -#include "tap.python_tilde_cglue.h" - -namespace tap::python { - - /// A Max message dynamically added to a tap.python~ instance for a method of the - /// user's Python class. It only registers the Max method; the Python side (the - /// bound function and its signature) is owned by the core's processor, which - /// the object's message handler dispatches to by name. Instances are owned via - /// unique_ptr in the object's message map and rebuilt on every reload. - class python_message { - public: - python_message(c74::max::t_object* owner, const std::string& name) - : m_owner{owner} - , m_name{name} { - if (m_owner == nullptr) { - return; // this occurs during dummy construction - } - - c74::max::t_max_err err{}; - - if (m_name == "int") { - err = c74::max::object_addmethod(m_owner, (c74::max::method)python_mess_int, m_name.c_str(), - c74::max::A_LONG, 0); - } - else if (m_name == "float") { - err = c74::max::object_addmethod(m_owner, (c74::max::method)python_mess_float, m_name.c_str(), - c74::max::A_FLOAT, 0); - } - else if (m_name == "symbol") { - err = c74::max::object_addmethod(m_owner, (c74::max::method)python_mess_symbol, m_name.c_str(), - c74::max::A_SYM, 0); - } - else if (m_name == "bang") { - err = c74::max::object_addmethod(m_owner, (c74::max::method)python_mess_bang, m_name.c_str(), 0); - } - else { - err = c74::max::object_addmethod(m_owner, (c74::max::method)python_mess_gimme, m_name.c_str(), - c74::max::A_GIMME, 0); - } - - if (err) { - c74::max::object_error(m_owner, "failed to add message for python method '%s'", m_name.c_str()); - } - } - - python_message(const python_message&) = delete; - python_message& operator=(const python_message&) = delete; - - private: - c74::max::t_object* m_owner; - std::string m_name; - }; - -} // namespace tap::python diff --git a/source/projects/tap.python_tilde/tap.python_tilde_test.cpp b/source/projects/tap.python_tilde/tap.python_tilde_test.cpp index 71aa753..28e3ae5 100644 --- a/source/projects/tap.python_tilde/tap.python_tilde_test.cpp +++ b/source/projects/tap.python_tilde/tap.python_tilde_test.cpp @@ -2,6 +2,7 @@ /// @copyright Copyright 2022-2026 Timothy Place. All rights reserved. /// @license Use of this source code is governed by the MIT License found in the License.md file. +#include #include #include #include @@ -523,10 +524,10 @@ SCENARIO("Methods named like messages Max sends with C arguments are not exposed } THEN("found means neither null nor what Max answers for a name it does not have (1.0.2)") { const auto answered = c74::max::object_getmethod(nullptr, c74::max::gensym("maxtest_host_answers")); - CHECK(python::found_method(nullptr, not_found) == false); - CHECK(python::found_method(not_found, not_found) == false); - CHECK(python::found_method(answered, not_found) == true); - CHECK(my_object.not_found_method() == not_found); // asked of Max, not taken from &method_false + CHECK(runtime::found_method(nullptr, not_found) == false); + CHECK(runtime::found_method(not_found, not_found) == false); + CHECK(runtime::found_method(answered, not_found) == true); + CHECK(runtime::not_found_method(my_object.maxobj()) == not_found); // asked of Max, not taken from &method_false } THEN("audio is bound regardless") { CHECK(all_equal(render(my_object, 0.5), 0.5)); @@ -535,6 +536,34 @@ SCENARIO("Methods named like messages Max sends with C arguments are not exposed std::filesystem::remove(file); } +SCENARIO("Every object reserves the names Max sends it; an audio object, the audio ones as well (plan 9.2)") { + const auto every = runtime::reserved_messages(false); + const auto audio = runtime::reserved_messages(true); + const auto has = [](const std::vector& names, const std::string& name) { + return std::find(names.begin(), names.end(), name) != names.end(); + }; + + THEN("both are sorted, and every object reserves what Max sends with C arguments, and filechanged") { + CHECK(std::is_sorted(every.begin(), every.end())); + CHECK(std::is_sorted(audio.begin(), audio.end())); + for (const auto* name : {"anything", "assist", "fileusage", "filechanged", "notify", "patchlineupdate"}) { + CHECK(has(every, name)); + } + } + THEN("an audio object reserves every object's names and exactly the audio ones besides") { + auto expected = every; + for (const auto& name : runtime::audio_messages()) { + CHECK_FALSE(has(every, name)); + expected.push_back(name); + } + std::sort(expected.begin(), expected.end()); + CHECK(audio == expected); + for (const auto* name : {"dsp64", "dspsetup", "dspstate", "inputchanged", "mode", "latency"}) { + CHECK(has(audio, name)); + } + } +} + SCENARIO("With @mode worker, process() runs on a thread of its own, @latency milliseconds behind (plan 2.5)") { ext_main(nullptr); test_wrapper an_instance;