From 5903981c7e4d5d612650b8e8806ec2a743fa528d Mon Sep 17 00:00:00 2001 From: Taoxuan-168 <2168187423@qq.com> Date: Mon, 9 Nov 2026 14:06:12 +0800 Subject: [PATCH] Add maix_lvgl sub-project, MaixPy build/packaging integration, and docs --- docs/doc/en/lvgl/lvgl.md | 124 + docs/doc/en/sidebar.yaml | 5 + docs/doc/zh/lvgl/lvgl.md | 124 + docs/doc/zh/sidebar.yaml | 5 + maix_lvgl/.gitignore | 14 + maix_lvgl/CMakeLists.txt | 10 + maix_lvgl/LICENSE | 21 + maix_lvgl/README.md | 170 + maix_lvgl/README_ZH.md | 160 + maix_lvgl/binding/.gitkeep | 0 .../components/lvgl_binding/CMakeLists.txt | 33 + maix_lvgl/components/lvgl_binding/Kconfig | 3 + .../components/lvgl_binding/component.py | 3 + maix_lvgl/configs/config_platform_maixcam2.mk | 0 maix_lvgl/docs/screenshot.png | Bin 0 -> 6797 bytes maix_lvgl/examples/demo.py | 48 + maix_lvgl/examples/selftest.py | 46 + maix_lvgl/main/CMakeLists.txt | 14 + maix_lvgl/main/Kconfig | 0 maix_lvgl/main/include/main.h | 1 + maix_lvgl/main/src/main.cpp | 8 + maix_lvgl/maix_lvgl/__init__.py | 156 + maix_lvgl/maix_lvgl/driver.py | 130 + maix_lvgl/project.py | 67 + maix_lvgl/pyproject.toml | 3 + maix_lvgl/runtime/lvpy_runtime.c | 1186 ++++++ maix_lvgl/runtime/lvpy_runtime.h | 129 + maix_lvgl/scripts/regenerate_binding.sh | 5 + maix_lvgl/setup.py | 159 + maix_lvgl/tools/gen_api_docs.py | 831 +++++ maix_lvgl/tools/maixcdk_lvgl.py | 146 + maix_lvgl/tools/omnipython_lvgl/LICENSE | 21 + maix_lvgl/tools/omnipython_lvgl/VERSION | 1 + .../tools/omnipython_lvgl/binding/__init__.py | 5 + .../tools/omnipython_lvgl/binding/analyze.py | 591 +++ .../omnipython_lvgl/binding/api_model.py | 1332 +++++++ .../omnipython_lvgl/binding/api_policy.json | 174 + .../omnipython_lvgl/binding/api_policy.py | 265 ++ .../omnipython_lvgl/binding/api_report.py | 595 +++ .../omnipython_lvgl/binding/artifacts.py | 78 + .../tools/omnipython_lvgl/binding/context.py | 169 + .../omnipython_lvgl/binding/emit_backend.py | 677 ++++ .../omnipython_lvgl/binding/emit_c_cpython.py | 1095 ++++++ .../binding/emit_c_micropython_style.py | 3241 +++++++++++++++++ .../binding/emit_circuitpython.py | 27 + .../binding/emit_circuitpython_glue.py | 331 ++ .../omnipython_lvgl/binding/emit_cpython.py | 32 + .../binding/emit_cpython_glue.py | 493 +++ .../binding/emit_cpython_native.py | 1651 +++++++++ .../binding/emit_micropython.py | 28 + .../tools/omnipython_lvgl/binding/emit_pyi.py | 156 + .../binding/emit_pyi_canonical.py | 549 +++ .../tools/omnipython_lvgl/binding/generate.py | 319 ++ .../omnipython_lvgl/binding/generator.py | 163 + .../tools/omnipython_lvgl/binding/helpers.py | 167 + maix_lvgl/tools/omnipython_lvgl/binding/ir.py | 641 ++++ .../tools/omnipython_lvgl/binding/naming.py | 45 + .../tools/omnipython_lvgl/binding/parse.py | 155 + .../omnipython_lvgl/binding/preprocess.py | 43 + .../tools/omnipython_lvgl/binding/runtime.py | 106 + .../binding/runtime_exports.py | 69 + .../tools/omnipython_lvgl/binding/util.py | 60 + .../omnipython_lvgl/binding/verify_api.py | 197 + .../binding/verify_namespace.py | 202 + .../omnipython_lvgl/binding/verify_pyi.py | 533 +++ .../fake_libc_include/X11/Intrinsic.h | 4 + .../fake_libc_include/X11/Xlib.h | 4 + .../fake_libc_include/X11/_X11_fake_defines.h | 16 + .../X11/_X11_fake_typedefs.h | 38 + .../omnipython_lvgl/fake_libc_include/_ansi.h | 2 + .../fake_libc_include/_fake_defines.h | 262 ++ .../fake_libc_include/_fake_typedefs.h | 236 ++ .../fake_libc_include/_syslist.h | 2 + .../omnipython_lvgl/fake_libc_include/aio.h | 2 + .../fake_libc_include/alloca.h | 2 + .../omnipython_lvgl/fake_libc_include/ar.h | 2 + .../omnipython_lvgl/fake_libc_include/argz.h | 2 + .../fake_libc_include/arpa/inet.h | 2 + .../fake_libc_include/asm-generic/int-ll64.h | 2 + .../fake_libc_include/assert.h | 2 + .../fake_libc_include/complex.h | 2 + .../omnipython_lvgl/fake_libc_include/cpio.h | 2 + .../omnipython_lvgl/fake_libc_include/ctype.h | 2 + .../fake_libc_include/dirent.h | 2 + .../omnipython_lvgl/fake_libc_include/dlfcn.h | 2 + .../fake_libc_include/emmintrin.h | 2 + .../fake_libc_include/endian.h | 2 + .../omnipython_lvgl/fake_libc_include/envz.h | 2 + .../omnipython_lvgl/fake_libc_include/errno.h | 2 + .../fake_libc_include/fastmath.h | 2 + .../omnipython_lvgl/fake_libc_include/fcntl.h | 2 + .../fake_libc_include/features.h | 2 + .../omnipython_lvgl/fake_libc_include/fenv.h | 2 + .../omnipython_lvgl/fake_libc_include/float.h | 2 + .../fake_libc_include/fmtmsg.h | 2 + .../fake_libc_include/fnmatch.h | 2 + .../omnipython_lvgl/fake_libc_include/ftw.h | 2 + .../fake_libc_include/getopt.h | 2 + .../omnipython_lvgl/fake_libc_include/glob.h | 2 + .../omnipython_lvgl/fake_libc_include/grp.h | 2 + .../omnipython_lvgl/fake_libc_include/iconv.h | 2 + .../fake_libc_include/ieeefp.h | 2 + .../fake_libc_include/immintrin.h | 2 + .../fake_libc_include/inttypes.h | 2 + .../fake_libc_include/iso646.h | 2 + .../fake_libc_include/langinfo.h | 2 + .../fake_libc_include/libgen.h | 2 + .../fake_libc_include/libintl.h | 2 + .../fake_libc_include/limits.h | 2 + .../fake_libc_include/linux/socket.h | 2 + .../fake_libc_include/linux/version.h | 2 + .../fake_libc_include/locale.h | 2 + .../fake_libc_include/malloc.h | 2 + .../omnipython_lvgl/fake_libc_include/math.h | 2 + .../mir_toolkit/client_types.h | 2 + .../fake_libc_include/monetary.h | 2 + .../fake_libc_include/mqueue.h | 2 + .../omnipython_lvgl/fake_libc_include/ndbm.h | 2 + .../fake_libc_include/net/if.h | 2 + .../omnipython_lvgl/fake_libc_include/netdb.h | 2 + .../fake_libc_include/netinet/in.h | 2 + .../fake_libc_include/netinet/tcp.h | 2 + .../fake_libc_include/newlib.h | 2 + .../fake_libc_include/nl_types.h | 2 + .../fake_libc_include/openssl/err.h | 2 + .../fake_libc_include/openssl/evp.h | 2 + .../fake_libc_include/openssl/hmac.h | 2 + .../fake_libc_include/openssl/ssl.h | 2 + .../fake_libc_include/openssl/x509v3.h | 2 + .../omnipython_lvgl/fake_libc_include/paths.h | 2 + .../omnipython_lvgl/fake_libc_include/poll.h | 2 + .../fake_libc_include/process.h | 2 + .../fake_libc_include/pthread.h | 2 + .../omnipython_lvgl/fake_libc_include/pwd.h | 2 + .../omnipython_lvgl/fake_libc_include/reent.h | 2 + .../fake_libc_include/regdef.h | 2 + .../omnipython_lvgl/fake_libc_include/regex.h | 2 + .../omnipython_lvgl/fake_libc_include/sched.h | 2 + .../fake_libc_include/search.h | 2 + .../fake_libc_include/semaphore.h | 2 + .../fake_libc_include/setjmp.h | 2 + .../fake_libc_include/signal.h | 2 + .../fake_libc_include/smmintrin.h | 2 + .../omnipython_lvgl/fake_libc_include/spawn.h | 2 + .../fake_libc_include/stdalign.h | 2 + .../fake_libc_include/stdarg.h | 2 + .../fake_libc_include/stdatomic.h | 2 + .../fake_libc_include/stdbool.h | 2 + .../fake_libc_include/stddef.h | 2 + .../fake_libc_include/stdint.h | 2 + .../omnipython_lvgl/fake_libc_include/stdio.h | 2 + .../fake_libc_include/stdlib.h | 2 + .../fake_libc_include/stdnoreturn.h | 2 + .../fake_libc_include/string.h | 2 + .../fake_libc_include/strings.h | 2 + .../fake_libc_include/stropts.h | 2 + .../fake_libc_include/sys/ioctl.h | 2 + .../fake_libc_include/sys/ipc.h | 2 + .../fake_libc_include/sys/mman.h | 2 + .../fake_libc_include/sys/msg.h | 2 + .../fake_libc_include/sys/poll.h | 2 + .../fake_libc_include/sys/resource.h | 2 + .../fake_libc_include/sys/select.h | 2 + .../fake_libc_include/sys/sem.h | 2 + .../fake_libc_include/sys/shm.h | 2 + .../fake_libc_include/sys/socket.h | 2 + .../fake_libc_include/sys/stat.h | 2 + .../fake_libc_include/sys/statvfs.h | 2 + .../fake_libc_include/sys/sysctl.h | 2 + .../fake_libc_include/sys/time.h | 2 + .../fake_libc_include/sys/times.h | 2 + .../fake_libc_include/sys/types.h | 2 + .../fake_libc_include/sys/uio.h | 2 + .../fake_libc_include/sys/un.h | 2 + .../fake_libc_include/sys/utsname.h | 2 + .../fake_libc_include/sys/wait.h | 2 + .../fake_libc_include/syslog.h | 2 + .../omnipython_lvgl/fake_libc_include/tar.h | 2 + .../fake_libc_include/termios.h | 2 + .../fake_libc_include/tgmath.h | 2 + .../fake_libc_include/threads.h | 2 + .../omnipython_lvgl/fake_libc_include/time.h | 2 + .../omnipython_lvgl/fake_libc_include/trace.h | 2 + .../fake_libc_include/ulimit.h | 2 + .../fake_libc_include/unctrl.h | 2 + .../fake_libc_include/unistd.h | 2 + .../omnipython_lvgl/fake_libc_include/utime.h | 2 + .../omnipython_lvgl/fake_libc_include/utmp.h | 2 + .../omnipython_lvgl/fake_libc_include/utmpx.h | 2 + .../omnipython_lvgl/fake_libc_include/wchar.h | 2 + .../fake_libc_include/wctype.h | 2 + .../fake_libc_include/wordexp.h | 2 + .../fake_libc_include/xcb/xcb.h | 2 + .../omnipython_lvgl/fake_libc_include/zlib.h | 33 + maix_lvgl/tools/regenerate_binding.py | 227 ++ setup.py | 45 +- 196 files changed, 18920 insertions(+), 1 deletion(-) create mode 100644 docs/doc/en/lvgl/lvgl.md create mode 100644 docs/doc/zh/lvgl/lvgl.md create mode 100644 maix_lvgl/.gitignore create mode 100644 maix_lvgl/CMakeLists.txt create mode 100644 maix_lvgl/LICENSE create mode 100644 maix_lvgl/README.md create mode 100644 maix_lvgl/README_ZH.md create mode 100644 maix_lvgl/binding/.gitkeep create mode 100644 maix_lvgl/components/lvgl_binding/CMakeLists.txt create mode 100644 maix_lvgl/components/lvgl_binding/Kconfig create mode 100644 maix_lvgl/components/lvgl_binding/component.py create mode 100644 maix_lvgl/configs/config_platform_maixcam2.mk create mode 100644 maix_lvgl/docs/screenshot.png create mode 100644 maix_lvgl/examples/demo.py create mode 100644 maix_lvgl/examples/selftest.py create mode 100644 maix_lvgl/main/CMakeLists.txt create mode 100644 maix_lvgl/main/Kconfig create mode 100644 maix_lvgl/main/include/main.h create mode 100644 maix_lvgl/main/src/main.cpp create mode 100644 maix_lvgl/maix_lvgl/__init__.py create mode 100644 maix_lvgl/maix_lvgl/driver.py create mode 100755 maix_lvgl/project.py create mode 100644 maix_lvgl/pyproject.toml create mode 100644 maix_lvgl/runtime/lvpy_runtime.c create mode 100644 maix_lvgl/runtime/lvpy_runtime.h create mode 100644 maix_lvgl/scripts/regenerate_binding.sh create mode 100644 maix_lvgl/setup.py create mode 100644 maix_lvgl/tools/gen_api_docs.py create mode 100644 maix_lvgl/tools/maixcdk_lvgl.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/LICENSE create mode 100644 maix_lvgl/tools/omnipython_lvgl/VERSION create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/__init__.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/analyze.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/api_model.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/api_policy.json create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/api_policy.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/api_report.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/artifacts.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/context.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_backend.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_c_cpython.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_c_micropython_style.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython_glue.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_glue.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_native.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_micropython.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi_canonical.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/generate.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/generator.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/helpers.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/ir.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/naming.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/parse.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/preprocess.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/runtime.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/runtime_exports.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/util.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/verify_api.py create mode 100755 maix_lvgl/tools/omnipython_lvgl/binding/verify_namespace.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/binding/verify_pyi.py create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Intrinsic.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Xlib.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_defines.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_typedefs.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_ansi.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_defines.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_typedefs.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_syslist.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/aio.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/alloca.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ar.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/argz.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/arpa/inet.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/asm-generic/int-ll64.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/assert.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/complex.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/cpio.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ctype.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dirent.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dlfcn.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/emmintrin.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/endian.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/envz.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/errno.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fastmath.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fcntl.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/features.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fenv.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/float.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fmtmsg.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fnmatch.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ftw.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/getopt.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/glob.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/grp.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iconv.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ieeefp.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/immintrin.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/inttypes.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iso646.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/langinfo.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libgen.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libintl.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/limits.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/socket.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/version.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/locale.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/malloc.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/math.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mir_toolkit/client_types.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/monetary.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mqueue.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ndbm.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/net/if.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netdb.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/in.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/tcp.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/newlib.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/nl_types.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/err.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/evp.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/hmac.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/ssl.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/x509v3.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/paths.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/poll.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/process.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pthread.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pwd.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/reent.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regdef.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regex.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sched.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/search.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/semaphore.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/setjmp.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/signal.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/smmintrin.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/spawn.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdalign.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdarg.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdatomic.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdbool.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stddef.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdint.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdio.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdlib.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdnoreturn.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/string.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/strings.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stropts.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ioctl.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ipc.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/mman.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/msg.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/poll.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/resource.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/select.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sem.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/shm.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/socket.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/stat.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/statvfs.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sysctl.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/time.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/times.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/types.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/uio.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/un.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/utsname.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/wait.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/syslog.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tar.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/termios.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tgmath.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/threads.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/time.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/trace.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ulimit.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unctrl.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unistd.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utime.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmp.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmpx.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wchar.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wctype.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wordexp.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/xcb/xcb.h create mode 100644 maix_lvgl/tools/omnipython_lvgl/fake_libc_include/zlib.h create mode 100644 maix_lvgl/tools/regenerate_binding.py diff --git a/docs/doc/en/lvgl/lvgl.md b/docs/doc/en/lvgl/lvgl.md new file mode 100644 index 00000000..9cd15a67 --- /dev/null +++ b/docs/doc/en/lvgl/lvgl.md @@ -0,0 +1,124 @@ +--- +title: LVGL GUI +update: + - date: 2026-11-09 + author: Tao + version: 1.0.0 + content: Initial document +--- + +## Introduction + +MaixPy provides the [LVGL](https://lvgl.io/) 9.1.0 Python bindings through the `maix_lvgl` module. The API is close to the MicroPython `lvgl` binding: + +```python +import maix_lvgl as lv +``` + +`maix_lvgl` is built by MaixCDK's LVGL component and is already installed with the MaixPy wheel, so **no separate installation is needed**. + +API documentation: + +- [lvgl module](/api/maix_lvgl/lvgl.html) +- [lvgl functions](/api/maix_lvgl/lvgl_functions.html) +- [lvgl classes](/api/maix_lvgl/lvgl_classes.html) +- [maix_lvgl backend](/api/maix_lvgl/maix_lvgl.html) + +## Quick start + +```python +import time +from maix import app, display, touchscreen +import maix_lvgl as lv + +disp = display.Display() +ts = touchscreen.TouchScreen() + +try: + lv.init(disp, ts) # pass MaixPy display and touchscreen + + scr = lv.screen_active() + btn = lv.button(scr) + btn.set_size(240, 120) + btn.center() + + label = lv.label(btn) + label.set_text("Hello MaixCAM2") + + def on_click(event): + label.set_text("Clicked!") + + btn.add_event_cb(on_click, lv.EVENT.CLICKED, None) + + while not app.need_exit(): + lv.timer_handler() # advances the LVGL tick + time.sleep(0.005) +finally: + lv.deinit() + ts.close() + disp.close() +``` + +A button is shown in the center of the screen. Tapping it changes the label to `Clicked!`. + +## Initialization and main loop + +`lv.init(display, touchscreen)` accepts the MaixPy `maix.display.Display` and `maix.touchscreen.TouchScreen` objects: + +- `lv.init()` opens the display and touchscreen automatically. +- `lv.init(disp, False)` uses the display without touch input. + +Call `lv.timer_handler()` in the main loop. This is the `maix_lvgl` version: it advances `lv_tick_inc()` using the monotonic clock before running LVGL's timer handler. **Do not use the raw `lvgl.timer_handler()`**, otherwise the tick never advances and clicks/animations stop working. + +Call `lv.deinit()` when finished. If you created `display`/`touchscreen` yourself, close them separately. + +## Widgets + +```python +scr = lv.screen_active() + +# Label +label = lv.label(scr) +label.set_text("Hello") +label.center() + +# Button with a label +btn = lv.button(scr) +btn.set_size(240, 120) +btn.center() +btn_label = lv.label(btn) +btn_label.set_text("Click me") +btn_label.center() + +# Slider +slider = lv.slider(scr) +slider.set_size(200, 20) +slider.center() + +# Switch +sw = lv.switch(scr) +sw.center() +``` + +Event callbacks use the same style as LVGL: + +```python +def on_click(event): + print("clicked") + +btn.add_event_cb(on_click, lv.EVENT.CLICKED, None) +``` + +## Display and touch + +- The display driver renders LVGL into a BGRA8888 buffer and shows it with `display.show()`. +- Touch coordinates are processed by the MaixPy touch driver and already use the 640×480 screen coordinate system. +- Only one `maix.display.Display` user is allowed at a time. Stop the launcher or other apps before running. +- Tap targets must be large enough; very small buttons are easy to miss. + +## Notes + +- **JPEG images**: jpegio is not compiled in (it depends on LVGL 9.5 internals, which are not available in 9.1.0), so `lv.image` JPEG decoding is unavailable. +- **Chinese text**: only Montserrat fonts are enabled (matching MaixCDK's LVGL configuration). Chinese glyphs require a CJK bitmap font or FreeType. +- **Version**: LVGL 9.1.0, generated with [omnipython-lvgl](https://github.com/PyDevices/omnipython-lvgl). +- When building MaixPy yourself, `setup.py` builds `maix_lvgl` and packages it into the MaixPy wheel. diff --git a/docs/doc/en/sidebar.yaml b/docs/doc/en/sidebar.yaml index 37febd53..90c50363 100644 --- a/docs/doc/en/sidebar.yaml +++ b/docs/doc/en/sidebar.yaml @@ -51,6 +51,11 @@ items: - file: gui/i18n.md label: I18N (Multi language) +- label: LVGL GUI + items: + - file: lvgl/lvgl.md + label: Using LVGL + - label: AI Vision items: - file: vision/ai.md diff --git a/docs/doc/zh/lvgl/lvgl.md b/docs/doc/zh/lvgl/lvgl.md new file mode 100644 index 00000000..ebf187da --- /dev/null +++ b/docs/doc/zh/lvgl/lvgl.md @@ -0,0 +1,124 @@ +--- +title: LVGL 图形界面 +update: + - date: 2026-11-09 + author: Tao + version: 1.0.0 + content: 初版文档 +--- + +## 简介 + +MaixPy 通过 `maix_lvgl` 模块提供 [LVGL](https://lvgl.io/) 9.1.0 的 Python 绑定,写法与 MicroPython 的 `lvgl` 基本一致: + +```python +import maix_lvgl as lv +``` + +`maix_lvgl` 由 MaixCDK 的 LVGL 组件构建,并已随 MaixPy 的 wheel 一起安装,**无需单独安装**。 + +API 文档: + +- [lvgl 模块](/api/maix_lvgl/lvgl.html) +- [lvgl 函数](/api/maix_lvgl/lvgl_functions.html) +- [lvgl 类](/api/maix_lvgl/lvgl_classes.html) +- [maix_lvgl 后端](/api/maix_lvgl/maix_lvgl.html) + +## 快速开始 + +```python +import time +from maix import app, display, touchscreen +import maix_lvgl as lv + +disp = display.Display() +ts = touchscreen.TouchScreen() + +try: + lv.init(disp, ts) # 传入 MaixPy 的屏幕和触摸屏 + + scr = lv.screen_active() + btn = lv.button(scr) + btn.set_size(240, 120) + btn.center() + + label = lv.label(btn) + label.set_text("Hello MaixCAM2") + + def on_click(event): + label.set_text("Clicked!") + + btn.add_event_cb(on_click, lv.EVENT.CLICKED, None) + + while not app.need_exit(): + lv.timer_handler() # 自动推进 LVGL tick + time.sleep(0.005) +finally: + lv.deinit() + ts.close() + disp.close() +``` + +运行后屏幕中央会显示一个按钮,点击后文字变为 `Clicked!`。 + +## 初始化与主循环 + +`lv.init(display, touchscreen)` 接受 MaixPy 的 `maix.display.Display` 和 `maix.touchscreen.TouchScreen` 对象: + +- 不传参数时自动打开屏幕和触摸屏:`lv.init()` +- 只需要屏幕、不需要触摸:`lv.init(disp, False)` + +主循环中调用 `lv.timer_handler()`。该函数由 `maix_lvgl` 提供,会先按单调时间推进 `lv_tick_inc()`,再执行 LVGL 的 timer handler。**不要直接使用原生 `lvgl.timer_handler()`**,否则 tick 不会前进,点击和动画都会失效。 + +退出时调用 `lv.deinit()`;如果 `display`/`touchscreen` 是你自己创建的,还需要分别调用它们的 `close()`。 + +## 常用控件 + +```python +scr = lv.screen_active() + +# 标签 +label = lv.label(scr) +label.set_text("Hello") +label.center() + +# 按钮 + 按钮上的标签 +btn = lv.button(scr) +btn.set_size(240, 120) +btn.center() +btn_label = lv.label(btn) +btn_label.set_text("Click me") +btn_label.center() + +# 滑块 +slider = lv.slider(scr) +slider.set_size(200, 20) +slider.center() + +# 开关 +sw = lv.switch(scr) +sw.center() +``` + +事件回调和 LVGL 原生写法一致: + +```python +def on_click(event): + print("clicked") + +btn.add_event_cb(on_click, lv.EVENT.CLICKED, None) +``` + +## 屏幕与触摸 + +- 显示驱动会把 LVGL 渲染到 BGRA8888 缓冲区,再通过 `display.show()` 显示。 +- 触摸坐标由 MaixPy 的触摸驱动处理,已经是 640×480 的屏幕坐标。 +- 同一时间只能有一个 `maix.display.Display` 使用者。运行前请停止 launcher 或其他占用屏幕的应用。 +- 点击目标要足够大,过小的按钮容易点偏。 + +## 注意事项 + +- **JPEG 图片**:当前绑定未编入 jpegio(其依赖 LVGL 9.5 的内部接口,与 9.1.0 不兼容),`lv.image` 的 JPEG 解码不可用。 +- **中文显示**:默认只启用了 Montserrat 英文字体(与 MaixCDK 的 LVGL 配置一致)。显示中文需要 CJK 点阵字体或 FreeType。 +- **版本**:LVGL 9.1.0,绑定生成器参考 [omnipython-lvgl](https://github.com/PyDevices/omnipython-lvgl)。 +- 如果自行构建 MaixPy,`setup.py` 会自动构建 `maix_lvgl` 并打包进 MaixPy wheel。 diff --git a/docs/doc/zh/sidebar.yaml b/docs/doc/zh/sidebar.yaml index 745f5301..e2505403 100644 --- a/docs/doc/zh/sidebar.yaml +++ b/docs/doc/zh/sidebar.yaml @@ -51,6 +51,11 @@ items: - file: gui/i18n.md label: I18N 国际化(多语言) +- label: LVGL 图形界面 + items: + - file: lvgl/lvgl.md + label: LVGL 使用 + - label: AI 视觉 items: - file: vision/ai.md diff --git a/maix_lvgl/.gitignore b/maix_lvgl/.gitignore new file mode 100644 index 00000000..752ff52c --- /dev/null +++ b/maix_lvgl/.gitignore @@ -0,0 +1,14 @@ +build/ +dist/ +*.so +*.egg-info/ +__pycache__/ +*.pyc +.build/ +binding/lvgl_python.c +binding/lvgl.pyi +binding/lv_conf.h +binding/.binding_stamp.json + +# Generated API documentation (recreated by setup.py) +docs/api/ diff --git a/maix_lvgl/CMakeLists.txt b/maix_lvgl/CMakeLists.txt new file mode 100644 index 00000000..08bba7a7 --- /dev/null +++ b/maix_lvgl/CMakeLists.txt @@ -0,0 +1,10 @@ + +# !!! This file is auto generated by MaixCDK, don't modify it manually !!! + +cmake_minimum_required(VERSION 3.13) + +# cmake used vars defined in MaixCDK/tools/cmake/project.py's get_configs function + +include(${SDK_PATH}/tools/cmake/compile.cmake) +project(${PROJECT_ID}) + diff --git a/maix_lvgl/LICENSE b/maix_lvgl/LICENSE new file mode 100644 index 00000000..ca9ec154 --- /dev/null +++ b/maix_lvgl/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Sipeed + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/maix_lvgl/README.md b/maix_lvgl/README.md new file mode 100644 index 00000000..e2a301d0 --- /dev/null +++ b/maix_lvgl/README.md @@ -0,0 +1,170 @@ +# maix_lvgl + +[中文文档](README_ZH.md) | English + +LVGL bindings for MaixPy on MaixCAM2 with the MicroPython-style API. This is a +standard **MaixCDK project**: the LVGL library is downloaded and built by +MaixCDK, the binding is generated from that source, and `setup.py` packages the +result the same way MaixPy does. + +![maix_lvgl on MaixCAM2](docs/screenshot.png) + +*Rendered by MaixCAM2 through `maix.display.Display` (640×480, BGRA8888).* + +The binding is generated with the generator from +[PyDevices/omnipython-lvgl](https://github.com/PyDevices/omnipython-lvgl) +(MIT), vendored under `tools/omnipython_lvgl/`. + +Prebuilt wheel: [Releases](https://github.com/Taoxuan-168/Maix_LVGL/releases). + +## Quick start + +```python +import time +from maix import app, display, touchscreen +import maix_lvgl as lv + +disp = display.Display() +ts = touchscreen.TouchScreen() + +try: + lv.init(disp, ts) # pass MaixPy display + touchscreen + + scr = lv.screen_active() + btn = lv.button(scr) # same style as MicroPython's lvgl + btn.set_size(240, 120) + btn.center() + label = lv.label(btn) + label.set_text("Hello MaixCAM2") + + btn.add_event_cb(lambda e: print("clicked"), lv.EVENT.CLICKED, None) + + while not app.need_exit(): + lv.timer_handler() # maix_lvgl version: advances the LVGL tick + time.sleep(0.005) +finally: + lv.deinit() + ts.close() + disp.close() +``` + +## Standard MaixCDK project layout + +``` +maix_lvgl/ +├── CMakeLists.txt # MaixCDK project entry +├── project.py # MaixCDK build driver +├── Kconfig # project config +├── main/ # entry component (depends on lvgl_binding) +├── components/lvgl_binding/ # LVGL CPython extension component +│ ├── CMakeLists.txt # links MaixCDK's lvgl + python3, generates binding +│ ├── component.py # add_requirements: lvgl, python3 +│ └── Kconfig +├── binding/ # generated C binding + pyi + lv_conf.h +├── runtime/ # CPython runtime glue (lvpy_runtime.c/h) +├── maix_lvgl/ # Python backend + built extension (in the wheel) +├── tools/ +│ ├── maixcdk_lvgl.py # locate MaixCDK / its LVGL source +│ ├── regenerate_binding.py# regenerate binding from MaixCDK's LVGL (stamped) +│ └── omnipython_lvgl/ # vendored generator (MIT) +├── configs/config_platform_maixcam2.mk +├── setup.py # project.py build + wheel packaging (like MaixPy) +└── dist/ +``` + +`components/lvgl_binding` declares `ADD_REQUIREMENTS lvgl python3`, so +MaixCDK downloads its pinned LVGL (9.1.0 today, from +`components/3rd_party/lvgl/Kconfig`), compiles it together with the rest of +the stack, and the binding links against that exact library. + +## Building + +```bash +export MAIXCDK_PATH=/path/to/MaixCDK +python3 setup.py bdist_wheel +``` + +What happens: + +1. `setup.py` runs `python project.py build -p maixcam2 --release` (same + pattern as MaixPy's `setup.py`). +2. MaixCDK downloads its LVGL source and dependencies (first build), then the + `lvgl_binding` component's custom target regenerates + `binding/lvgl_python.c` from that source when it changed. +3. The component compiles and links against MaixCDK's `lvgl` and `python3` + components with MaixCDK's cross toolchain. +4. The wheel is packaged as `cp313-manylinux2014_aarch64`: + `maix_lvgl/` contains `__init__.py`, `driver.py`, + `lvgl.cpython-313-aarch64-linux-gnu.so` and `dl_lib/libdatachannel.so`. + +The build also generates MaixPy-style API documentation from +`binding/lvgl.pyi` into `docs/api/` (`api.json`, `config.json`, `README.md`, +`README2.md`, `sidebar.yaml` and `maix_lvgl/{lvgl,maix_lvgl}.md`), the same +build-time flow as MaixPy's `components/maix/gen_api.py` -> `docs/api/maix`. +The generated docs are a build artifact and are not tracked in git; run +`python3 tools/gen_api_docs.py` to regenerate them alone. + +Build requirements: MaixCDK with MaixCAM2 toolchain/Python headers under +`dl/extracted`, **cmake 3.x** (MaixCDK's freetype subproject rejects cmake 4), +`pycparser` (`pip install 'pycparser>=3.0'`), host `gcc`, and network access +for the first dependency download. + +Binding regeneration is cached in `binding/.binding_stamp.json` and runs +automatically during `project.py build`. Force it with: + +```bash +python3 tools/regenerate_binding.py --force +# or +./scripts/regenerate_binding.sh +``` + +`--skip-build` reuses the existing MaixCDK build when re-packaging: + +```bash +python3 setup.py bdist_wheel --skip-build +``` + +## Configuration notes + +The binding uses MaixCDK's LVGL `lv_conf.h` as-is (so struct layouts match the +library MaixCDK compiles): `LV_USE_OS=LV_OS_PTHREAD`, `LV_USE_RLOTTIE=1`, +`LV_COLOR_DEPTH=32`. Two build-system-only bits are removed +(`global_config.h` include and the `lv_ui_mutex_*` declarations), and the +generated C has Python access stripped from fields whose types are +`pthread_mutex_t` (`lv_thread_sync_t`, `lv_draw_global_info_t.circle_cache_mutex`, +`lv_cache_t.lock`), which have no Python representation. + +MaixCAM2's display only accepts BGRA8888, which is byte-identical to LVGL's +little-endian ARGB8888 output; `FMT_RGB565` is rejected by the display driver. + +## Tick and main loop + +`lv_tick_set_cb()` cannot be used from the generated CPython binding: that API +takes no `user_data`, so the Python callback is not kept alive and the tick +stays at 0 (no LVGL timer, including the indev read timer, ever fires). +`maix_lvgl.timer_handler()` advances `lv_tick_inc()` on the main thread before +calling LVGL's timer handler; the re-exported `lv.timer_handler` already +points to it. + +Do not call the raw `lvgl.timer_handler()` unless you advance `lv_tick_inc()` +yourself. + +## Verified + +- Wheel built through MaixCDK's `project.py`, installed on MaixCAM2 + (MaixPy 4.12.5) from inside `maix_lvgl/`; 640×480 BGRA8888 rendering + confirmed by screenshot. +- Touch indev: 25 read callbacks in 50 timer-handler passes; manual + `indev.read()` also wired correctly. +- Earlier builds of the same backend: 74 consecutive `lv.EVENT.CLICKED` + hits, clean `lv.deinit()`. + +## Known limitations + +- **JPEG images**: upstream jpegio depends on LVGL 9.5 image-cache internals + that do not exist in 9.1.0, so it is not compiled. +- **Chinese text**: only Montserrat fonts are enabled (MaixCDK's LVGL config). +- **Touch targets**: touch is verified; widgets must cover the actual touched + area. +- **Display ownership**: only one `maix.display.Display` user at a time; stop + the launcher/other apps before `lv.init()`. diff --git a/maix_lvgl/README_ZH.md b/maix_lvgl/README_ZH.md new file mode 100644 index 00000000..a7f46be9 --- /dev/null +++ b/maix_lvgl/README_ZH.md @@ -0,0 +1,160 @@ +# maix_lvgl + +[English](README.md) | 中文 + +面向 MaixPy(MaixCAM2)的 LVGL 绑定,API 与 MicroPython 的 `lvgl` 写法一致。 +本项目是一个**标准 MaixCDK 工程**:LVGL 由 MaixCDK 自动下载并编译,绑定基于 +MaixCDK 的 LVGL 源码生成,`setup.py` 按 MaixPy 的方式打包 wheel。 + +![maix_lvgl 在 MaixCAM2 上运行](docs/screenshot.png) + +*由 MaixCAM2 通过 `maix.display.Display` 实际渲染(640×480,BGRA8888)。* + +绑定生成参考并使用了 [PyDevices/omnipython-lvgl](https://github.com/PyDevices/omnipython-lvgl) +的生成器(MIT 协议,已内置在 `tools/omnipython_lvgl/`)。 + +预构建 wheel:[Releases](https://github.com/Taoxuan-168/Maix_LVGL/releases)。 + +## 快速开始 + +```python +import time +from maix import app, display, touchscreen +import maix_lvgl as lv + +disp = display.Display() +ts = touchscreen.TouchScreen() + +try: + lv.init(disp, ts) # 直接传入 MaixPy 屏幕和触摸屏 + + scr = lv.screen_active() + btn = lv.button(scr) # 与 MicroPython 写法一致 + btn.set_size(240, 120) # 按钮大一些,方便点击 + btn.center() + label = lv.label(btn) + label.set_text("Hello MaixCAM2") + + btn.add_event_cb(lambda e: print("clicked"), lv.EVENT.CLICKED, None) + + while not app.need_exit(): + lv.timer_handler() # maix_lvgl 版本:自动推进 tick + time.sleep(0.005) +finally: + lv.deinit() + ts.close() + disp.close() +``` + +## 标准 MaixCDK 工程结构 + +``` +maix_lvgl/ +├── CMakeLists.txt # MaixCDK 工程入口 +├── project.py # MaixCDK 构建驱动 +├── Kconfig # 工程配置 +├── main/ # 入口组件(依赖 lvgl_binding) +├── components/lvgl_binding/ # LVGL CPython 扩展组件 +│ ├── CMakeLists.txt # 链接 MaixCDK 的 lvgl + python3,并生成绑定 +│ ├── component.py # add_requirements: lvgl, python3 +│ └── Kconfig +├── binding/ # 生成的 C 绑定 + pyi + lv_conf.h +├── runtime/ # CPython 运行时胶水(lvpy_runtime.c/h) +├── maix_lvgl/ # Python 后端 + 构建出的扩展(wheel 中) +├── tools/ +│ ├── maixcdk_lvgl.py # 定位 MaixCDK 及其 LVGL 源码 +│ ├── regenerate_binding.py# 从 MaixCDK 的 LVGL 重新生成绑定(带 stamp 缓存) +│ └── omnipython_lvgl/ # 内置生成器(MIT) +├── configs/config_platform_maixcam2.mk +├── setup.py # project.py build + wheel 打包(模仿 MaixPy) +└── dist/ +``` + +`components/lvgl_binding` 通过 `ADD_REQUIREMENTS lvgl python3` 依赖 MaixCDK 的 +LVGL 组件:MaixCDK 会自动下载其 Kconfig 固定的 LVGL(当前 9.1.0)、编译整条 +依赖栈,绑定则链接这份实际的 LVGL 库。 + +## 构建 + +```bash +export MAIXCDK_PATH=/path/to/MaixCDK +python3 setup.py bdist_wheel +``` + +流程: + +1. `setup.py` 调用 `python project.py build -p maixcam2 --release`(与 MaixPy + 的 `setup.py` 相同模式)。 +2. MaixCDK 下载其 LVGL 源码和依赖(首次构建);`lvgl_binding` 组件的自定义 + 目标在源码变化时从 MaixCDK 的 LVGL 重新生成 `binding/lvgl_python.c`。 +3. 组件用 MaixCDK 的交叉工具链编译,并链接 MaixCDK 的 `lvgl`、`python3` + 组件。 +4. 打包为 `cp313-manylinux2014_aarch64` wheel:`maix_lvgl/` 内包含 + `__init__.py`、`driver.py`、`lvgl.cpython-313-aarch64-linux-gnu.so` 和 + `dl_lib/libdatachannel.so`。 + +构建时还会从 `binding/lvgl.pyi` 生成 MaixPy 风格的 API 文档到 `docs/api/` +(`api.json`、`config.json`、`README.md`、`README2.md`、`sidebar.yaml`,以及 +`maix_lvgl/{lvgl,maix_lvgl}.md` 模块页),与 MaixPy 的 +`components/maix/gen_api.py` → `docs/api/maix` 采用相同的构建时流程; +生成物不纳入 git,可单独运行 `python3 tools/gen_api_docs.py` 重新生成。 + +构建要求:带 MaixCAM2 工具链/Python 头文件的 MaixCDK(`dl/extracted` 下)、 +**cmake 3.x**(MaixCDK 的 freetype 子工程不兼容 cmake 4)、`pycparser` +(`pip install 'pycparser>=3.0'`)、宿主 `gcc`,以及首次下载依赖的网络。 + +绑定重新生成带缓存(`binding/.binding_stamp.json`),在 `project.py build` +时自动执行。强制重生成: + +```bash +python3 tools/regenerate_binding.py --force +# 或 +./scripts/regenerate_binding.sh +``` + +打包时复用已有 MaixCDK 构建可用: + +```bash +python3 setup.py bdist_wheel --skip-build +``` + +## 配置说明 + +绑定直接使用 MaixCDK 的 LVGL `lv_conf.h`(保证与 MaixCDK 编译出的库结构体 +一致):`LV_USE_OS=LV_OS_PTHREAD`、`LV_USE_RLOTTIE=1`、`LV_COLOR_DEPTH=32`。 +仅移除两处构建系统专用的内容(`global_config.h` include 和 +`lv_ui_mutex_*` 声明);生成后的 C 会去掉 `pthread_mutex_t` 类型字段的 Python +访问(`lv_thread_sync_t`、`lv_draw_global_info_t.circle_cache_mutex`、 +`lv_cache_t.lock`),因为这些类型无法映射到 Python。 + +MaixCAM2 的显示只接受 BGRA8888,而 LVGL 在小端平台 ARGB8888 的字节顺序正好是 +B,G,R,A,与 `FMT_BGRA8888` 一致;显示驱动不接受 `FMT_RGB565`。 + +## tick 与主循环 + +`lv_tick_set_cb()` 在生成的 CPython 绑定中不可用:该 API 没有 `user_data` +参数,Python 回调无法被保持,`lv_tick_get()` 会一直是 0,导致 LVGL 的全部 +定时器(包括触摸 indev 的读取定时器)都不运行。 + +因此 `maix_lvgl.timer_handler()` 会在主线程先按单调时间推进 +`lv.tick_inc()`,再调用 LVGL 的 `timer_handler()`。重导出的 +`lv.timer_handler` 已指向该版本。 + +不要直接调用原生 `lvgl.timer_handler()`,除非你自己推进 `lv.tick_inc()`。 + +## 已验证 + +- 通过 MaixCDK 的 `project.py` 构建 wheel,安装到 MaixCAM2(MaixPy 4.12.5) + 后从 `maix_lvgl/` 包内加载扩展;640×480 BGRA8888 渲染截图正常。 +- 触摸 indev:50 次 timer_handler 触发 25 次 read 回调;手动 `indev.read()` + 也正常。 +- 同一后端较早的构建:连续 74 次 `lv.EVENT.CLICKED` 命中、`lv.deinit()` 正常。 + +## 已知限制 + +- **JPEG 图片**:上游 jpegio 依赖 LVGL 9.5 的 image-cache 内部结构,LVGL 9.1.0 + 中不存在,因此未编译。 +- **中文显示**:只启用了 Montserrat 字体(MaixCDK 的 LVGL 配置如此)。 +- **点击目标**:触摸已验证,但控件本身要覆盖你实际触摸的区域。 +- **显示独占**:同一时间只能有一个 `maix.display.Display` 使用者,运行前需停止 + launcher 或其他应用。 diff --git a/maix_lvgl/binding/.gitkeep b/maix_lvgl/binding/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/maix_lvgl/components/lvgl_binding/CMakeLists.txt b/maix_lvgl/components/lvgl_binding/CMakeLists.txt new file mode 100644 index 00000000..325650f5 --- /dev/null +++ b/maix_lvgl/components/lvgl_binding/CMakeLists.txt @@ -0,0 +1,33 @@ +############### Add include ################### +list(APPEND ADD_INCLUDE "${PROJECT_PATH}/binding" + "${PROJECT_PATH}/runtime") +list(APPEND ADD_PRIVATE_INCLUDE "") +############################################### + +############ Add source files ################# +set(binding_dir "${PROJECT_PATH}/binding") +file(MAKE_DIRECTORY "${binding_dir}") +set(binding_src "${binding_dir}/lvgl_python.c") +set_property(SOURCE "${binding_src}" PROPERTY GENERATED 1) +list(APPEND ADD_SRCS "${PROJECT_PATH}/runtime/lvpy_runtime.c" + "${binding_src}") +############################################### + +###### Add required/dependent components ###### +list(APPEND ADD_REQUIREMENTS lvgl python3) +############################################### + +#### Add compile option for this component #### +list(APPEND ADD_DEFINITIONS -DLV_CPYTHON_BUILD + -DLV_CONF_INCLUDE_SIMPLE) +############################################### + +###### Generate binding before compiling ###### +add_custom_target(generate_lvgl_binding ALL + COMMAND ${python} -u "${PROJECT_PATH}/tools/regenerate_binding.py" --sdk-path "${SDK_PATH}" + COMMENT "Generating LVGL binding from MaixCDK's LVGL sources" + VERBATIM) +############################################### + +register_component(DYNAMIC) +add_dependencies(lvgl_binding generate_lvgl_binding) diff --git a/maix_lvgl/components/lvgl_binding/Kconfig b/maix_lvgl/components/lvgl_binding/Kconfig new file mode 100644 index 00000000..62aa47e8 --- /dev/null +++ b/maix_lvgl/components/lvgl_binding/Kconfig @@ -0,0 +1,3 @@ + +menu "maix_lvgl component configuration" +endmenu diff --git a/maix_lvgl/components/lvgl_binding/component.py b/maix_lvgl/components/lvgl_binding/component.py new file mode 100644 index 00000000..74a656ab --- /dev/null +++ b/maix_lvgl/components/lvgl_binding/component.py @@ -0,0 +1,3 @@ +def add_requirements(platform, component_dirs): + """MaixCDK resolves lvgl (source + library) and python3 (headers/lib).""" + return ["lvgl", "python3"] diff --git a/maix_lvgl/configs/config_platform_maixcam2.mk b/maix_lvgl/configs/config_platform_maixcam2.mk new file mode 100644 index 00000000..e69de29b diff --git a/maix_lvgl/docs/screenshot.png b/maix_lvgl/docs/screenshot.png new file mode 100644 index 0000000000000000000000000000000000000000..2a045c1b877cdd08b8878515e7ec8432d9b5abea GIT binary patch literal 6797 zcmeHMdr(tX8jn&-D^;dirB)zYX^V=GuG9i0CS9$f#hUu4X(13=MOIM}qQscT)paaw zsUY%*7$C#6EMrl^LkKaDU>%-;q>2zCAyG_-l#oCIgplOky*F!sWji~wGyB&L|0QA0 zch2{HzsGkD-+#V0V%gHSmZDIoWxIEMvLA(7d;x`8^yHP7;a|2qP-;-9w+`<9?v8IZrCdIr zwJ!8=H|Nv`*Wzyu_vnu={cdn^v9Dm$ieGN*T=QMwXYaiJ`I{?#KDo2vgLRE0oE^$Kgh#RG_hnl^M;y<*HNgy?>j#1heGZ7=}}Jv3Uz(w&D)tM)caTV zN23>^;@&E$#VtlPe(>o@=1Zsx$8sJ|zk)(_tzTHUP@DziEU;riI{xqE@xq4NHTQ9uhM5i{(C2(4D(W zL4ALezXo14(PHTAWra2Vz7dHSKjN6^)UzbQ#rX1cwe`3Zx>t!RD|0TrV`Bq>bfbfC zk^9K%55@$63bgx|pE)=D*#S)gM@O1DZupxLJYxe7VgoDUw&cRjSCP{5IJz1Nf!-PI zI`6PR@j(C-z331Dam)bST_NsTQ~%nF+#b_Vgt<8w?NMb~fzsdJc`n+bp(<}(4jbu?@{&K7H7zJ)Ege9y)2?Xy~U18iaxJ&J~ zq(z}C;wBIyu1Hz#jbAnORpHj;cU__S`3NvdYzN)gO zV`DgdVAqB21F-Qowuhaz9|V&oo^MTO7(29f9Z!_S?H-(7*C#o0I5A%w$r(;Rfyusd zJD!!(cWNW;dB#?23!lVB7l{in4QDoFGUD^Qc!RvDX?KgRxgk+8*3^}x={+E^uc!LP zO14w=Z5W5rU>~(>v6ELkXnH}qpl5y(*E%P5)Uw-}do}~?59MBp*!R{(OGqPmYp*5v zhF*mmqG|;kgKHIIoFs7&zdJ@?^CV01J>DfMY3BmNeeWJ7NH;}fY^~|&Hel=XvLh_I z^ip+ef|&VdzBfsdrmAc$g)En`cKu~iG0o-mx-MOcWLaCV zr+2FxK~#hhGr|DQOm;?~uN{g0Zna-|ycCU}BbBIsJsLVqYf%aQXzWZ{`eJ-9YYdE)oSa0l!u};xvk1%H+p?NfF zuWvtBZR;{yd1{7V+Uj=^SmH)KEk{~zb3-|0ThGhZrLAtOEX|`;hkNq0ng~HAf=*WTsBr6}6HmJkv@&XXj3HKIt4iU3w z8ctNE9%#$9kh#WF{a@8;2==ZsVa(wSCb9?gC^lBT{bG>usd z5@!|-Q^ju9=UqC}ln1-&@C?^7O;1LI=4f$M2+?jO$99-`Bq<)U3C&3J{wJv;LTLhr zDK>v{Cn8hWWVH$lwQCV7dMkrX$|U7g0)v^~BDU_VW&6R3hUkRhBie_h|Hz_3xrXjr-@;dVol48yc}&g8Ip^oK@&)4lqshJ{WA?RByS%Vrv(!$6DT!a_%nY( zGp9+uz|;MyFe$4V_Iy~IXXPkUwpTTHBQarZ5NPAt8h|r6B7MAQ$MV2yhY5k^qkQF6 zthwm~`J8^KL7bn?+={2U}Bb!7~dL?V1Q z7Op{pE0SM`NCX$hZXws@{5u#yEfn_Afbcg_xZzWo9lNB5vG-wwv3{8=9Y$}2_I@zy?&46vb@AoL& zc*YJy>AmU4^IzcD{8Yx3=wj=0d=RBA-jSle8IK&h&Bl|Z;ejA7eQdu=)Ba22eW4Zq zi7@&)7%$-cm~^|nIL2z2EWv`EAtr>r^8w>q&!qY?Y(+{(8c*AC`PvK-T;>MOf=i`u z^7Ls%JXL9n&{1ms$Y~K$&gku2{eXw1dfQ-(AlVot5;8Yr0_H17SM+tT3=_a^kf9NC zWo)vjU~a(#Z(Fm08a&!+)S0zxOhQXxn%wl858V`r=Z7N{M_`U1qP%9F1;@XP5YK*A zHFi^OrapC{>#XU-Uh$2a1@q=VyQZivDG45kaJG?jt13TBOs&uqhp&d|7a0Z_-~3%-3oN#O1$r4!ReNJ0WZ zzKdoLLBNKuPJPx1kL}1MLk>ysuU6b}4%xeffK^^)Q9*A^?Jfic)Y<{ABl$x2LFb73 z*fz{jIP$1VSR^m8xw`GrqH}C7^Zuy7;fc$tGR8eg3YHeO4QKXqDjg{oy1#HP z6@taQ5`FlaQ^P+}5=@W%jIUKpBO6}-b;6Sw7_Yw9*zKC!uWv^p9$25YJR#W#bQt*c z0jHaqjEpT3e~{TcDOoi5ITG?V^0F hh5u1pZ-zX6DeK~#ePbW&3n 0: + _lvgl.tick_inc(delta) + _last_tick = now + return _lvgl.timer_handler() + + +def process(): + """Run one LVGL timer-handler pass and return its next delay (ms).""" + return timer_handler() + + +def run(fps=60): + """Run the LVGL loop until MaixPy asks the application to exit.""" + from maix import app + + period = 1.0 / fps + while not app.need_exit(): + timer_handler() + time.sleep(period) + + +def deinit(): + """Stop LVGL and release the display/touchscreen opened by :func:`init`.""" + global _display_driver, _touch_driver, _initialized + if not _initialized: + return + if _touch_driver is not None: + _touch_driver.deinit() + _touch_driver = None + if _display_driver is not None: + _display_driver.deinit() + _display_driver = None + _lvgl.deinit() + _last_tick = None + _initialized = False + + +# Re-export every LVGL binding name so ``import maix_lvgl as lv`` behaves like +# ``import lvgl as lv`` (MicroPython-style API). +def __getattr__(name): + return getattr(_lvgl, name) + + +def __dir__(): + return sorted(set(globals()) | set(dir(_lvgl))) + + +__all__ = [n for n in dir(_lvgl) if not n.startswith("_")] + [ + "init", + "deinit", + "run", + "process", + "timer_handler", +] diff --git a/maix_lvgl/maix_lvgl/driver.py b/maix_lvgl/maix_lvgl/driver.py new file mode 100644 index 00000000..4d9ea7bb --- /dev/null +++ b/maix_lvgl/maix_lvgl/driver.py @@ -0,0 +1,130 @@ +"""LVGL drivers for MaixPy display and touchscreen. + +The display driver renders LVGL into a Python ``bytearray`` (BGRA8888, which +matches LVGL's 32-bit ARGB8888 output on little-endian targets) and pushes it +to ``maix.display.Display`` with ``show()``. The touch driver feeds +``maix.touchscreen.TouchScreen`` events into an LVGL pointer indev. +""" +from __future__ import annotations + +import time + +import lvgl as lv + +from maix import display as maix_display +from maix import image as maix_image +from maix import touchscreen as maix_touchscreen + +_BGRA8888 = maix_image.Format.FMT_BGRA8888 + + +class DisplayDriver: + """Bind one LVGL display to a MaixPy display object.""" + + def __init__(self, display=None, width=None, height=None): + self._owned_display = display is None + if display is None: + if width is None or height is None: + probe = maix_display.Display() + size = probe.size() + probe.close() + width = size[0] if width is None else width + height = size[1] if height is None else height + display = maix_display.Display(width, height, _BGRA8888) + self.display = display + self.width = display.width() + self.height = display.height() + + # LVGL paints directly into this buffer. It is full-screen so a flush + # callback can hand the whole frame to MaixPy without stitching areas. + self._buffer = bytearray(self.width * self.height * 4) + self._disp = lv.display_create(self.width, self.height) + self._disp.set_color_format(lv.COLOR_FORMAT.ARGB8888) + self._disp.set_buffers( + self._buffer, None, len(self._buffer), lv.DISPLAY_RENDER_MODE.FULL + ) + self._disp.set_flush_cb(self._flush) + # Input devices attach to the default display (LVGL sets it on + # lv_indev_create); make this display the default explicitly. + self._disp.set_default() + + # The LVGL tick is advanced from maix_lvgl.timer_handler() on the + # main thread. lv_tick_set_cb can't be used here: that API takes no + # user_data, so the generated CPython binding does not keep the + # Python callback alive and the tick would stay at 0. + + def _flush(self, disp, area, px): + if disp.flush_is_last(): + # ARGB8888 in LVGL is byte-ordered B,G,R,A on little-endian, which + # is exactly MaixPy's FMT_BGRA8888. + img = maix_image.from_bytes( + self.width, + self.height, + _BGRA8888, + bytes(self._buffer), + True, + ) + self.display.show(img, maix_image.Fit.FIT_FILL) + disp.flush_ready() + + def deinit(self): + if self._disp is not None: + try: + self._disp.delete() + except Exception: + pass + self._disp = None + if self._owned_display and self.display is not None: + try: + self.display.close() + except Exception: + pass + self.display = None + + +class TouchDriver: + """Bind a MaixPy touchscreen to an LVGL pointer indev.""" + + def __init__(self, touchscreen=None, display=None): + self._owned_touchscreen = touchscreen is None + if touchscreen is None: + touchscreen = maix_touchscreen.TouchScreen() + self.touchscreen = touchscreen + self._indev = lv.indev_create() + self._indev.set_type(lv.INDEV_TYPE.POINTER) + # LVGL skips an indev whose display is NULL, so bind it explicitly. + if display is not None: + self._indev.set_display(display) + self._indev.set_read_cb(self._read) + + def _read(self, indev, data): + # TouchScreen.read() returns [x, y, pressed] in display coordinates; + # MaixCDK already applies the panel's axis mapping. + values = None + try: + values = self.touchscreen.read() + except Exception: + values = None + if values and len(values) >= 3: + x, y, pressed = values[0], values[1], values[2] + else: + x, y, pressed = 0, 0, 0 + data.point.x = int(x) + data.point.y = int(y) + data.state = ( + lv.INDEV_STATE.PRESSED if pressed else lv.INDEV_STATE.RELEASED + ) + + def deinit(self): + if self._indev is not None: + try: + self._indev.delete() + except Exception: + pass + self._indev = None + if self._owned_touchscreen and self.touchscreen is not None: + try: + self.touchscreen.close() + except Exception: + pass + self.touchscreen = None diff --git a/maix_lvgl/project.py b/maix_lvgl/project.py new file mode 100755 index 00000000..478c983e --- /dev/null +++ b/maix_lvgl/project.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python +#-*- coding = utf-8 -*- + +# +# @file from https://github.com/Neutree/c_cpp_project_framework +# @author neucrack +# @license Apache 2.0 +# + +import sys, os + +def is_project_valid(): + return os.path.exists("main") + +def get_sdk_path(): + sdk_path = None + sdk_env_name = "MAIXCDK_PATH" + + # 1. get SDK absolute path from MAIXCDK_PATH env + try: + if os.environ[sdk_env_name]: + sdk_path = os.environ[sdk_env_name] + except Exception: + pass + + # 2. check if in MaixCDK repo, higher priority + path = os.path.abspath("../../") + if os.path.exists(path+"/tools/cmake/project.py"): + sdk_path = path + + # 3. check if MaixCDK path valid + if not sdk_path: + print("") + print("Error: can not find MaixCDK, please set MAIXCDK_PATH env to MaixCDK directory by `export MAIXCDK_PATH=xxxxx`") + print("") + sys.exit(1) + if not os.path.exists(sdk_path): + print("") + print(f"Error: MaixCDK set to {sdk_path}, but not exists!") + print("") + sys.exit(1) + return os.path.abspath(sdk_path) + +def exec_project_py(): + # 1. check main component + if not is_project_valid(): + print("") + print("Error: can not find main component, please execute this command in your project root directory") + print("") + sys.exit(1) + + # 2. get MaixCDK path + sdk_path = get_sdk_path() + print("-- SDK_PATH:{}".format(sdk_path)) + project_path = os.path.abspath(".") + + # 3. execute project script from SDK + project_file_path = sdk_path+"/tools/cmake/project.py" + sys.path.insert(0, os.path.dirname(project_file_path)) + from project import main + main(sdk_path, project_path) + +def main(): + exec_project_py() + +if __name__ == "__main__": + main() diff --git a/maix_lvgl/pyproject.toml b/maix_lvgl/pyproject.toml new file mode 100644 index 00000000..ef6ed758 --- /dev/null +++ b/maix_lvgl/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["setuptools>=61", "wheel", "pycparser>=3.0"] +build-backend = "setuptools.build_meta" diff --git a/maix_lvgl/runtime/lvpy_runtime.c b/maix_lvgl/runtime/lvpy_runtime.c new file mode 100644 index 00000000..a025237c --- /dev/null +++ b/maix_lvgl/runtime/lvpy_runtime.c @@ -0,0 +1,1186 @@ +#include "lvpy_runtime.h" +#include "lvgl/src/lvgl_private.h" +#include + +PyObject *PyLvReferenceError = NULL; +PyObject *mp_lv_global_user_data = NULL; +PyObject *lvpy_nesting_obj = NULL; + +PyTypeObject py_C_Pointer_type; +PyTypeObject py_lv_base_struct_type; +PyTypeObject py_blob_type; + +static PyThread_type_lock lvgl_lock = NULL; +static long lvgl_lock_owner = -1; +static int lvgl_lock_depth = 0; +static int lvpy_nesting_count = 0; +static int lvpy_lock_save_key = -1; + +static void lvpy_drain_pending_releases_if_idle(void); +static void lvpy_unlock_nodrain(void); +static void lvpy_defer_release(PyObject *obj); + +typedef struct { + PyTypeObject *type; + size_t size; +} lv_struct_size_entry; + +static lv_struct_size_entry *struct_size_entries = NULL; +static size_t struct_size_entry_count = 0; +static size_t struct_size_entry_cap = 0; + +void lvpy_lock(void) +{ + if (!lvgl_lock) { + return; + } + long tid = PyThread_get_thread_ident(); + if (lvgl_lock_depth > 0 && lvgl_lock_owner == tid) { + lvgl_lock_depth++; + return; + } + PyThread_acquire_lock(lvgl_lock, WAIT_LOCK); + lvgl_lock_owner = tid; + lvgl_lock_depth = 1; +} + +static void lvpy_unlock_nodrain(void) +{ + if (!lvgl_lock || lvgl_lock_depth == 0) { + return; + } + long tid = PyThread_get_thread_ident(); + if (lvgl_lock_owner != tid) { + return; + } + lvgl_lock_depth--; + if (lvgl_lock_depth == 0) { + lvgl_lock_owner = -1; + PyThread_release_lock(lvgl_lock); + } +} + +/* Every generated wrapper unlocks after its LVGL call, with the GIL held. + * That is the safe moment to let go of callback dicts whose registrations + * ended inside the call (see lvpy_release_callback_user_data). */ +void lvpy_unlock(void) +{ + lvpy_unlock_nodrain(); + lvpy_drain_pending_releases_if_idle(); +} + +void lvpy_release_lock_for_python(void) +{ + long tid = PyThread_get_thread_ident(); + if (lvgl_lock_owner != tid || lvgl_lock_depth == 0) { + if (lvpy_lock_save_key >= 0) { + PyThread_set_key_value(lvpy_lock_save_key, (void *)(intptr_t)0); + } + return; + } + if (lvpy_lock_save_key >= 0) { + PyThread_set_key_value(lvpy_lock_save_key, (void *)(intptr_t)lvgl_lock_depth); + } + while (lvgl_lock_depth > 0) { + lvpy_unlock_nodrain(); + } +} + +void lvpy_reacquire_lock_after_python(void) +{ + if (lvpy_lock_save_key < 0) { + return; + } + int saved = (int)(intptr_t)PyThread_get_key_value(lvpy_lock_save_key); + for (int i = 0; i < saved; i++) { + lvpy_lock(); + } + PyThread_set_key_value(lvpy_lock_save_key, (void *)(intptr_t)0); +} + +void lvpy_nesting_inc(void) +{ + lvpy_nesting_count++; + if (lvpy_nesting_obj) { + PyObject *val = PyLong_FromLong(lvpy_nesting_count); + if (val) { + PyObject_SetAttrString(lvpy_nesting_obj, "value", val); + Py_DECREF(val); + } else { + PyErr_Clear(); + } + } +} + +void lvpy_nesting_dec(void) +{ + if (lvpy_nesting_count > 0) { + lvpy_nesting_count--; + } + if (lvpy_nesting_obj) { + PyObject *val = PyLong_FromLong(lvpy_nesting_count); + if (val) { + PyObject_SetAttrString(lvpy_nesting_obj, "value", val); + Py_DECREF(val); + } else { + PyErr_Clear(); + } + } +} + +void lv_struct_register_size(PyTypeObject *type, size_t size) +{ + if (!type || size == 0) return; + for (size_t i = 0; i < struct_size_entry_count; i++) { + if (struct_size_entries[i].type == type) { + struct_size_entries[i].size = size; + return; + } + } + if (struct_size_entry_count >= struct_size_entry_cap) { + size_t new_cap = struct_size_entry_cap ? struct_size_entry_cap * 2 : 32; + lv_struct_size_entry *grown = realloc(struct_size_entries, new_cap * sizeof(lv_struct_size_entry)); + if (!grown) return; + struct_size_entries = grown; + struct_size_entry_cap = new_cap; + } + struct_size_entries[struct_size_entry_count].type = type; + struct_size_entries[struct_size_entry_count].size = size; + struct_size_entry_count++; +} + +size_t lv_struct_get_size(PyTypeObject *type) +{ + if (!type) return 0; + for (size_t i = 0; i < struct_size_entry_count; i++) { + if (struct_size_entries[i].type == type) { + return struct_size_entries[i].size; + } + } + return 0; +} + +void lv_struct_expose_size(PyTypeObject *type) +{ + PyObject *size_obj; + + if (!type) { + return; + } + size_t size = lv_struct_get_size(type); + if (size == 0) { + return; + } + if (PyType_Ready(type) < 0) { + PyErr_Clear(); + return; + } + size_obj = PyLong_FromSize_t(size); + if (!size_obj) { + PyErr_Clear(); + return; + } + if (type->tp_dict == NULL) { + type->tp_dict = PyDict_New(); + if (type->tp_dict == NULL) { + Py_DECREF(size_obj); + PyErr_Clear(); + return; + } + } + if (PyDict_SetItemString(type->tp_dict, "__SIZE__", size_obj) < 0) { + PyErr_Clear(); + } + Py_DECREF(size_obj); +} + +static PyObject *py_nesting_get_value(PyObject *self, void *closure) +{ + (void)self; + (void)closure; + return PyLong_FromLong(lvpy_nesting_count); +} + +static int py_nesting_set_value(PyObject *self, PyObject *value, void *closure) +{ + (void)self; + (void)closure; + if (!value) { + PyErr_SetString(PyExc_TypeError, "cannot delete nesting value"); + return -1; + } + lvpy_nesting_count = (int)PyLong_AsLong(value); + if (PyErr_Occurred()) return -1; + return 0; +} + +static PyGetSetDef py_nesting_getset[] = { + {"value", py_nesting_get_value, py_nesting_set_value, NULL}, + {NULL} +}; + +static PyTypeObject py_nesting_type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "lvgl._Nesting", + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_getset = py_nesting_getset, +}; + +PyObject *lvpy_create_nesting_obj(void) +{ + if (PyType_Ready(&py_nesting_type) < 0) return NULL; + return PyType_GenericNew(&py_nesting_type, NULL, NULL); +} + +static PyObject *py_lv_dereference(PyObject *self, PyObject *args) +{ + py_lv_struct_t *inst = (py_lv_struct_t *)self; + Py_ssize_t size = 0; + if (!PyArg_ParseTuple(args, "|n", &size)) return NULL; + if (!inst->data) { + PyErr_SetString(PyLvReferenceError, "struct data is NULL"); + return NULL; + } + if (size <= 0) { + size = (Py_ssize_t)lv_struct_get_size(Py_TYPE(self)); + } + if (size <= 0) { + PyErr_SetString(PyExc_ValueError, "__dereference__ requires a byte size for this object"); + return NULL; + } + return PyMemoryView_FromMemory((char *)inst->data, size, PyBUF_WRITE); +} + +static PyObject *py_blob_cast(PyObject *self, PyObject *args) +{ + py_lv_struct_t *inst = (py_lv_struct_t *)self; + PyObject *type_obj = NULL; + if (!PyArg_ParseTuple(args, "|O", &type_obj)) return NULL; + if (!type_obj) { + return PyLong_FromVoidPtr(inst->data); + } + if (!PyType_Check(type_obj)) { + PyErr_SetString(PyExc_TypeError, "cast argument must be a type"); + return NULL; + } + py_lv_struct_t *out = PyObject_New(py_lv_struct_t, (PyTypeObject *)type_obj); + if (!out) return NULL; + out->data = inst->data; + out->owns_data = 0; + return (PyObject *)out; +} + +static PyObject *py_lv_struct_cast(PyObject *cls, PyObject *args) +{ + PyObject *type_obj = NULL; + PyObject *ptr_obj = NULL; + + (void)cls; + if (!PyArg_ParseTuple(args, "OO", &type_obj, &ptr_obj)) { + return NULL; + } + if (!PyType_Check(type_obj)) { + PyErr_SetString(PyExc_TypeError, "cast argument must be a type"); + return NULL; + } + void *ptr = mp_to_ptr(ptr_obj); + lvpy_drain_pending_releases_if_idle(); + if (!ptr) { + if (PyErr_Occurred()) return NULL; + Py_RETURN_NONE; + } + py_lv_struct_t *out = PyObject_New(py_lv_struct_t, (PyTypeObject *)type_obj); + if (!out) { + return NULL; + } + out->data = ptr; + out->owns_data = 0; + return (PyObject *)out; +} + +static PyObject *py_lv_cast_instance(PyObject *self, PyObject *args) +{ + PyObject *ptr_obj = NULL; + + if (!PyArg_ParseTuple(args, "O", &ptr_obj)) { + return NULL; + } + void *ptr = mp_to_ptr(ptr_obj); + lvpy_drain_pending_releases_if_idle(); + if (!ptr && PyErr_Occurred()) return NULL; + py_lv_struct_t *s = (py_lv_struct_t *)self; + if (s->data && s->owns_data && s->data != ptr) { + /* The struct now views someone else's memory: let go of its own. */ + lvpy_release_struct_holder(s->data); + free(s->data); + } + if (s->data != ptr) s->owns_data = 0; + s->data = ptr; + return Py_NewRef(self); +} + +static PyMethodDef py_base_struct_methods[] = { + {"__cast__", (PyCFunction)py_lv_struct_cast, METH_VARARGS | METH_CLASS, NULL}, + {"__cast_instance__", py_lv_cast_instance, METH_VARARGS, NULL}, + {"__dereference__", py_lv_dereference, METH_VARARGS, NULL}, + {NULL, NULL, 0, NULL} +}; + +/* Match MicroPython lv_struct_subscr: Struct(N) allocates N elements; s[i] views element i. */ +static PyObject *py_lv_struct_subscript(PyObject *self, PyObject *key) +{ + if (!PyLong_Check(key)) { + PyErr_SetString(PyExc_TypeError, "struct indices must be integers"); + return NULL; + } + Py_ssize_t index = PyLong_AsSsize_t(key); + if (index == -1 && PyErr_Occurred()) { + return NULL; + } + if (index < 0) { + PyErr_SetString(PyExc_IndexError, "struct index out of range"); + return NULL; + } + size_t element_size = lv_struct_get_size(Py_TYPE(self)); + if (element_size == 0) { + PyErr_SetString(PyExc_TypeError, "struct has unknown size"); + return NULL; + } + py_lv_struct_t *inst = (py_lv_struct_t *)self; + if (!inst->data) { + PyErr_SetString(PyLvReferenceError, "struct data is NULL"); + return NULL; + } + py_lv_struct_t *out = PyObject_New(py_lv_struct_t, Py_TYPE(self)); + if (!out) { + return NULL; + } + out->data = (char *)inst->data + element_size * (size_t)index; + out->owns_data = 0; + return (PyObject *)out; +} + +static int py_lv_struct_ass_subscript(PyObject *self, PyObject *key, PyObject *value) +{ + if (!PyLong_Check(key)) { + PyErr_SetString(PyExc_TypeError, "struct indices must be integers"); + return -1; + } + Py_ssize_t index = PyLong_AsSsize_t(key); + if (index == -1 && PyErr_Occurred()) { + return -1; + } + if (index < 0) { + PyErr_SetString(PyExc_IndexError, "struct index out of range"); + return -1; + } + size_t element_size = lv_struct_get_size(Py_TYPE(self)); + if (element_size == 0) { + PyErr_SetString(PyExc_TypeError, "struct has unknown size"); + return -1; + } + py_lv_struct_t *inst = (py_lv_struct_t *)self; + if (!inst->data) { + PyErr_SetString(PyLvReferenceError, "struct data is NULL"); + return -1; + } + void *element_addr = (char *)inst->data + element_size * (size_t)index; + if (value == NULL) { + memset(element_addr, 0, element_size); + return 0; + } + if (!PyObject_TypeCheck(value, Py_TYPE(self))) { + PyErr_Format(PyExc_TypeError, "expected %s", Py_TYPE(self)->tp_name); + return -1; + } + py_lv_struct_t *other = (py_lv_struct_t *)value; + if (!other->data) { + PyErr_SetString(PyLvReferenceError, "struct data is NULL"); + return -1; + } + memcpy(element_addr, other->data, element_size); + return 0; +} + +static PyMappingMethods py_lv_struct_as_mapping = { + .mp_length = NULL, + .mp_subscript = py_lv_struct_subscript, + .mp_ass_subscript = py_lv_struct_ass_subscript, +}; + +static PyMethodDef py_blob_methods[] = { + {"__dereference__", py_lv_dereference, METH_VARARGS, NULL}, + {"__cast__", py_blob_cast, METH_VARARGS, NULL}, + {NULL, NULL, 0, NULL} +}; + +bool mp_obj_is_true(PyObject *obj) +{ + return obj && obj != Py_None && PyObject_IsTrue(obj); +} + +PyObject *convert_to_bool(bool b) +{ + return PyBool_FromLong(b ? 1 : 0); +} + +PyObject *convert_to_str(const char *str) +{ + if (!str) Py_RETURN_NONE; + return PyUnicode_FromString(str); +} + +const char *convert_from_str(PyObject *obj) +{ + if (!obj || obj == Py_None) return NULL; + return PyUnicode_AsUTF8(obj); +} + +PyObject *mp_obj_new_int(long v) { return PyLong_FromLong(v); } +PyObject *mp_obj_new_int_from_uint(unsigned long v) { return PyLong_FromUnsignedLong(v); } +PyObject *mp_obj_new_int_from_ll(long long v) { return PyLong_FromLongLong(v); } +PyObject *mp_obj_new_int_from_ull(unsigned long long v) { return PyLong_FromUnsignedLongLong(v); } +PyObject *mp_obj_new_float_from_f(float v) { return PyFloat_FromDouble(v); } + +long mp_obj_get_int(PyObject *obj) { return PyLong_AsLong(obj); } + +unsigned long long mp_obj_get_ull(PyObject *obj) +{ + return (unsigned long long)PyLong_AsUnsignedLongLong(obj); +} + +double mp_obj_get_float(PyObject *obj) { return PyFloat_AsDouble(obj); } + +void *copy_buffer(const void *buffer, size_t size) +{ + void *copy = malloc(size); + if (copy) memcpy(copy, buffer, size); + return copy; +} + +static void *py_array_to_ptr(PyObject *arr, size_t element_size) +{ + if (!arr || arr == Py_None) return NULL; + if (PyUnicode_Check(arr) || PyBytes_Check(arr) || PyByteArray_Check(arr) || + PyObject_CheckBuffer(arr)) { + return mp_to_ptr(arr); + } + if (!PySequence_Check(arr)) { + PyErr_Format(PyExc_TypeError, "Expected sequence or buffer, got '%s'", + Py_TYPE(arr)->tp_name); + return NULL; + } + Py_ssize_t len = PySequence_Size(arr); + if (len < 0) return NULL; + void *buf = malloc((size_t)len * element_size); + if (!buf) { + PyErr_NoMemory(); + return NULL; + } + unsigned char *element_addr = (unsigned char *)buf; + for (Py_ssize_t i = 0; i < len; i++) { + PyObject *item = PySequence_GetItem(arr, i); + if (!item) { + free(buf); + return NULL; + } + unsigned long long val = PyLong_AsUnsignedLongLong(item); + Py_DECREF(item); + if (PyErr_Occurred()) { + free(buf); + return NULL; + } + memcpy(element_addr, &val, element_size); + element_addr += element_size; + } + return buf; +} + +static PyObject *py_array_from_ptr(void *lv_arr, size_t element_size) +{ + (void)element_size; + if (!lv_arr) Py_RETURN_NONE; + return ptr_to_mp(lv_arr); +} + +void *mp_array_to_u8ptr(PyObject *arr) { return py_array_to_ptr(arr, 1); } +void *mp_array_to_i32ptr(PyObject *arr) { return py_array_to_ptr(arr, 4); } +void *mp_array_to_u16ptr(PyObject *arr) { return py_array_to_ptr(arr, 2); } +void *mp_array_to_u32ptr(PyObject *arr) { return py_array_to_ptr(arr, 4); } + +PyObject *mp_array_from_u8ptr(void *arr) { return py_array_from_ptr(arr, 1); } +PyObject *mp_array_from_u16ptr(void *arr) { return py_array_from_ptr(arr, 2); } +PyObject *mp_array_from_i32ptr(void *arr) { return py_array_from_ptr(arr, 4); } +PyObject *mp_array_from_u32ptr(void *arr) { return py_array_from_ptr(arr, 4); } + +PyObject *mp_read_ptr_C_Pointer(void *field) +{ + return ptr_to_mp(field); +} + +PyObject *lv_to_mp_struct(PyTypeObject *type, void *lv_struct) +{ + if (!lv_struct) Py_RETURN_NONE; + py_lv_struct_t *self = PyObject_New(py_lv_struct_t, type); + if (!self) return NULL; + self->data = lv_struct; + self->owns_data = 0; + return (PyObject *)self; +} + +PyObject *lv_to_mp_struct_own(PyTypeObject *type, void *lv_struct) +{ + if (!lv_struct) Py_RETURN_NONE; + py_lv_struct_t *self = PyObject_New(py_lv_struct_t, type); + if (!self) { + free(lv_struct); + return NULL; + } + self->data = lv_struct; + self->owns_data = 1; + return (PyObject *)self; +} + +void py_lv_struct_dealloc(py_lv_struct_t *self) +{ + if (self->data && self->owns_data) { + lvpy_release_struct_holder(self->data); + free(self->data); + self->data = NULL; + } + Py_TYPE(self)->tp_free((PyObject *)self); +} + +py_lv_struct_t *mp_to_lv_struct(PyObject *obj) +{ + if (!obj || obj == Py_None) return NULL; + if (!PyObject_TypeCheck(obj, &py_lv_base_struct_type) && + !PyObject_TypeCheck(obj, &py_blob_type)) { + PyErr_SetString(PyExc_TypeError, "Expected struct object"); + return NULL; + } + return (py_lv_struct_t *)obj; +} + +static int py_lv_struct_apply_dict(py_lv_struct_t *self, PyObject *dict) +{ + PyObject *key, *value; + Py_ssize_t pos = 0; + while (PyDict_Next(dict, &pos, &key, &value)) { + if (PyObject_SetAttr((PyObject *)self, key, value) < 0) { + return -1; + } + } + return 0; +} + +PyObject *make_new_lv_struct(PyTypeObject *type, PyObject *args, PyObject *kwargs, size_t elem_size) +{ + (void)kwargs; + Py_ssize_t count = 1; + PyObject *other = NULL; + if (!PyArg_ParseTuple(args, "|O", &other)) return NULL; + if (other && PyLong_Check(other)) { + count = PyLong_AsSsize_t(other); + other = NULL; + } + if (elem_size == 0) { + elem_size = lv_struct_get_size(type); + } + py_lv_struct_t *self = PyObject_New(py_lv_struct_t, type); + if (!self) return NULL; + if (other && PyObject_TypeCheck(other, type)) { + self->data = ((py_lv_struct_t *)other)->data; + self->owns_data = 0; + return (PyObject *)self; + } + if (elem_size == 0) { + self->data = NULL; + self->owns_data = 0; + } else { + self->data = calloc((size_t)count, elem_size); + self->owns_data = self->data ? 1 : 0; + } + if (other && PyDict_Check(other)) { + if (!self->data) { + Py_DECREF(self); + PyErr_SetString(PyExc_TypeError, "cannot construct struct from dict without a known size"); + return NULL; + } + if (py_lv_struct_apply_dict(self, other) < 0) { + Py_DECREF(self); + return NULL; + } + } + return (PyObject *)self; +} + +static PyObject *py_C_Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{ + return make_new_lv_struct(type, args, kwds, 0); +} + +static void py_lv_delete_cb(lv_event_t *e); + +static int lvpy_obj_has_event_cb(lv_obj_t *lv_obj, lv_event_cb_t cb) +{ + uint32_t count = lv_obj_get_event_count(lv_obj); + for (uint32_t i = 0; i < count; i++) { + lv_event_dsc_t *dsc = lv_obj_get_event_dsc(lv_obj, i); + if (dsc && lv_event_dsc_get_cb(dsc) == cb) return 1; + } + return 0; +} + +PyTypeObject *py_get_base_obj_type(void) +{ + return py_lv_obj_types[0] ? py_lv_obj_types[0]->py_type : NULL; +} + +PyObject *lv_to_mp(lv_obj_t *lv_obj) +{ + if (!lv_obj) Py_RETURN_NONE; + py_lv_obj_t *self = (py_lv_obj_t *)lv_obj->user_data; + if (!self) { + PyTypeObject *py_type = py_get_base_obj_type(); + py_lv_obj_type_t **iter = &py_lv_obj_types[0]; + const lv_obj_class_t *cls = lv_obj_get_class(lv_obj); + for (; *iter; iter++) { + if ((*iter)->lv_obj_class == cls) { + py_type = (*iter)->py_type; + break; + } + } + self = PyObject_New(py_lv_obj_t, py_type); + if (!self) return NULL; + self->lv_obj = lv_obj; + self->callbacks = NULL; + lv_obj->user_data = self; + /* A wrapper that was dropped and recreated must not stack a second + * delete hook on the object; the first one is still registered. */ + if (!lvpy_obj_has_event_cb(lv_obj, py_lv_delete_cb)) { + lv_obj_add_event_cb(lv_obj, py_lv_delete_cb, LV_EVENT_DELETE, NULL); + } + /* PyObject_New → refcnt 1; return transfers that new reference. */ + return (PyObject *)self; + } + /* Cache hit: user_data is a borrowed association. Caller needs a new ref. */ + Py_INCREF((PyObject *)self); + return (PyObject *)self; +} + +lv_obj_t *mp_to_lv(PyObject *obj) +{ + if (!obj || obj == Py_None) return NULL; + py_lv_obj_t *self = (py_lv_obj_t *)obj; + PyTypeObject *base = py_get_base_obj_type(); + if (base && !PyObject_TypeCheck(obj, base) && + !PyType_IsSubtype(Py_TYPE(obj), base)) { + PyErr_SetString(PyExc_TypeError, "Expected LVGL object"); + return NULL; + } + if (!self->lv_obj) { + PyErr_SetString(PyLvReferenceError, "Referenced object was deleted!"); + return NULL; + } + return self->lv_obj; +} + +PyObject *mp_get_callbacks(PyObject *obj) +{ + py_lv_obj_t *self = (py_lv_obj_t *)obj; + if (!self->callbacks) { + self->callbacks = PyDict_New(); + if (!self->callbacks) return NULL; + } + return self->callbacks; +} + +void lvpy_dealloc_obj(py_lv_obj_t *self) +{ + if (self->lv_obj) { + if (lv_is_initialized()) { + self->lv_obj->user_data = NULL; + } + self->lv_obj = NULL; + } + Py_XDECREF(self->callbacks); + self->callbacks = NULL; + Py_TYPE(self)->tp_free((PyObject *)self); +} + +void *mp_to_ptr(PyObject *obj) +{ + if (!obj || obj == Py_None) return NULL; + if (PyDict_Check(obj)) return (void *)obj; + if (PyObject_TypeCheck(obj, &py_lv_base_struct_type) || + PyObject_TypeCheck(obj, &py_blob_type)) { + return ((py_lv_struct_t *)obj)->data; + } + if (PyObject_CheckBuffer(obj)) { + /* The pointer is only valid while the buffer is exported. Hold the + * export in a memoryview until the outermost LVGL call returns, so + * Python code run during the call (an event callback, say) can't + * resize or free the memory LVGL is reading. */ + PyObject *view = PyMemoryView_FromObject(obj); + if (!view) return NULL; + Py_buffer *b = PyMemoryView_GET_BUFFER(view); + if (!PyBuffer_IsContiguous(b, 'C')) { + Py_DECREF(view); + PyErr_Format(PyExc_BufferError, "'%s' buffer is not contiguous", + Py_TYPE(obj)->tp_name); + return NULL; + } + void *p = b->buf; + lvpy_defer_release(view); + return p; + } + if (PyUnicode_Check(obj)) { + return (void *)PyUnicode_AsUTF8(obj); + } + PyErr_Format(PyExc_TypeError, "Cannot convert '%s' to pointer", Py_TYPE(obj)->tp_name); + return NULL; +} + +PyObject *ptr_to_mp(void *data) +{ + return lv_to_mp_struct(&py_blob_type, data); +} + +PyObject *get_callback_dict_from_user_data(void *user_data) +{ + if (!user_data) return NULL; + PyObject *obj = (PyObject *)user_data; + if (PyDict_Check(obj)) return obj; + return mp_get_callbacks(obj); +} + +/* Py_IsFinalizing() is 3.13+; _Py_IsFinalizing() covers 3.10-3.12. Both + * report whether the interpreter is inside Py_FinalizeEx(). */ +#if PY_VERSION_HEX >= 0x030d0000 +#define LVPY_IS_FINALIZING() Py_IsFinalizing() +#else +#define LVPY_IS_FINALIZING() _Py_IsFinalizing() +#endif + +/* Registry of the per-registration callback dicts THIS runtime created. + * + * py_lv_delete_cb sweeps every event descriptor on a dying object -- + * including registrations made by LVGL internals or other C code, whose + * user_data is an arbitrary C pointer. Probing such a pointer with + * PyDict_Check() dereferences ob_type on non-PyObject memory and can + * segfault (observed under lv_deinit(): a foreign dsc's user_data pointed + * into an LVGL heap block). Never type-guess: a pointer is releasable iff + * we recorded it at creation. All access happens with the GIL held + * (mp_lv_callback runs from Python; py_lv_delete_cb takes the GIL). */ +/* Each entry is one reference we own on a callback dict, on behalf of one + * holder. An event registration's holder is NULL: lv_obj_add_event_cb and + * friends take one reference per call and release it by dict pointer. A + * struct's holder is the struct itself (the containing_struct that the + * generated setters pass): every callback set on that struct shares one + * reference, released when the struct's owner lets go of it -- the Python + * wrapper's dealloc for a struct it owns, LVGL's ext_data free_cb for a + * timer or a running animation. */ +typedef struct { + PyObject *dict; + void *holder; +} lvpy_dict_entry_t; + +static lvpy_dict_entry_t *lvpy_dict_registry = NULL; +static size_t lvpy_dict_registry_len = 0; +static size_t lvpy_dict_registry_cap = 0; + +static void lvpy_registry_add(void *user_data, void *holder) +{ + if (!user_data) return; + if (lvpy_dict_registry_len == lvpy_dict_registry_cap) { + size_t cap = lvpy_dict_registry_cap ? lvpy_dict_registry_cap * 2 : 32; + lvpy_dict_entry_t *grown = (lvpy_dict_entry_t *)realloc( + lvpy_dict_registry, cap * sizeof(lvpy_dict_entry_t)); + if (!grown) return; /* untracked dict leaks at release time; safe */ + lvpy_dict_registry = grown; + lvpy_dict_registry_cap = cap; + } + lvpy_dict_registry[lvpy_dict_registry_len].dict = (PyObject *)user_data; + lvpy_dict_registry[lvpy_dict_registry_len].holder = holder; + lvpy_dict_registry_len++; +} + +void lvpy_register_callback_dict(void *user_data) +{ + lvpy_registry_add(user_data, NULL); +} + +static void lvpy_registry_drop(size_t i) +{ + lvpy_dict_registry[i] = lvpy_dict_registry[--lvpy_dict_registry_len]; +} + +static int lvpy_registry_has(void *user_data, void *holder) +{ + for (size_t i = 0; i < lvpy_dict_registry_len; i++) { + if (lvpy_dict_registry[i].dict == (PyObject *)user_data && + lvpy_dict_registry[i].holder == holder) return 1; + } + return 0; +} + +/* Remove one entry for the dict: an event registration's (holder NULL) if + * there is one, else any. Returns 1 if an entry was removed. */ +static int lvpy_registry_remove(void *user_data) +{ + size_t found = lvpy_dict_registry_len; + for (size_t i = 0; i < lvpy_dict_registry_len; i++) { + if (lvpy_dict_registry[i].dict != (PyObject *)user_data) continue; + if (lvpy_dict_registry[i].holder == NULL) { found = i; break; } + if (found == lvpy_dict_registry_len) found = i; + } + if (found == lvpy_dict_registry_len) return 0; + lvpy_registry_drop(found); + return 1; +} + +int lvpy_is_per_registration_callback_dict(void *user_data) +{ + if (!user_data) return 0; + for (size_t i = 0; i < lvpy_dict_registry_len; i++) { + if (lvpy_dict_registry[i].dict == (PyObject *)user_data) return 1; + } + return 0; +} + +/* Dicts whose registration has ended but whose reference cannot be dropped + * yet. LVGL sends LV_EVENT_DELETE to every descriptor in order, and the + * runtime's own hook is the first one on the object, so a user DELETE + * callback on the same object still reads its dict after py_lv_delete_cb + * has run. A callback may also delete its own widget or remove its own + * event while the trampoline holds a borrowed reference into the dict. So + * the DECREF waits until no LVGL call and no Python callback is in flight: + * the outermost wrapper's unlock, or a release made at top level. */ +static PyObject **lvpy_pending_releases = NULL; +static size_t lvpy_pending_len = 0; +static size_t lvpy_pending_cap = 0; + +static void lvpy_drain_pending_releases_if_idle(void) +{ + if (lvgl_lock_depth != 0 || lvpy_nesting_count != 0) return; + if (lvpy_pending_len == 0) return; + if (LVPY_IS_FINALIZING()) return; + /* Take the batch first: a __del__ run by a DECREF may call back into + * LVGL and reach here again. */ + PyObject **batch = lvpy_pending_releases; + size_t count = lvpy_pending_len; + lvpy_pending_releases = NULL; + lvpy_pending_len = 0; + lvpy_pending_cap = 0; + for (size_t i = 0; i < count; i++) { + Py_DECREF(batch[i]); + } + free(batch); +} + +static void lvpy_defer_release(PyObject *obj) +{ + if (lvpy_pending_len == lvpy_pending_cap) { + size_t cap = lvpy_pending_cap ? lvpy_pending_cap * 2 : 32; + PyObject **grown = (PyObject **)realloc(lvpy_pending_releases, cap * sizeof(PyObject *)); + if (!grown) return; /* leak this one rather than crash */ + lvpy_pending_releases = grown; + lvpy_pending_cap = cap; + } + lvpy_pending_releases[lvpy_pending_len++] = obj; +} + +void lvpy_release_callback_user_data(void *user_data) +{ + /* Belt on top of the registry: once Py_FinalizeEx() is tearing the + * interpreter down, skip the DECREF and leak; the OS reclaims it. */ + if (LVPY_IS_FINALIZING()) return; + if (user_data && lvpy_registry_remove(user_data)) { + lvpy_defer_release((PyObject *)user_data); + lvpy_drain_pending_releases_if_idle(); + } +} + +void lvpy_release_struct_holder(void *holder) +{ + if (!holder || LVPY_IS_FINALIZING()) return; + int released = 0; + for (size_t i = 0; i < lvpy_dict_registry_len;) { + if (lvpy_dict_registry[i].holder == holder) { + lvpy_defer_release(lvpy_dict_registry[i].dict); + lvpy_registry_drop(i); + released = 1; + } else { + i++; + } + } + if (released) lvpy_drain_pending_releases_if_idle(); +} + +/* A timer created with a Python callback: lv_timer_create registered the + * dict as an event-style entry (holder NULL) before the timer existed. Make + * the timer its holder, and let LVGL release it on every path that frees + * the timer. Also the hook for lv_timer_set_cb on a timer LVGL created. */ +#if LV_USE_EXT_DATA +static void lvpy_timer_ext_free(void *data) +{ + PyGILState_STATE gstate = PyGILState_Ensure(); + lvpy_release_struct_holder(data); + PyGILState_Release(gstate); +} + +static void lvpy_anim_ext_free(void *data) +{ + PyGILState_STATE gstate = PyGILState_Ensure(); + lvpy_release_struct_holder(data); + PyGILState_Release(gstate); +} +#endif + +void lvpy_timer_bind(lv_timer_t *timer) +{ +#if LV_USE_EXT_DATA + if (!timer || !timer->user_data) return; + void *dict = timer->user_data; + if (!lvpy_registry_has(dict, timer)) { + size_t i; + for (i = 0; i < lvpy_dict_registry_len; i++) { + if (lvpy_dict_registry[i].dict == (PyObject *)dict && + lvpy_dict_registry[i].holder == NULL) break; + } + if (i == lvpy_dict_registry_len) return; /* not our dict */ + lvpy_dict_registry[i].holder = timer; + } + lv_timer_set_external_data(timer, timer, lvpy_timer_ext_free); +#else + (void)timer; +#endif +} + +/* lv_anim_start copied the Python-owned struct, dict pointer included, into + * LVGL's list. The running copy takes its own reference, released by LVGL's + * free_cb when the animation completes or is deleted; the Python struct keeps + * its reference so the animation can be started again from it. */ +void lvpy_anim_bind(lv_anim_t *anim) +{ +#if LV_USE_EXT_DATA + if (!anim) return; + void *dict = anim->user_data; + if (dict && lvpy_is_per_registration_callback_dict(dict)) { + if (!lvpy_registry_has(dict, anim)) { + Py_INCREF((PyObject *)dict); + lvpy_registry_add(dict, anim); + } + lv_anim_set_external_data(anim, anim, lvpy_anim_ext_free); + } else { + /* Whatever ext_data the copy inherited belongs to another holder. */ + lv_anim_set_external_data(anim, NULL, NULL); + } +#else + (void)anim; +#endif +} + +static void *lvpy_peek_event_dsc_list_cb_user_data( + uint32_t count, + lv_event_dsc_t *(*get_dsc)(uint32_t index, void *ctx), + void *ctx, + lv_event_cb_t cb, + void *specific_user_data) +{ + for (uint32_t i = 0; i < count; i++) { + lv_event_dsc_t *dsc = get_dsc(i, ctx); + if (!dsc) continue; + if (lv_event_dsc_get_cb(dsc) != cb) continue; + void *ud = lv_event_dsc_get_user_data(dsc); + if (specific_user_data != NULL && ud != specific_user_data) continue; + return ud; + } + return NULL; +} + +typedef struct { + lv_obj_t *obj; +} lvpy_obj_peek_ctx; + +static lv_event_dsc_t *lvpy_obj_peek_get_dsc(uint32_t index, void *ctx) +{ + lvpy_obj_peek_ctx *c = (lvpy_obj_peek_ctx *)ctx; + return lv_obj_get_event_dsc(c->obj, index); +} + +void *lvpy_peek_obj_event_cb_user_data(lv_obj_t *obj, lv_event_cb_t cb, void *specific_user_data) +{ + if (!obj) return NULL; + lvpy_obj_peek_ctx ctx = {obj}; + return lvpy_peek_event_dsc_list_cb_user_data( + lv_obj_get_event_count(obj), lvpy_obj_peek_get_dsc, &ctx, cb, specific_user_data); +} + +typedef struct { + lv_display_t *disp; +} lvpy_display_peek_ctx; + +static lv_event_dsc_t *lvpy_display_peek_get_dsc(uint32_t index, void *ctx) +{ + lvpy_display_peek_ctx *c = (lvpy_display_peek_ctx *)ctx; + return lv_display_get_event_dsc(c->disp, index); +} + +void *lvpy_peek_display_event_cb_user_data(lv_display_t *disp, lv_event_cb_t cb, void *specific_user_data) +{ + if (!disp) return NULL; + lvpy_display_peek_ctx ctx = {disp}; + return lvpy_peek_event_dsc_list_cb_user_data( + lv_display_get_event_count(disp), lvpy_display_peek_get_dsc, &ctx, cb, specific_user_data); +} + +typedef struct { + lv_indev_t *indev; +} lvpy_indev_peek_ctx; + +static lv_event_dsc_t *lvpy_indev_peek_get_dsc(uint32_t index, void *ctx) +{ + lvpy_indev_peek_ctx *c = (lvpy_indev_peek_ctx *)ctx; + return lv_indev_get_event_dsc(c->indev, index); +} + +void *lvpy_peek_indev_event_cb_user_data(lv_indev_t *indev, lv_event_cb_t cb, void *specific_user_data) +{ + if (!indev) return NULL; + lvpy_indev_peek_ctx ctx = {indev}; + return lvpy_peek_event_dsc_list_cb_user_data( + lv_indev_get_event_count(indev), lvpy_indev_peek_get_dsc, &ctx, cb, specific_user_data); +} + +static void py_lv_delete_cb(lv_event_t *e) +{ + PyGILState_STATE gstate = PyGILState_Ensure(); + lv_obj_t *lv_obj = lv_event_get_target(e); + if (lv_obj) { + uint32_t count = lv_obj_get_event_count(lv_obj); + for (uint32_t i = 0; i < count; i++) { + lv_event_dsc_t *dsc = lv_obj_get_event_dsc(lv_obj, i); + if (dsc) { + lvpy_release_callback_user_data(lv_event_dsc_get_user_data(dsc)); + } + } + py_lv_obj_t *self = (py_lv_obj_t *)lv_obj->user_data; + if (self) self->lv_obj = NULL; + } + PyGILState_Release(gstate); +} + +void *mp_lv_callback(PyObject *py_callback, void *lv_callback, const char *callback_name, + void **user_data_ptr, void *containing_struct, + void *(*get_user_data)(void *), void (*set_user_data)(void *, void *)) +{ + if (lv_callback && py_callback && PyCallable_Check(py_callback)) { + void *user_data = NULL; + if (user_data_ptr) { + /* The holder owns one reference to its dict. For an event + * registration (containing_struct NULL) that is the registration + * itself, released by lvpy_release_callback_user_data when the + * event is removed or the object deleted; each call is a new + * holder. For a struct field it is the struct: its callbacks + * share one reference, released with the struct. A fresh dict is + * born with that reference; a dict already there gets one taken, + * unless this struct holds it already. */ + if (!*user_data_ptr) { + *user_data_ptr = PyDict_New(); + if (!*user_data_ptr) return NULL; + lvpy_registry_add(*user_data_ptr, containing_struct); + } else if (PyDict_Check((PyObject *)*user_data_ptr) && + !(containing_struct && lvpy_registry_has(*user_data_ptr, containing_struct))) { + Py_INCREF((PyObject *)*user_data_ptr); + lvpy_registry_add(*user_data_ptr, containing_struct); + } + user_data = *user_data_ptr; + } else if (get_user_data && set_user_data) { + user_data = get_user_data(containing_struct); + if (!user_data) { + user_data = PyDict_New(); + lvpy_registry_add(user_data, containing_struct); + set_user_data(containing_struct, user_data); + } + } + if (user_data) { + PyObject *callbacks = get_callback_dict_from_user_data(user_data); + if (callbacks) { + /* The dict's own reference is the only one the callback + * needs: it lives exactly as long as the registration. */ + PyDict_SetItemString(callbacks, callback_name, py_callback); + } + } + return lv_callback; + } + return mp_to_ptr(py_callback); +} + +PyObject *mp_lv_funcptr(PyObject *wrapper, void *lv_fun, void *lv_callback, + const char *func_name, void *user_data) +{ + (void)wrapper; + if (!lv_fun) Py_RETURN_NONE; + if (lv_fun == lv_callback) { + PyObject *callbacks = get_callback_dict_from_user_data(user_data); + if (callbacks) { + /* The dict owns its value: return a reference of our own. */ + PyObject *cb = PyDict_GetItemString(callbacks, func_name); + if (cb) return Py_NewRef(cb); + } + } + Py_RETURN_NONE; +} + +void py_lv_runtime_init_types(void) +{ + if (!lvgl_lock) { + lvgl_lock = PyThread_allocate_lock(); + } + if (lvpy_lock_save_key < 0) { + lvpy_lock_save_key = PyThread_create_key(); + } + if (!PyLvReferenceError) { + PyLvReferenceError = PyErr_NewException("lvgl.LvReferenceError", NULL, NULL); + } + if (!mp_lv_global_user_data) { + mp_lv_global_user_data = PyDict_New(); + } + if (!lvpy_nesting_obj) { + lvpy_nesting_obj = lvpy_create_nesting_obj(); + } + if (PyType_Ready(&py_lv_base_struct_type) < 0) return; + if (PyType_Ready(&py_blob_type) < 0) return; + if (PyType_Ready(&py_C_Pointer_type) < 0) return; +} + +PyTypeObject py_lv_base_struct_type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "lvgl.Struct", + .tp_basicsize = sizeof(py_lv_struct_t), + .tp_dealloc = (destructor)py_lv_struct_dealloc, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_as_mapping = &py_lv_struct_as_mapping, + .tp_methods = py_base_struct_methods, +}; + +PyTypeObject py_blob_type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "lvgl.Blob", + .tp_basicsize = sizeof(py_lv_struct_t), + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_base = &py_lv_base_struct_type, + .tp_methods = py_blob_methods, +}; + +PyTypeObject py_C_Pointer_type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "lvgl.C_Pointer", + .tp_basicsize = sizeof(py_lv_struct_t), + .tp_dealloc = (destructor)py_lv_struct_dealloc, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, + .tp_base = &py_lv_base_struct_type, + .tp_new = py_C_Pointer_new, +}; diff --git a/maix_lvgl/runtime/lvpy_runtime.h b/maix_lvgl/runtime/lvpy_runtime.h new file mode 100644 index 00000000..3693de7c --- /dev/null +++ b/maix_lvgl/runtime/lvpy_runtime.h @@ -0,0 +1,129 @@ +#ifndef LVPY_RUNTIME_H +#define LVPY_RUNTIME_H + +#define PY_SSIZE_T_CLEAN +#include +#include +#include +#include +#include + +#include "lvgl/lvgl.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Shared LVGL / Python glue (no MicroPython runtime). */ + +extern PyObject *PyLvReferenceError; +extern PyObject *mp_lv_global_user_data; +extern PyObject *lvpy_nesting_obj; + +typedef struct { + PyObject_HEAD + void *data; + int owns_data; +} py_lv_struct_t; + +typedef struct { + PyObject_HEAD + lv_obj_t *lv_obj; + PyObject *callbacks; +} py_lv_obj_t; + +typedef struct { + const lv_obj_class_t *lv_obj_class; + PyTypeObject *py_type; +} py_lv_obj_type_t; + +extern py_lv_obj_type_t *py_lv_obj_types[]; + +PyTypeObject *py_get_base_obj_type(void); + +/* LVGL global lock (an application may call task_handler from a timer thread). */ +void lvpy_lock(void); +void lvpy_unlock(void); +void lvpy_release_lock_for_python(void); +void lvpy_reacquire_lock_after_python(void); + +void lvpy_nesting_inc(void); +void lvpy_nesting_dec(void); + +void lv_struct_register_size(PyTypeObject *type, size_t size); +size_t lv_struct_get_size(PyTypeObject *type); +void lv_struct_expose_size(PyTypeObject *type); + +/* Primitive convertors (names match generated binding code). */ +bool mp_obj_is_true(PyObject *obj); +PyObject *convert_to_bool(bool b); +PyObject *convert_to_str(const char *str); +const char *convert_from_str(PyObject *obj); +PyObject *mp_obj_new_int(long v); +PyObject *mp_obj_new_int_from_uint(unsigned long v); +PyObject *mp_obj_new_int_from_ll(long long v); +PyObject *mp_obj_new_int_from_ull(unsigned long long v); +PyObject *mp_obj_new_float_from_f(float v); +long mp_obj_get_int(PyObject *obj); +unsigned long long mp_obj_get_ull(PyObject *obj); +double mp_obj_get_float(PyObject *obj); + +void *mp_to_ptr(PyObject *obj); +PyObject *ptr_to_mp(void *data); + +PyObject *lv_to_mp_struct(PyTypeObject *type, void *lv_struct); +PyObject *lv_to_mp_struct_own(PyTypeObject *type, void *lv_struct); +void py_lv_struct_dealloc(py_lv_struct_t *self); +py_lv_struct_t *mp_to_lv_struct(PyObject *obj); +PyObject *make_new_lv_struct(PyTypeObject *type, PyObject *args, PyObject *kwargs, size_t elem_size); +void *copy_buffer(const void *buffer, size_t size); + +void *mp_array_to_u8ptr(PyObject *arr); +void *mp_array_to_u16ptr(PyObject *arr); +void *mp_array_to_u32ptr(PyObject *arr); +void *mp_array_to_i32ptr(PyObject *arr); +PyObject *mp_array_from_u8ptr(void *arr); +PyObject *mp_array_from_u16ptr(void *arr); +PyObject *mp_array_from_i32ptr(void *arr); +PyObject *mp_array_from_u32ptr(void *arr); +PyObject *mp_read_ptr_C_Pointer(void *field); + +PyObject *lv_to_mp(lv_obj_t *lv_obj); +lv_obj_t *mp_to_lv(PyObject *obj); +PyObject *mp_get_callbacks(PyObject *obj); + +void lvpy_dealloc_obj(py_lv_obj_t *self); +PyObject *get_callback_dict_from_user_data(void *user_data); + +/* Per-registration callback dicts (add_event_cb with user_data=None) are Py_INCREF'd in mp_lv_callback. */ +int lvpy_is_per_registration_callback_dict(void *user_data); +void lvpy_release_callback_user_data(void *user_data); +void lvpy_release_struct_holder(void *holder); +void lvpy_timer_bind(lv_timer_t *timer); +void lvpy_anim_bind(lv_anim_t *anim); +void *lvpy_peek_obj_event_cb_user_data(lv_obj_t *obj, lv_event_cb_t cb, void *specific_user_data); +void *lvpy_peek_display_event_cb_user_data(lv_display_t *disp, lv_event_cb_t cb, void *specific_user_data); +void *lvpy_peek_indev_event_cb_user_data(lv_indev_t *indev, lv_event_cb_t cb, void *specific_user_data); + +void *mp_lv_callback(PyObject *py_callback, void *lv_callback, const char *callback_name, + void **user_data_ptr, void *containing_struct, + void *(*get_user_data)(void *), void (*set_user_data)(void *, void *)); + +PyObject *mp_lv_funcptr(PyObject *wrapper, void *lv_fun, void *lv_callback, + const char *func_name, void *user_data); + +#define mp_write_ptr_C_Pointer(obj) (((py_lv_struct_t *)obj)->data) + +extern PyTypeObject py_C_Pointer_type; +extern PyTypeObject py_lv_base_struct_type; +extern PyTypeObject py_blob_type; +extern PyTypeObject py_lv_obj_type; /* defined in generated lvgl_python.c (phase 5+) */ + +void py_lv_runtime_init_types(void); +PyObject *lvpy_create_nesting_obj(void); + +#ifdef __cplusplus +} +#endif + +#endif /* LVPY_RUNTIME_H */ diff --git a/maix_lvgl/scripts/regenerate_binding.sh b/maix_lvgl/scripts/regenerate_binding.sh new file mode 100644 index 00000000..5992d765 --- /dev/null +++ b/maix_lvgl/scripts/regenerate_binding.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# Force-regenerate binding/lvgl_python.c from MaixCDK's LVGL source. +set -euo pipefail +cd "$(dirname "$0")/.." +python3 tools/regenerate_binding.py --force diff --git a/maix_lvgl/setup.py b/maix_lvgl/setup.py new file mode 100644 index 00000000..e6e0b5e2 --- /dev/null +++ b/maix_lvgl/setup.py @@ -0,0 +1,159 @@ +"""Build the maix_lvgl wheel through MaixCDK's project.py. + +Like MaixPy, this is a standard MaixCDK project: ``main/`` is the entry +component and ``components/lvgl_binding`` holds the LVGL CPython extension. +``python3 setup.py bdist_wheel`` runs ``python project.py build -p maixcam2`` +so MaixCDK downloads and compiles its pinned LVGL together with the rest of +the stack, then packages the resulting ``lvgl`` extension plus the +``maix_lvgl`` Python package (and the non-system shared libraries it needs). +""" +from __future__ import annotations + +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +from setuptools import Distribution, Extension, setup +from setuptools.command.build_ext import build_ext + +try: + from setuptools.command.bdist_wheel import bdist_wheel as _bdist_wheel +except ImportError: # older setuptools + from wheel.bdist_wheel import bdist_wheel as _bdist_wheel + +ROOT = Path(__file__).resolve().parent +BOARD = "maixcam2" +EXT_NAME = "lvgl.cpython-313-aarch64-linux-gnu.so" +BUILT_LIB = ROOT / "build" / "lvgl_binding" / "liblvgl_binding.so" +BUILT_DL_LIB = ROOT / "build" / "dl_lib" +PLATFORM = "manylinux2014_aarch64" + + +class BinaryDistribution(Distribution): + def has_ext_modules(self): + return True + + +def _check_cmake(): + try: + out = subprocess.check_output(["cmake", "--version"], text=True) + except (OSError, subprocess.CalledProcessError): + raise SystemExit("cmake is required (MaixCDK builds with CMake).") + match = re.search(r"version (\d+)\.", out) + if match and int(match.group(1)) >= 4: + print( + "-- WARNING: cmake 4.x is not compatible with some third-party " + "projects bundled by MaixCDK (e.g. freetype requires cmake >= 3.0). " + "Use cmake 3.x (e.g. 3.31) on PATH for this build.", + file=sys.stderr, + ) + + +def _check_pycparser(): + try: + import pycparser # noqa: F401 + except ImportError: + raise SystemExit( + "pycparser is required to generate the LVGL binding. " + "Install it with: python3 -m pip install 'pycparser>=3.0'" + ) + + +class MaixCDKBuildExt(build_ext): + """Build through MaixCDK, then stage the extension for the wheel.""" + + def run(self): + if "--skip-build" not in sys.argv: + sdk = os.environ.get("MAIXCDK_PATH") + if not sdk: + raise SystemExit( + "Please set MAIXCDK_PATH to the MaixCDK checkout, e.g.\n" + " export MAIXCDK_PATH=/path/to/MaixCDK" + ) + _check_cmake() + _check_pycparser() + # The repository does not track generated binding files; create + # them (from MaixCDK's LVGL source) before CMake configures. + gen = [ + sys.executable, + str(ROOT / "tools" / "regenerate_binding.py"), + "--sdk-path", + sdk, + ] + print("-- generating LVGL binding from MaixCDK source") + subprocess.check_call(gen, cwd=ROOT) + + docs = [ + sys.executable, + str(ROOT / "tools" / "gen_api_docs.py"), + "--pyi", + str(ROOT / "binding" / "lvgl.pyi"), + "--out", + str(ROOT / "docs" / "api"), + ] + print("-- generating API documentation") + subprocess.check_call(docs, cwd=ROOT) + cmd = [ + sys.executable, + "project.py", + "build", + "-p", + BOARD, + "--release", + "--config-file", + f"configs/config_platform_{BOARD}.mk", + ] + print("-- building with MaixCDK:", " ".join(cmd)) + subprocess.check_call(cmd, cwd=ROOT) + + if not BUILT_LIB.is_file(): + raise SystemExit( + f"MaixCDK build did not produce {BUILT_LIB}. " + "Run `python3 project.py build -p maixcam2 --release` to see why." + ) + + pkg_dir = Path(self.build_lib) / "maix_lvgl" + pkg_dir.mkdir(parents=True, exist_ok=True) + shutil.copy2(BUILT_LIB, pkg_dir / EXT_NAME) + + dl_dir = pkg_dir / "dl_lib" + dl_dir.mkdir(exist_ok=True) + # libdatachannel is the only shared library in MaixCDK's dl_lib that + # MaixCAM2 firmware does not already provide; opencv/ffmpeg/AX/ssl are + # in the system search path. + datachannel = BUILT_DL_LIB / "libdatachannel.so" + if datachannel.is_file(): + shutil.copy2(datachannel, dl_dir / "libdatachannel.so") + + +class MaixLvglWheel(_bdist_wheel): + def finalize_options(self): + super().finalize_options() + if not getattr(self, "plat_name_supplied", False): + self.plat_name = PLATFORM + self.plat_name_supplied = True + + +setup( + name="maix-lvgl", + version="0.1.0", + description=( + "LVGL bindings for MaixPy (MaixCAM2), generated from MaixCDK's LVGL " + "source with the omnipython-lvgl generator." + ), + long_description=(ROOT / "README.md").read_text(encoding="utf-8"), + long_description_content_type="text/markdown", + author="Sipeed", + license="MIT", + python_requires=">=3.11", + packages=["maix_lvgl"], + package_dir={"maix_lvgl": "maix_lvgl"}, + package_data={"maix_lvgl": ["*.so", "dl_lib/*.so*"]}, + include_package_data=True, + ext_modules=[Extension("lvgl", sources=[])], + cmdclass={"build_ext": MaixCDKBuildExt, "bdist_wheel": MaixLvglWheel}, + distclass=BinaryDistribution, +) diff --git a/maix_lvgl/tools/gen_api_docs.py b/maix_lvgl/tools/gen_api_docs.py new file mode 100644 index 00000000..71b772d6 --- /dev/null +++ b/maix_lvgl/tools/gen_api_docs.py @@ -0,0 +1,831 @@ +#!/usr/bin/env python3 +"""Generate MaixPy-style Markdown API docs from binding/lvgl.pyi. + +The output mirrors MaixPy's docs/api structure: + + docs/api/ + ├── api.json + ├── config.json + ├── README.md + ├── README2.md + ├── sidebar.yaml + └── maix_lvgl/ + ├── lvgl.md + └── maix_lvgl.md + +The module pages use the same Section/table/code-block layout as MaixPy's +MaixCDK doc_tool output (Module / Enum / Variable / Function / Class). +""" +from __future__ import annotations + +import argparse +import json +import re +import shutil +from dataclasses import dataclass, field +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +MODULE = "maix_lvgl" + + +@dataclass +class Method: + name: str + signature: str + args: list[tuple[str, str, str | None]] = field(default_factory=list) + ret: str = "" + + +@dataclass +class Field: + name: str + type: str + + +@dataclass +class Class: + name: str + bases: list[str] = field(default_factory=list) + methods: list[Method] = field(default_factory=list) + fields: list[Field] = field(default_factory=list) + nested: list["Class"] = field(default_factory=list) + + +def _strip_trailer(text: str) -> str: + text = re.sub(r"\s*:\s*\.\.\.\s*$", "", text.strip()) + return re.sub(r"\s+", " ", text) + + +def _logical_lines(text: str) -> list[str]: + lines: list[str] = [] + buf = "" + for raw in text.splitlines(): + line = raw.rstrip() + buf = line if not buf else buf + " " + line.strip() + stripped = buf.lstrip() + if stripped.startswith(("def ", "class ")) and buf.count("(") > buf.count(")"): + continue + lines.append(buf) + buf = "" + if buf: + lines.append(buf) + return lines + + +def _split_args(text: str) -> list[str]: + parts: list[str] = [] + depth = 0 + current = "" + for ch in text: + if ch in "([{": + depth += 1 + elif ch in ")]}": + depth -= 1 + if ch == "," and depth == 0: + parts.append(current.strip()) + current = "" + else: + current += ch + if current.strip(): + parts.append(current.strip()) + return parts + + +def parse_signature(signature: str): + text = signature.strip() + if text.startswith("def "): + text = text[4:] + name, rest = text.split("(", 1) + depth = 1 + index = 0 + while index < len(rest): + if rest[index] == "(": + depth += 1 + elif rest[index] == ")": + depth -= 1 + if depth == 0: + break + index += 1 + args_text = rest[:index] + tail = rest[index + 1 :].strip() + ret = "" + if tail.startswith("->"): + ret = tail[2:].strip().rstrip(":").strip() + args: list[tuple[str, str, str | None]] = [] + for part in _split_args(args_text): + if part in ("/", "*") or part.startswith("**"): + continue + if part.startswith("*"): + part = part[1:] + if not part: + continue + if ":" in part: + arg_name, arg_type = part.split(":", 1) + arg_name, arg_type = arg_name.strip(), arg_type.strip() + else: + arg_name, arg_type = part, "" + default = None + if "=" in arg_type: + arg_type, default = arg_type.split("=", 1) + arg_type, default = arg_type.strip(), default.strip() + if arg_name in ("self", "cls"): + continue + args.append((arg_type, arg_name, default)) + return name.strip(), args, ret + + +def parse_pyi(text: str): + classes: list[Class] = [] + functions: list[Method] = [] + variables: list[Field] = [] + current: Class | None = None + nested: Class | None = None + + for line in _logical_lines(text): + stripped = line.strip() + if not stripped or stripped.startswith(("#", "from ", "import ")): + continue + indent = len(line) - len(line.lstrip()) + class_match = re.match(r"class\s+(\w+)\s*(?:\(([^)]*)\))?\s*:", stripped) + def_match = re.match(r"def\s+(\w+)\s*\((.*)\)\s*(?:->\s*(.*?))?\s*:\s*\.\.\.", stripped) + field_match = re.match(r"(\w+)\s*:\s*(.+)", stripped) + + if indent == 0: + nested = None + if class_match: + bases = [b.strip() for b in (class_match.group(2) or "").split(",") if b.strip()] + current = Class(class_match.group(1), bases) + classes.append(current) + continue + if def_match: + name, args, ret = parse_signature(_strip_trailer(stripped)) + functions.append(Method(name, _strip_trailer(stripped), args, ret)) + current = None + continue + if field_match: + variables.append(Field(field_match.group(1), _strip_trailer(field_match.group(2)))) + continue + + if current is None: + continue + if indent == 4: + if class_match: + bases = [b.strip() for b in (class_match.group(2) or "").split(",") if b.strip()] + nested = Class(class_match.group(1), bases) + current.nested.append(nested) + continue + nested = None + if def_match: + name, args, ret = parse_signature(_strip_trailer(stripped)) + current.methods.append(Method(name, _strip_trailer(stripped), args, ret)) + continue + if field_match: + current.fields.append(Field(field_match.group(1), _strip_trailer(field_match.group(2)))) + continue + + target = nested if nested is not None else current + if def_match: + name, args, ret = parse_signature(_strip_trailer(stripped)) + target.methods.append(Method(name, _strip_trailer(stripped), args, ret)) + elif field_match: + target.fields.append(Field(field_match.group(1), _strip_trailer(field_match.group(2)))) + + return classes, functions, variables + + +def classify(cls: Class) -> str: + name = cls.name + bases = " ".join(cls.bases) + if "Exception" in bases or name == "_Struct" or (name.startswith("_") and name not in ("_Struct",)): + return "skip" + if ( + cls.fields + and not cls.methods + and not cls.nested + and all(re.fullmatch(r"(ClassVar\[)?int(\])?", f.type.strip()) for f in cls.fields) + ): + return "enum" + return "class" + + +# --------------------------------------------------------------------------- +# api.json model (subset of MaixPy's api tree shape) +# --------------------------------------------------------------------------- +def _doc_for_method(method: Method) -> dict: + doc: dict = {"brief": ""} + params = [] + for arg_type, arg_name, default in method.args: + text = f"{arg_name}: {arg_type}" + if default is not None: + text += f", default {default}" + params.append(text) + if params: + doc["param"] = params + if method.ret and method.ret not in ("None", "NoneType"): + doc["return"] = method.ret + return doc + + +def _c_def(method: Method, with_self: bool = False) -> str: + ret = method.ret or "void" + args = [] + if with_self: + args.append("self") + for arg_type, arg_name, _default in method.args: + args.append(f"{arg_type} {arg_name}".strip() if arg_type else arg_name) + return f"{ret} {method.name}({', '.join(args)})" + + +def _py_def(method: Method) -> str: + args = [] + for arg_type, arg_name, default in method.args: + text = f"{arg_name}: {arg_type}" if arg_type else arg_name + if default is not None: + text += f" = {default}" + args.append(text) + ret = f" -> {method.ret}" if method.ret else "" + return f"def {method.name}({', '.join(args)}){ret}" + + +def _method_item(method: Method, full_name: str) -> dict: + return { + "type": "func", + "name": method.name, + "doc": {**_doc_for_method(method), "maixpy": full_name}, + "args": [[a[0], a[1], a[2]] for a in method.args], + "ret_type": method.ret, + "static": False, + "def": _c_def(method), + "py_def": _py_def(method), + } + + +def _class_item(cls: Class, full_name: str) -> dict: + members = {} + for method in cls.methods: + members[method.name] = _method_item(method, f"{full_name}.{method.name}") + for fld in cls.fields: + members[fld.name] = { + "type": "var", + "name": fld.name, + "doc": {"brief": f"{cls.name} field", "maixpy": f"{full_name}.{fld.name}"}, + "value": fld.type, + "static": False, + "readonly": False, + "def": f"{fld.type} {fld.name}", + } + item = { + "type": "class", + "name": cls.name, + "doc": {"brief": "", "maixpy": full_name}, + "def": f"class {cls.name}" + (f"({', '.join(cls.bases)})" if cls.bases else ""), + "members": members, + } + if cls.nested: + item["nested"] = [ + { + "type": "enum", + "name": nested.name, + "doc": {"brief": "", "maixpy": f"{full_name}.{nested.name}"}, + "values": [[f.name, None, "int"] for f in nested.fields], + "def": f"enum {nested.name}", + } + for nested in cls.nested + ] + return item + + +def build_modules(classes, functions, variables) -> dict: + lvgl_members: dict = {} + for func in sorted(functions, key=lambda m: m.name): + lvgl_members[func.name] = _method_item(func, f"{MODULE}.lvgl.{func.name}") + for var in sorted(variables, key=lambda f: f.name): + lvgl_members[var.name] = { + "type": "var", + "name": var.name, + "doc": {"brief": "", "maixpy": f"{MODULE}.lvgl.{var.name}"}, + "value": var.type, + "static": False, + "readonly": False, + "def": f"{var.type} {var.name}", + } + for cls in sorted(classes, key=lambda c: c.name): + if classify(cls) == "enum": + lvgl_members[cls.name] = { + "type": "enum", + "name": cls.name, + "doc": {"brief": "", "maixpy": f"{MODULE}.lvgl.{cls.name}"}, + "values": [[f.name, None, "int"] for f in cls.fields], + "def": f"enum class {cls.name}", + } + elif classify(cls) == "class": + lvgl_members[cls.name] = _class_item(cls, f"{MODULE}.lvgl.{cls.name}") + + backend = { + "type": "module", + "doc": {"brief": "maix_lvgl backend: bind MaixPy display/touchscreen to LVGL"}, + "members": { + "init": { + "type": "func", + "name": "init", + "doc": { + "brief": "Initialize LVGL and bind MaixPy display/touchscreen.", + "param": [ + "display: maix.display.Display, opened internally when omitted", + "touchscreen: maix.touchscreen.TouchScreen, pass False to disable input", + "width: display width when opening internally", + "height: display height when opening internally", + ], + "maixpy": "maix_lvgl.init", + }, + "args": [["Display | None", "display", "None"], ["TouchScreen | bool | None", "touchscreen", "None"], ["int | None", "width", "None"], ["int | None", "height", "None"]], + "ret_type": "DisplayDriver", + "static": False, + "def": "DisplayDriver init(Display * display, TouchScreen * touchscreen, int width, int height)", + "py_def": "def init(display=None, touchscreen=None, width=None, height=None)", + }, + "deinit": { + "type": "func", + "name": "deinit", + "doc": {"brief": "Stop LVGL and release resources opened by init().", "maixpy": "maix_lvgl.deinit"}, + "args": [], + "ret_type": "None", + "static": False, + "def": "void deinit()", + "py_def": "def deinit()", + }, + "timer_handler": { + "type": "func", + "name": "timer_handler", + "doc": { + "brief": "Advance the LVGL tick and run one timer-handler pass.", + "maixpy": "maix_lvgl.timer_handler", + }, + "args": [], + "ret_type": "int", + "static": False, + "def": "int timer_handler()", + "py_def": "def timer_handler()", + }, + "process": { + "type": "func", + "name": "process", + "doc": {"brief": "Alias of timer_handler().", "maixpy": "maix_lvgl.process"}, + "args": [], + "ret_type": "int", + "static": False, + "def": "int process()", + "py_def": "def process()", + }, + "run": { + "type": "func", + "name": "run", + "doc": { + "brief": "Run the LVGL loop until maix.app.need_exit() becomes true.", + "maixpy": "maix_lvgl.run", + }, + "args": [["int", "fps", "60"]], + "ret_type": "None", + "static": False, + "def": "void run(int fps)", + "py_def": "def run(fps=60)", + }, + "DisplayDriver": { + "type": "class", + "name": "DisplayDriver", + "doc": {"brief": "Wrap a maix.display.Display and push LVGL frames to it.", "maixpy": "maix_lvgl.DisplayDriver"}, + "def": "class DisplayDriver", + "members": { + "__init__": { + "type": "func", + "name": "__init__", + "doc": {"brief": "Create the LVGL display and its flush callback.", "maixpy": "maix_lvgl.DisplayDriver.__init__"}, + "args": [["Display | None", "display", "None"], ["int | None", "width", "None"], ["int | None", "height", "None"]], + "ret_type": "None", + "static": False, + "def": "DisplayDriver(Display * display, int width, int height)", + "py_def": "def __init__(display=None, width=None, height=None)", + }, + "deinit": { + "type": "func", + "name": "deinit", + "doc": {"brief": "Delete the LVGL display and close an internally opened display.", "maixpy": "maix_lvgl.DisplayDriver.deinit"}, + "args": [], + "ret_type": "None", + "static": False, + "def": "void deinit()", + "py_def": "def deinit()", + }, + }, + }, + "TouchDriver": { + "type": "class", + "name": "TouchDriver", + "doc": {"brief": "Feed maix.touchscreen.TouchScreen input into an LVGL pointer indev.", "maixpy": "maix_lvgl.TouchDriver"}, + "def": "class TouchDriver", + "members": { + "__init__": { + "type": "func", + "name": "__init__", + "doc": {"brief": "Create the LVGL pointer indev.", "maixpy": "maix_lvgl.TouchDriver.__init__"}, + "args": [["TouchScreen | None", "touchscreen", "None"], ["display_t | None", "display", "None"]], + "ret_type": "None", + "static": False, + "def": "TouchDriver(TouchScreen * touchscreen, display_t * display)", + "py_def": "def __init__(touchscreen=None, display=None)", + }, + "deinit": { + "type": "func", + "name": "deinit", + "doc": {"brief": "Delete the LVGL indev and close an internally opened touchscreen.", "maixpy": "maix_lvgl.TouchDriver.deinit"}, + "args": [], + "ret_type": "None", + "static": False, + "def": "void deinit()", + "py_def": "def deinit()", + }, + }, + }, + }, + } + + return { + "type": "root", + "members": { + MODULE: { + "type": "module", + "doc": { + "brief": "LVGL 9.1.0 bindings for MaixPy on MaixCAM2 (MaixCDK project)", + }, + "members": { + "lvgl": { + "type": "module", + "doc": { + "brief": "LVGL 9.1.0 CPython bindings, generated from MaixCDK's LVGL source with omnipython-lvgl", + }, + "members": lvgl_members, + }, + "maix_lvgl": backend, + }, + } + }, + } + + +# --------------------------------------------------------------------------- +# Markdown rendering (MaixPy doc_tool/gen_markdown.py layout) +# --------------------------------------------------------------------------- +def _escape(name: str) -> str: + return name.replace("_", r"\_") + + +def _prefix(text: str, prefix: str = "> ") -> str: + return "\n".join(prefix + line for line in text.splitlines()) + + +def _doc_table(doc: dict) -> str: + skip = {"maixpy", "maixcdk", "py_doc", "brief"} + content = "" + for key, value in doc.items(): + if key in skip: + continue + if isinstance(value, list): + content += f"| **{key}** | " + for index, item in enumerate(value): + content += f"**{index + 1}**. {item.replace(chr(10), '
')}
" + content += "|\n" + elif isinstance(value, dict): + content += f"| **{key}** | " + for k, v in value.items(): + content += f"**{k}**: {str(v).replace(chr(10), '
')}
" + content += "|\n" + else: + content += f"| **{key}** | {str(value).replace(chr(10), '
')} |\n" + return content + + +def _has_doc_kv(doc: dict) -> bool: + skip = {"maixpy", "maixcdk", "py_doc", "brief"} + return any(key not in skip for key in doc) + + +class _Ids: + def __init__(self): + self.ids = {} + + def update(self, heading: str, name: str, anchor: str | None = None) -> str: + anchor = anchor or name + key = anchor.lower() + if key not in self.ids: + self.ids[key] = {"count": 1} + return f"{heading} {_escape(name)} {{#{anchor}}}" + self.ids[key]["count"] += 1 + return f"{heading} {_escape(name)} {{#{anchor}-{self.ids[key]['count']}}}" + + +def module_to_md(full_name: str, module: dict, start_comment: str, subpages=None) -> str: + brief = module["doc"] if isinstance(module["doc"], str) else module["doc"].get("brief", "") + content = f"---\ntitle: {full_name}\n---\n\n{brief}\n\n" + content += start_comment + ids = _Ids() + + def func_block(heading: str, name: str, item: dict) -> str: + block = ids.update(heading, name) + "\n\n" + block += item["doc"].get("brief", "") + "\n\n" + if _has_doc_kv(item["doc"]): + block += "| item | description |\n" + block += "| --- | --- |\n" + block += _doc_table(item["doc"]) + block += "\n> C++ defination code:\n> ```cpp\n{}\n> ```\n".format( + _prefix(item.get("def", "")) + ) + return block + + # Module + content += ids.update("##", "Module") + "\n\n" + if subpages: + content += "| page | brief |\n| --- | --- |\n" + for label, filename, brief in subpages: + content += f"| [{label}]({filename}) | {brief} |\n" + else: + submodules = [ + (key, item) + for key, item in module["members"].items() + if item["type"] == "module" + ] + if submodules: + content += "| module | brief |\n| --- | --- |\n" + for key, item in submodules: + content += f"| [{_escape(key)}](./{key}.md) | {item['doc'].get('brief', '')} |\n" + else: + content += "No module\n" + content += "\n\n" + + # Enum + content += ids.update("##", "Enum") + "\n\n" + for key, item in module["members"].items(): + if item["type"] != "enum": + continue + content += ids.update("###", key) + "\n\n" + content += item["doc"].get("brief", "") + "\n\n" + content += "| item | describe |\n| --- | --- |\n" + content += _doc_table(item["doc"]) + content += "| **values** | |\n| --- | --- |\n" + for value in item["values"]: + content += f"| **{value[0]}** | {value[2]} |\n" + content += "\n> C++ defination code:\n> ```cpp\n{}\n> ```\n".format( + _prefix(item.get("def", "")) + ) + content += "\n\n" + + # Variable + content += ids.update("##", "Variable") + "\n\n" + for key, item in module["members"].items(): + if item["type"] != "var": + continue + content += ids.update("###", key) + "\n\n" + content += item["doc"].get("brief", "") + "\n\n" + content += "| item | description |\n| --- | --- |\n" + content += _doc_table(item["doc"]) + if item.get("value"): + content += f"| **value** | **{item['value']}** |\n" + content += f"| **readonly**| {item.get('readonly', False)} |\n" + content += "\n> C++ defination code:\n> ```cpp\n{}\n> ```\n".format( + _prefix(item.get("def", "")) + ) + content += "\n\n" + + # Function + content += ids.update("##", "Function") + "\n\n" + for key, item in module["members"].items(): + if item["type"] != "func": + continue + content += func_block("###", key, item) + content += "\n\n" + + # Class + content += ids.update("##", "Class") + "\n\n" + for key, item in module["members"].items(): + if item["type"] != "class": + continue + content += ids.update("###", key) + "\n\n" + content += item["doc"].get("brief", "") + "\n\n" + if _has_doc_kv(item["doc"]): + content += "| item | description |\n| --- | --- |\n" + content += _doc_table(item["doc"]) + content += "\n> C++ defination code:\n> ```cpp\n{}\n> ```\n\n".format( + _prefix(item.get("def", "")) + ) + members = item.get("members", {}) + if members: + content += "\n**Members**\n\n" + for member_key, member in members.items(): + if member["type"] == "func": + content += f"- `{_escape(member_key)}` — `{member.get('def', '')}`\n" + else: + content += f"- `{_escape(member_key)}`: `{member.get('value', '')}`\n" + content += "\n" + for nested in item.get("nested", []): + content += ids.update("####", f"enum {nested['name']}", f"enum-{nested['name']}") + "\n\n" + content += "| item | describe |\n| --- | --- |\n" + content += "| **values** | |\n| --- | --- |\n" + for value in nested["values"]: + content += f"| **{value[0]}** | {value[2]} |\n" + content += "\n" + return content + + +def _start_comment(full_name: str) -> str: + return ( + f"\n> You can use `{full_name}` to access this module with maix_lvgl\n" + "> This module is generated from [MaixCDK](https://github.com/sipeed/MaixCDK) " + "and [omnipython-lvgl](https://github.com/PyDevices/omnipython-lvgl)\n\n" + ) + + +def generate(pyi_path: Path, out_dir: Path, merge: bool = False) -> None: + classes, functions, variables = parse_pyi(pyi_path.read_text(encoding="utf-8")) + api_tree = build_modules(classes, functions, variables) + + out_dir.mkdir(parents=True, exist_ok=True) + module_dir = out_dir / MODULE + if module_dir.exists(): + shutil.rmtree(module_dir) + module_dir.mkdir(parents=True) + if not merge: + for name in ("api.json", "config.json", "README.md", "README2.md", "sidebar.yaml"): + (out_dir / name).unlink(missing_ok=True) + + # api.json + api_path = out_dir / "api.json" + if merge and api_path.is_file(): + try: + existing = json.loads(api_path.read_text(encoding="utf-8")) + existing.setdefault("members", {})[MODULE] = api_tree["members"][MODULE] + api_path.write_text( + json.dumps(existing, indent=4, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + except (OSError, json.JSONDecodeError): + api_path.write_text( + json.dumps(api_tree, indent=4, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + else: + api_path.write_text( + json.dumps(api_tree, indent=4, ensure_ascii=False) + "\n", + encoding="utf-8", + ) + + # config.json (MaixPy's own is kept in merge mode) + config_path = out_dir / "config.json" + if not config_path.is_file(): + config_path.write_text( + json.dumps({"import": "config_en", "name": "maix_lvgl API Reference"}, indent=4) + "\n", + encoding="utf-8", + ) + + # Module pages: split the large lvgl module into overview/functions/classes + root = api_tree["members"][MODULE] + lvgl = root["members"]["lvgl"] + + def subset(*types): + return {k: v for k, v in lvgl["members"].items() if v["type"] in types} + + overview_subpages = [ + ("functions", "lvgl_functions.md", "Function reference"), + ("classes", "lvgl_classes.md", "Class reference"), + ] + functions_subpages = [ + ("lvgl", "lvgl.md", "Module overview, enums and variables"), + ("classes", "lvgl_classes.md", "Class reference"), + ] + classes_subpages = [ + ("lvgl", "lvgl.md", "Module overview, enums and variables"), + ("functions", "lvgl_functions.md", "Function reference"), + ] + pages = [ + ("lvgl.md", "maix_lvgl.lvgl", {**lvgl, "members": subset("enum", "var")}, overview_subpages), + ("lvgl_functions.md", "maix_lvgl.lvgl.functions", {**lvgl, "members": subset("func")}, functions_subpages), + ("lvgl_classes.md", "maix_lvgl.lvgl.classes", {**lvgl, "members": subset("class")}, classes_subpages), + ] + for filename, full_name, module, subpages in pages: + content = module_to_md(full_name, module, _start_comment(full_name), subpages) + (module_dir / filename).write_text(content, encoding="utf-8") + + backend = root["members"]["maix_lvgl"] + backend_name = f"{MODULE}.maix_lvgl" + content = module_to_md( + backend_name, backend, _start_comment(backend_name) + ) + (module_dir / "maix_lvgl.md").write_text(content, encoding="utf-8") + + # README (Brief) + readme = ( + "---\n" + "title: maix_lvgl API -- LVGL bindings for MaixPy on MaixCAM2\n" + "---\n\n" + "**API documentation for maix_lvgl (LVGL 9.1.0 bindings for MaixPy).**\n\n" + "If you want to **preview API doc offline**:\n" + "1. Download the wheel from the [Releases page](https://github.com/Taoxuan-168/Maix_LVGL/releases).\n" + "2. Build maix_lvgl; the API doc is generated in the `maix_lvgl/docs/api/` directory.\n\n" + "> For maix_lvgl developer: This API documentation is generated from " + "`binding/lvgl.pyi`, DO NOT edit this file manually!\n\n" + "maix_lvgl API documentation, modules:\n\n" + "| module | brief |\n" + "| --- | --- |\n" + ) + for name, module in root["members"].items(): + readme += f"|[maix_lvgl.{name}](./{MODULE}/{name}.md) | {module['doc'].get('brief', '')} |\n" + readme_path = out_dir / "README.md" + if merge and readme_path.is_file(): + existing = readme_path.read_text(encoding="utf-8") + if not existing.endswith("\n"): + existing += "\n" + rows = [ + ("maix_lvgl.lvgl", f"./{MODULE}/lvgl.md", + "Module overview, enums and variables"), + ("maix_lvgl.lvgl.functions", f"./{MODULE}/lvgl_functions.md", + "LVGL module functions"), + ("maix_lvgl.lvgl.classes", f"./{MODULE}/lvgl_classes.md", + "LVGL widget and struct classes"), + ("maix_lvgl.maix_lvgl", f"./{MODULE}/maix_lvgl.md", + "maix_lvgl backend: display/touchscreen, init/deinit/run"), + ] + for key, path, brief in rows: + if key not in existing: + existing += f"|[{key}]({path}) | {brief} |\n" + readme_path.write_text(existing, encoding="utf-8") + else: + readme_path.write_text(readme, encoding="utf-8") + + # README2 (offline note; keep MaixPy's in merge mode) + readme2_path = out_dir / "README2.md" + if not (merge and readme2_path.is_file()): + readme2_path.write_text( + "Where is the API docs?\n" + "=====\n\n" + "API docs is generated from `binding/lvgl.pyi` during the build and can be\n" + "read locally in `maix_lvgl/docs/api/`.\n\n" + "If you want to preview API doc offline, there are two ways:\n" + "1. Download the wheel from the [Releases page](https://github.com/Taoxuan-168/Maix_LVGL/releases).\n" + "2. Build maix_lvgl project; API doc is generated in `maix_lvgl/docs/api/`.\n", + encoding="utf-8", + ) + + # sidebar.yaml + sidebar = ( + "items:\n" + "- file: README.md\n" + " label: Brief\n" + "- collapsed: false\n" + " items:\n" + ) + for name in root["members"]: + sidebar += ( + " - collapsed: false\n" + f" file: {MODULE}/{name}.md\n" + f" label: {name}\n" + ) + sidebar += " label: maix_lvgl\n" + sidebar_path = out_dir / "sidebar.yaml" + if merge and sidebar_path.is_file(): + existing = sidebar_path.read_text(encoding="utf-8") + if "maix_lvgl/" not in existing: + if not existing.endswith("\n"): + existing += "\n" + existing += ( + "- collapsed: false\n" + " items:\n" + " - collapsed: false\n" + f" file: {MODULE}/lvgl.md\n" + " label: lvgl\n" + " - collapsed: false\n" + f" file: {MODULE}/maix_lvgl.md\n" + " label: maix_lvgl\n" + " label: maix_lvgl\n" + ) + sidebar_path.write_text(existing, encoding="utf-8") + else: + sidebar_path.write_text(sidebar, encoding="utf-8") + + print( + f"API docs: {out_dir} (modules {len(root['members'])}, " + f"functions {len(functions)}, variables {len(variables)}, " + f"classes {sum(1 for c in classes if classify(c) == 'class')}, " + f"enums {sum(1 for c in classes if classify(c) == 'enum')})" + ) + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--pyi", default=str(ROOT / "binding" / "lvgl.pyi")) + parser.add_argument("--out", default=str(ROOT / "docs" / "api")) + parser.add_argument("--merge", action="store_true", help="merge into an existing MaixPy docs/api") + args = parser.parse_args() + generate(Path(args.pyi), Path(args.out), merge=args.merge) + + +if __name__ == "__main__": + main() diff --git a/maix_lvgl/tools/maixcdk_lvgl.py b/maix_lvgl/tools/maixcdk_lvgl.py new file mode 100644 index 00000000..8ac7bb3e --- /dev/null +++ b/maix_lvgl/tools/maixcdk_lvgl.py @@ -0,0 +1,146 @@ +"""Locate MaixCDK, its pinned LVGL source/configuration and cross toolchain. + +The project intentionally does not vendor LVGL. The build uses the LVGL source +and configuration that MaixCDK already manages under +``/dl/extracted/lvgl_srcs/lvgl`` (downloaded from the version pinned +by ``components/3rd_party/lvgl/Kconfig``), so upgrading LVGL in MaixCDK makes +the next build pick it up automatically. +""" +from __future__ import annotations + +import hashlib +import os +import re +import shutil +import tarfile +import tempfile +import urllib.request +from pathlib import Path + +PROJECT_ROOT = Path(__file__).resolve().parent.parent +LVGL_COMPONENT = Path("components/3rd_party/lvgl") + +# The generator artifacts bundled in tools/omnipython_lvgl. +GENERATOR_VERSION_FILE = PROJECT_ROOT / "tools" / "omnipython_lvgl" / "VERSION" + + +def find_maixcdk() -> Path: + """Return the MaixCDK root, from MAIXCDK_PATH or the usual neighbors.""" + candidates = [] + env = os.environ.get("MAIXCDK_PATH") + if env: + candidates.append(Path(env)) + candidates.extend( + [ + PROJECT_ROOT.parent / "MaixCDK", + PROJECT_ROOT.parent.parent / "MaixCDK", + Path.home() / "MaixCDK", + ] + ) + for candidate in candidates: + if (candidate / LVGL_COMPONENT / "component.py").is_file(): + return candidate.resolve() + raise RuntimeError( + "MaixCDK not found. Set MAIXCDK_PATH to the MaixCDK checkout " + "(e.g. export MAIXCDK_PATH=/path/to/MaixCDK)." + ) + + +def lvgl_version(sdk: Path) -> str: + """Read the LVGL version pinned by MaixCDK's lvgl Kconfig defaults.""" + text = (sdk / LVGL_COMPONENT / "Kconfig").read_text(encoding="utf-8") + + def default(name: str, fallback: int) -> int: + match = re.search( + rf"config\s+{name}\b[\s\S]{{0,200}}?default\s+(\d+)", text + ) + return int(match.group(1)) if match else fallback + + return "{}.{}.{}".format( + default("LVGL_VERSION_MAJOR", 9), + default("LVGL_VERSION_MINOR", 1), + default("LVGL_VERSION_PATCH", 0), + ) + + +def _download_info(sdk: Path) -> dict: + """Extract the version -> sha256 map from MaixCDK's lvgl component.py.""" + text = (sdk / LVGL_COMPONENT / "component.py").read_text(encoding="utf-8") + return { + version: sha + for version, sha in re.findall( + r'if\s+version\s*==\s*"([^"]+)"\s*:\s*\n\s*sha256sum\s*=\s*"([0-9a-f]{64})"', + text, + ) + } + + +def lvgl_source_dir(sdk: Path) -> Path: + """Path MaixCDK uses for extracted LVGL sources (contains lvgl.h).""" + return sdk / "dl" / "extracted" / "lvgl_srcs" / "lvgl" + + +def ensure_lvgl_source(sdk: Path, version: str, log=print) -> Path: + """Return the LVGL source tree, downloading it into MaixCDK if needed.""" + target = lvgl_source_dir(sdk) + if (target / "lvgl.h").is_file(): + return target + + # Older MaixCDK layouts may have left lvgl-/ behind. + legacy = target.parent / f"lvgl-{version}" + if (legacy / "lvgl.h").is_file(): + if not target.exists(): + target.parent.mkdir(parents=True, exist_ok=True) + shutil.move(str(legacy), str(target)) + return target + + sha_map = _download_info(sdk) + if version not in sha_map: + raise RuntimeError( + f"MaixCDK's lvgl component does not support version {version} " + f"(supported: {', '.join(sha_map) or 'none'})" + ) + url = f"https://github.com/lvgl/lvgl/archive/refs/tags/v{version}.tar.gz" + log(f"downloading LVGL {version} into {target} ...") + target.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory() as tmp: + archive = Path(tmp) / f"lvgl-{version}.tar.gz" + urllib.request.urlretrieve(url, archive) + digest = hashlib.sha256(archive.read_bytes()).hexdigest() + if digest != sha_map[version]: + raise RuntimeError( + f"LVGL {version} sha256 mismatch: {digest} != {sha_map[version]}" + ) + with tarfile.open(archive) as tar: + tar.extractall(tmp, filter="data") + extracted = Path(tmp) / f"lvgl-{version}" + if not (extracted / "lvgl.h").is_file(): + raise RuntimeError(f"unexpected LVGL archive layout: {extracted}") + if target.exists(): + shutil.rmtree(target) + shutil.move(str(extracted), str(target)) + log(f"LVGL source ready: {target}") + return target + + +def lv_conf_path(sdk: Path) -> Path: + return sdk / LVGL_COMPONENT / "conf" / "lv_conf.h" + + +def generator_version() -> str: + if GENERATOR_VERSION_FILE.is_file(): + return GENERATOR_VERSION_FILE.read_text(encoding="utf-8").strip() + return "unknown" + + +def stamp(sdk: Path, version: str, lvgl_dir: Path, conf: Path) -> dict: + """Inputs that decide whether the generated binding is still current.""" + header = lvgl_dir / "lvgl.h" + return { + "lvgl_version": version, + "lvgl_header": str(header), + "lvgl_header_mtime_ns": header.stat().st_mtime_ns, + "lvgl_header_size": header.stat().st_size, + "lv_conf_sha256": hashlib.sha256(conf.read_bytes()).hexdigest(), + "generator_version": generator_version(), + } diff --git a/maix_lvgl/tools/omnipython_lvgl/LICENSE b/maix_lvgl/tools/omnipython_lvgl/LICENSE new file mode 100644 index 00000000..24cd7457 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Brad Barnett + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/maix_lvgl/tools/omnipython_lvgl/VERSION b/maix_lvgl/tools/omnipython_lvgl/VERSION new file mode 100644 index 00000000..0282ff7f --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/VERSION @@ -0,0 +1 @@ +9.5.53 diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/__init__.py b/maix_lvgl/tools/omnipython_lvgl/binding/__init__.py new file mode 100644 index 00000000..92b6b8f8 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/__init__.py @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""LVGL binding generator: preprocess → analyze → emit (.c and .pyi).""" diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/analyze.py b/maix_lvgl/tools/omnipython_lvgl/binding/analyze.py new file mode 100644 index 00000000..f0660e98 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/analyze.py @@ -0,0 +1,591 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Walk preprocessed C AST; build func/object/enum/struct metadata for emit.""" +from __future__ import print_function + +import collections +import copy +import json +import re +from os.path import commonprefix + +from pycparser import c_ast, c_generator, c_parser + +from . import runtime +from .helpers import ( + ctor_name_from_obj_name, + get_enum_name, + is_global_callback, + is_struct, + obj_name_from_ext_name, + obj_name_from_func_name, + simplify_identifier, + str_enum_to_str, +) +from .parse import ( + add_default_declname, + convert_array_to_ptr, + function_prototype, + get_name, + get_type, + remove_arg_names, + remove_declname, + remove_explicit_struct, + remove_quals, +) +from .ir import DeclarationIndex, parse_ast +from .api_model import build_api_model +from .api_policy import ApiPolicy +from .util import memoize + + +class MissingConversionException(ValueError): + pass + + +def has_ctor(obj_name): + return ctor_name_from_obj_name(obj_name) in [ + ctor.name for ctor in runtime.get("obj_ctors") + ] + + +def get_ctor(obj_name): + return next( + ctor + for ctor in runtime.get("obj_ctors") + if ctor.name == ctor_name_from_obj_name(obj_name) + ) + + +def get_methods(obj_name): + api_model = runtime.get("api_model") + method_names = { + function.c_name + for function in api_model.functions + if function.role == "object_method" + and function.receiver == obj_name + and function.visibility == "public" + } + return [func for func in runtime.get("funcs") if func.name in method_names] + + +@memoize +def noncommon_part(member_name, stem_name): + common_part = commonprefix([member_name, stem_name]) + n = len(common_part) - 1 + while n > 0 and member_name[n] != "_": + n -= 1 + return member_name[n + 1 :] + + +@memoize +def get_first_arg(func): + if not func.type.args: + return None + if not len(func.type.args.params) >= 1: + return None + if not func.type.args.params[0].type: + return None + return func.type.args.params[0].type + + +@memoize +def get_first_arg_type(func): + declaration_index = runtime.get("declaration_index") + if func.name in declaration_index.functions_by_name: + return declaration_index.first_argument_type_name(func.name) + # Callback wrapper declarations are synthesized after the immutable + # declaration index is built. Their receiver classification still needs + # the concrete AST node created by lowering. + first_arg = get_first_arg(func) + if not first_arg or not first_arg.type: + return None + return get_type(first_arg.type, remove_quals=True) + + +def get_base_struct_name(struct_name): + return struct_name[:-2] if struct_name.endswith("_t") else struct_name + + +# "struct function" starts with struct name (without _t), and their first argument is a pointer to the struct +# Need also to take into account struct functions of aliases of current struct. +@memoize +def get_struct_functions(struct_name): + funcs = runtime.get("funcs") + declaration_index = runtime.get("declaration_index") + function_names = { + function.name for function in declaration_index.struct_functions(struct_name) + } + return [func for func in funcs if func.name in function_names] + + +@memoize +def is_struct_function(func): + return func in get_struct_functions(get_first_arg_type(func)) + + +# is_static_member returns true if function does not receive the obj as the first argument +# and the object is not a struct function + + +@memoize +def is_static_member(func, obj_type=None): + if obj_type is None: + obj_type = runtime.get("base_obj_type") + first_arg = get_first_arg(func) + # print("/* %s : get_first_arg = %s */" % (get_name(func), first_arg)) + if first_arg: + if isinstance(first_arg, c_ast.ArrayDecl): + return True # Arrays cannot have non static members + if is_struct_function(func): + return False + first_arg_type = get_first_arg_type(func) + return (first_arg_type == None) or (first_arg_type != obj_type) +def get_enum_members(obj_name): + enums = runtime.get("enums", {}) + if obj_name not in enums: + return [] + return [enum_member_name for enum_member_name, value in enums[obj_name].items()] + + +def get_enum_member_name(enum_member): + if enum_member[0].isdigit(): + enum_member = "_" + enum_member # needs to be a valid attribute name + return enum_member + + +def get_enum_value(obj_name, enum_member): + return runtime.get("enums")[obj_name][enum_member] + +def register_int_ptr_type(mp_to_lv, lv_to_mp, lv_mp_type, convertor, *types): + for ptr_type in types: + for qualified_ptr_type in [ptr_type, "const " + ptr_type]: + mp_to_lv[qualified_ptr_type] = "mp_array_to_%s" % (convertor) + lv_to_mp[qualified_ptr_type] = "mp_array_from_%s" % (convertor) + lv_mp_type[qualified_ptr_type] = "void*" + + +def analyze(ctx=None): + """Populate one binding context from its parsed translation unit.""" + if ctx is None: + ctx = runtime.current_context() + + args = ctx.args + s = ctx.s + module_prefix = ctx.module_prefix + base_obj_name = ctx.base_obj_name + base_obj_type = ctx.base_obj_type + create_obj_pattern = ctx.create_obj_pattern + + obj_metadata = collections.OrderedDict() + func_metadata = collections.OrderedDict() + callback_metadata = collections.OrderedDict() + + func_prototypes = {} + + parser = getattr(ctx, "parser", None) or c_parser.CParser() + gen = getattr(ctx, "gen", None) or c_generator.CGenerator() + ast = getattr(ctx, "parsed_ast", None) + if ast is None: + ast = parser.parse(s, filename="") + + if args.json is not None: + with open(args.json, "r") as f: + lvgl_json = json.load(f) + if not lvgl_json: + # if the json is an empty dictionary + lvgl_json = None + else: + lvgl_json = None + + # *************** Fix *********************************** + # this is a fix for structures not getting populated properly from + # forward declarations. pycparser doesn't make the connection between + # a forwrd declaration and the actual declaration so the structures get created + # without any fields. Since there are no fields things like callbacks break + # because the generation code looks for specific field names + # to know if it is valid to be used as a callback. + forward_struct_decls = {} + + for item in ast.ext[:]: + # Locate a forward declaration + if ( + isinstance(item, c_ast.Decl) + and item.name is None + and isinstance(item.type, c_ast.Struct) + and item.type.name is not None + ): + # check to see if there are no fields , and of not store the structure + # as a foward declaration. If it does have fields then build a single + # object that represents the structure with the fiels. + if item.type.decls is None: + forward_struct_decls[item.type.name] = [item] + else: + if item.type.name in forward_struct_decls: + decs = forward_struct_decls[item.type.name] + if len(decs) == 2: + decl, td = decs + + td.type.type.decls = item.type.decls[:] + + ast.ext.remove(decl) + ast.ext.remove(item) + # there are 3 objects that get created for a formard declaration. + # a structure without any fields, a typedef pointing to that structure. + # and the last is another structure that has fields. So we need to capture + # all 3 parts to build a single object that represents a structure. + elif ( + isinstance(item, c_ast.Typedef) + and isinstance(item.type, c_ast.TypeDecl) + and item.name + and item.type.declname + and item.name == item.type.declname + and isinstance(item.type.type, c_ast.Struct) + and item.type.type.decls is None + ): + if item.type.type.name in forward_struct_decls: + forward_struct_decls[item.type.type.name].append(item) + + # ******************************************************************** + + declaration_ir = getattr(ctx, "declaration_ir", None) + if declaration_ir is None: + declaration_ir = parse_ast(ast) + declaration_index = DeclarationIndex.from_ir( + declaration_ir, module_prefix=module_prefix + ) + api_model = getattr(ctx, "api_model", None) + if api_model is None: + api_model = build_api_model( + declaration_ir, + module_prefix=module_prefix, + base_obj_type=base_obj_type, + policy=ApiPolicy.default(module_prefix=module_prefix), + ) + + + # Types and structs + + typedefs = [ + x.type for x in ast.ext if isinstance(x, c_ast.Typedef) + ] # and not (hasattr(x.type, 'declname') and lv_base_obj_pattern.match(x.type.declname))] + # print('/* %s */' % str(typedefs)) + synonym = {} + for t in typedefs: + if isinstance(t, c_ast.TypeDecl) and isinstance(t.type, c_ast.IdentifierType): + if t.declname != t.type.names[0]: + synonym[t.declname] = t.type.names[0] + # eprint('%s === %s' % (t.declname, t.type.names[0])) + if isinstance(t, c_ast.TypeDecl) and isinstance(t.type, c_ast.Struct): + if t.declname != t.type.name: + synonym[t.declname] = t.type.name + # eprint('%s === struct %s' % (t.declname, t.type.name)) + struct_typedefs = [typedef for typedef in typedefs if is_struct(typedef.type)] + structs_without_typedef = collections.OrderedDict( + (decl.type.name, decl.type) + for decl in ast.ext + if hasattr(decl, "type") and is_struct(decl.type) + ) + + # for typedefs that referenced to a forward declaration struct, replace it with the real definition. + for typedef in struct_typedefs: + if typedef.type.decls is None: # None means it's a forward declaration + struct_name = typedef.type.name + # check if it's found in `structs_without_typedef`. It actually has the typedef. Replace type with it. + if typedef.type.name in structs_without_typedef: + typedef.type = structs_without_typedef[struct_name] + + structs = collections.OrderedDict( + (typedef.declname, typedef.type) + for typedef in struct_typedefs + if typedef.declname and typedef.type.decls + ) # and not lv_base_obj_pattern.match(typedef.declname)) + structs.update(structs_without_typedef) # This is for struct without typedef + explicit_structs = collections.OrderedDict( + (typedef.type.name, typedef.declname) + for typedef in struct_typedefs + if typedef.type.name + ) # and not lv_base_obj_pattern.match(typedef.type.name)) + opaque_structs = collections.OrderedDict( + (typedef.declname, c_ast.Struct(name=typedef.declname, decls=[])) + for typedef in typedefs + if isinstance(typedef.type, c_ast.Struct) and typedef.type.decls == None + ) + structs.update({k: v for k, v in opaque_structs.items() if k not in structs}) + # print('/* --> opaque structs len = %d */' % len(opaque_structs)) + # print('/* --> opaque structs %s */' % ',\n'.join([struct_name for struct_name in opaque_structs])) + # print('/* --> structs:\n%s */' % ',\n'.join(sorted(str(structs[struct_name]) for struct_name in structs if struct_name))) + # print('/* --> structs_without_typedef:\n%s */' % ',\n'.join(sorted(str(structs_without_typedef[struct_name]) for struct_name in structs_without_typedef if struct_name))) + # print('/* --> explicit_structs:\n%s */' % ',\n'.join(sorted(struct_name + " = " + str(explicit_structs[struct_name]) for struct_name in explicit_structs if struct_name))) + # print('/* --> structs without typedef:\n%s */' % ',\n'.join(sorted(str(structs[struct_name]) for struct_name in structs_without_typedef))) + + # Functions and objects + + func_defs = [x.decl for x in ast.ext if isinstance(x, c_ast.FuncDef)] + func_decls = [ + x + for x in ast.ext + if isinstance(x, c_ast.Decl) and isinstance(x.type, c_ast.FuncDecl) + ] + all_funcs = func_defs + func_decls + funcs = [ + f for f in all_funcs if not f.name.startswith("_") + ] # functions that start with underscore are usually internal + # eprint('... %s' % ',\n'.join(sorted('%s' % func.name for func in funcs))) + constructor_names = { + function.c_name + for function in api_model.functions + if function.role == "constructor" and function.visibility == "public" + } + obj_ctors = [func for func in funcs if func.name in constructor_names] + # eprint('CTORS(%d): %s' % (len(obj_ctors), ', '.join(sorted('%s' % ctor.name for ctor in obj_ctors)))) + for obj_ctor in obj_ctors: + funcs.remove(obj_ctor) + obj_names = [create_obj_pattern.match(ctor.name).group(1) for ctor in obj_ctors] + + + # All object should inherit directly from base_obj, and not according to lv_ext, as disccussed on https://github.com/littlevgl/lv_binding_micropython/issues/19 + parent_obj_names = { + child_name: base_obj_name for child_name in obj_names if child_name != base_obj_name + } + parent_obj_names[base_obj_name] = None + + # Populate inheritance hierarchy according to lv_ext structures + # exts = {obj_name_from_ext_name(ext.name): ext for ext in ast.ext if hasattr(ext, 'name') and ext.name is not None and lv_ext_pattern.match(ext.name)} + # for obj_name, ext in exts.items(): + # try: + # parent_ext_name = ext.type.type.decls[0].type.type.names[0] + # if lv_ext_pattern.match(parent_ext_name): + # parent_obj_names[obj_name] = obj_name_from_ext_name(parent_ext_name) + # except AttributeError: + # pass + + # Parse Enums + + enum_defs = [ + x for x in ast.ext if hasattr(x, "type") and isinstance(x.type, c_ast.Enum) + ] + enum_defs += [ + x.type + for x in ast.ext + if hasattr(x, "type") + and hasattr(x.type, "type") + and isinstance(x.type, c_ast.TypeDecl) + and isinstance(x.type.type, c_ast.Enum) + ] + + # parse function pointers + func_typedefs = collections.OrderedDict( + (t.name, t) + for t in ast.ext + if isinstance(t, c_ast.Typedef) + and isinstance(t.type, c_ast.PtrDecl) + and isinstance(t.type.type, c_ast.FuncDecl) + ) + + # Global blobs + blobs = collections.OrderedDict( + (decl.name, decl.type.type) + for decl in ast.ext + if isinstance(decl, c_ast.Decl) + and "extern" in decl.storage + and hasattr(decl, "type") + and isinstance(decl.type, c_ast.TypeDecl) + and not decl.name.startswith("_") + ) + + # Not an LVGL declaration: a binding-internal callback re-entrancy + # counter (see the matching mp_lv_funcptr/{func}_callback increments in + # emit_c_micropython_style.py). It is deliberately private in the + # canonical API model (see api_model.build_api_model) yet still emitted + # as a real MicroPython/CircuitPython module global, because PyDevices' + # LVGL coordinator (display_driver.py in PyDevices/pydevices lib/) reads + # it to detect reentrant lv.task_handler() calls from inside an LVGL + # callback. Do not + # remove this on the assumption it is unused C state; its only reader + # is Python code outside this translation unit. + blobs["_nesting"] = parser.parse("extern int _nesting;").ext[0].type.type + + int_constants = [] + # Type convertors + # + + + class MissingConversionException(ValueError): + pass + + + mp_to_lv = { + "mp_obj_t": "(mp_obj_t)", + "va_list": None, + "void *": "mp_to_ptr", + "const uint8_t *": "mp_to_ptr", + "const void *": "mp_to_ptr", + "bool": "mp_obj_is_true", + "char *": "(char*)convert_from_str", + "char **": "mp_write_ptr_C_Pointer", + "const char *": "convert_from_str", + "const char **": "mp_write_ptr_C_Pointer", + "%s_obj_t *" % module_prefix: "mp_to_lv", + "uint8_t": "(uint8_t)mp_obj_get_int", + "uint16_t": "(uint16_t)mp_obj_get_int", + "uint32_t": "(uint32_t)mp_obj_get_int", + "uint64_t": "(uint64_t)mp_obj_get_ull", + "unsigned": "(unsigned)mp_obj_get_int", + "unsigned int": "(unsigned int)mp_obj_get_int", + "unsigned char": "(unsigned char)mp_obj_get_int", + "unsigned short": "(unsigned short)mp_obj_get_int", + "unsigned long": "(unsigned long)mp_obj_get_int", + "unsigned long int": "(unsigned long int)mp_obj_get_int", + "unsigned long long": "(unsigned long long)mp_obj_get_ull", + "unsigned long long int": "(unsigned long long int)mp_obj_get_ull", + "int8_t": "(int8_t)mp_obj_get_int", + "int16_t": "(int16_t)mp_obj_get_int", + "int32_t": "(int32_t)mp_obj_get_int", + "int64_t": "(int64_t)mp_obj_get_ull", + "size_t": "(size_t)mp_obj_get_int", + "int": "(int)mp_obj_get_int", + "char": "(char)mp_obj_get_int", + "short": "(short)mp_obj_get_int", + "long": "(long)mp_obj_get_int", + "long int": "(long int)mp_obj_get_int", + "long long": "(long long)mp_obj_get_ull", + "long long int": "(long long int)mp_obj_get_ull", + "float": "(float)mp_obj_get_float", + } + + lv_to_mp = { + "mp_obj_t": "(mp_obj_t)", + "va_list": None, + "void *": "ptr_to_mp", + "const uint8_t *": "ptr_to_mp", + "const void *": "ptr_to_mp", + "bool": "convert_to_bool", + "char *": "convert_to_str", + "char **": "mp_read_ptr_C_Pointer", + "const char *": "convert_to_str", + "const char **": "mp_read_ptr_C_Pointer", + "%s_obj_t *" % module_prefix: "lv_to_mp", + "uint8_t": "mp_obj_new_int_from_uint", + "uint16_t": "mp_obj_new_int_from_uint", + "uint32_t": "mp_obj_new_int_from_uint", + "uint64_t": "mp_obj_new_int_from_ull", + "unsigned": "mp_obj_new_int_from_uint", + "unsigned int": "mp_obj_new_int_from_uint", + "unsigned char": "mp_obj_new_int_from_uint", + "unsigned short": "mp_obj_new_int_from_uint", + "unsigned long": "mp_obj_new_int_from_uint", + "unsigned long int": "mp_obj_new_int_from_uint", + "unsigned long long": "mp_obj_new_int_from_ull", + "unsigned long long int": "mp_obj_new_int_from_ull", + "int8_t": "mp_obj_new_int", + "int16_t": "mp_obj_new_int", + "int32_t": "mp_obj_new_int", + "int64_t": "mp_obj_new_int_from_ll", + "size_t": "mp_obj_new_int_from_uint", + "int": "mp_obj_new_int", + "char": "mp_obj_new_int", + "short": "mp_obj_new_int", + "long": "mp_obj_new_int", + "long int": "mp_obj_new_int", + "long long": "mp_obj_new_int_from_ll", + "long long int": "mp_obj_new_int_from_ll", + "float": "mp_obj_new_float_from_f", + } + + lv_mp_type = { + "mp_obj_t": "%s*" % base_obj_type, + "va_list": None, + "void *": "void*", + "const uint8_t *": "void*", + "const void *": "void*", + "bool": "bool", + "char *": "char*", + "char **": "char**", + "const char *": "char*", + "const char **": "char**", + "%s_obj_t *" % module_prefix: "%s*" % base_obj_type, + "uint8_t": "int", + "uint16_t": "int", + "uint32_t": "int", + "uint64_t": "int", + "unsigned": "int", + "unsigned int": "int", + "unsigned char": "int", + "unsigned short": "int", + "unsigned long": "int", + "unsigned long int": "int", + "unsigned long long": "int", + "unsigned long long int": "int", + "int8_t": "int", + "int16_t": "int", + "int32_t": "int", + "int64_t": "int", + "size_t": "int", + "int": "int", + "char": "int", + "short": "int", + "long": "int", + "long int": "int", + "long long": "int", + "long long int": "int", + "void": None, + "float": "float", + } + + lv_to_mp_byref = {} + lv_to_mp_funcptr = {} + + # Add native array supported types + # These types would be converted automatically to/from array type. + # Supported array (pointer) types are signed/unsigned int: 8bit, 16bit, 32bit and 64bit. + + register_int_ptr_type(mp_to_lv, lv_to_mp, lv_mp_type, "u8ptr", "unsigned char *", "uint8_t *") + + register_int_ptr_type(mp_to_lv, lv_to_mp, lv_mp_type, "u16ptr", "unsigned short *", "uint16_t *") + + register_int_ptr_type(mp_to_lv, lv_to_mp, lv_mp_type, "i16ptr", "short *", "int16_t *") + + register_int_ptr_type( + mp_to_lv, lv_to_mp, lv_mp_type, + "u32ptr", + "uint32_t *", + "unsigned *", + "unsigned int *", + "unsigned long *", + "unsigned long int *", + "size_t *", + ) + + register_int_ptr_type( + mp_to_lv, lv_to_mp, lv_mp_type, + "i32ptr", + "int32_t *", + "signed *", + "signed int *", + "signed long *", + "signed long int *", + "long *", + "long int *", + "int *", + ) + + register_int_ptr_type( + mp_to_lv, lv_to_mp, lv_mp_type, + "u64ptr", "int64_t *", "signed long long *", "long long *", "long long int *" + ) + + register_int_ptr_type( + mp_to_lv, lv_to_mp, lv_mp_type, + "i64ptr", "uint64_t *", "unsigned long long *", "unsigned long long int *" + ) + + state = locals() + for name in ctx.export_names(): + if name in state: + setattr(ctx, name, state[name]) + + + # diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/api_model.py b/maix_lvgl/tools/omnipython_lvgl/binding/api_model.py new file mode 100644 index 00000000..0b27890e --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/api_model.py @@ -0,0 +1,1332 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Target-neutral public API model built from the declaration IR. + +This module describes the API independently of any C runtime or binding +backend. Conversion details and target exceptions are intentionally separate +so the three backends can lower the same model. +""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass, field, replace +from os.path import commonprefix +from typing import Any, Mapping, Optional, Tuple + +from .ir import ( + CEnum, + CField, + CParameter, + CStruct, + CType, + DeclarationIndex, + DeclarationIR, + SourceLocation, +) + +TARGETS = ("micropython", "circuitpython", "cpython") +API_SCHEMA_VERSION = 3 + + +# These are the established public spellings used by the upstream-compatible +# Python API. They describe enum ownership and naming only; they do not alter +# C declarations or generated C output. +_MODULE_ENUM_NAME_OVERRIDES = { + "animimg_part_t": "ANIM_IMAGE_PART", + "cache_reserve_cond_res_t": "CACHE_RESERVE_COND", + "indev_gesture_type_t": "INDEV_GESTURE", + "event_code_t": "EVENT", + "align_t": "ALIGN", + "color_format_t": "COLOR_FORMAT", + "grad_dir_t": "GRAD_DIR", + "grad_extend_t": "GRAD_EXTEND", + "base_dir_t": "BASE_DIR", + "opa_t": "OPA", + "text_align_t": "TEXT_ALIGN", + "palette_t": "PALETTE", + "font_kerning_t": "FONT_KERNING", + "font_subpx_t": "FONT_SUBPX", + "font_glyph_format_t": "FONT_GLYPH_FORMAT", + "dir_t": "DIR", + "result_t": "RESULT", + "log_level_t": "LOG_LEVEL", + "font_fmt_txt_bitmap_format_t": "FONT_FMT_TXT", + "font_fmt_txt_cmap_type_t": "FONT_FMT_TXT_CMAP", + "fs_whence_t": "FS_SEEK", +} +_WIDGET_ENUM_NAME_OVERRIDES = { + "barcode_encoding_t": ("barcode", "ENCODING_CODE128"), + "menu_mode_header_t": ("menu", "HEADER"), + "menu_mode_root_back_button_t": ("menu", "ROOT_BACK_BUTTON"), + "obj_tree_walk_res_t": ("obj", "TREE_WALK"), +} + + +def api_hash_for_dict(data: Mapping[str, Any]) -> str: + """Hash API content without trusting or including its stored hash field.""" + + content = dict(data) + content.pop("api_hash", None) + encoded = json.dumps(content, sort_keys=True, separators=(",", ":")).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def _type_to_dict(type_: CType) -> Mapping[str, Any]: + result = {"kind": type_.kind} + if type_.name is not None: + result["name"] = type_.name + if type_.qualifiers: + result["qualifiers"] = list(type_.qualifiers) + if type_.target is not None: + result["target"] = _type_to_dict(type_.target) + if type_.element is not None: + result["element"] = _type_to_dict(type_.element) + if type_.dimensions: + result["dimensions"] = list(type_.dimensions) + if type_.return_type is not None: + result["return_type"] = _type_to_dict(type_.return_type) + if type_.parameters: + result["parameters"] = [_parameter_to_dict(parameter) for parameter in type_.parameters] + if type_.variadic: + result["variadic"] = True + return result + + +def _field_to_dict( + field_: CField, view: Optional[ApiTypeView] = None +) -> Mapping[str, Any]: + result = {"name": field_.name, "type": _type_to_dict(field_.type)} + if view is not None: + result["view"] = view.to_dict() + if field_.bit_width is not None: + result["bit_width"] = field_.bit_width + return result + + +def _location_to_dict(location: SourceLocation) -> Mapping[str, Any]: + return { + "file": location.file, + "line": location.line, + "column": location.column, + } + + +@dataclass(frozen=True) +class ApiTypeView: + """Target-neutral interpretation of one C type at the Python boundary.""" + + python_type: str + category: str + conversion: str + nullable: Optional[bool] = None + lifetime: Optional[str] = None + + def to_dict(self) -> Mapping[str, Any]: + result = { + "python_type": self.python_type, + "category": self.category, + "conversion": self.conversion, + } + if self.nullable is not None: + result["nullable"] = self.nullable + if self.lifetime is not None: + result["lifetime"] = self.lifetime + return result + + +def _parameter_to_dict( + parameter: CParameter, view: Optional[ApiTypeView] = None +) -> Mapping[str, Any]: + result = {"name": parameter.name, "type": _type_to_dict(parameter.type)} + if view is not None: + result["view"] = view.to_dict() + if parameter.location.file is not None: + result["location"] = { + "file": parameter.location.file, + "line": parameter.location.line, + "column": parameter.location.column, + } + return result + + +@dataclass(frozen=True) +class ApiFunction: + c_name: str + python_name: str + role: str + parameters: Tuple[CParameter, ...] + return_type: CType + receiver: Optional[str] = None + static: bool = False + variadic: bool = False + storage: Tuple[str, ...] = () + function_specifiers: Tuple[str, ...] = () + available_on: Tuple[str, ...] = TARGETS + visibility: str = "public" + policy_reason: Optional[str] = None + location: Optional[SourceLocation] = field(default=None) + parameter_views: Tuple[ApiTypeView, ...] = () + return_view: Optional[ApiTypeView] = None + + def to_dict(self) -> Mapping[str, Any]: + result = { + "c_name": self.c_name, + "python_name": self.python_name, + "role": self.role, + "parameters": [ + _parameter_to_dict( + parameter, + self.parameter_views[index] + if index < len(self.parameter_views) + else None, + ) + for index, parameter in enumerate(self.parameters) + ], + "return_type": _type_to_dict(self.return_type), + "static": self.static, + "variadic": self.variadic, + "storage": list(self.storage), + "function_specifiers": list(self.function_specifiers), + "available_on": list(self.available_on), + "visibility": self.visibility, + } + if self.return_view is not None: + result["return_view"] = self.return_view.to_dict() + if self.policy_reason is not None: + result["policy_reason"] = self.policy_reason + if self.receiver is not None: + result["receiver"] = self.receiver + if self.location is not None: + result["location"] = _location_to_dict(self.location) + return result + + +@dataclass(frozen=True) +class ApiStruct: + c_name: Optional[str] + python_name: str + kind: str + fields: Tuple[CField, ...] + typedef_names: Tuple[str, ...] = () + complete: bool = False + available_on: Tuple[str, ...] = TARGETS + methods: Tuple[str, ...] = () + visibility: str = "public" + policy_reason: Optional[str] = None + location: Optional[SourceLocation] = field(default=None) + field_views: Tuple[ApiTypeView, ...] = () + + def to_dict(self) -> Mapping[str, Any]: + result = { + "c_name": self.c_name, + "python_name": self.python_name, + "kind": self.kind, + "fields": [ + _field_to_dict( + field_, + self.field_views[index] + if index < len(self.field_views) + else None, + ) + for index, field_ in enumerate(self.fields) + ], + "typedef_names": list(self.typedef_names), + "complete": self.complete, + "available_on": list(self.available_on), + "methods": list(self.methods), + "visibility": self.visibility, + } + if self.policy_reason is not None: + result["policy_reason"] = self.policy_reason + if self.location is not None: + result["location"] = _location_to_dict(self.location) + return result + + +@dataclass(frozen=True) +class ApiEnum: + c_name: Optional[str] + python_name: str + members: Tuple[Tuple[str, Optional[str]], ...] + member_type: str = "int" + typedef_names: Tuple[str, ...] = () + complete: bool = False + available_on: Tuple[str, ...] = TARGETS + visibility: str = "public" + policy_reason: Optional[str] = None + location: Optional[SourceLocation] = field(default=None) + module_name: Optional[str] = None + owners: Tuple[Tuple[str, str], ...] = () + + def to_dict(self) -> Mapping[str, Any]: + result = { + "c_name": self.c_name, + "python_name": self.python_name, + "members": [ + {"name": name, "value": value} for name, value in self.members + ], + "member_type": self.member_type, + "typedef_names": list(self.typedef_names), + "complete": self.complete, + "available_on": list(self.available_on), + "visibility": self.visibility, + "module_name": self.module_name, + "owners": [ + {"object": object_name, "name": nested_name} + for object_name, nested_name in self.owners + ], + } + if self.policy_reason is not None: + result["policy_reason"] = self.policy_reason + if self.location is not None: + result["location"] = _location_to_dict(self.location) + return result + + +@dataclass(frozen=True) +class ApiTypedef: + name: str + type: CType + c_name: Optional[str] = None + callback: bool = False + available_on: Tuple[str, ...] = TARGETS + visibility: str = "public" + policy_reason: Optional[str] = None + location: Optional[SourceLocation] = field(default=None) + type_view: Optional[ApiTypeView] = None + + def to_dict(self) -> Mapping[str, Any]: + result = { + "name": self.name, + "c_name": self.c_name or self.name, + "type": _type_to_dict(self.type), + "callback": self.callback, + "available_on": list(self.available_on), + "visibility": self.visibility, + } + if self.type_view is not None: + result["view"] = self.type_view.to_dict() + if self.policy_reason is not None: + result["policy_reason"] = self.policy_reason + if self.location is not None: + result["location"] = _location_to_dict(self.location) + return result + + +@dataclass(frozen=True) +class ApiVariable: + c_name: str + type: CType + python_name: Optional[str] = None + storage: Tuple[str, ...] = () + available_on: Tuple[str, ...] = TARGETS + visibility: str = "public" + policy_reason: Optional[str] = None + location: Optional[SourceLocation] = field(default=None) + type_view: Optional[ApiTypeView] = None + + def to_dict(self) -> Mapping[str, Any]: + result = { + "c_name": self.c_name, + "python_name": self.python_name or self.c_name, + "type": _type_to_dict(self.type), + "storage": list(self.storage), + "available_on": list(self.available_on), + "visibility": self.visibility, + } + if self.type_view is not None: + result["view"] = self.type_view.to_dict() + if self.policy_reason is not None: + result["policy_reason"] = self.policy_reason + if self.location is not None: + result["location"] = _location_to_dict(self.location) + return result + + +@dataclass(frozen=True) +class ApiConstant: + c_name: str + python_name: str + value: Optional[str] + available_on: Tuple[str, ...] = TARGETS + visibility: str = "public" + policy_reason: Optional[str] = None + location: Optional[SourceLocation] = field(default=None) + + def to_dict(self) -> Mapping[str, Any]: + result = { + "c_name": self.c_name, + "python_name": self.python_name, + "value": self.value, + "available_on": list(self.available_on), + "visibility": self.visibility, + } + if self.policy_reason is not None: + result["policy_reason"] = self.policy_reason + if self.location is not None: + result["location"] = _location_to_dict(self.location) + return result + + +@dataclass(frozen=True) +class ApiObject: + python_name: str + c_type: str + constructor: Optional[str] + methods: Tuple[str, ...] + parent: Optional[str] = None + available_on: Tuple[str, ...] = TARGETS + visibility: str = "public" + policy_reason: Optional[str] = None + + def to_dict(self) -> Mapping[str, Any]: + return { + "python_name": self.python_name, + "c_type": self.c_type, + "constructor": self.constructor, + "methods": list(self.methods), + "parent": self.parent, + "available_on": list(self.available_on), + "visibility": self.visibility, + **( + {"policy_reason": self.policy_reason} + if self.policy_reason is not None + else {} + ), + } + + +@dataclass(frozen=True) +class ApiModel: + module_prefix: str + functions: Tuple[ApiFunction, ...] + objects: Tuple[ApiObject, ...] + structs: Tuple[ApiStruct, ...] + enums: Tuple[ApiEnum, ...] + typedefs: Tuple[ApiTypedef, ...] + variables: Tuple[ApiVariable, ...] + constants: Tuple[ApiConstant, ...] = () + schema_version: int = API_SCHEMA_VERSION + + def _content_dict(self) -> Mapping[str, Any]: + return { + "schema_version": self.schema_version, + "module_prefix": self.module_prefix, + "functions": [ + item.to_dict() for item in sorted(self.functions, key=lambda x: x.c_name) + ], + "objects": [ + item.to_dict() for item in sorted(self.objects, key=lambda x: x.python_name) + ], + "structs": [ + item.to_dict() + for item in sorted( + self.structs, key=lambda x: (x.python_name, x.c_name or "") + ) + ], + "enums": [ + item.to_dict() + for item in sorted( + self.enums, key=lambda x: (x.python_name, x.c_name or "") + ) + ], + "typedefs": [ + item.to_dict() for item in sorted(self.typedefs, key=lambda x: x.name) + ], + "variables": [ + item.to_dict() for item in sorted(self.variables, key=lambda x: x.c_name) + ], + "constants": [ + item.to_dict() + for item in sorted(self.constants, key=lambda x: x.python_name) + ], + } + + @property + def api_hash(self) -> str: + return api_hash_for_dict(self._content_dict()) + + def validation_errors(self) -> Tuple[str, ...]: + """Return semantic model errors that do not require a target backend.""" + + errors = [] + seen = {} + + def add(scope: str, name: str, source: str) -> None: + key = (scope, name) + previous = seen.get(key) + if previous is not None: + errors.append( + "duplicate export %s.%s (%s and %s)" + % (scope, name, previous, source) + ) + else: + seen[key] = source + + for function in self.functions: + if function.visibility != "public": + continue + scope = ( + "module" + if function.role == "module" + else "constructor.%s" % function.receiver + if function.role == "constructor" + else "%s.%s" % (function.role, function.receiver or "") + ) + add(scope, function.python_name, function.c_name) + if not set(function.available_on) <= set(TARGETS): + errors.append("unknown target on function %s" % function.c_name) + if not function.available_on: + errors.append("public function has no targets: %s" % function.c_name) + + for obj in self.objects: + if obj.visibility == "public": + add("module", obj.python_name, "object " + obj.python_name) + if len(obj.methods) != len(set(obj.methods)): + errors.append("duplicate object methods: %s" % obj.python_name) + for struct in self.structs: + if struct.visibility == "public": + add("module", struct.python_name, "struct " + struct.python_name) + for enum in self.enums: + if enum.visibility == "public": + if enum.module_name is not None: + add("module", enum.module_name, "enum " + enum.python_name) + for object_name, nested_name in enum.owners: + add( + "object." + object_name, + nested_name, + "enum " + enum.python_name, + ) + members = [name for name, _value in enum.members] + if len(members) != len(set(members)): + errors.append("duplicate enum members: %s" % enum.python_name) + type_names = { + item.python_name + for item in self.structs + self.enums + if item.visibility == "public" + } + for typedef in self.typedefs: + if typedef.visibility == "public": + # A typedef that names a concrete struct/enum is the C alias + # for that same Python type, not a second module export. + if typedef.name in type_names and typedef.type.kind in { + "struct", + "union", + "enum", + }: + continue + add("module", typedef.name, "typedef " + typedef.c_name) + for variable in self.variables: + if variable.visibility == "public": + add("module", variable.python_name or variable.c_name, "variable " + variable.c_name) + for constant in self.constants: + if constant.visibility == "public": + add("module", constant.python_name, "constant " + constant.c_name) + return tuple(errors) + + def to_dict(self) -> Mapping[str, Any]: + result = dict(self._content_dict()) + result["api_hash"] = self.api_hash + return result + + def to_json(self) -> str: + return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" + + +def _strip_prefix(name: str, module_prefix: str) -> str: + prefix = module_prefix + "_" + return name[len(prefix) :] if name.startswith(prefix) else name + + +def _python_type_name(name: str, module_prefix: str) -> str: + """Return the legacy Python spelling for an LVGL typedef/tag name.""" + + name = name.removeprefix("_" + module_prefix + "_") + name = name.removeprefix(module_prefix + "_") + if name and name[0].isdigit(): + return "_" + name + return name + + +def _python_enum_name(name: Optional[str], module_prefix: str) -> str: + if not name: + return "" + return _python_type_name(name, module_prefix).removesuffix("_t").upper() + + +def _python_enum_member_name(name: str, enum_name: str, module_prefix: str) -> str: + for prefix in ( + "ENUM_" + module_prefix.upper() + "_" + enum_name + "_", + module_prefix.upper() + "_" + enum_name + "_", + ): + if name.startswith(prefix): + return name[len(prefix) :] + if name.startswith("ENUM_" + module_prefix.upper() + "_"): + return name[len("ENUM_" + module_prefix.upper() + "_") :] + return name + + +def _same_struct(index: DeclarationIndex, left: Optional[str], right: Optional[str]) -> bool: + if left is None or right is None: + return left == right + return index._struct_identity(left) == index._struct_identity(right) + + +def _public_struct_name(struct: CStruct) -> str: + if struct.typedef_names: + # The preprocessor can expose both a private implementation alias and + # its public spelling. Prefer the stable public spelling and make the + return sorted( + struct.typedef_names, + key=lambda name: (name.startswith("_"), name), + )[0] + if struct.name: + return struct.name + return "" + + +def _struct_method_name(function_name: str, struct_c_name: str) -> str: + """The name the runtimes give a struct method: the part of the function + name after the last ``_`` it shares with the struct's C name, so + lv_grad_linear_init on lv_grad_dsc_t is ``linear_init`` + (analyze.noncommon_part; lvgl-bindings#39).""" + n = len(commonprefix([function_name, struct_c_name])) - 1 + while n > 0 and function_name[n] != "_": + n -= 1 + return function_name[n + 1 :] + + +def _method_name(function_name: str, receiver: str, module_prefix: str) -> str: + plain = _strip_prefix(function_name, module_prefix) + stems = [receiver] + if receiver.endswith("_t"): + stems.append(receiver[:-2]) + for stem in stems: + if plain.startswith(stem + "_"): + return plain[len(stem) + 1 :] + return plain + + +def _enum_stem(enum: CEnum, module_prefix: str) -> str: + """Infer the public enum stem from its enumerator names.""" + + names = [member for member in enum.members if not member.startswith("_")] + if not names: + return "" + normalized = [ + name.removeprefix("ENUM_") + for name in names + if name.removeprefix("ENUM_").startswith(module_prefix.upper() + "_") + ] + if not normalized: + return "" + common_prefix = commonprefix(normalized) + common = common_prefix.rstrip("_") + if common_prefix and not common_prefix.endswith("_"): + common = common.rsplit("_", 1)[0] + if not common: + return "" + module_prefix_upper = module_prefix.upper() + "_" + if common.startswith(module_prefix_upper): + common = common[len(module_prefix_upper) :] + return common.removesuffix("_T").upper() + + +def _enum_exports( + enum: CEnum, + *, + module_prefix: str, + object_names: Tuple[str, ...], +) -> Tuple[Optional[str], Tuple[Tuple[str, str], ...], str]: + """Return module export, nested owners, and the C-derived enum stem.""" + + typedef_names = tuple( + name + for name in enum.typedef_names + if name.startswith(module_prefix + "_") + ) + typedef_name = ( + typedef_names[0][len(module_prefix) + 1 :] + if typedef_names + else "" + ) + stem = _enum_stem(enum, module_prefix) + if typedef_name in _MODULE_ENUM_NAME_OVERRIDES: + return _MODULE_ENUM_NAME_OVERRIDES[typedef_name], (), stem + widget_override = _WIDGET_ENUM_NAME_OVERRIDES.get(typedef_name) + if widget_override is not None: + owner, nested_name = widget_override + return None, ((owner, nested_name),), stem + if stem == "STR_SYMBOL": + return "SYMBOL", (), stem + + object_names = tuple(sorted(object_names, key=len, reverse=True)) + for object_name in object_names: + prefix = object_name.upper() + "_" + if stem.startswith(prefix): + nested_name = stem[len(prefix) :] + if nested_name: + # OBJ_FLAG is intentionally exported both as lv.OBJ_FLAG and + # as obj.FLAG by the established binding API. + if object_name == "obj" and nested_name == "FLAG": + return "OBJ_FLAG", ((object_name, nested_name),), stem + return None, ((object_name, nested_name),), stem + + if typedef_name: + module_name = _python_enum_name( + module_prefix + "_" + typedef_name, module_prefix + ) + else: + module_name = stem + return module_name or None, (), stem + + +_INTEGER_TYPES = frozenset( + { + "char", + "short", + "int", + "long", + "signed", + "unsigned", + "_Bool", + "bool", + "int8_t", + "uint8_t", + "int16_t", + "uint16_t", + "int32_t", + "uint32_t", + "int64_t", + "uint64_t", + "intptr_t", + "uintptr_t", + "size_t", + } +) +_INTEGER_WORDS = frozenset({"char", "short", "int", "long", "signed", "unsigned"}) + + +def _is_integer_name(name: Optional[str]) -> bool: + if not name: + return False + if name in _INTEGER_TYPES: + return True + words = set(name.split()) + return bool(words) and words <= _INTEGER_WORDS and "float" not in words + + +def _build_type_view_resolver( + objects: Tuple[ApiObject, ...], + structs: Tuple[ApiStruct, ...], + enums: Tuple[ApiEnum, ...], + typedefs: Tuple[ApiTypedef, ...], +): + """Create a target-neutral C-to-Python type-view resolver.""" + + def is_hidden_implementation(item) -> bool: + """Exclude declarations deliberately hidden by API policy. + + Declarations outside the LVGL prefix are still useful as boundary + types when a public LVGL function uses them. A non-default policy + reason, however, is an explicit decision that the implementation type + must not appear in public annotations (for example ``global_t``). + """ + + return ( + item.visibility == "private" + and item.policy_reason not in {None, "outside module prefix"} + ) + + object_by_c = { + item.c_type: item.python_name + for item in objects + if not is_hidden_implementation(item) + } + struct_by_c = {} + for item in structs: + object_name = next( + ( + object_.python_name + for object_ in objects + if object_.python_name + "_t" == item.python_name + or object_.c_type in item.typedef_names + or item.c_name == "_" + object_.c_type + ), + None, + ) + if object_name is not None: + for alias in (item.c_name,) + item.typedef_names: + if alias: + object_by_c[alias] = object_name + continue + if is_hidden_implementation(item): + continue + if item.c_name: + struct_by_c[item.c_name] = item.python_name + for alias in item.typedef_names: + struct_by_c[alias] = item.python_name + enum_by_c = {} + for item in enums: + if is_hidden_implementation(item): + continue + if item.module_name is not None: + python_type = item.module_name + elif item.owners: + owner, nested_name = item.owners[0] + python_type = "%s.%s" % (owner, nested_name) + else: + python_type = item.python_name + for alias in item.typedef_names: + enum_by_c[alias] = python_type + " | int" + if item.c_name: + enum_by_c[item.c_name] = python_type + " | int" + typedef_by_c = { + item.c_name or item.name: item for item in typedefs + } + + def named_view(name: Optional[str], seen: Tuple[str, ...]) -> ApiTypeView: + if not name: + return ApiTypeView("Any", "unknown", "unsupported") + if name in object_by_c: + return ApiTypeView(object_by_c[name], "object", "object_handle") + if name in struct_by_c: + return ApiTypeView(struct_by_c[name], "struct", "struct_value") + if name in enum_by_c: + return ApiTypeView(enum_by_c[name], "enum", "enum_int") + typedef = typedef_by_c.get(name) + if typedef is not None and name not in seen: + return view(typedef.type, seen + (name,), alias=name) + if name == "void": + return ApiTypeView("None", "void", "none") + if _is_integer_name(name): + return ApiTypeView("int", "scalar", "integer") + if name in {"float", "double"}: + return ApiTypeView("float", "scalar", "float") + if name == "va_list": + return ApiTypeView("Any", "opaque", "opaque") + return ApiTypeView("Any", "unknown", "unsupported") + + def view( + type_: CType, + seen: Tuple[str, ...] = (), + alias: Optional[str] = None, + ) -> ApiTypeView: + if type_.kind in {"primitive", "identifier"}: + return named_view(type_.name, seen) + if type_.kind in {"struct", "union"}: + result = named_view(type_.name, seen) + if type_.name is None and alias is not None: + result = named_view(alias, seen) + if result.category == "unknown": + return ApiTypeView("Any", "struct", "struct_value") + return result + if type_.kind == "enum": + result = named_view(type_.name, seen) + if type_.name is None and alias is not None: + result = named_view(alias, seen) + if result.category == "unknown": + return ApiTypeView("int", "enum", "enum_int") + return result + if type_.kind == "pointer": + target = type_.target or CType(kind="primitive", name="void") + if target.kind == "function": + return ApiTypeView( + callable_type(target), + "callback", + "callback", + ) + if target.kind in {"primitive", "identifier", "struct", "union", "enum"}: + target_view = view(target, seen) + if target_view.category == "object": + return ApiTypeView( + target_view.python_type, + "object_pointer", + "object_handle", + ) + if target_view.category == "struct": + return ApiTypeView( + target_view.python_type, + "struct_pointer", + "struct_pointer", + ) + if target_view.category == "enum": + return ApiTypeView( + target_view.python_type, + "enum_pointer", + "enum_pointer", + ) + if target.kind == "primitive" and target.name == "char": + return ApiTypeView("str", "string", "string") + if ( + target.kind == "primitive" and _is_integer_name(target.name) + ) or ( + target.kind == "identifier" + and target_view.category == "scalar" + and target_view.python_type == "int" + ): + return ApiTypeView("Any", "typed_buffer", "typed_buffer") + if target.kind == "primitive" and target.name == "void": + return ApiTypeView("Any", "opaque_pointer", "opaque") + return ApiTypeView("Any", "pointer", "pointer") + if type_.kind == "array": + element = type_.element or CType(kind="primitive", name="void") + element_type = view(element, seen).python_type + return ApiTypeView("Sequence[%s]" % element_type, "array", "array") + if type_.kind == "function": + return ApiTypeView(callable_type(type_), "callback", "callback") + if type_.kind == "ellipsis": + return ApiTypeView("Any", "variadic", "variadic") + return ApiTypeView("Any", "unknown", "unsupported") + + def callable_type(type_: CType) -> str: + parameters = [view(parameter.type).python_type for parameter in type_.parameters] + return_type = view(type_.return_type or CType(kind="primitive", name="void")) + if type_.variadic: + parameter_spec = "..." + else: + parameter_spec = "[%s]" % ", ".join(parameters) + return "Callable[%s, %s]" % (parameter_spec, return_type.python_type) + + return view + + +def build_api_model( + declarations: DeclarationIR, + *, + module_prefix: str = "lv", + base_obj_type: str = "lv_obj_t", + policy=None, +) -> ApiModel: + """Build a deterministic API model with explicit visibility policy.""" + if policy is None: + from .api_policy import ApiPolicy + + policy = ApiPolicy.default(module_prefix=module_prefix) + index = DeclarationIndex.from_ir(declarations, module_prefix=module_prefix) + + struct_names = { + id(struct): _public_struct_name(struct) for struct in declarations.structs + } + struct_python_names = { + id(struct): _python_type_name(struct_names[id(struct)], module_prefix) + for struct in declarations.structs + } + struct_receivers = {} + struct_c_receivers = {} + for struct in declarations.structs: + receiver = struct_names[id(struct)] + for function in index.struct_functions(receiver): + struct_receivers.setdefault( + function.name, struct_python_names[id(struct)] + ) + struct_c_receivers.setdefault(function.name, receiver) + + constructors = {} + for function in declarations.functions: + decision = policy.function(function.name) + plain = _strip_prefix(function.name, module_prefix) + if ( + decision.visibility != "public" + or not plain.endswith("_create") + or not function.parameters + ): + continue + if _same_struct( + index, + index.first_argument_type_name(function.name), + base_obj_type, + ): + constructors[plain[: -len("_create")]] = function.name + + functions = [] + object_methods = {name: [] for name in constructors} + for function in declarations.functions: + decision = policy.function(function.name) + plain = _strip_prefix(function.name, module_prefix) + role = "module" + receiver = None + if function.name in constructors.values(): + role = "constructor" + receiver = next( + name for name, c_name in constructors.items() if c_name == function.name + ) + elif decision.visibility == "public": + matching_objects = sorted( + ( + object_name + for object_name in constructors + if plain.startswith(object_name + "_") + ), + key=len, + reverse=True, + ) + if matching_objects: + role = "object_method" + receiver = matching_objects[0] + object_methods[receiver].append( + plain[len(receiver) + 1 :] + ) + if role == "module" and function.name in struct_receivers: + role = "struct_method" + receiver = struct_receivers[function.name] + functions.append( + ApiFunction( + c_name=function.name, + python_name=( + "create" + if role == "constructor" + else _struct_method_name( + function.name, struct_c_receivers[function.name] + ) + if role == "struct_method" + else _method_name(function.name, receiver, module_prefix) + if receiver is not None + else plain + ), + role=role, + receiver=receiver, + parameters=function.parameters, + return_type=function.return_type, + static=( + role == "object_method" + and not _same_struct( + index, + index.first_argument_type_name(function.name), + base_obj_type, + ) + ), + variadic=function.variadic, + storage=function.storage, + function_specifiers=function.function_specifiers, + available_on=decision.available_on, + visibility=decision.visibility, + policy_reason=decision.reason, + location=function.location, + ) + ) + + objects = tuple( + ApiObject( + python_name=name, + c_type=module_prefix + "_" + name + "_t", + constructor=constructors[name], + methods=tuple(sorted(object_methods[name])), + parent=None if name == "obj" else "obj", + available_on=tuple( + target + for target in TARGETS + if all( + target in function.available_on + for function in functions + if function.receiver == name + ) + ), + ) + for name in sorted(constructors) + ) + + # A C record is a public Python struct only when a public declaration can + # actually produce or consume it. Prefix-based visibility alone exposed + # object backing records and configuration-only implementation records in + # the stub even though no backend registered them. Compute this closure + # once from the target-neutral declarations instead of learning it from a + # generated target artifact. + struct_by_c_name = {} + for struct in declarations.structs: + for name in (struct.name,) + tuple(struct.typedef_names): + if name: + struct_by_c_name[name] = struct + + def referenced_type_names(type_): + names = set() + if type_ is None: + return names + if type_.kind in {"identifier", "struct", "union"} and type_.name: + names.add(type_.name) + names.update(referenced_type_names(type_.target)) + names.update(referenced_type_names(type_.element)) + names.update(referenced_type_names(type_.return_type)) + for parameter in type_.parameters: + names.update(referenced_type_names(parameter.type)) + return names + + object_c_types = {item.c_type for item in objects} + pending_struct_names = set() + for declaration, api_function in zip(declarations.functions, functions): + if api_function.visibility != "public": + continue + pending_struct_names.update(referenced_type_names(declaration.return_type)) + for parameter in declaration.parameters: + pending_struct_names.update(referenced_type_names(parameter.type)) + for variable in declarations.variables: + if policy.variable(variable.name).visibility == "public": + pending_struct_names.update(referenced_type_names(variable.type)) + pending_struct_names.difference_update(object_c_types) + + reachable_structs = set() + while pending_struct_names: + type_name = pending_struct_names.pop() + struct = struct_by_c_name.get(type_name) + if struct is None or id(struct) in reachable_structs: + continue + reachable_structs.add(id(struct)) + for field in struct.fields: + field_names = referenced_type_names(field.type) + field_names.difference_update(object_c_types) + pending_struct_names.update(field_names) + + function_by_name = {function.c_name: function for function in functions} + structs = [] + for struct in sorted( + declarations.structs, + key=lambda item: (_public_struct_name(item), item.name or ""), + ): + decision = policy.struct((struct.name,) + tuple(struct.typedef_names)) + record_names = {name for name in (struct.name,) + tuple(struct.typedef_names) if name} + if decision.visibility == "public" and record_names & object_c_types: + visibility = "private" + policy_reason = "represented by an LVGL object wrapper" + elif decision.visibility == "public" and id(struct) not in reachable_structs: + visibility = "private" + policy_reason = "not reachable from a public binding boundary" + else: + visibility = decision.visibility + policy_reason = decision.reason + structs.append(ApiStruct( + c_name=struct.name, + python_name=struct_python_names[id(struct)], + kind=struct.kind, + fields=struct.fields, + typedef_names=struct.typedef_names, + complete=struct.complete, + methods=tuple( + sorted( + function_by_name[function.name].python_name + for function in index.struct_functions(struct_names[id(struct)]) + if function.name in function_by_name + ) + ), + visibility=visibility, + policy_reason=policy_reason, + location=struct.location, + )) + structs = tuple(structs) + enums = [] + symbol_members = None + object_names = tuple(constructors) + for enum in sorted( + declarations.enums, + key=lambda item: ( + item.typedef_names[0] + if item.typedef_names + else item.name or "", + item.name or "", + ), + ): + if not enum.name and not enum.typedef_names: + continue + enum_name = _python_enum_name( + enum.typedef_names[0] if enum.typedef_names else enum.name, + module_prefix, + ) + module_name, owners, enum_stem = _enum_exports( + enum, + module_prefix=module_prefix, + object_names=object_names, + ) + decision = policy.enum((enum.name,) + tuple(enum.typedef_names)) + members = tuple( + ( + _python_enum_member_name(member, enum_stem, module_prefix), + value, + ) + for member, value in ( + enum.values or tuple((member, None) for member in enum.members) + ) + ) + enums.append( + ApiEnum( + c_name=enum.name, + python_name=enum_name, + members=members, + typedef_names=enum.typedef_names, + complete=enum.complete, + visibility=decision.visibility, + policy_reason=decision.reason, + location=enum.location, + module_name=module_name, + owners=owners, + ) + ) + if enum_stem == "STR_SYMBOL": + symbol_members = members + if symbol_members: + enums.append( + ApiEnum( + c_name=None, + python_name="SYMBOL", + members=symbol_members, + member_type="str", + complete=True, + location=next( + enum.location + for enum in enums + if enum.python_name == "STR_SYMBOL_ID" + ), + module_name="SYMBOL", + ) + ) + typedefs = tuple( + ApiTypedef( + name=_python_type_name(typedef.name, module_prefix), + c_name=typedef.name, + type=typedef.type, + callback=typedef.name in declarations.callback_typedefs, + visibility=(decision := policy.typedef(typedef.name)).visibility, + policy_reason=decision.reason, + location=typedef.location, + ) + for typedef in declarations.typedefs + ) + variables = list( + ApiVariable( + c_name=variable.name, + type=variable.type, + python_name=_strip_prefix(variable.name, module_prefix), + storage=variable.storage, + visibility=(decision := policy.variable(variable.name)).visibility, + policy_reason=decision.reason, + location=variable.location, + ) + for variable in declarations.variables + ) + # _nesting is not an LVGL declaration; it is a synthetic entry for the + # binding-internal callback re-entrancy counter injected into + # analyze.py's `blobs` (see analyze.py). It is deliberately private + # (not part of the documented public API) but still emitted as a real + # MicroPython/CircuitPython module global and stubbed, because + # PyDevices' display_driver.py (pydevices lib/) depends on it to + # detect reentrant lv.task_handler() calls. See emit_backend.py's + # module_registration_plan and emit_pyi_canonical.py's CanonicalPyiEmitter + # for the matching audited exceptions. + variables.append( + ApiVariable( + c_name="_nesting", + type=CType(kind="primitive", name="int"), + python_name="_nesting", + storage=("static",), + visibility="private", + policy_reason="Binding re-entrancy guard; not a user-facing LVGL symbol.", + ) + ) + constants = [] + anonymous_groups = {} + enum_prefix = "ENUM_" + module_prefix.upper() + "_" + for enum in declarations.enums: + for name, value in enum.values: + if not name.startswith(enum_prefix): + continue + suffix = name[len(enum_prefix) :] + group = suffix.rsplit("_", 1)[0] if "_" in suffix else suffix + anonymous_groups.setdefault(group, []).append((enum, name, value)) + for group, members in sorted(anonymous_groups.items()): + if len(members) > 1: + enums.append( + ApiEnum( + c_name=None, + python_name=group, + members=tuple( + ( + _python_enum_member_name(name, group, module_prefix), + value, + ) + for _enum, name, value in members + ), + complete=True, + location=members[0][0].location, + module_name=group, + ) + ) + else: + enum, name, value = members[0] + constants.append( + ApiConstant( + c_name=name, + python_name=name[len(enum_prefix) :], + value=value, + location=enum.location, + ) + ) + enum_tuple = tuple(enums) + type_view = _build_type_view_resolver( + objects, structs, enum_tuple, typedefs + ) + + def parameter_type_view(type_): + resolved = type_view(type_) + if type_.kind == "array" and type_.element is not None: + element = type_view(type_.element) + if element.category == "struct": + # Native runtimes consume one contiguous Struct allocation, + # constructed as ``point_t(count)`` and indexed in Python. + # A list of independently allocated wrappers is not a valid C + # array and must not be advertised as Sequence[point_t]. + return ApiTypeView( + element.python_type, + "struct_array", + "struct_pointer", + nullable=resolved.nullable, + lifetime=resolved.lifetime, + ) + return resolved + + functions = tuple( + replace( + function, + parameter_views=tuple( + parameter_type_view(parameter.type) + for parameter in function.parameters + ), + return_view=type_view(function.return_type), + ) + for function in functions + ) + structs = tuple( + replace( + struct, + field_views=tuple(type_view(field_.type) for field_ in struct.fields), + ) + for struct in structs + ) + typedefs = tuple( + replace( + typedef, + type_view=type_view(typedef.type, alias=typedef.c_name or typedef.name), + ) + for typedef in typedefs + ) + variables = tuple( + replace(variable, type_view=type_view(variable.type)) + for variable in variables + ) + return ApiModel( + module_prefix=module_prefix, + functions=functions, + objects=objects, + structs=structs, + enums=enum_tuple, + typedefs=typedefs, + variables=variables, + constants=tuple(constants), + ) + + +def write_api_model(model: ApiModel, path: Any) -> None: + """Write deterministic JSON for review, hashing, and downstream checks.""" + with open(path, "w", encoding="utf-8") as output: + output.write(model.to_json()) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/api_policy.json b/maix_lvgl/tools/omnipython_lvgl/binding/api_policy.json new file mode 100644 index 00000000..ddff5cf4 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/api_policy.json @@ -0,0 +1,174 @@ +{ + "schema_version": 1, + "private_functions": [ + { + "name": "mp_lv_deinit_gc", + "reason": "Binding lifecycle helper; not part of the user-facing LVGL module API.", + "test": "tests/test_api_policy.py::test_private_runtime_helpers_are_not_public" + }, + { + "name": "mp_lv_get_roots", + "reason": "Binding garbage-collector root helper; not part of the user-facing LVGL module API.", + "test": "tests/test_api_policy.py::test_private_runtime_helpers_are_not_public" + }, + { + "name": "mp_lv_init_gc", + "reason": "Binding lifecycle helper; not part of the user-facing LVGL module API.", + "test": "tests/test_api_policy.py::test_private_runtime_helpers_are_not_public" + }, + { + "name": "lv_global_default", + "reason": "Returns LVGL's private process-global state, whose implementation fields are deliberately not part of the Python API.", + "test": "tests/test_api_policy.py::test_private_global_accessor_is_not_public" + }, + { + "name": "lv_tjpgd_deinit", + "reason": "LV_USE_TJPGD is 0 on every target: the JPEG decoder is jpegio's, registered through lv_image_decoder_create by displayif (MicroPython), lvgl-circuitpython (CircuitPython) and lvgl-python (CPython); one TJpgDec per build (displayif#23, lvgl-bindings#14, lvgl-python#23).", + "test": "tests/test_api_policy.py::test_tjpgd_is_private_on_every_target" + }, + { + "name": "lv_tjpgd_init", + "reason": "LV_USE_TJPGD is 0 on every target: the JPEG decoder is jpegio's, registered through lv_image_decoder_create by displayif (MicroPython), lvgl-circuitpython (CircuitPython) and lvgl-python (CPython); one TJpgDec per build (displayif#23, lvgl-bindings#14, lvgl-python#23).", + "test": "tests/test_api_policy.py::test_tjpgd_is_private_on_every_target" + } + ], + "unsupported_functions": [ + { + "name": "lv_animimg_get_src", + "reason": "Returns a pointer-to-pointer image source array without a length, so the binding cannot construct a bounded Python sequence safely.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_arclabel_set_text_fmt", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_buttonmatrix_get_map", + "reason": "Returns a pointer-to-pointer string map without a bounded Python ownership contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_keyboard_get_map_array", + "reason": "Returns a pointer-to-pointer string map without a bounded Python ownership contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_label_set_text_fmt", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_label_set_text_vfmt", + "reason": "C va_list values have no portable Python representation and cannot cross the binding boundary.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_msgbox_add_text_fmt", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_spangroup_set_span_text_fmt", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_table_set_cell_value_fmt", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_subject_snprintf", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_span_set_text_fmt", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_snprintf", + "reason": "A Python binding cannot safely forward a C ellipsis argument list without a declared conversion contract.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_vsnprintf", + "reason": "C va_list values have no portable Python representation and cannot cross the binding boundary.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + }, + { + "name": "lv_text_set_text_vfmt", + "reason": "C va_list values have no portable Python representation and cannot cross the binding boundary.", + "test": "tests/test_api_policy.py::test_unsupported_functions_require_explicit_waivers" + } + ], + "private_structs": [ + { + "name": "lv_global_t", + "reason": "Process-global LVGL state is an implementation detail, not a public struct wrapper.", + "test": "tests/test_api_policy.py::test_private_global_struct_is_not_public" + }, + { + "name": "lv_obj_spec_attr_t", + "reason": "Private object storage reached only through LVGL's internal object implementation.", + "test": "tests/test_api_policy.py::test_private_object_storage_structs_are_not_public" + }, + { + "name": "lv_obj_style_t", + "reason": "Private object style storage reached only through LVGL's internal object implementation.", + "test": "tests/test_api_policy.py::test_private_object_storage_structs_are_not_public" + } + ], + "private_enums": [ + { + "name": "_lv_str_symbol_id_t", + "reason": "Internal identifier enum used to construct the public SYMBOL string namespace.", + "test": "tests/test_api_policy.py::test_symbol_identifier_enum_is_private" + } + ], + "private_variables": [ + { + "name": "lv_text_encoded_conv_wc", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + }, + { + "name": "lv_text_encoded_get_byte_id", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + }, + { + "name": "lv_text_encoded_get_char_id", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + }, + { + "name": "lv_text_encoded_next", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + }, + { + "name": "lv_text_encoded_prev", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + }, + { + "name": "lv_text_encoded_size", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + }, + { + "name": "lv_text_get_encoded_length", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + }, + { + "name": "lv_text_unicode_to_encoded", + "reason": "Internal text codec callback hook; the binding does not export callback globals.", + "test": "tests/test_api_policy.py::test_internal_callback_hooks_are_not_public" + } + ], + "target_exceptions": [] +} diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/api_policy.py b/maix_lvgl/tools/omnipython_lvgl/binding/api_policy.py new file mode 100644 index 00000000..1460f3da --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/api_policy.py @@ -0,0 +1,265 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Auditable visibility and target-availability policy for the API model.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence, Tuple + +from .api_model import TARGETS + + +@dataclass(frozen=True) +class PolicyRecord: + name: str + reason: str + test: str + + +@dataclass(frozen=True) +class TargetException: + name: str + target: str + reason: str + test: str + + +@dataclass(frozen=True) +class PolicyDecision: + visibility: str + available_on: Tuple[str, ...] = TARGETS + reason: Optional[str] = None + + +class ApiPolicy: + """Policy applied after parsing and before target lowering. + + The policy is intentionally independent of any emitter. A symbol may be + present in the declaration IR while being private to the binding or + unavailable on one target; those facts remain visible in the model. + """ + + def __init__( + self, + *, + module_prefix: str = "lv", + private_functions: Sequence[PolicyRecord] = (), + unsupported_functions: Sequence[PolicyRecord] = (), + private_structs: Sequence[PolicyRecord] = (), + private_enums: Sequence[PolicyRecord] = (), + private_variables: Sequence[PolicyRecord] = (), + target_exceptions: Sequence[TargetException] = (), + ) -> None: + self.module_prefix = module_prefix + private_functions = tuple(private_functions) + unsupported_functions = tuple(unsupported_functions) + private_structs = tuple(private_structs) + private_enums = tuple(private_enums) + private_variables = tuple(private_variables) + target_exceptions = tuple(target_exceptions) + self.private_functions = {record.name: record for record in private_functions} + self.unsupported_functions = { + record.name: record for record in unsupported_functions + } + self.private_structs = {record.name: record for record in private_structs} + self.private_enums = {record.name: record for record in private_enums} + self.private_variables = {record.name: record for record in private_variables} + self.target_exceptions = { + (record.name, record.target): record + for record in target_exceptions + } + if len(self.private_functions) != len(private_functions): + raise ValueError("duplicate private function in API policy") + if len(self.unsupported_functions) != len(unsupported_functions): + raise ValueError("duplicate unsupported function in API policy") + overlap = set(self.private_functions) & set(self.unsupported_functions) + if overlap: + raise ValueError( + "functions cannot be both private and unsupported: %s" + % ", ".join(sorted(overlap)) + ) + if len(self.private_structs) != len(private_structs): + raise ValueError("duplicate private struct in API policy") + if len(self.private_enums) != len(private_enums): + raise ValueError("duplicate private enum in API policy") + if len(self.private_variables) != len(private_variables): + raise ValueError("duplicate private variable in API policy") + if len(self.target_exceptions) != len(target_exceptions): + raise ValueError("duplicate target exception in API policy") + self._validate() + + @classmethod + def from_file(cls, path: Path, *, module_prefix: str = "lv") -> "ApiPolicy": + with Path(path).open(encoding="utf-8") as handle: + data = json.load(handle) + if data.get("schema_version") != 1: + raise ValueError("unsupported API policy schema") + + def records(key: str) -> Tuple[PolicyRecord, ...]: + return tuple( + PolicyRecord( + name=item["name"], + reason=item["reason"], + test=item["test"], + ) + for item in data.get(key, ()) + ) + + exceptions = tuple( + TargetException( + name=item["name"], + target=item["target"], + reason=item["reason"], + test=item["test"], + ) + for item in data.get("target_exceptions", ()) + ) + return cls( + module_prefix=module_prefix, + private_functions=records("private_functions"), + unsupported_functions=records("unsupported_functions"), + private_structs=records("private_structs"), + private_enums=records("private_enums"), + private_variables=records("private_variables"), + target_exceptions=exceptions, + ) + + @classmethod + def default(cls, *, module_prefix: str = "lv") -> "ApiPolicy": + return cls.from_file( + Path(__file__).with_name("api_policy.json"), + module_prefix=module_prefix, + ) + + def _validate(self) -> None: + if not self.module_prefix: + raise ValueError("API policy requires a module prefix") + for target in (record.target for record in self.target_exceptions.values()): + if target not in TARGETS: + raise ValueError("unknown API policy target: %s" % target) + for record in tuple(self.private_functions.values()) + tuple( + self.unsupported_functions.values() + ) + tuple( + self.private_structs.values() + ) + tuple( + self.private_enums.values() + ) + tuple(self.private_variables.values()): + if not record.reason or not record.test: + raise ValueError("API policy records require reason and test: %s" % record.name) + for record in self.target_exceptions.values(): + if not record.reason or not record.test: + raise ValueError( + "API target exceptions require reason and test: %s" % record.name + ) + + def function(self, name: str) -> PolicyDecision: + private = self.private_functions.get(name) + if private is not None: + return PolicyDecision("private", reason=private.reason) + unsupported = self.unsupported_functions.get(name) + if unsupported is not None: + return PolicyDecision("private", reason=unsupported.reason) + if not name.startswith(self.module_prefix + "_"): + return PolicyDecision("private", reason="outside module prefix") + return PolicyDecision( + "public", + available_on=self._available_on(name), + ) + + def struct(self, names: Sequence[Optional[str]]) -> PolicyDecision: + candidates = {name for name in names if name} + private = next( + (self.private_structs[name] for name in candidates if name in self.private_structs), + None, + ) + if private is not None: + return PolicyDecision("private", reason=private.reason) + if any( + name.startswith(self.module_prefix + "_") + or name.startswith("_" + self.module_prefix + "_") + for name in candidates + ): + return PolicyDecision("public") + return PolicyDecision("private", reason="outside module prefix") + + def enum(self, names: Sequence[Optional[str]]) -> PolicyDecision: + candidates = {name for name in names if name} + private = next( + (self.private_enums[name] for name in candidates if name in self.private_enums), + None, + ) + if private is not None: + return PolicyDecision("private", reason=private.reason) + if any( + name.startswith(self.module_prefix + "_") + or name.startswith("_" + self.module_prefix + "_") + for name in candidates + ): + return PolicyDecision("public") + return PolicyDecision("private", reason="outside module prefix") + + def typedef(self, name: str) -> PolicyDecision: + if name.startswith(self.module_prefix + "_"): + return PolicyDecision("public") + return PolicyDecision("private", reason="outside module prefix") + + def variable(self, name: str) -> PolicyDecision: + private = self.private_variables.get(name) + if private is not None: + return PolicyDecision("private", reason=private.reason) + if name.startswith(self.module_prefix + "_"): + return PolicyDecision("public") + return PolicyDecision("private", reason="outside module prefix") + + def _available_on(self, name: str) -> Tuple[str, ...]: + unavailable = { + record.target + for (record_name, _), record in self.target_exceptions.items() + if record_name == name + } + return tuple(target for target in TARGETS if target not in unavailable) + + +def validate_policy_against_declarations(policy: ApiPolicy, declarations: Any) -> None: + """Fail when a policy names a symbol absent from the parsed translation unit.""" + + function_names = {function.name for function in declarations.functions} + struct_names = { + name + for struct in declarations.structs + for name in (struct.name,) + tuple(struct.typedef_names) + if name + } + missing = [] + for name in policy.private_functions: + if name not in function_names: + missing.append("function " + name) + for name in policy.unsupported_functions: + if name not in function_names: + missing.append("function " + name) + for name in policy.private_structs: + if name not in struct_names: + missing.append("struct " + name) + enum_names = { + name + for enum in declarations.enums + for name in (enum.name,) + tuple(enum.typedef_names) + if name + } + for name in policy.private_enums: + if name not in enum_names: + missing.append("enum " + name) + variable_names = {variable.name for variable in declarations.variables} + for name in policy.private_variables: + if name not in variable_names: + missing.append("variable " + name) + for name, _target in policy.target_exceptions: + if name not in function_names: + missing.append("function " + name) + if missing: + raise ValueError("API policy names missing declarations: %s" % ", ".join(sorted(missing))) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/api_report.py b/maix_lvgl/tools/omnipython_lvgl/binding/api_report.py new file mode 100644 index 00000000..391d5aec --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/api_report.py @@ -0,0 +1,595 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Report canonical API inventory, target parity, and baseline compatibility. + +The report is deliberately observational. It validates the canonical model, +then makes target availability and remaining legacy-baseline differences +explicit without silently turning either into a backend-specific contract. +""" + +from __future__ import annotations + +import argparse +import fnmatch +import gzip +import hashlib +import json +import sys +from pathlib import Path +from typing import Any, Mapping + +from .api_model import TARGETS +from .verify_api import validate_api_data + +REPORT_SCHEMA_VERSION = 2 + +TARGET_ARTIFACTS = { + "micropython": "lvgl_micropython.c", + "circuitpython": "lvgl_circuitpython.c", + "cpython": "lvgl_python.c", +} + + +def load_json(path: Path) -> Any: + """Load a JSON artifact, including the compact ``.json.gz`` baseline.""" + + if path.suffix == ".gz": + with gzip.open(path, "rt", encoding="utf-8") as stream: + return json.load(stream) + return json.loads(path.read_text(encoding="utf-8")) + + +def write_json(path: Path, data: Any) -> None: + """Write deterministic JSON, optionally with reproducible gzip encoding.""" + + rendered = json.dumps(data, separators=(",", ":"), sort_keys=True) + "\n" + if path.suffix == ".gz": + with path.open("wb") as raw: + with gzip.GzipFile(filename="", mode="wb", fileobj=raw, mtime=0) as stream: + stream.write(rendered.encode("utf-8")) + return + path.write_text(rendered, encoding="utf-8") + + +def target_artifact_hashes(generated_dir: Path) -> dict[str, dict[str, str]]: + """Hash each generated target C artifact for an auditable report.""" + + result = {} + for target in TARGETS: + path = generated_dir / TARGET_ARTIFACTS[target] + result[target] = { + "file": path.name, + "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), + } + return result + + +def _available(record: Mapping[str, Any], target: str) -> bool: + return ( + record.get("visibility") == "public" + and target in record.get("available_on", ()) + ) + + +def _entry(section: str, name: str) -> str: + return "%s.%s" % (section, name) + + +def _effective_methods(objects: list[Mapping[str, Any]]) -> dict[str, set[str]]: + """Return direct plus inherited object methods, detecting bad cycles.""" + + by_name = {item["python_name"]: item for item in objects} + cache: dict[str, set[str]] = {} + + def visit(name: str, active: tuple[str, ...] = ()) -> set[str]: + if name in cache: + return set(cache[name]) + if name in active: + cycle = " -> ".join(active + (name,)) + raise ValueError("object inheritance cycle: %s" % cycle) + item = by_name.get(name) + if item is None: + raise ValueError("object has unknown parent: %s" % name) + methods = set(item.get("methods", ())) + parent = item.get("parent") + if parent is not None: + methods.update(visit(parent, active + (name,))) + cache[name] = methods + return set(methods) + + for name in by_name: + visit(name) + return cache + + +def public_export_sets(data: Mapping[str, Any]) -> dict[str, set[str]]: + """Build qualified public exports for each target from ``api.json``. + + Object methods are expanded through the canonical inheritance graph. A + method is reported in the namespace of every object that inherits it, + matching the effective Python-facing API rather than only its declaring + C type. + """ + + functions = data.get("functions", ()) + objects = data.get("objects", ()) + function_by_object_method = { + (item.get("receiver"), item.get("python_name")): item + for item in functions + if item.get("role") == "object_method" + } + function_by_struct_method = { + (item.get("receiver"), item.get("python_name")): item + for item in functions + if item.get("role") == "struct_method" + } + effective_methods = _effective_methods(list(objects)) + object_by_name = {item["python_name"]: item for item in objects} + type_names = { + item.get("python_name") + for section in ("structs", "enums") + for item in data.get(section, ()) + if item.get("visibility") == "public" + } + + result = {target: set() for target in TARGETS} + for target in TARGETS: + for function in functions: + if not _available(function, target): + continue + role = function.get("role") + name = function.get("python_name") + if role == "module": + result[target].add(_entry("module.function", name)) + elif role == "constructor": + receiver = function.get("receiver") + result[target].add(_entry("object", "%s.create" % receiver)) + elif role == "struct_method": + receiver = function.get("receiver") + result[target].add( + _entry("struct", "%s.%s" % (receiver, name)) + ) + + for object_ in objects: + if not _available(object_, target): + continue + object_name = object_["python_name"] + result[target].add(_entry("object", object_name)) + for method_name in effective_methods[object_name]: + declaring = function_by_object_method.get( + (object_name, method_name) + ) + if declaring is None: + parent = object_.get("parent") + while parent is not None and declaring is None: + declaring = function_by_object_method.get( + (parent, method_name) + ) + parent = object_by_name.get(parent, {}).get("parent") + if declaring is not None and _available(declaring, target): + result[target].add( + _entry("object", "%s.%s" % (object_name, method_name)) + ) + + for struct in data.get("structs", ()): + if not _available(struct, target): + continue + result[target].add(_entry("struct", struct["python_name"])) + for (receiver, name), function in function_by_struct_method.items(): + if _available(function, target): + result[target].add( + _entry("struct", "%s.%s" % (receiver, name)) + ) + + for enum in data.get("enums", ()): + if not _available(enum, target): + continue + member_names = [member["name"] for member in enum.get("members", ())] + module_name = enum.get("module_name") + if module_name is not None: + result[target].add(_entry("enum", module_name)) + result[target].update( + _entry("enum", "%s.%s" % (module_name, member_name)) + for member_name in member_names + ) + for owner_name, nested_name in ( + (item.get("object"), item.get("name")) + for item in enum.get("owners", ()) + ): + if owner_name not in object_by_name: + continue + for object_record in objects: + if not _available(object_record, target): + continue + current = object_record + inherits_from_owner = False + while current is not None: + if current["python_name"] == owner_name: + inherits_from_owner = True + break + parent = current.get("parent") + current = object_by_name.get(parent) if parent else None + if inherits_from_owner: + result[target].add( + _entry( + "object", + "%s.%s" % ( + object_record["python_name"], + nested_name, + ), + ) + ) + for typedef in data.get("typedefs", ()): + if not _available(typedef, target): + continue + if ( + typedef.get("name") in type_names + and typedef.get("type", {}).get("kind") + in {"struct", "union", "enum"} + ): + continue + result[target].add(_entry("typedef", typedef["name"])) + for variable in data.get("variables", ()): + if _available(variable, target): + result[target].add( + _entry("variable", variable.get("python_name") or variable["c_name"]) + ) + for constant in data.get("constants", ()): + if _available(constant, target): + result[target].add(_entry("constant", constant["python_name"])) + return result + + +def _record_inventory(data: Mapping[str, Any]) -> dict[str, dict[str, int]]: + sections = ( + "functions", + "objects", + "structs", + "enums", + "typedefs", + "variables", + "constants", + ) + inventory = {} + for section in sections: + counts: dict[str, int] = {} + for item in data.get(section, ()): + visibility = item.get("visibility", "unknown") + counts[visibility] = counts.get(visibility, 0) + 1 + inventory[section] = dict(sorted(counts.items())) + return inventory + + +def _parity(exports: Mapping[str, set[str]]) -> dict[str, Any]: + sets = [set(exports[target]) for target in TARGETS] + union = set().union(*sets) + intersection = set(sets[0]).intersection(*sets[1:]) + return { + "union_count": len(union), + "intersection_count": len(intersection), + "common_coverage": len(intersection) / float(len(union) or 1), + "all_targets_equal": all(item == sets[0] for item in sets[1:]), + "coverage_of_union": { + target: len(exports[target]) / float(len(union) or 1) + for target in TARGETS + }, + "missing_for_target": { + target: sorted(union - exports[target]) for target in TARGETS + }, + "target_unique": { + target: sorted(exports[target] - intersection) for target in TARGETS + }, + "availability_exceptions": sorted( + union - intersection + ), + } + + +def _expand_manifest(manifest: Mapping[str, Any]) -> set[str]: + signatures = manifest.get("signatures", ()) + + def signature(index: int) -> Mapping[str, Any]: + return signatures[index] + + entries: set[str] = set() + for name in manifest.get("functions", {}): + entries.add(_entry("module.function", name)) + for name, value in manifest.get("objects", {}).items(): + entries.add(_entry("object", name)) + entries.update( + _entry("object", "%s.%s" % (name, member)) + for member in value.get("members", {}) + ) + for name, value in manifest.get("enums", {}).items(): + enum = signature(value) + entries.add(_entry("enum", name)) + entries.update( + _entry("enum", "%s.%s" % (name, member)) + for member in enum.get("members", ()) + ) + entries.update(_entry("struct", name) for name in manifest.get("structs", ())) + entries.update(_entry("blob", name) for name in manifest.get("blobs", ())) + entries.update( + _entry("constant", name) for name in manifest.get("int_constants", ()) + ) + for name, members in manifest.get("struct_functions", {}).items(): + entries.update( + _entry("struct_function", "%s.%s" % (name, member)) + for member in members + ) + return entries + + +def _model_compatibility_entries(data: Mapping[str, Any]) -> set[str]: + """Project the model into the sections used by the historical baseline.""" + + exports = public_export_sets(data)[TARGETS[0]] + result = set() + for value in exports: + if value.startswith("object.") and value.rsplit(".", 1)[-1] == "create": + continue + if value.startswith("variable."): + result.add(_entry("blob", value.split(".", 1)[1])) + elif value.startswith("constant."): + result.add(_entry("constant", value.split(".", 1)[1])) + elif value.startswith("struct."): + result.add(value) + elif value.startswith("enum."): + result.add(value) + elif value.startswith("module.function."): + result.add(value) + elif value.startswith("object."): + result.add(value) + return result + + +def _classify_differences( + differences: Mapping[str, list[str]], classification: Mapping[str, Any] | None +) -> Mapping[str, Any]: + """Classify historical-baseline differences with an auditable rule file.""" + + if classification is None: + return {"classified": [], "unexplained": {key: list(value) for key, value in differences.items()}} + if classification.get("schema_version") != 1: + raise ValueError("unsupported baseline classification schema") + rules = classification.get("rules", ()) + buckets: dict[str, dict[str, Any]] = {} + used = set() + unexplained = {side: [] for side in differences} + for side, entries in differences.items(): + for entry in entries: + matches = [ + rule for rule in rules + if rule.get("side") == side + and any(fnmatch.fnmatchcase(entry, pattern) for pattern in rule.get("patterns", ())) + ] + if len(matches) > 1: + raise ValueError("overlapping baseline classification rules for %s" % entry) + if not matches: + unexplained[side].append(entry) + continue + rule = matches[0] + rule_id = rule.get("id") + if not rule_id or not rule.get("classification") or not rule.get("reason"): + raise ValueError("baseline classification rules require id, classification, and reason") + used.add(rule_id) + bucket = buckets.setdefault( + rule_id, + {key: rule[key] for key in ("id", "classification", "reason")}, + ) + bucket.setdefault("entries", []).append(entry) + stale = sorted(rule.get("id") for rule in rules if rule.get("id") not in used) + if stale: + raise ValueError("stale baseline classification rules: %s" % ", ".join(stale)) + return {"classified": [buckets[key] for key in sorted(buckets)], "unexplained": unexplained} + + +def _baseline_report( + data: Mapping[str, Any], baseline: Mapping[str, Any] | None, + classification: Mapping[str, Any] | None = None, +) -> Mapping[str, Any] | None: + if baseline is None: + return None + base = baseline.get("baseline") + if not isinstance(base, Mapping): + raise ValueError("baseline must contain a compact baseline manifest") + expected = _expand_manifest(base) + actual = _model_compatibility_entries(data) + common = expected & actual + differences = {"missing": sorted(expected - actual), "extra": sorted(actual - expected)} + classifications = _classify_differences(differences, classification) + explained = not any(classifications["unexplained"].values()) + return { + "baseline_schema": baseline.get("schema"), + "baseline_entries": len(expected), + "candidate_entries": len(actual), + "name_location_matches": len(common), + "coverage": len(common) / float(len(expected) or 1), + **differences, + "classification": classifications, + "historical_target_comparisons": { + target: { + "coverage": baseline.get("targets", {}) + .get(target, {}) + .get("comparison", {}) + .get("coverage") + } + for target in TARGETS + }, + "interpretation": ( + "Every historical difference is classified by the audited policy." + if explained + else "The candidate projection is diagnostic while canonical lowering " + "is still under construction; it is not a release gate." + ), + } + + +def build_report( + data: Mapping[str, Any], baseline: Mapping[str, Any] | None = None, + classification: Mapping[str, Any] | None = None, + target_artifacts: Mapping[str, Mapping[str, str]] | None = None, +) -> Mapping[str, Any]: + """Build a deterministic report from canonical model JSON data.""" + + errors = validate_api_data(data) + if errors: + raise ValueError("invalid canonical API model: %s" % "; ".join(errors)) + exports = public_export_sets(data) + report = { + "schema_version": REPORT_SCHEMA_VERSION, + "api_hash": data["api_hash"], + "inventory": _record_inventory(data), + "target_exports": { + target: {"count": len(exports[target])} for target in TARGETS + }, + "target_parity": _parity(exports), + "baseline_compatibility": _baseline_report(data, baseline, classification), + } + if target_artifacts is not None: + report["target_artifacts"] = { + target: dict(target_artifacts[target]) for target in TARGETS + } + return report + + +def _markdown(report: Mapping[str, Any]) -> str: + lines = [ + "# LVGL canonical API report", + "", + "- API hash: `%s`" % report["api_hash"], + "- Report schema: `%s`" % report["schema_version"], + "", + "## Target exports", + "", + "| Target | Qualified exports | Coverage of union |", + "| --- | ---: | ---: |", + ] + parity = report["target_parity"] + for target in TARGETS: + lines.append( + "| %s | %d | %.2f%% |" + % ( + target, + report["target_exports"][target]["count"], + parity["coverage_of_union"][target] * 100.0, + ) + ) + lines.extend( + [ + "", + "- Shared exports: %d" % parity["intersection_count"], + "- Union exports: %d" % parity["union_count"], + "- Common-target API coverage: %.2f%%" + % (parity["common_coverage"] * 100.0), + "- Availability exceptions: %d" % len(parity["availability_exceptions"]), + "", + "## Record inventory", + "", + "| Section | Visibility counts |", + "| --- | --- |", + ] + ) + for section, counts in report["inventory"].items(): + rendered = ", ".join( + "%s=%d" % (visibility, count) + for visibility, count in counts.items() + ) + lines.append("| `%s` | %s |" % (section, rendered or "none")) + artifacts = report.get("target_artifacts") + if artifacts is not None: + lines.extend( + [ + "", + "## Generated target artifacts", + "", + "| Target | File | SHA-256 |", + "| --- | --- | --- |", + ] + ) + for target in TARGETS: + artifact = artifacts[target] + lines.append( + "| %s | `%s` | `%s` |" + % (target, artifact["file"], artifact["sha256"]) + ) + baseline = report.get("baseline_compatibility") + if baseline is not None: + lines.extend( + [ + "", + "## Historical baseline projection", + "", + "- Candidate coverage: %.2f%% (%d/%d)" + % ( + baseline["coverage"] * 100.0, + baseline["name_location_matches"], + baseline["baseline_entries"], + ), + "- Missing: %d" % len(baseline["missing"]), + "- Extra: %d" % len(baseline["extra"]), + "- Classified differences: %d" + % len(baseline["classification"]["classified"]), + "- Unexplained differences: %d" + % sum( + len(entries) + for entries in baseline["classification"]["unexplained"].values() + ), + "", + baseline["interpretation"], + ] + ) + return "\n".join(lines) + "\n" + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("api", type=Path, help="generated/api.json") + parser.add_argument( + "--baseline", + type=Path, + help="optional normalized upstream baseline JSON", + ) + parser.add_argument( + "--classification", type=Path, + help="optional audited historical-baseline difference classifications", + ) + parser.add_argument( + "--format", choices=("json", "markdown"), default="json" + ) + parser.add_argument("--output", type=Path, help="write report to this path") + args = parser.parse_args(argv) + + data = load_json(args.api) + baseline = ( + load_json(args.baseline) + if args.baseline is not None + else None + ) + classification = ( + load_json(args.classification) + if args.classification is not None + else None + ) + report = build_report( + data, + baseline, + classification, + target_artifact_hashes(args.api.parent), + ) + rendered = ( + json.dumps(report, indent=2, sort_keys=True) + "\n" + if args.format == "json" + else _markdown(report) + ) + if args.output is None: + sys.stdout.write(rendered) + else: + args.output.write_text(rendered, encoding="utf-8") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/artifacts.py b/maix_lvgl/tools/omnipython_lvgl/binding/artifacts.py new file mode 100644 index 00000000..ea595a86 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/artifacts.py @@ -0,0 +1,78 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Hash and compare generated binding artifacts.""" + +from __future__ import annotations + +import hashlib +from pathlib import Path +from typing import Dict, Iterable, Mapping + + +DEFAULT_ARTIFACTS = ( + "api.json", + "lvgl.pp", + "lvgl.pyi", + "lvgl_circuitpython.c", + "lvgl_circuitpython.h", + "lvgl_micropython.c", + "lvgl_python.c", +) + + +def sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for chunk in iter(lambda: handle.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def manifest_for_directory( + directory: Path, + filenames: Iterable[str] = DEFAULT_ARTIFACTS, +) -> Dict[str, object]: + """Return deterministic sizes and SHA-256 hashes for generated files.""" + + directory = Path(directory) + files: Dict[str, Dict[str, object]] = {} + for filename in sorted(set(filenames)): + path = directory / filename + if not path.is_file(): + continue + files[filename] = { + "bytes": path.stat().st_size, + "sha256": sha256_file(path), + } + return {"schema": 1, "files": files} + + +def compare_manifests( + expected: Mapping[str, object], actual: Mapping[str, object] +) -> Dict[str, object]: + """Return missing, unexpected, and changed artifact names.""" + + expected_files = expected.get("files", {}) + actual_files = actual.get("files", {}) + if not isinstance(expected_files, Mapping) or not isinstance(actual_files, Mapping): + raise ValueError("artifact manifests must contain mapping-valued files") + + expected_names = set(expected_files) + actual_names = set(actual_files) + changed = sorted( + name + for name in expected_names & actual_names + if expected_files[name] != actual_files[name] + ) + return { + "missing": sorted(expected_names - actual_names), + "unexpected": sorted(actual_names - expected_names), + "changed": changed, + "equal": not ( + expected_names - actual_names + or actual_names - expected_names + or changed + ), + } diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/context.py b/maix_lvgl/tools/omnipython_lvgl/binding/context.py new file mode 100644 index 00000000..f7e84adf --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/context.py @@ -0,0 +1,169 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Per-generation BindingContext; synced into runtime for analyze/emit.""" +from __future__ import print_function + +import collections +import re +from dataclasses import dataclass, fields +from typing import Any, Mapping + + +@dataclass(frozen=True) +class EmitterResult: + """Explicit per-run state returned by a native C emitter.""" + + headers: Any + enums: Any + generated_structs: Any + generated_struct_functions: Any + struct_aliases: Any + callbacks_used_on_structs: Any + generated_callbacks: Any + generated_funcs: Any + enum_referenced: Any + generated_obj_names: Any + generated_globals: Any + module_funcs: Any + functions_not_generated: Any + + @classmethod + def capture(cls, namespace: Mapping[str, Any]) -> "EmitterResult": + """Capture the declared emitter outputs from one function scope.""" + return cls(**{field.name: namespace[field.name] for field in fields(cls)}) + + def apply(self, ctx: "BindingContext") -> None: + """Publish one completed result without touching module globals.""" + for field in fields(self): + setattr(ctx, field.name, getattr(self, field.name)) + + +class BindingContext: + """Holds all inputs and intermediate state for one generation run.""" + + EXPORT_NAMES = ( + "module_name", + "module_prefix", + "base_obj_name", + "base_obj_type", + "lv_ext_pattern", + "lv_obj_pattern", + "lv_func_pattern", + "create_obj_pattern", + "lv_method_pattern", + "lv_base_obj_pattern", + "lv_str_enum_pattern", + "lv_callback_type_pattern", + "lv_global_callback_pattern", + "lv_func_returns_array", + "lv_enum_name_pattern", + "obj_metadata", + "func_metadata", + "callback_metadata", + "func_prototypes", + "parser", + "gen", + "parsed_ast", + "ast", + "declaration_ir", + "declaration_index", + "api_model", + "lvgl_json", + "forward_struct_decls", + "typedefs", + "synonym", + "struct_typedefs", + "structs_without_typedef", + "structs", + "explicit_structs", + "opaque_structs", + "func_defs", + "func_decls", + "all_funcs", + "funcs", + "obj_ctors", + "obj_names", + "parent_obj_names", + "enum_defs", + "func_typedefs", + "blobs", + "int_constants", + "mp_to_lv", + "lv_to_mp", + "lv_mp_type", + "lv_to_mp_byref", + "lv_to_mp_funcptr", + "headers", + "enums", + "generated_structs", + "generated_struct_functions", + "struct_aliases", + "callbacks_used_on_structs", + "generated_callbacks", + "generated_funcs", + "enum_referenced", + "generated_obj_names", + "generated_globals", + "module_funcs", + "functions_not_generated", + "args", + "pp_cmd", + "cmd_line", + "s", + ) + + def __init__(self, args, source, pp_cmd, cmd_line, emit_print): + self.args = args + self.s = source + self.pp_cmd = pp_cmd + self.cmd_line = cmd_line + self.emit_print = emit_print + self.module_name = args.module_name + self.module_prefix = ( + args.module_prefix if args.module_prefix else args.module_name + ) + self.base_obj_name = "obj" + self.base_obj_type = None + self.parsed_ast = None + self.declaration_ir = None + self.declaration_index = None + self.headers = list(args.input) + + def init_patterns(self): + p = self.module_prefix + b = self.base_obj_name + self.base_obj_type = "%s_%s_t" % (p, b) + self.lv_ext_pattern = re.compile("^{prefix}_([^_]+)_ext_t".format(prefix=p)) + self.lv_obj_pattern = re.compile( + "^{prefix}_([^_]+)".format(prefix=p), re.IGNORECASE + ) + self.lv_func_pattern = re.compile( + "^{prefix}_(.+)".format(prefix=p), re.IGNORECASE + ) + self.create_obj_pattern = re.compile( + "^{prefix}_(.+)_create$".format(prefix=p) + ) + self.lv_method_pattern = re.compile( + "^{prefix}_[^_]+_(.+)".format(prefix=p), re.IGNORECASE + ) + self.lv_base_obj_pattern = re.compile( + "^(struct _){{0,1}}{prefix}_{base_name}_t( [*]){{0,1}}".format( + prefix=p, base_name=b + ) + ) + self.lv_str_enum_pattern = re.compile( + "^_?{prefix}_STR_(.+)".format(prefix=p.upper()) + ) + self.lv_callback_type_pattern = re.compile( + "({prefix}_){{0,1}}(.+)_cb(_t){{0,1}}".format(prefix=p) + ) + self.lv_global_callback_pattern = re.compile(".*g_cb_t") + self.lv_func_returns_array = re.compile(".*_array$") + self.lv_enum_name_pattern = re.compile( + "^(ENUM_){{0,1}}({prefix}_){{0,1}}(.*)".format(prefix=p.upper()) + ) + + def export_names(self): + return self.EXPORT_NAMES diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_backend.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_backend.py new file mode 100644 index 00000000..914149d7 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_backend.py @@ -0,0 +1,677 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Shared setup for target C-lowering runs. + +The individual emitters own VM-specific C output. This module owns only the +target-neutral Python-side state needed before a lowering run begins. +""" + +from __future__ import annotations + +import collections +import os +from dataclasses import dataclass + +from pycparser import c_ast + +from . import runtime + + +_EMIT_DEFAULTS = ( + "generated_struct_functions", + "struct_aliases", + "callbacks_used_on_structs", + "generated_callbacks", + "generated_funcs", + "enum_referenced", + "generated_obj_names", + "generated_globals", + "module_funcs", + "functions_not_generated", +) + + +@dataclass(frozen=True) +class FunctionReturnLowering: + """C and metadata fragments for one exported function return value.""" + + build_result: str + build_return_value: str + metadata_return_type: str + + +@dataclass(frozen=True) +class CallbackReturnLowering: + """C fragments for one callback result through the MP compatibility API.""" + + result_assignment: str + return_value: str + + +@dataclass(frozen=True) +class TargetLoweringProfile: + """The small, explicit set of VM constraints visible to shared lowering.""" + + target: str + supports_dynamic_function_pointer: bool + + +@dataclass(frozen=True) +class EnumNamespacePlan: + """Target-neutral contents and nesting for one exported enum namespace.""" + + name: str + members: tuple[str, ...] + nested_names: tuple[str, ...] + widget_scoped_nested_names: tuple[str, ...] + + +@dataclass(frozen=True) +class ModuleRegistrationPlan: + """Target-neutral declarations exported from the module at one phase. + + Backends use different C APIs to publish these objects, but must expose + the same declaration set and retain declaration order. This plan keeps + the selection policy independent from those VM-specific C APIs. + """ + + int_constants: tuple[str, ...] + generated_globals: tuple[str, ...] + enum_names: tuple[str, ...] + struct_names: tuple[str, ...] + struct_alias_names: tuple[str, ...] + object_names: tuple[str, ...] + module_functions: tuple[object, ...] + + +@dataclass +class TypeDiscovery: + """Shared recursive discovery of C-to-Python conversion requirements. + + Backends provide only native C emission hooks for arrays, structs, and + function pointers. Typedef traversal, aliases, pointer fallbacks, enum + conversion, and conversion-map updates are common policy. + """ + + get_name: object + get_type: object + structs: dict + typedefs: list + struct_aliases: dict + mp_to_lv: dict + lv_to_mp: dict + lv_mp_type: dict + lv_to_mp_byref: dict + lv_to_mp_funcptr: dict + generated_funcptr_helpers: dict + try_generate_struct: object + try_generate_array: object + emit_function_pointer: object + missing_conversion: type + report_error: object + + def typedef_name(self, node): + if isinstance(node, (c_ast.PtrDecl, c_ast.FuncDecl)): + return self.typedef_name(node.type) + if hasattr(node, "declname"): + return node.declname + if hasattr(node, "name"): + return node.name + return "unnamed_arg" + + def generate(self, type_ast): + if isinstance(type_ast, str): + raise SyntaxError("Internal error! try_generate_type argument is a string.") + if isinstance(type_ast, c_ast.TypeDecl): + return self.generate(type_ast.type) + + type_name = self.get_name(type_ast) + if isinstance(type_ast, c_ast.Enum): + self.mp_to_lv[type_name] = self.mp_to_lv["int"] + self.mp_to_lv["%s *" % type_name] = self.mp_to_lv["int *"] + self.lv_to_mp[type_name] = self.lv_to_mp["int"] + self.lv_to_mp["%s *" % type_name] = self.lv_to_mp["int *"] + self.lv_mp_type[type_name] = self.lv_mp_type["int"] + self.lv_mp_type["%s *" % type_name] = self.lv_mp_type["int *"] + return self.mp_to_lv[type_name] + if type_name in self.mp_to_lv: + return self.mp_to_lv[type_name] + if isinstance(type_ast, c_ast.ArrayDecl) and self.try_generate_array(type_ast): + return self.mp_to_lv[type_name] + + if isinstance(type_ast, (c_ast.PtrDecl, c_ast.ArrayDecl)): + pointee_name = self.get_name(type_ast.type.type) + ptr_type = self.get_type(type_ast, remove_quals=True) + if pointee_name in self.structs: + self.try_generate_struct(pointee_name, self.structs[pointee_name]) + if ( + isinstance(type_ast.type, c_ast.TypeDecl) + and isinstance(type_ast.type.type, c_ast.Struct) + and type_ast.type.type.name in self.structs + ): + self.try_generate_struct( + pointee_name, self.structs[type_ast.type.type.name] + ) + if isinstance(type_ast.type, c_ast.FuncDecl): + self._generate_function_pointer(type_ast, ptr_type, pointee_name) + self.mp_to_lv.setdefault(ptr_type, self.mp_to_lv["void *"]) + self.lv_to_mp.setdefault(ptr_type, self.lv_to_mp["void *"]) + self.lv_mp_type.setdefault(ptr_type, "void*") + return self.mp_to_lv[ptr_type] + + if type_name in self.structs: + if self.try_generate_struct(type_name, self.structs[type_name]): + return self.mp_to_lv[type_name] + for new_type_ast in [ + item for item in self.typedefs if self.typedef_name(item) == type_name + ]: + new_type = self.get_type(new_type_ast, remove_quals=True) + if ( + isinstance(new_type_ast, c_ast.TypeDecl) + and isinstance(new_type_ast.type, c_ast.Struct) + and not new_type_ast.type.decls + ): + explicit_name = new_type_ast.type.name + else: + explicit_name = new_type + if type_name == explicit_name: + continue + if explicit_name in self.structs: + if self.try_generate_struct(new_type, self.structs[explicit_name]): + if explicit_name == new_type: + self.struct_aliases[new_type] = type_name + if type_name != new_type and self.generate(new_type_ast): + self._copy_typedef_conversions(type_name, new_type) + return self.mp_to_lv[type_name] + return None + + def _generate_function_pointer(self, type_ast, ptr_type, pointee_name): + if ptr_type in self.lv_to_mp_funcptr: + existing = self.lv_to_mp_funcptr[ptr_type] + self.lv_to_mp.setdefault(ptr_type, "mp_lv_%s" % existing) + self.mp_to_lv.setdefault(ptr_type, self.mp_to_lv["void *"]) + self.lv_mp_type.setdefault(ptr_type, "function pointer") + return + if isinstance(type_ast.type.type.type, c_ast.TypeDecl): + pointee_name = type_ast.type.type.type.declname + helper_name = "funcptr_%s" % pointee_name + suffix = 1 + while helper_name in self.generated_funcptr_helpers: + helper_name = "funcptr_%s_%d" % (pointee_name, suffix) + suffix += 1 + self.generated_funcptr_helpers[helper_name] = True + func = c_ast.Decl( + name=helper_name, + quals=[], + align=[], + storage=[], + funcspec=[], + type=type_ast.type, + init=None, + bitsize=None, + ) + try: + generated = self.emit_function_pointer(helper_name, func) + if generated: + self.lv_to_mp_funcptr[ptr_type] = helper_name + self.lv_to_mp[ptr_type] = "mp_lv_%s" % helper_name + self.lv_mp_type[ptr_type] = "function pointer" + else: + self.lv_to_mp[ptr_type] = self.lv_to_mp["void *"] + self.lv_mp_type[ptr_type] = "void*" + except self.missing_conversion as exp: + self.report_error(func, exp) + + def _copy_typedef_conversions(self, type_name, new_type): + self.mp_to_lv[type_name] = self.mp_to_lv[new_type] + type_ptr = "%s *" % type_name + new_type_ptr = "%s *" % new_type + if new_type_ptr in self.mp_to_lv: + self.mp_to_lv[type_ptr] = self.mp_to_lv[new_type_ptr] + if new_type in self.lv_to_mp: + self.lv_to_mp[type_name] = self.lv_to_mp[new_type] + self.lv_mp_type[type_name] = self.lv_mp_type[new_type] + if new_type in self.lv_to_mp_funcptr: + self.lv_to_mp_funcptr[type_name] = self.lv_to_mp_funcptr[new_type] + if new_type in self.lv_to_mp_byref: + self.lv_to_mp_byref[type_name] = self.lv_to_mp_byref[new_type] + if new_type_ptr in self.lv_to_mp: + self.lv_to_mp[type_ptr] = self.lv_to_mp[new_type_ptr] + if new_type_ptr in self.lv_mp_type: + self.lv_mp_type[type_ptr] = self.lv_mp_type[new_type_ptr] + + +def object_generation_order(obj_names, parent_obj_names): + """Return objects once each, with every known parent before its child.""" + ordered = [] + emitted = set() + visiting = set() + + def add(name): + if name is None or name in emitted: + return + if name in visiting: + raise ValueError("object inheritance cycle at %s" % name) + visiting.add(name) + add(parent_obj_names.get(name)) + visiting.remove(name) + emitted.add(name) + ordered.append(name) + + for obj_name in obj_names: + add(obj_name) + return tuple(ordered) + + +def failed_generation( + *, method, problem, funcs, render_method, api_model=None, target=None +): + """Build the common diagnostic and remove one failed declaration.""" + name = getattr(method, "name", None) + function = next( + ( + item + for item in getattr(api_model, "functions", ()) + if item.c_name == name + ), + None, + ) + if ( + function is not None + and function.visibility == "public" + and target in function.available_on + ): + raise RuntimeError( + "unsupported public function for %s: %s: %s" + % (target, name, problem) + ) + remaining = list(funcs) + try: + remaining.remove(method) + except ValueError: + pass + return ( + """ +/* + * Function NOT generated: + * {problem} + * {method} + */ + """.format(method=render_method(method), problem=problem), + remaining, + ) + + +_TARGET_PROFILES = { + "micropython": TargetLoweringProfile("micropython", True), + "circuitpython": TargetLoweringProfile("circuitpython", True), + "cpython": TargetLoweringProfile("cpython", False), +} + + +def prepare_target_lowering(ctx, *, target, max_phase): + """Set common emitter state without imposing a VM-specific C contract.""" + try: + profile = _TARGET_PROFILES[target] + except KeyError: + raise ValueError("unsupported target lowering profile: %s" % target) + runtime.set_("emit_options", {"target": target, "max_phase": max_phase}) + runtime.set_("target_lowering_profile", profile) + for name in _EMIT_DEFAULTS: + if name not in runtime.export_names(): + continue + if name in ("generated_globals", "module_funcs"): + runtime.set_(name, []) + else: + runtime.set_(name, collections.OrderedDict()) + if not hasattr(ctx, "headers") or ctx.headers is None: + runtime.set_("headers", list(ctx.args.input)) + + +def require_target_lowering(target): + """Return the configured phase after verifying an emitter's target. + + A backend entry point selects the target before handing control to its + native emitter. Native emitters must not retain fallback paths for other + backends: those paths conceal ownership mistakes and make a future + refactor unsafe. Keep the check next to the common lowering setup so all + emitters can adopt the same boundary. + """ + emit_options = runtime.get("emit_options", {}) + actual_target = emit_options.get("target") + if actual_target != target: + raise RuntimeError( + "{target} emitter requires target={target!r}; got {actual!r}".format( + target=target, actual=actual_target + ) + ) + return emit_options.get("max_phase") + + +def require_one_of_target_lowerings(*targets): + """Return configured target and phase, constrained to shared emitters. + + Some C-lowering code is intentionally shared by multiple VM backends. + That code must still require an explicitly configured target; it may not + quietly fall back to one target when setup is missing. + """ + if not targets: + raise ValueError("at least one target is required") + emit_options = runtime.get("emit_options", {}) + actual_target = emit_options.get("target") + if actual_target not in targets: + expected = ", ".join(repr(target) for target in targets) + raise RuntimeError( + "shared emitter requires one of ({expected}); got {actual!r}".format( + expected=expected, actual=actual_target + ) + ) + return actual_target, emit_options.get("max_phase") + + +def resolve_emitter_headers(inputs): + """Return the public headers plus LVGL's private declarations. + + Every backend lowers against the same declaration surface. LVGL's public + umbrella header deliberately omits a few declarations used by generated + wrappers, so each native emitter must add the paired private header. + """ + headers = list(inputs) + for header in headers: + if "lvgl.h" not in header: + continue + path, _ = os.path.split(header) + headers.append( + os.path.join(path, "src", "lvgl_private.h") + if path and path != "lvgl.h" + else "src/lvgl_private.h" + ) + break + return headers + + +def target_banner(target, *, include): + """Return the optional target marker for a generated-file banner.""" + return " *\n * Target: {target}\n".format(target=target) if include else "" + + +def enum_namespace_plan(*, enums, get_enum_members, is_method_of, is_widget_scoped): + """Build the common enum namespace relationship plan in declaration order. + + The three targets choose different C representations for enum namespaces, + but their public nesting and widget-scoped-reference policy is identical. + Keeping this discovery here makes that contract explicit without imposing a + VM-specific emitted C shape. + """ + enum_names = tuple(enums) + return tuple( + EnumNamespacePlan( + name=enum_name, + members=tuple(get_enum_members(enum_name)), + nested_names=tuple( + other for other in enum_names if is_method_of(other, enum_name) + ), + widget_scoped_nested_names=tuple( + other + for other in enum_names + if is_method_of(other, enum_name) and is_widget_scoped(other) + ), + ) + for enum_name in enum_names + ) + + +def module_registration_plan( + *, + max_phase, + int_constants, + generated_globals, + enums, + enum_referenced, + generated_structs, + struct_aliases, + obj_names, + module_funcs, + public_struct_names=None, + public_enum_names=None, +): + """Select the shared public module surface for a completed phase. + + A declaration remains in its original discovery order. Backends receive + empty tuples for features not available in the requested phase, rather + than each reimplementing phase gates and referenced-enum filtering. + """ + return ModuleRegistrationPlan( + int_constants=tuple(int_constants) if max_phase >= 1 else (), + # _nesting (the binding-internal callback re-entrancy counter; see + # analyze.py and emit_c_micropython_style.py) is deliberately kept + # in the emitted module globals here even though the canonical API + # model marks it private: PyDevices' display_driver.py (pydevices + # lib/) reads it at runtime on MicroPython/CircuitPython. CPython's + # native emitter never adds it to generated_globals in the first + # place (it uses its own ContextVar-scoped lvpy_nesting_inc/dec + # instead), so this is a no-op there. + generated_globals=( + tuple(generated_globals) if max_phase >= 1 else () + ), + enum_names=( + tuple( + name + for name in enums + if name not in enum_referenced + and ( + public_enum_names is None + or name in public_enum_names + ) + ) + if max_phase >= 2 + else () + ), + struct_names=( + tuple( + name + for name, generated in generated_structs.items() + if generated + and ( + public_struct_names is None + or name in public_struct_names + ) + ) + if max_phase >= 3 + else () + ), + struct_alias_names=( + tuple( + name + for name, alias in struct_aliases.items() + if public_struct_names is None + or alias in public_struct_names + ) + if max_phase >= 3 + else () + ), + object_names=tuple(obj_names) if max_phase >= 5 else (), + module_functions=tuple(module_funcs) if max_phase >= 6 else (), + ) + + +def public_struct_c_names(api_model, target): + """Return canonical C spellings of public structs for one target.""" + if api_model is None: + return None + names = {"C_Pointer"} + for struct in api_model.structs: + if struct.visibility != "public" or target not in struct.available_on: + continue + if struct.c_name: + names.add(struct.c_name) + names.update(struct.typedef_names) + return frozenset(names) + + +def public_enum_module_names(api_model, target): + """Return canonical module-level enum names for one target.""" + if api_model is None: + return None + return frozenset( + enum.module_name + for enum in api_model.enums + if enum.visibility == "public" + and target in enum.available_on + and enum.module_name is not None + ) + + +def mp_obj_get_ull_to_bytes_source(): + """Return the VM-version-safe 64-bit integer conversion lowering. + + MicroPython 1.29 renamed ``mp_obj_int_to_bytes_impl`` and changed its + signature. CircuitPython 11.0 is built on MicroPython 1.29 and has only + the new helper; 10.x is MicroPython 1.27 and has only the old one. On + CircuitPython, ``MICROPY_VERSION_MAJOR`` is CircuitPython's own major + (genhdr/mpversion.h), not the core's, so the two are told apart by that. + The two native emitters share this lowering, so it belongs to their + shared backend contract rather than to either emitter's large C template. + """ + return ( + "#if defined(CIRCUITPY) && CIRCUITPY && MICROPY_VERSION_MAJOR < 11\n" + " mp_obj_int_to_bytes_impl(obj, big_endian, sizeof(val), (byte*)&val);\n" + "#elif defined(CIRCUITPY) && CIRCUITPY\n" + " mp_obj_int_to_bytes(obj, sizeof(val), (byte*)&val, big_endian, false, false);\n" + "#elif defined(MICROPY_VERSION_MAJOR) && defined(MICROPY_VERSION_MINOR) && \\\n" + " ((MICROPY_VERSION_MAJOR > 1) || " + "(MICROPY_VERSION_MAJOR == 1 && MICROPY_VERSION_MINOR > 28))\n" + " mp_obj_int_to_bytes(obj, sizeof(val), (byte*)&val, big_endian, false, false);\n" + "#else\n" + " mp_obj_int_to_bytes_impl(obj, big_endian, sizeof(val), (byte*)&val);\n" + "#endif" + ) + + +def function_return_lowering( + *, + return_type, + qualified_return_type, + is_pointer, + lv_to_mp, + lv_mp_type, +): + """Lower a resolved LVGL function return through the shared MP surface. + + All three targets present function results through the common ``mp_obj_t`` + compatibility surface, including CPython's native backend. Conversion + lookup remains emitter-owned because it may trigger recursive type + lowering; once available, this rule owns the identical void, pointer-cast, + and API-metadata behavior. + """ + if return_type == "void": + return FunctionReturnLowering("", "mp_const_none", "NoneType") + return FunctionReturnLowering( + "%s _res = " % qualified_return_type, + "{type}({cast}_res)".format( + type=lv_to_mp[return_type], cast="(void*)" if is_pointer else "" + ), + lv_mp_type[return_type], + ) + + +def callback_return_lowering(*, return_type, mp_to_lv): + """Lower a callback result after the emitter resolves its conversion. + + Callback conversion discovery stays emitter-owned because it can recurse + into type generation. Once that mapping exists, all native targets use + the same ``mp_call_function_n_kw`` result storage and conversion policy. + """ + if return_type == "void": + return CallbackReturnLowering("", "") + return CallbackReturnLowering( + "mp_obj_t callback_result = ", " %s(callback_result)" % mp_to_lv[return_type] + ) + + +def callback_return_conversion_available(*, return_type, mp_to_lv, generate_type): + """Ensure the conversion used by a callback return is available. + + The recursive type-generation hook remains supplied by the emitter, but + both native backends follow the same policy: ``void`` needs no conversion; + every other missing mapping gets exactly one generation attempt before the + caller reports its existing target-neutral diagnostic. + """ + return return_type == "void" or conversion_available( + conversions=mp_to_lv, type_name=return_type, generate_type=generate_type + ) + + +def conversion_available(*, conversions, type_name, generate_type): + """Ensure a target-neutral conversion mapping exists, with one retry. + + Conversion maps are populated lazily because lowering a declaration may + expose additional types. Native backends share the same rule: use an + existing non-empty mapping, otherwise generate once and check again. The + caller retains the context-specific error text and C lowering. + """ + if conversions.get(type_name): + return True + generate_type() + return bool(conversions.get(type_name)) + + +def function_reuse_allowed( + *, + function_name, + original_name, + original_generated, + supports_dynamic_function_pointer, +): + """Return whether two equivalent exported functions may share a wrapper. + + A dynamic-function-pointer wrapper can safely stand in for any equivalent + LVGL declaration. A direct-symbol wrapper, used by the native CPython + backend, may only reuse itself: reusing it for another symbol would call + the wrong LVGL function. This is an implementation constraint, not a + public-API exception. + """ + if not original_generated: + return False + return supports_dynamic_function_pointer or function_name == original_name + + +def struct_pointer_helpers_source( + *, + accept_none, + unused_qualifier, + sanitized_struct_name, + struct_name, + struct_tag, +): + """Return the common struct-pointer wrapper lowering. + + Native emitters expose LVGL structs through the same ``mp_lv_struct_t`` + representation. The CPython compatibility fallback accepts ``None`` for + nullable write pointers, while MicroPython/CircuitPython retain their + historic strict conversion. ``unused_qualifier`` preserves each VM's C + warning policy without duplicating the conversion contract. + """ + none_guard = " if (self_in == mp_const_none) return NULL;\n" if accept_none else "" + return """static inline const mp_obj_type_t *get_mp_{sanitized_struct_name}_type(void); + +{unused_qualifier}static inline void* mp_write_ptr_{sanitized_struct_name}(mp_obj_t self_in) +{{ +{none_guard} mp_lv_struct_t *self = MP_OBJ_TO_PTR(cast(self_in, get_mp_{sanitized_struct_name}_type())); + return ({struct_tag}{struct_name}*)self->data; +}} + +#define mp_write_{sanitized_struct_name}(struct_obj) *(({struct_tag}{struct_name}*)mp_write_ptr_{sanitized_struct_name}(struct_obj)) + +{unused_qualifier}static inline mp_obj_t mp_read_ptr_{sanitized_struct_name}(void *field) +{{ + return lv_to_mp_struct(get_mp_{sanitized_struct_name}_type(), field); +}}""".format( + none_guard=none_guard, + unused_qualifier=unused_qualifier, + sanitized_struct_name=sanitized_struct_name, + struct_tag=struct_tag, + struct_name=struct_name, + ) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_c_cpython.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_c_cpython.py new file mode 100644 index 00000000..b4155660 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_c_cpython.py @@ -0,0 +1,1095 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Main CPython emit loop (PyObject* API); calls cpython_glue and cpython_native.""" +from __future__ import print_function + +import collections +import copy +import re +from os.path import commonprefix + +from pycparser import c_ast, c_generator, c_parser + +from .analyze import ( + MissingConversionException, + get_base_struct_name, + get_ctor, + get_enum_member_name, + get_enum_members, + get_enum_value, + get_first_arg_type, + get_methods, + get_struct_functions, + has_ctor, + is_static_member, + is_struct_function, + noncommon_part, +) +from .helpers import ( + collect_enum_referenced, + ctor_name_from_obj_name, + get_enum_name, + is_global_callback, + is_method_of, + is_obj_ctor, + is_struct, + is_widget_scoped_only_enum, + method_name_from_func_name, + obj_name_from_ext_name, + obj_name_from_func_name, + sanitize, + simplify_identifier, + str_enum_to_str, +) +from .parse import ( + add_default_declname, + convert_array_to_ptr, + function_prototype, + get_name, + get_type, + remove_arg_names, + remove_declname, + remove_explicit_struct, + remove_quals, +) +from . import runtime +from .emit_backend import ( + TypeDiscovery, + callback_return_conversion_available, + callback_return_lowering, + function_return_lowering, + failed_generation, + object_generation_order, + require_target_lowering, + resolve_emitter_headers, + struct_pointer_helpers_source, + target_banner, +) +from .runtime_exports import filter_module_funcs_for_target, filter_registration_module_funcs +from .util import eprint, memoize +from .context import EmitterResult + + +def emit_c(ctx): + """Emit CPython C from one context without module-level run state.""" + print = ctx.emit_print + args = ctx.args + blobs = ctx.blobs + cmd_line = ctx.cmd_line + enum_defs = ctx.enum_defs + func_typedefs = ctx.func_typedefs + funcs = ctx.funcs + gen = ctx.gen + int_constants = ctx.int_constants + lv_mp_type = ctx.lv_mp_type + lv_str_enum_pattern = ctx.lv_str_enum_pattern + lv_to_mp = ctx.lv_to_mp + lv_to_mp_byref = ctx.lv_to_mp_byref + lv_to_mp_funcptr = ctx.lv_to_mp_funcptr + lvgl_json = ctx.lvgl_json + module_name = ctx.module_name + mp_to_lv = ctx.mp_to_lv + obj_names = ctx.obj_names + parent_obj_names = ctx.parent_obj_names + pp_cmd = ctx.pp_cmd + structs = ctx.structs + synonym = ctx.synonym + typedefs = ctx.typedefs + + generated_structs = getattr(ctx, "generated_structs", collections.OrderedDict()) + generated_struct_functions = ctx.generated_struct_functions + struct_aliases = ctx.struct_aliases + callbacks_used_on_structs = ctx.callbacks_used_on_structs + generated_callbacks = ctx.generated_callbacks + generated_funcs = ctx.generated_funcs + enum_referenced = ctx.enum_referenced + generated_obj_names = ctx.generated_obj_names + generated_globals = ctx.generated_globals + module_funcs = ctx.module_funcs + functions_not_generated = ctx.functions_not_generated + enums = getattr(ctx, "enums", collections.OrderedDict()) + + headers = resolve_emitter_headers(args.input) + + _emit_target = "cpython" + _emit_max_phase = require_target_lowering(_emit_target) + _target_banner = target_banner(_emit_target, include=True) + + print( + """ +/* + * Auto-Generated file, DO NOT EDIT! + * +{target_banner} * Command line: + * {cmd_line} + * + * Preprocessing command: + * {pp_cmd} + * + * Generating Objects: {objs} + */ + +/* + * CPython includes + */ + +#define PY_SSIZE_T_CLEAN +#include +#include +#include +#include "lvpy_runtime.h" + +/* + * {module_name} includes + */ + +{lv_headers} +""".format( + module_name=module_name, + target_banner=_target_banner, + cmd_line=cmd_line, + pp_cmd=pp_cmd, + objs=", ".join( + ["%s(%s)" % (objname, parent_obj_names[objname]) for objname in obj_names] + ), + lv_headers="\n".join('#include "%s"' % header for header in headers), + ) + ) + + # + # Enable objects, if supported + # + + if len(obj_names) > 0 and (_emit_max_phase is None or _emit_max_phase >= 5): + print( + """ +#define LV_OBJ_T lv_obj_t +""" + ) + + # Helper functions live in lvpy_runtime.c — except the string-array + # argument converter, which is emitted here so the generated file and + # the runtime need not be versioned together for it. + print( + """ +/* + * String-array arguments (const char * const map[] and friends). + * + * LVGL stores these pointers (lv_buttonmatrix_set_map keeps map_p; it never + * copies), so the array and its strings must outlive the call. A Python + * sequence of str converts to a NULL-terminated char*[] whose array (via a + * capsule) and string objects are retained on the widget's callback dict + * under a per-function key: the pointers live exactly as long as the widget, + * and a repeat call for the same function releases the previous retention. + * Non-sequence inputs fall through to mp_to_ptr (blob passthrough / the + * usual TypeError). + */ + +static void lvpy_str_arr_capsule_free(PyObject *capsule) +{ + PyMem_Free(PyCapsule_GetPointer(capsule, NULL)); +} + +static void *lvpy_str_arr_arg(PyObject *self, PyObject *arg, const char *key) +{ + if (!arg || arg == Py_None) return NULL; + if (PyUnicode_Check(arg) || PyBytes_Check(arg) || !PySequence_Check(arg)) + return mp_to_ptr(arg); + PyObject *items = PySequence_Tuple(arg); + if (!items) return NULL; + Py_ssize_t n = PyTuple_GET_SIZE(items); + const char **arr = (const char **)PyMem_Malloc(((size_t)n + 1) * sizeof(char *)); + if (!arr) { Py_DECREF(items); PyErr_NoMemory(); return NULL; } + for (Py_ssize_t i = 0; i < n; i++) { + PyObject *item = PyTuple_GET_ITEM(items, i); + const char *s = PyUnicode_Check(item) ? PyUnicode_AsUTF8(item) : NULL; + if (!s) { + PyMem_Free(arr); + Py_DECREF(items); + if (!PyErr_Occurred()) + PyErr_Format(PyExc_TypeError, + "sequence of str expected; item %zd is '%s'", + i, Py_TYPE(item)->tp_name); + return NULL; + } + arr[i] = s; + } + arr[n] = NULL; + PyObject *capsule = PyCapsule_New((void *)arr, NULL, lvpy_str_arr_capsule_free); + if (!capsule) { PyMem_Free(arr); Py_DECREF(items); return NULL; } + PyObject *pair = PyTuple_Pack(2, items, capsule); + Py_DECREF(items); + Py_DECREF(capsule); + if (!pair) return NULL; + PyObject *callbacks = mp_get_callbacks(self); + int rc = callbacks ? PyDict_SetItemString(callbacks, key, pair) : -1; + Py_DECREF(pair); + if (rc != 0) return NULL; + return (void *)arr; +} + +/* + * Struct-array arguments (const lv_point_precise_t points[] and friends). + * + * A list or tuple of structs (or dicts, as for a struct argument) converts to + * a C array, the way MicroPython converts it; anything else goes through + * mp_to_ptr, so a packed buffer still works. LVGL may keep the pointer + * (lv_line_set_points does), so the array or buffer is retained under a + * per-function key: on the widget's callback dict when self is a widget, + * else in a module dict keyed by self's address. A repeat call for the same + * function releases the previous one. + */ + +typedef void *(*lvpy_struct_writer_t)(PyObject *); + +static PyObject *lvpy_struct_arr_keep; + +static int lvpy_struct_arr_retain(PyObject *self, const char *key, PyObject *keep) +{ +#ifdef LV_OBJ_T + if (self && PyObject_TypeCheck(self, &py_lv_obj_type)) { + PyObject *callbacks = mp_get_callbacks(self); + return callbacks ? PyDict_SetItemString(callbacks, key, keep) : -1; + } +#endif + if (!lvpy_struct_arr_keep && !(lvpy_struct_arr_keep = PyDict_New())) return -1; + PyObject *k = PyUnicode_FromFormat("%p:%s", (void *)self, key); + if (!k) return -1; + int rc = PyDict_SetItem(lvpy_struct_arr_keep, k, keep); + Py_DECREF(k); + return rc; +} + +static void *lvpy_struct_arr_arg(PyObject *self, PyObject *arg, const char *key, + size_t elem_size, lvpy_struct_writer_t write) +{ + if (!arg || arg == Py_None) return NULL; + void *arr; + PyObject *keep; + if (PyList_Check(arg) || PyTuple_Check(arg)) { + PyObject *items = PySequence_Tuple(arg); + if (!items) return NULL; + Py_ssize_t n = PyTuple_GET_SIZE(items); + arr = PyMem_Malloc(n ? (size_t)n * elem_size : 1); + if (!arr) { Py_DECREF(items); PyErr_NoMemory(); return NULL; } + for (Py_ssize_t i = 0; i < n; i++) { + void *p = write(PyTuple_GET_ITEM(items, i)); + if (PyErr_Occurred()) { PyMem_Free(arr); Py_DECREF(items); return NULL; } + memcpy((char *)arr + (size_t)i * elem_size, p, elem_size); + } + Py_DECREF(items); + keep = PyCapsule_New(arr, NULL, lvpy_str_arr_capsule_free); + if (!keep) { PyMem_Free(arr); return NULL; } + } else { + arr = mp_to_ptr(arg); + if (PyErr_Occurred()) return NULL; + Py_INCREF(arg); + keep = arg; + } + int rc = lvpy_struct_arr_retain(self, key, keep); + Py_DECREF(keep); + if (rc != 0) return NULL; + return arr; +} + +/* + * Fixed-size struct arrays inside a struct (lv_point_precise_t p[3]). + * + * Reading the field gives a view over the parent struct's memory, so + * d.p[1].x = 7 and d.p[1] = point write through, and len(d.p) works. The view + * holds the parent so the memory stays alive. Assigning the field takes a + * sequence of exactly that many structs (or dicts), or a packed buffer of the + * array's size; anything else raises and leaves the field unchanged + * (lvgl-bindings#38). + */ + +typedef PyObject *(*lvpy_struct_reader_t)(void *); + +typedef struct { + PyObject_HEAD + PyObject *owner; + char *data; + Py_ssize_t len; + size_t elem_size; + lvpy_struct_reader_t read; + lvpy_struct_writer_t write; +} lvpy_struct_array_t; + +static void lvpy_struct_array_dealloc(PyObject *self) +{ + Py_XDECREF(((lvpy_struct_array_t *)self)->owner); + Py_TYPE(self)->tp_free(self); +} + +static Py_ssize_t lvpy_struct_array_len(PyObject *self) +{ + return ((lvpy_struct_array_t *)self)->len; +} + +static PyObject *lvpy_struct_array_item(PyObject *self_in, Py_ssize_t i) +{ + lvpy_struct_array_t *self = (lvpy_struct_array_t *)self_in; + if (i < 0 || i >= self->len) { + PyErr_SetString(PyExc_IndexError, "struct array index out of range"); + return NULL; + } + return self->read(self->data + (size_t)i * self->elem_size); +} + +static int lvpy_struct_array_ass_item(PyObject *self_in, Py_ssize_t i, PyObject *value) +{ + lvpy_struct_array_t *self = (lvpy_struct_array_t *)self_in; + if (value == NULL) { + PyErr_SetString(PyExc_TypeError, "can't delete struct array items"); + return -1; + } + if (i < 0 || i >= self->len) { + PyErr_SetString(PyExc_IndexError, "struct array assignment index out of range"); + return -1; + } + void *p = self->write(value); + if (PyErr_Occurred()) return -1; + memcpy(self->data + (size_t)i * self->elem_size, p, self->elem_size); + return 0; +} + +static PySequenceMethods lvpy_struct_array_as_sequence = { + .sq_length = lvpy_struct_array_len, + .sq_item = lvpy_struct_array_item, + .sq_ass_item = lvpy_struct_array_ass_item, +}; + +/* dir() on a struct instance: what object.__dir__ finds, plus the fields and + * methods the struct's getattro resolves by name (lvgl-bindings#40). */ +static inline PyObject *lvpy_struct_dir(PyObject *self, const char *const *fields, + PyMethodDef *methods) +{ + PyObject *names = PyObject_CallMethod((PyObject *)&PyBaseObject_Type, "__dir__", "O", self); + if (names == NULL) return NULL; + PyObject *list = PySequence_List(names); + Py_DECREF(names); + if (list == NULL) return NULL; + for (; *fields != NULL; fields++) { + PyObject *s = PyUnicode_FromString(*fields); + if (s == NULL || PyList_Append(list, s) < 0) { Py_XDECREF(s); Py_DECREF(list); return NULL; } + Py_DECREF(s); + } + for (; methods->ml_name != NULL; methods++) { + PyObject *s = PyUnicode_FromString(methods->ml_name); + if (s == NULL || PyList_Append(list, s) < 0) { Py_XDECREF(s); Py_DECREF(list); return NULL; } + Py_DECREF(s); + } + return list; +} + +static PyTypeObject lvpy_struct_array_type = { + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "lvgl.StructArray", + .tp_basicsize = sizeof(lvpy_struct_array_t), + .tp_dealloc = lvpy_struct_array_dealloc, + .tp_as_sequence = &lvpy_struct_array_as_sequence, + .tp_flags = Py_TPFLAGS_DEFAULT, +}; + +static inline PyObject *lvpy_struct_array_new(PyObject *owner, void *data, + Py_ssize_t len, size_t elem_size, lvpy_struct_reader_t read, lvpy_struct_writer_t write) +{ + if (!(lvpy_struct_array_type.tp_flags & Py_TPFLAGS_READY) && + PyType_Ready(&lvpy_struct_array_type) < 0) + return NULL; + lvpy_struct_array_t *self = PyObject_New(lvpy_struct_array_t, &lvpy_struct_array_type); + if (!self) return NULL; + Py_XINCREF(owner); + self->owner = owner; + self->data = (char *)data; + self->len = len; + self->elem_size = elem_size; + self->read = read; + self->write = write; + return (PyObject *)self; +} + +/* Sets an exception and leaves data unchanged on any mismatch. */ +static inline void lvpy_struct_array_assign(void *data, Py_ssize_t len, + size_t elem_size, lvpy_struct_writer_t write, PyObject *value) +{ + size_t total = (size_t)len * elem_size; + if (PyBytes_Check(value) || PyByteArray_Check(value) || PyMemoryView_Check(value)) { + Py_buffer view; + if (PyObject_GetBuffer(value, &view, PyBUF_C_CONTIGUOUS) < 0) return; + if ((size_t)view.len != total) + PyErr_Format(PyExc_ValueError, "expected a buffer of %zu bytes, got %zd", + total, view.len); + else + memcpy(data, view.buf, total); + PyBuffer_Release(&view); + return; + } + if (!PySequence_Check(value) || PyUnicode_Check(value)) { + PyErr_Format(PyExc_TypeError, "expected a sequence of %zd structs, got '%s'", + len, Py_TYPE(value)->tp_name); + return; + } + PyObject *items = PySequence_Tuple(value); + if (!items) return; + if (PyTuple_GET_SIZE(items) != len) { + PyErr_Format(PyExc_ValueError, "expected %zd items, got %zd", + len, PyTuple_GET_SIZE(items)); + Py_DECREF(items); + return; + } + /* Convert every item before writing any, so a bad item changes nothing. */ + char *tmp = (char *)PyMem_Malloc(total ? total : 1); + if (!tmp) { Py_DECREF(items); PyErr_NoMemory(); return; } + for (Py_ssize_t i = 0; i < len; i++) { + void *p = write(PyTuple_GET_ITEM(items, i)); + if (PyErr_Occurred()) { PyMem_Free(tmp); Py_DECREF(items); return; } + memcpy(tmp + (size_t)i * elem_size, p, elem_size); + } + memcpy(data, tmp, total); + PyMem_Free(tmp); + Py_DECREF(items); +} +""" + ) + + # + # Add regular enums with integer values + # + + enums = collections.OrderedDict() + for enum_def in enum_defs: + # Skip stdatomic.h memory_order, no bindings needed. + if isinstance(enum_def, c_ast.TypeDecl) and enum_def.declname == "memory_order": + continue + + # eprint("--> %s" % enum_def) + while hasattr(enum_def.type, "name") and not enum_def.type.values: + enum_def = next( + e + for e in enum_defs + if hasattr(e.type, "name") + and e.type.name == enum_def.type.name + and e.type.values + ) + member_names = [ + member.name + for member in enum_def.type.values.enumerators + if not member.name.startswith("_") + ] + enum_name = commonprefix(member_names) + enum_name = "_".join(enum_name.split("_")[:-1]) # remove suffix + enum = collections.OrderedDict() + for member in enum_def.type.values.enumerators: + if member.name.startswith("_"): + continue + member_name = ( + member.name[len(enum_name) + 1 :] if len(enum_name) > 0 else member.name + ) + if member_name[0].isdigit(): + member_name = "_" + member_name + if len(enum_name) > 0 and get_enum_name(enum_name) != "ENUM": + enum[member_name] = "MP_ROM_INT(%s)" % member.name + else: + int_constants.append(member.name) + if len(enum) > 0: + if len(get_enum_name(enum_name)) > 0: + prev_enum = enums.get(enum_name) + if prev_enum: + prev_enum.update(enum) + else: + enums[enum_name] = enum + + for enum in [ + enum for enum in enums if len(enums[enum]) == 1 and enum.startswith("ENUM") + ]: + int_constants.append("%s_%s" % (enum, next(iter(enums[enum])))) + del enums[enum] + + # Add special string enums + + generated_globals = [] + + print( + """ +/* + * LVGL string constants + */ +""" + ) + + for enum_def in enum_defs: + if not enum_def.type.values: + continue + member_names = [ + str_enum_to_str(member.name) + for member in enum_def.type.values.enumerators + if lv_str_enum_pattern.match(member.name) + ] + enum_name = commonprefix(member_names) + enum_name = "_".join(enum_name.split("_")[:-1]) # remove suffix + enum = collections.OrderedDict() + if enum_name: + for member in enum_def.type.values.enumerators: + full_name = str_enum_to_str(member.name) + member_name = full_name[len(enum_name) + 1 :] + generated_globals.append(full_name) + enum[member_name] = full_name + if len(enum) > 0: + if enum_name in enums: + enums[enum_name].update(enum) + else: + enums[enum_name] = enum + + + # eprint('--> enums: \n%s' % enums) + + runtime.set_("enums", enums) + + # eprint(',\n'.join(sorted('%s : %s' % (name, get_type(blobs[name])) for name in blobs))) + + # + # Callbacks helper functions + # + + + def decl_to_callback(decl): + # print('/* decl_to_callback %s */' % decl) + if not hasattr(decl, "type"): + return None + if isinstance(decl.type, c_ast.PtrDecl) and isinstance( + decl.type.type, c_ast.FuncDecl + ): + return (decl.name, decl.type.type) + # print('/* callback: ADDED CALLBACK: %s\n%s */' % (gen.visit(decl.type.type), decl.type.type)) + elif isinstance(decl.type, c_ast.FuncDecl): + return (decl.name, decl.type) + # print('/* callback: ADDED CALLBACK: %s\n%s */' % (gen.visit(decl.type.type), decl.type.type)) + elif isinstance(decl.type, c_ast.TypeDecl) and hasattr(decl.type.type, "names"): + func_typedef_name = decl.type.type.names[0] + while func_typedef_name in synonym: + # eprint('decl_to_callback: %s --> %s' % (func_typedef_name, synonym[func_typedef_name])) + func_typedef_name = synonym[func_typedef_name] + # print('/* --> callback: TYPEDEF CALLBACK: %s: %s */' % (decl.name if hasattr(decl, 'name') else None, func_typedef_name)) + if func_typedef_name in func_typedefs: + return (decl.name, func_typedefs[func_typedef_name].type.type) + # print('/* callback: ADDED CALLBACK: %s\n%s */' % (func_typedef_name, func_typedefs[func_typedef_name])) + else: + return None + + + def get_user_data_accessors(containing_struct, containing_struct_name=None): + if not containing_struct_name and containing_struct and containing_struct.name: + containing_struct_name = containing_struct.name + if not containing_struct_name: + return None, None + base_struct_name = get_base_struct_name(containing_struct_name) + getter_name = base_struct_name + "_get_user_data" + setter_name = base_struct_name + "_set_user_data" + # print('/* struct functions = %s */' % [s.name + ':' + str(len(s.type.args.params)) for s in get_struct_functions(containing_struct_name)]) + # print('/* getter_name = %s */' % getter_name) + struct_functions = get_struct_functions(containing_struct_name) + getters = [ + s + for s in struct_functions + if s.name == getter_name and len(s.type.args.params) == 1 + ] + setters = [ + s + for s in struct_functions + if s.name == setter_name and len(s.type.args.params) == 2 + ] + if getters and setters: + return getters[0], setters[0] + else: + return None, None + + + def get_user_data( + func, func_name=None, containing_struct=None, containing_struct_name=None + ): + args = func.args.params + if not func_name: + func_name = get_arg_name(func.type) + # print('/* --> callback: func_name = %s, args = %s */' % (func_name, repr(args))) + user_data_found = False + user_data = "None" + if len(args) > 0 and isinstance(args[0].type, c_ast.PtrDecl): + # if isinstance(args[0].type.type.type, c_ast.Struct): + # struct_arg_type_name = args[0].type.type.type.name # PtrDecl.TypeDecl.Struct. Needed to omit 'struct' keyword. + # else: + # struct_arg_type_name = get_type(args[0].type.type, remove_quals = True) + struct_arg_type_name = get_type(args[0].type.type, remove_quals=True) + # print('/* --> get_user_data: containing_struct_name = %s, struct_arg_type_name = %s */' % (containing_struct_name, struct_arg_type_name)) + if containing_struct_name and struct_arg_type_name != containing_struct_name: + return None, None, None + if not containing_struct: + try_generate_type(args[0].type) + if struct_arg_type_name in structs: + containing_struct = structs[struct_arg_type_name] + # print('/* --> containing_struct = %s */' % containing_struct) + # if struct_arg_type_name in mp_to_lv: + # print('/* --> callback: %s First argument is %s */' % (gen.visit(func), struct_arg_type_name)) + if containing_struct: + flatten_struct_decls = flatten_struct(containing_struct.decls) + user_data = "user_data" + user_data_found = user_data in [decl.name for decl in flatten_struct_decls] + # print('/* --> callback: user_data=%s user_data_found=%s containing_struct=%s */' % (user_data, user_data_found, containing_struct)) + if not user_data_found and lvgl_json is not None: + containing_struct_j = next( + ( + struct + for struct in lvgl_json["structures"] + if struct["name"] == struct_arg_type_name + ), + None, + ) + if ( + containing_struct_j is None + and struct_arg_type_name.startswith("lv_") + and None + is not next( + ( + fwd_decl + for fwd_decl in lvgl_json["forward_decls"] + if fwd_decl["name"] == struct_arg_type_name + ), + None, + ) + ): + struct_arg_type_name_with_underscore = "_" + struct_arg_type_name + containing_struct_j = next( + ( + struct + for struct in lvgl_json["structures"] + if struct["name"] == struct_arg_type_name_with_underscore + ), + None, + ) + if containing_struct_j is not None: + user_data_found = any( + user_data == field["name"] + for field in containing_struct_j["fields"] + ) + return (user_data if user_data_found else None), *get_user_data_accessors( + containing_struct, containing_struct_name + ) + + + # + # Generate structs when needed + # + + generated_structs = collections.OrderedDict() + generated_struct_functions = collections.OrderedDict() + generated_struct_method_funcs = collections.OrderedDict() + struct_aliases = collections.OrderedDict() + callbacks_used_on_structs = [] + runtime.set_("generated_structs", generated_structs) + runtime.set_("generated_struct_functions", generated_struct_functions) + runtime.set_("generated_struct_method_funcs", generated_struct_method_funcs) + runtime.set_("struct_aliases", struct_aliases) + runtime.set_("callbacks_used_on_structs", callbacks_used_on_structs) + + + def flatten_struct(struct_decls): + result = [] + if not struct_decls: + return result + for decl in struct_decls: + if is_struct(decl.type): + result.extend(flatten_struct(decl.type.decls)) + else: + result.append(decl) + return result + + + def try_generate_struct(struct_name, struct): + from .emit_cpython_native import try_generate_struct_cpython + + return try_generate_struct_cpython(struct_name, struct) + + + def try_generate_array_type(type_ast): + return None + + + generated_funcptr_helpers = collections.OrderedDict() + + + def emit_function_pointer(helper_name, func): + print("#define %s NULL\n" % helper_name) + print( + "static inline PyObject *mp_lv_{f}(void *func){{ return " + "mp_lv_funcptr(NULL, func, NULL, \"\", NULL); }}\n".format( + f=helper_name + ) + ) + return True + + + type_discovery = TypeDiscovery( + get_name=get_name, + get_type=get_type, + structs=structs, + typedefs=typedefs, + struct_aliases=struct_aliases, + mp_to_lv=mp_to_lv, + lv_to_mp=lv_to_mp, + lv_mp_type=lv_mp_type, + lv_to_mp_byref=lv_to_mp_byref, + lv_to_mp_funcptr=lv_to_mp_funcptr, + generated_funcptr_helpers=generated_funcptr_helpers, + try_generate_struct=try_generate_struct, + try_generate_array=try_generate_array_type, + emit_function_pointer=emit_function_pointer, + missing_conversion=MissingConversionException, + report_error=lambda func, exp: gen_func_error(func, exp), + ) + get_arg_name = type_discovery.typedef_name + + + def try_generate_type(type_ast): + return type_discovery.generate(type_ast) + + + # + # Emit C callback functions + # + + generated_callbacks = collections.OrderedDict() + generated_funcs = collections.OrderedDict() + + if _emit_max_phase is None or _emit_max_phase > 1: + + if _emit_max_phase is not None and _emit_max_phase >= 2: + from .emit_cpython_glue import emit_phase2_enums_cpython + + emit_phase2_enums_cpython() + + if _emit_max_phase is None or _emit_max_phase >= 4: + + def gen_callback_func(func, func_name=None, user_data_argument=False): + from .emit_cpython_native import gen_callback_func_cpython + + return gen_callback_func_cpython(func, func_name, user_data_argument) + + + generated_funcs = collections.OrderedDict() + + + def gen_mp_func(func, obj_name): + from .emit_cpython_native import gen_py_func + + return gen_py_func(func, obj_name) + + + def gen_func_error(method, exp): + diagnostic, funcs = failed_generation( + method=method, + problem=exp, + funcs=runtime.get("funcs"), + render_method=lambda value: ( + gen.visit(value) if isinstance(value, c_ast.Node) else value + ), + api_model=runtime.get("api_model"), + target=_emit_target, + ) + print(diagnostic) + runtime.set_("funcs", funcs) + + + # + # Emit Mpy objects definitions + # + + enum_referenced = collections.OrderedDict() + + + def gen_obj(obj_name): + from .emit_cpython_native import gen_py_obj + + return gen_py_obj(obj_name) + + + # + # Generate Enum objects + # + + if _emit_max_phase is None: + for enum_name in list(enums.keys()): + gen_obj(enum_name) + + # + # Generate all other objects. Generate parent objects first + # + + if _emit_max_phase is None or _emit_max_phase >= 5: + + from .emit_cpython_native import bind_emit_helpers + + bind_emit_helpers(locals()) + + generated_obj_names = collections.OrderedDict() + for obj_name in object_generation_order(obj_names, parent_obj_names): + gen_obj(obj_name) + generated_obj_names[obj_name] = True + + from .emit_cpython_native import bound_helper + + _gf = bound_helper("generated_funcs") + if _gf is not None: + generated_funcs = _gf + runtime.set_("generated_funcs", generated_funcs) + + # + # Generate structs which contain function members + # First argument of a function could be it's parent struct + # Need to make sure these structs are generated *before* struct-functions are + # Otherwise we will not know of all the structs when generating struct-functions + # + + + def try_generate_structs_from_first_argument(): + for func in funcs: + if func.name in generated_funcs: + continue + args = func.type.args.params if func.type.args else [] + if len(args) < 1: + continue + arg_type = get_type(args[0].type, remove_quals=True) + if arg_type not in mp_to_lv or not mp_to_lv[arg_type]: + try: + try_generate_type(args[0].type) + except MissingConversionException as e: + print( + """ +/* + * {struct} not generated: {err} + */ + """.format(struct=arg_type, err=e) + ) + + + # + # Generate globals + # + + # eprint("/* Generating globals */") + + + def gen_func_error(method, exp): + diagnostic, funcs = failed_generation( + method=method, + problem=exp, + funcs=runtime.get("funcs"), + render_method=lambda value: ( + gen.visit(value) if isinstance(value, c_ast.Node) else value + ), + api_model=runtime.get("api_model"), + target=_emit_target, + ) + print(diagnostic) + runtime.set_("funcs", funcs) + + def _emit_cpython_struct_methods(struct_list=None): + from .emit_cpython_native import ( + emit_struct_methods_cpython, + gen_py_func, + _resolved_struct_method_py_func_name, + ) + + if struct_list is None: + struct_names = list(generated_structs.keys()) + else: + struct_names = struct_list + for struct_name in struct_names: + if not generated_structs.get(struct_name): + continue + if generated_struct_functions.get(struct_name): + continue + struct_funcs = list(get_struct_functions(struct_name)) + method_entries = [] + seen_method_names = set() + for struct_func in struct_funcs: + try: + emit_name = struct_func.name + "_struct_method" + if generated_struct_method_funcs.get(emit_name) is not True: + gen_py_func(struct_func, struct_name) + resolved = _resolved_struct_method_py_func_name( + struct_func.name, generated_struct_method_funcs + ) + if not resolved: + continue + method_name = sanitize( + noncommon_part(struct_func.name, struct_name) + ) + if method_name in seen_method_names: + continue + seen_method_names.add(method_name) + method_entries.append((resolved, method_name)) + except MissingConversionException as exp: + gen_func_error(struct_func, exp) + emit_struct_methods_cpython(struct_name, method_entries) + generated_struct_functions[struct_name] = True + + + def _emit_struct_locals_dicts(include_methods=False, struct_list=None): + return None + + + def gen_global(global_name, global_type_ast): + global_type = get_type(global_type_ast, remove_quals=True) + if global_name == "_nesting": + return + try_generate_type(global_type_ast) + cpython_global_types = runtime.get( + "cpython_global_types", collections.OrderedDict() + ) + cpython_global_types[global_name] = ( + global_type if generated_structs.get(global_type, False) else None + ) + runtime.set_("cpython_global_types", cpython_global_types) + generated_globals.append(global_name) + + + for global_name in blobs: + try: + gen_global(global_name, blobs[global_name]) + except MissingConversionException as exp: + gen_func_error(global_name, exp) + + if _emit_max_phase is None or _emit_max_phase >= 4: + from .emit_cpython_native import bind_emit_helpers, bound_helper + + _gf = bound_helper("generated_funcs") + if _gf is not None: + generated_funcs = _gf + bind_emit_helpers(locals()) + try_generate_structs_from_first_argument() + _emit_struct_locals_dicts(include_methods=True) + + if _emit_max_phase is None or _emit_max_phase >= 6: + # + # Generate all module functions (not including method functions which were already generated) + # + + print( + """ +/* + * + * Global Module Functions + * + */ +""" + ) + + # eprint("/* Generating global module functions /*") + from .emit_cpython_native import bound_helper + + _candidates = [ + generated_funcs, + runtime.get("generated_funcs", {}), + bound_helper("generated_funcs", {}), + ] + generated_funcs = max(_candidates, key=len) + module_funcs = [func for func in funcs if func.name not in generated_funcs] + module_funcs = filter_module_funcs_for_target( + module_funcs, _emit_target, runtime.get("api_model") + ) + runtime.set_("_cpython_module_exports", list(module_funcs)) + for module_func in module_funcs[ + : + ]: # clone list because we are changing it in the loop. + if module_func.name in generated_funcs: + continue # generated_funcs could change inside the loop so need to recheck. + try: + gen_mp_func(module_func, None) + # A new function can create new struct with new function structs + new_structs = [ + s + for s in generated_structs + if generated_structs[s] and not generated_struct_functions.get(s) + ] + if new_structs: + _emit_struct_locals_dicts(include_methods=True, struct_list=new_structs) + except MissingConversionException as exp: + gen_func_error(module_func, exp) + module_funcs.remove(module_func) + + _emit_cpython_struct_methods() + module_funcs = filter_registration_module_funcs(module_funcs) + + functions_not_generated = [ + func.name for func in funcs if func.name not in generated_funcs + ] + if len(functions_not_generated) > 0: + print( + """ +/* + * Functions not generated: + * {funcs} + * + */ + +""".format(funcs="\n * ".join(functions_not_generated)) + ) + + if _emit_max_phase is None or _emit_max_phase >= 7: + # + # Generate callback functions (struct field callbacks) + # + + # eprint("/* Generating callback functions */") + for func_name, func, struct_name in callbacks_used_on_structs: + try: + # print('/* --> gen_callback_func %s */' % func_name) + gen_callback_func(func, func_name="%s_%s" % (struct_name, func_name)) + except MissingConversionException as exp: + gen_func_error(func, exp) + + # Callback lowering can discover additional concrete structs after + # phase 6. Every generated CPython struct type references a method + # table, including structs with no methods, so close that discovery + # set before module initialization is emitted. + while True: + pending_struct_methods = [ + name + for name, generated in generated_structs.items() + if generated and not generated_struct_functions.get(name) + ] + if not pending_struct_methods: + break + _emit_cpython_struct_methods(pending_struct_methods) + + # Emit the CPython module definition. + from .emit_cpython_glue import finish_py_module + runtime.set_("generated_funcs", generated_funcs) + runtime.set_("module_funcs", module_funcs) + runtime.set_("generated_structs", generated_structs) + runtime.set_("struct_aliases", struct_aliases) + runtime.set_("generated_globals", generated_globals) + runtime.set_("int_constants", int_constants) + runtime.set_("obj_names", obj_names) + runtime.set_( + "enum_referenced", + collect_enum_referenced(runtime.get("enums", {}), obj_names), + ) + print( + """ +py_lv_obj_type_t *py_lv_obj_types[] = {{ + {obj_types}NULL +}}; +""".format( + obj_types=",\n ".join( + ["&py_lv_%s_mapping" % sanitize(o) for o in obj_names] + ) + + (",\n " if obj_names and (_emit_max_phase is None or _emit_max_phase >= 5) else "") + if len(obj_names) > 0 and (_emit_max_phase is None or _emit_max_phase >= 5) + else "", + ) + ) + finish_py_module(_emit_max_phase or 7) + EmitterResult.capture(locals()).apply(ctx) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_c_micropython_style.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_c_micropython_style.py new file mode 100644 index 00000000..38452828 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_c_micropython_style.py @@ -0,0 +1,3241 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Main MP-style C emitter (mp_obj_t API); used by MicroPython and CircuitPython.""" +from __future__ import print_function + +import collections +import copy +import re +from os.path import commonprefix + +from pycparser import c_ast, c_generator, c_parser + +from .analyze import ( + MissingConversionException, + get_base_struct_name, + get_ctor, + get_enum_member_name, + get_enum_members, + get_enum_value, + get_first_arg_type, + get_methods, + get_struct_functions, + has_ctor, + is_static_member, + is_struct_function, + noncommon_part, +) +from .helpers import ( + ctor_name_from_obj_name, + export_name, + get_enum_name, + is_global_callback, + is_method_of, + is_obj_ctor, + is_struct, + is_widget_scoped_only_enum, + method_name_from_func_name, + obj_name_from_ext_name, + obj_name_from_func_name, + sanitize, + simplify_identifier, + str_enum_to_str, +) +from .parse import ( + add_default_declname, + convert_array_to_ptr, + function_prototype, + get_name, + get_type, + remove_arg_names, + remove_declname, + remove_explicit_struct, + remove_quals, +) +from . import runtime +from .emit_backend import ( + TypeDiscovery, + callback_return_conversion_available, + callback_return_lowering, + conversion_available, + function_reuse_allowed, + function_return_lowering, + failed_generation, + mp_obj_get_ull_to_bytes_source, + object_generation_order, + public_struct_c_names, + public_enum_module_names, + require_one_of_target_lowerings, + resolve_emitter_headers, + struct_pointer_helpers_source, + target_banner, +) +from .runtime_exports import filter_module_funcs_for_target, filter_registration_module_funcs +from .util import eprint, guarded, memoize +from .context import EmitterResult + + +def emit_c(ctx): + """Emit MP-style C from one context without module-level run state.""" + print = ctx.emit_print + args = ctx.args + base_obj_name = ctx.base_obj_name + base_obj_type = ctx.base_obj_type + blobs = ctx.blobs + callback_metadata = ctx.callback_metadata + cmd_line = ctx.cmd_line + enum_defs = ctx.enum_defs + func_metadata = ctx.func_metadata + func_prototypes = ctx.func_prototypes + func_typedefs = ctx.func_typedefs + funcs = ctx.funcs + gen = ctx.gen + int_constants = ctx.int_constants + lv_base_obj_pattern = ctx.lv_base_obj_pattern + lv_func_returns_array = ctx.lv_func_returns_array + lv_mp_type = ctx.lv_mp_type + lv_str_enum_pattern = ctx.lv_str_enum_pattern + lv_to_mp = ctx.lv_to_mp + lv_to_mp_byref = ctx.lv_to_mp_byref + lv_to_mp_funcptr = ctx.lv_to_mp_funcptr + lvgl_json = ctx.lvgl_json + module_name = ctx.module_name + mp_to_lv = ctx.mp_to_lv + obj_metadata = ctx.obj_metadata + obj_names = ctx.obj_names + parent_obj_names = ctx.parent_obj_names + parser = ctx.parser + pp_cmd = ctx.pp_cmd + structs = ctx.structs + structs_without_typedef = ctx.structs_without_typedef + synonym = ctx.synonym + typedefs = ctx.typedefs + + generated_structs = getattr(ctx, "generated_structs", collections.OrderedDict()) + generated_struct_functions = ctx.generated_struct_functions + struct_aliases = ctx.struct_aliases + callbacks_used_on_structs = ctx.callbacks_used_on_structs + generated_callbacks = ctx.generated_callbacks + generated_funcs = ctx.generated_funcs + enum_referenced = ctx.enum_referenced + generated_obj_names = ctx.generated_obj_names + generated_globals = ctx.generated_globals + module_funcs = ctx.module_funcs + functions_not_generated = ctx.functions_not_generated + enums = getattr(ctx, "enums", collections.OrderedDict()) + + headers = resolve_emitter_headers(args.input) + + _emit_target, _emit_max_phase = require_one_of_target_lowerings( + "micropython", "circuitpython" + ) + _target_banner = target_banner( + _emit_target, include=_emit_target != "micropython" + ) + + print( + """ +/* + * Auto-Generated file, DO NOT EDIT! + * +{target_banner} * Command line: + * {cmd_line} + * + * Preprocessing command: + * {pp_cmd} + * + * Generating Objects: {objs} + */ + +/* + * Mpy includes + */ + +#include +#include +#include "py/obj.h" +#include "py/objint.h" +#include "py/objstr.h" +#include "py/objtuple.h" +#include "py/runtime.h" +#include "py/binary.h" +#include "py/objarray.h" +#include "py/objtype.h" +#include "py/objexcept.h" + +/* + * {module_name} includes + */ + +{lv_headers} +""".format( + module_name=module_name, + target_banner=_target_banner, + cmd_line=cmd_line, + pp_cmd=pp_cmd, + objs=", ".join( + ["%s(%s)" % (objname, parent_obj_names[objname]) for objname in obj_names] + ), + lv_headers="\n".join('#include "%s"' % header for header in headers), + ) + ) + + # + # Enable objects, if supported + # + + if len(obj_names) > 0 and (_emit_max_phase is None or _emit_max_phase >= 5): + print( + """ +#define LV_OBJ_T {obj_type} + +typedef struct mp_lv_obj_type_t {{ + const lv_obj_class_t *lv_obj_class; + const mp_obj_type_t *mp_obj_type; +}} mp_lv_obj_type_t; + +static const mp_lv_obj_type_t mp_lv_{base_obj}_type; +static const mp_lv_obj_type_t *mp_lv_obj_types[]; + +static inline const mp_obj_type_t *get_BaseObj_type(void) +{{ + return mp_lv_{base_obj}_type.mp_obj_type; +}} + +MP_DEFINE_EXCEPTION(LvReferenceError, Exception) + """.format(obj_type=base_obj_type, base_obj=base_obj_name) + ) + + # + # Emit Mpy helper functions + # + + _mp_obj_get_ull_to_bytes = mp_obj_get_ull_to_bytes_source() + + print( + """ +/* + * Helper functions + */ + +#ifndef GENMPY_UNUSED +#ifdef __GNUC__ +#define GENMPY_UNUSED __attribute__ ((unused)) +#else +#define GENMPY_UNUSED +#endif // __GNUC__ +#endif // GENMPY_UNUSED + +// Custom function mp object + +typedef mp_obj_t (*mp_fun_ptr_var_t)(size_t n, const mp_obj_t *, void *ptr); + +typedef struct mp_lv_obj_fun_builtin_var_t { + mp_obj_base_t base; + mp_uint_t n_args; + mp_fun_ptr_var_t mp_fun; + void *lv_fun; +} mp_lv_obj_fun_builtin_var_t; + +static mp_obj_t lv_fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args); +static mp_int_t mp_func_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags); + +GENMPY_UNUSED static MP_DEFINE_CONST_OBJ_TYPE( + mp_lv_type_fun_builtin_var, + MP_QSTR_function, + MP_TYPE_FLAG_BINDS_SELF | MP_TYPE_FLAG_BUILTIN_FUN, + call, lv_fun_builtin_var_call, + unary_op, mp_obj_int_unary_op, + buffer, mp_func_get_buffer +); + +GENMPY_UNUSED static MP_DEFINE_CONST_OBJ_TYPE( + mp_lv_type_fun_builtin_static_var, + MP_QSTR_function, + MP_TYPE_FLAG_BUILTIN_FUN, + call, lv_fun_builtin_var_call, + unary_op, mp_obj_int_unary_op, + buffer, mp_func_get_buffer +); + +static mp_obj_t lv_fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + assert(MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_var) || + MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_static_var)); + mp_lv_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in); + mp_arg_check_num(n_args, n_kw, self->n_args, self->n_args, false); + return self->mp_fun(n_args, args, self->lv_fun); +} + +static mp_int_t mp_func_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + (void)flags; + assert(MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_var) || + MP_OBJ_IS_TYPE(self_in, &mp_lv_type_fun_builtin_static_var)); + mp_lv_obj_fun_builtin_var_t *self = MP_OBJ_TO_PTR(self_in); + + bufinfo->buf = &self->lv_fun; + bufinfo->len = sizeof(self->lv_fun); + bufinfo->typecode = BYTEARRAY_TYPECODE; + return 0; +} + +#define MP_DEFINE_CONST_LV_FUN_OBJ_VAR(obj_name, n_args, mp_fun, lv_fun) \\ + const mp_lv_obj_fun_builtin_var_t obj_name = \\ + {{&mp_lv_type_fun_builtin_var}, n_args, mp_fun, lv_fun} + +#define MP_DEFINE_CONST_LV_FUN_OBJ_STATIC_VAR(obj_name, n_args, mp_fun, lv_fun) \\ + const mp_lv_obj_fun_builtin_var_t obj_name = \\ + {{&mp_lv_type_fun_builtin_static_var}, n_args, mp_fun, lv_fun} + +// Casting + +typedef struct mp_lv_struct_t +{ + mp_obj_base_t base; + void *data; +} mp_lv_struct_t; + +static const mp_lv_struct_t mp_lv_null_obj; + +#ifdef LV_OBJ_T +static mp_int_t mp_lv_obj_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags); +#else +static mp_int_t mp_lv_obj_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags){ return 0; } +#endif + +static mp_int_t mp_blob_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags); + +static mp_obj_t get_native_obj(mp_obj_t mp_obj) +{ + if (!MP_OBJ_IS_OBJ(mp_obj)) return mp_obj; + const mp_obj_type_t *native_type = ((mp_obj_base_t*)mp_obj)->type; + if (native_type == NULL) + return NULL; + if (MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, parent) == NULL || + (MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, buffer) == mp_blob_get_buffer) || + (MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, buffer) == mp_lv_obj_get_buffer)) + return mp_obj; + while (MP_OBJ_TYPE_GET_SLOT_OR_NULL(native_type, parent)) native_type = MP_OBJ_TYPE_GET_SLOT(native_type, parent); + return mp_obj_cast_to_native_base(mp_obj, MP_OBJ_FROM_PTR(native_type)); +} + +static mp_obj_t dict_to_struct(mp_obj_t dict, const mp_obj_type_t *type); + +static mp_obj_t make_new_lv_struct( + const mp_obj_type_t *type, + size_t n_args, + size_t n_kw, + const mp_obj_t *args); + +static mp_obj_t cast(mp_obj_t mp_obj, const mp_obj_type_t *mp_type) +{ + mp_obj_t res = NULL; + if (mp_obj == mp_const_none && MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_type, make_new) == &make_new_lv_struct) { + res = MP_OBJ_FROM_PTR(&mp_lv_null_obj); + } else if (MP_OBJ_IS_OBJ(mp_obj)) { + res = get_native_obj(mp_obj); + if (res){ + const mp_obj_type_t *res_type = ((mp_obj_base_t*)res)->type; + if (res_type != mp_type){ + if (res_type == &mp_type_dict && + MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_type, make_new) == &make_new_lv_struct) + res = dict_to_struct(res, mp_type); + else res = NULL; + } + } + } + if (res == NULL) nlr_raise( + mp_obj_new_exception_msg_varg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Can't convert %s to %s!"), mp_obj_get_type_str(mp_obj), qstr_str(mp_type->name))); + return res; +} + +// object handling +// This section is enabled only when objects are supported + +#ifdef LV_OBJ_T + +typedef struct mp_lv_obj_t { + mp_obj_base_t base; + LV_OBJ_T *lv_obj; + LV_OBJ_T *callbacks; +} mp_lv_obj_t; + +static inline LV_OBJ_T *mp_to_lv(mp_obj_t mp_obj) +{ + if (mp_obj == NULL || mp_obj == mp_const_none) return NULL; + mp_obj_t native_obj = get_native_obj(mp_obj); + if (native_obj == MP_OBJ_NULL || + MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_obj_get_type(native_obj), buffer) != mp_lv_obj_get_buffer) { + nlr_raise( + mp_obj_new_exception_msg_varg( + &mp_type_SyntaxError, + MP_ERROR_TEXT("Can't convert %s to an LVGL object!"), + mp_obj_get_type_str(mp_obj))); + } + mp_lv_obj_t *mp_lv_obj = MP_OBJ_TO_PTR(native_obj); + if (mp_lv_obj->lv_obj == NULL) { + nlr_raise( + mp_obj_new_exception_msg( + &mp_type_LvReferenceError, MP_ERROR_TEXT("Referenced object was deleted!"))); + } + return mp_lv_obj->lv_obj; +} + +static inline LV_OBJ_T *mp_get_callbacks(mp_obj_t mp_obj) +{ + if (mp_obj == NULL || mp_obj == mp_const_none) return NULL; + mp_lv_obj_t *mp_lv_obj = MP_OBJ_TO_PTR(get_native_obj(mp_obj)); + if (mp_lv_obj == NULL) + nlr_raise( + mp_obj_new_exception_msg( + &mp_type_SyntaxError, MP_ERROR_TEXT("'user_data' argument must be either a dict or None!"))); + if (!mp_lv_obj->callbacks) mp_lv_obj->callbacks = mp_obj_new_dict(0); + return mp_lv_obj->callbacks; +} + +static inline const mp_obj_type_t *get_BaseObj_type(void); + +static void mp_lv_delete_cb(lv_event_t * e) +{ + LV_OBJ_T *lv_obj = e->current_target; + if (lv_obj){ + mp_lv_obj_t *self = lv_obj->user_data; + if (self) { + self->lv_obj = NULL; + } + } +} + +static inline mp_obj_t lv_to_mp(LV_OBJ_T *lv_obj) +{ + if (lv_obj == NULL) return mp_const_none; + mp_lv_obj_t *self = (mp_lv_obj_t*)lv_obj->user_data; + if (!self) + { + // Find the object type + const mp_obj_type_t *mp_obj_type = get_BaseObj_type(); + const lv_obj_class_t *lv_obj_class = lv_obj_get_class(lv_obj); + const mp_lv_obj_type_t **iter = &mp_lv_obj_types[0]; + for (; *iter; iter++) { + if ((*iter)->lv_obj_class == lv_obj_class) { + mp_obj_type = (*iter)->mp_obj_type; + break; + } + } + + // Create the MP object + self = m_new_obj(mp_lv_obj_t); + *self = (mp_lv_obj_t){ + .base = {(const mp_obj_type_t *)mp_obj_type}, + .lv_obj = lv_obj, + .callbacks = NULL, + }; + + // Register the Python object in user_data + lv_obj->user_data = self; + + // Register a "Delete" event callback + lv_obj_add_event_cb(lv_obj, mp_lv_delete_cb, LV_EVENT_DELETE, NULL); + } + return MP_OBJ_FROM_PTR(self); +} + +static void* mp_to_ptr(mp_obj_t self_in); + +static mp_obj_t cast_obj_type(const mp_obj_type_t* type, mp_obj_t obj) +{ + mp_lv_obj_t *self = m_new_obj(mp_lv_obj_t); + *self = (mp_lv_obj_t){ + .base = {type}, + .lv_obj = mp_to_ptr(obj), + .callbacks = NULL, + }; + if (!self->lv_obj) return mp_const_none; + return MP_OBJ_FROM_PTR(self); +} + +static mp_obj_t cast_obj(mp_obj_t type_obj, mp_obj_t obj) +{ + return cast_obj_type((const mp_obj_type_t *)type_obj, obj); +} + +static mp_obj_t make_new( + const mp_lv_obj_fun_builtin_var_t *lv_obj_var, + const mp_obj_type_t *type, + size_t n_args, + size_t n_kw, + const mp_obj_t *args) +{ + mp_obj_t lv_obj; + if (n_args == 0 && n_kw == 0) // allow no args, and pass NULL as parent in such case + { + const mp_obj_t no_args[] = {mp_const_none}; + lv_obj = mp_call_function_n_kw(MP_OBJ_FROM_PTR(lv_obj_var), 1, 0, no_args); + } + else + { + lv_obj = mp_call_function_n_kw(MP_OBJ_FROM_PTR(lv_obj_var), n_args, n_kw, args); + } + + if (!lv_obj) return mp_const_none; + + mp_lv_obj_t *self = MP_OBJ_TO_PTR(lv_obj); + if (self->base.type != type) + return cast_obj_type(type, lv_obj); + return lv_obj; +} + +static MP_DEFINE_CONST_FUN_OBJ_2(cast_obj_obj, cast_obj); +static MP_DEFINE_CONST_CLASSMETHOD_OBJ(cast_obj_class_method, MP_ROM_PTR(&cast_obj_obj)); + +static mp_int_t mp_lv_obj_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + (void)flags; + mp_lv_obj_t *self = MP_OBJ_TO_PTR(self_in); + + bufinfo->buf = &self->lv_obj; + bufinfo->len = sizeof(self->lv_obj); + bufinfo->typecode = BYTEARRAY_TYPECODE; + return 0; +} + +static mp_obj_t mp_lv_obj_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) +{ + mp_lv_obj_t *lhs = MP_OBJ_TO_PTR(lhs_in); + mp_lv_obj_t *rhs = MP_OBJ_TO_PTR(rhs_in); + switch (op) + { + case MP_BINARY_OP_EQUAL: + return mp_obj_new_bool(lhs->lv_obj == rhs->lv_obj); + case MP_BINARY_OP_NOT_EQUAL: + return mp_obj_new_bool(lhs->lv_obj != rhs->lv_obj); + default: + return MP_OBJ_NULL; + } +} + +// Register LVGL root pointers +MP_REGISTER_ROOT_POINTER(void *mp_lv_roots); +MP_REGISTER_ROOT_POINTER(void *mp_lv_user_data); +MP_REGISTER_ROOT_POINTER(int mp_lv_roots_initialized); +MP_REGISTER_ROOT_POINTER(int lvgl_mod_initialized); + +void *mp_lv_user_data; +int lvgl_mod_initialized = 0; + +/* LV_GLOBAL_CUSTOM() must use this — not a cached C global. GC moves the + * lv_global_t allocation and only updates MP_STATE_VM(mp_lv_roots). */ +void *mp_lv_get_roots(void) +{ + return MP_STATE_VM(mp_lv_roots); +} + +void mp_lv_init_gc(void) +{ + if (!MP_STATE_VM(mp_lv_roots_initialized)) { + // mp_printf(&mp_plat_print, "[ INIT GC ]"); + MP_STATE_VM(mp_lv_roots) = m_new0(lv_global_t, 1); + MP_STATE_VM(mp_lv_roots_initialized) = 1; + } +} + +void mp_lv_deinit_gc(void) +{ + + // mp_printf(&mp_plat_print, "[ DEINIT GC ]"); + MP_STATE_VM(mp_lv_roots) = NULL; + MP_STATE_VM(mp_lv_user_data) = NULL; + MP_STATE_VM(mp_lv_roots_initialized) = 0; + MP_STATE_VM(lvgl_mod_initialized) = 0; + lvgl_mod_initialized = 0; + +} + +#ifndef LV_CIRCUITPYTHON_BUILD +static mp_obj_t lvgl_mod_init(void) { + mp_lv_init_gc(); + if (!lv_is_initialized()) { + lv_init(); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(lvgl_mod_init_obj, lvgl_mod_init); + + +static mp_obj_t lvgl_mod_deinit(void) { + if (lv_is_initialized()) { + lv_deinit(); + } + mp_lv_deinit_gc(); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(lvgl_mod_deinit_obj, lvgl_mod_deinit); +#endif /* !LV_CIRCUITPYTHON_BUILD */ + +#else // LV_OBJ_T + +typedef struct mp_lv_obj_type_t { + mp_obj_type_t *mp_obj_type; +} mp_lv_obj_type_t; + +#endif + +static inline mp_obj_t convert_to_bool(bool b) +{ + return b? mp_const_true: mp_const_false; +} + +static inline mp_obj_t convert_to_str(const char *str) +{ + return str? mp_obj_new_str(str, strlen(str)): mp_const_none; +} + +static inline const char *convert_from_str(mp_obj_t str) +{ + if (str == NULL || str == mp_const_none) + return NULL; + + if (MP_OBJ_IS_TYPE(str, &mp_type_bytearray) || + MP_OBJ_IS_TYPE(str, &mp_type_memoryview)) { + mp_buffer_info_t buffer_info; + if (mp_get_buffer(str, &buffer_info, MP_BUFFER_READ)) { + return buffer_info.buf; + } + } + + return mp_obj_str_get_str(str); +} + +// struct handling + +static mp_lv_struct_t *mp_to_lv_struct(mp_obj_t mp_obj) +{ + if (mp_obj == NULL || mp_obj == mp_const_none) return NULL; + mp_obj_t native_obj = get_native_obj(mp_obj); + if ( (!MP_OBJ_IS_OBJ(native_obj)) || (MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_obj_get_type(native_obj), make_new) != &make_new_lv_struct) ) nlr_raise( + mp_obj_new_exception_msg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Expected Struct object!"))); + mp_lv_struct_t *mp_lv_struct = MP_OBJ_TO_PTR(native_obj); + return mp_lv_struct; +} + +static inline size_t get_lv_struct_size(const mp_obj_type_t *type) +{ + mp_obj_dict_t *self = MP_OBJ_TO_PTR(MP_OBJ_TYPE_GET_SLOT(type, locals_dict)); + mp_map_elem_t *elem = mp_map_lookup(&self->map, MP_OBJ_NEW_QSTR(MP_QSTR___SIZE__), MP_MAP_LOOKUP); + if (elem == NULL) { + return 0; + } else { + return (size_t)mp_obj_get_int(elem->value); + } +} + +static mp_obj_t make_new_lv_struct( + const mp_obj_type_t *type, + size_t n_args, + size_t n_kw, + const mp_obj_t *args) +{ + if ((!MP_OBJ_IS_TYPE(type, &mp_type_type)) || MP_OBJ_TYPE_GET_SLOT_OR_NULL(type, make_new) != &make_new_lv_struct) + nlr_raise( + mp_obj_new_exception_msg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Argument is not a struct type!"))); + size_t size = get_lv_struct_size(type); + mp_arg_check_num(n_args, n_kw, 0, 1, false); + mp_lv_struct_t *self = m_new_obj(mp_lv_struct_t); + mp_lv_struct_t *other = (n_args > 0) && (!mp_obj_is_int(args[0])) ? mp_to_lv_struct(cast(args[0], type)): NULL; + size_t count = (n_args > 0) && (mp_obj_is_int(args[0]))? mp_obj_get_int(args[0]): 1; + *self = (mp_lv_struct_t){ + .base = {type}, + .data = (size == 0 || (other && other->data == NULL))? NULL: m_malloc(size * count) + }; + if (self->data) { + if (other) { + memcpy(self->data, other->data, size * count); + } else { + memset(self->data, 0, size * count); + } + } + return MP_OBJ_FROM_PTR(self); +} + +static mp_obj_t lv_struct_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) +{ + mp_lv_struct_t *lhs = MP_OBJ_TO_PTR(lhs_in); + mp_lv_struct_t *rhs = MP_OBJ_TO_PTR(rhs_in); + switch (op) + { + case MP_BINARY_OP_EQUAL: + return mp_obj_new_bool(lhs->data == rhs->data); + case MP_BINARY_OP_NOT_EQUAL: + return mp_obj_new_bool(lhs->data != rhs->data); + default: + return MP_OBJ_NULL; + } +} + +static mp_obj_t lv_struct_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) +{ + mp_lv_struct_t *self = mp_to_lv_struct(self_in); + + if ((!self) || (!self->data)) + return NULL; + if (!mp_obj_is_int(index)) { + nlr_raise( + mp_obj_new_exception_msg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Subscript index must be an integer!"))); + } + + const mp_obj_type_t *type = mp_obj_get_type(self_in); + size_t element_size = get_lv_struct_size(type); + if (element_size == 0) return mp_const_none; + size_t element_index = mp_obj_get_int(index); + void *element_addr = (byte*)self->data + element_size*element_index; + + if (value == MP_OBJ_NULL) { + memset(element_addr, 0, element_size); + return self_in; + } + + mp_lv_struct_t *element_at_index = m_new_obj(mp_lv_struct_t); + *element_at_index = (mp_lv_struct_t){ + .base = {type}, + .data = element_addr + }; + + if (value != MP_OBJ_SENTINEL){ + mp_lv_struct_t *other = mp_to_lv_struct(cast(value, type)); + if ((!other) || (!other->data)) + return NULL; + memcpy(element_at_index->data, other->data, element_size); + } + + return MP_OBJ_FROM_PTR(element_at_index); +} + +GENMPY_UNUSED static void *copy_buffer(const void *buffer, size_t size) +{ + void *new_buffer = m_malloc(size); + memcpy(new_buffer, buffer, size); + return new_buffer; +} + +// Reference an existing lv struct (or part of it) + +static mp_obj_t lv_to_mp_struct(const mp_obj_type_t *type, void *lv_struct) +{ + if (lv_struct == NULL) return mp_const_none; + mp_lv_struct_t *self = m_new_obj(mp_lv_struct_t); + *self = (mp_lv_struct_t){ + .base = {type}, + .data = lv_struct + }; + return MP_OBJ_FROM_PTR(self); +} + +static void call_parent_methods(mp_obj_t obj, qstr attr, mp_obj_t *dest) +{ + const mp_obj_type_t *type = mp_obj_get_type(obj); + while (MP_OBJ_TYPE_HAS_SLOT(type, locals_dict)) { + // generic method lookup + // this is a lookup in the object (ie not class or type) + assert(MP_OBJ_TYPE_GET_SLOT(type, locals_dict)->base.type == &mp_type_dict); // MicroPython restriction, for now + mp_map_t *locals_map = &MP_OBJ_TYPE_GET_SLOT(type, locals_dict)->map; + mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(attr), MP_MAP_LOOKUP); + if (elem != NULL) { + mp_convert_member_lookup(obj, type, elem->value, dest); + break; + } + if (MP_OBJ_TYPE_GET_SLOT_OR_NULL(type, parent) == NULL) { + break; + } + // search parents + type = MP_OBJ_TYPE_GET_SLOT(type, parent); + } +} + +// Convert dict to struct + +static mp_obj_t dict_to_struct(mp_obj_t dict, const mp_obj_type_t *type) +{ + mp_obj_t mp_struct = make_new_lv_struct(type, 0, 0, NULL); + mp_obj_t native_dict = cast(dict, &mp_type_dict); + mp_map_t *map = mp_obj_dict_get_map(native_dict); + if (map == NULL) return mp_const_none; + for (uint i = 0; i < map->alloc; i++) { + mp_obj_t key = map->table[i].key; + mp_obj_t value = map->table[i].value; + if (key != MP_OBJ_NULL) { + mp_obj_t dest[] = {MP_OBJ_SENTINEL, value}; + MP_OBJ_TYPE_GET_SLOT(type, attr)(mp_struct, mp_obj_str_get_qstr(key), dest); + if (dest[0]) nlr_raise( + mp_obj_new_exception_msg_varg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Cannot set field %s on struct %s!"), qstr_str(mp_obj_str_get_qstr(key)), qstr_str(type->name))); + } + } + return mp_struct; +} + +// Convert mp object to ptr + +static void* mp_to_ptr(mp_obj_t self_in) +{ + mp_buffer_info_t buffer_info; + if (self_in == NULL || self_in == mp_const_none) + return NULL; + +// if (MP_OBJ_IS_INT(self_in)) +// return (void*)mp_obj_get_int(self_in); + + // If an object is user instance, take it as is so it could be used as user_data + if (mp_obj_is_instance_type(mp_obj_get_type(self_in))){ + return MP_OBJ_TO_PTR(self_in); + } + + if (!mp_get_buffer(self_in, &buffer_info, MP_BUFFER_READ)) { + // No buffer protocol - this is not a Struct or a Blob, it's some other mp object. + // We only allow setting dict directly, since it's useful to setting user_data for passing data to C. + // On other cases throw an exception, to avoid a crash later + if (MP_OBJ_IS_TYPE(self_in, &mp_type_dict)) + return MP_OBJ_TO_PTR(self_in); + else nlr_raise( + mp_obj_new_exception_msg_varg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Cannot convert '%s' to pointer!"), mp_obj_get_type_str(self_in))); + } + + if (MP_OBJ_IS_STR_OR_BYTES(self_in) || + MP_OBJ_IS_TYPE(self_in, &mp_type_bytearray) || + MP_OBJ_IS_TYPE(self_in, &mp_type_memoryview)) + return buffer_info.buf; + else + { + void *result; + if (buffer_info.len != sizeof(result) || buffer_info.typecode != BYTEARRAY_TYPECODE){ + nlr_raise( + mp_obj_new_exception_msg_varg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Cannot convert %s to pointer! (buffer does not represent a pointer)"), mp_obj_get_type_str(self_in))); + } + memcpy(&result, buffer_info.buf, sizeof(result)); + return result; + } +} + +// Blob is a wrapper for void* + +static void mp_blob_print(const mp_print_t *print, + mp_obj_t self_in, + mp_print_kind_t kind) +{ + mp_printf(print, "Blob"); +} + +static mp_int_t mp_blob_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + (void)flags; + mp_lv_struct_t *self = MP_OBJ_TO_PTR(self_in); + + bufinfo->buf = &self->data; + bufinfo->len = sizeof(self->data); + bufinfo->typecode = BYTEARRAY_TYPECODE; + return 0; +} + +static const mp_obj_fun_builtin_var_t mp_lv_dereference_obj; + +// Sometimes (but not always!) Blob represents a Micropython object. +// In such cases it's safe to cast the Blob back to the Micropython object +// cast argument is the underlying object type, and it's optional. + +static mp_obj_t mp_blob_cast(size_t argc, const mp_obj_t *argv) +{ + mp_obj_t self = argv[0]; + void *ptr = mp_to_ptr(self); + if (argc == 1) return MP_OBJ_FROM_PTR(ptr); + mp_obj_t type = argv[1]; + if (!MP_OBJ_IS_TYPE(type, &mp_type_type)) + nlr_raise( + mp_obj_new_exception_msg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Cast argument must be a type!"))); + return cast(MP_OBJ_FROM_PTR(ptr), type); +} + +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_blob_cast_obj, 1, 2, mp_blob_cast); + +static const mp_rom_map_elem_t mp_blob_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___dereference__), MP_ROM_PTR(&mp_lv_dereference_obj) }, + { MP_ROM_QSTR(MP_QSTR___cast__), MP_ROM_PTR(&mp_blob_cast_obj) }, +}; + +static MP_DEFINE_CONST_DICT(mp_blob_locals_dict, mp_blob_locals_dict_table); + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_blob_type, + MP_QSTR_Blob, + MP_TYPE_FLAG_NONE, + binary_op, lv_struct_binary_op, + print, mp_blob_print, + locals_dict, &mp_blob_locals_dict, + buffer, mp_blob_get_buffer +); + +static const mp_lv_struct_t mp_lv_null_obj = { {&mp_blob_type}, NULL }; + +static inline mp_obj_t ptr_to_mp(void *data) +{ + return lv_to_mp_struct(&mp_blob_type, data); +} + +// Cast pointer to struct + +static mp_obj_t mp_lv_cast(mp_obj_t type_obj, mp_obj_t ptr_obj) +{ + void *ptr = mp_to_ptr(ptr_obj); + if (!ptr) return mp_const_none; + mp_lv_struct_t *self = m_new_obj(mp_lv_struct_t); + *self = (mp_lv_struct_t){ + .base = {(const mp_obj_type_t*)type_obj}, + .data = ptr + }; + return MP_OBJ_FROM_PTR(self); +} + +// Cast instance. Can be used in ISR when memory allocation is prohibited + +static inline mp_obj_t mp_lv_cast_instance(mp_obj_t self_in, mp_obj_t ptr_obj) +{ + mp_lv_struct_t *self = MP_OBJ_TO_PTR(self_in); + self->data = mp_to_ptr(ptr_obj); + return self_in; +} + +static MP_DEFINE_CONST_FUN_OBJ_2(mp_lv_cast_obj, mp_lv_cast); +static MP_DEFINE_CONST_CLASSMETHOD_OBJ(mp_lv_cast_class_method, MP_ROM_PTR(&mp_lv_cast_obj)); + +static MP_DEFINE_CONST_FUN_OBJ_2(mp_lv_cast_instance_obj, mp_lv_cast_instance); + +// Dereference a struct/blob. This allows access to the raw data the struct holds + +static mp_obj_t mp_lv_dereference(size_t argc, const mp_obj_t *argv) +{ + mp_obj_t self_in = argv[0]; + mp_obj_t size_in = argc > 1? argv[1]: mp_const_none; + mp_lv_struct_t *self = MP_OBJ_TO_PTR(self_in); + size_t size = 0; + if (size_in == mp_const_none){ + const mp_obj_type_t *type = self->base.type; + size = get_lv_struct_size(type); + } else { + size = (size_t)mp_obj_get_int(size_in); + } + if (size == 0) return mp_const_none; + mp_obj_array_t *view = MP_OBJ_TO_PTR(mp_obj_new_memoryview(BYTEARRAY_TYPECODE, + size, self->data)); + view->typecode |= 0x80; // used to indicate writable buffer + return MP_OBJ_FROM_PTR(view); +} + +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_lv_dereference_obj, 1, 2, mp_lv_dereference); + +// Callback function handling +// Callback is either a callable object or a pointer. If it's a callable object, set user_data to the callback. +// Multiple callbacks are kept per object/struct using a dict that associate callback name with callback object +// In case of an lv_obj_t, user_data is mp_lv_obj_t which contains a member "callbacks" for that dict. +// In case of a struct, user_data is a pointer to that dict directly + +static mp_obj_t get_callback_dict_from_user_data(void *user_data) +{ + if (user_data){ + mp_obj_t obj = MP_OBJ_FROM_PTR(user_data); +#ifdef LV_OBJ_T + return + MP_OBJ_IS_TYPE(obj, &mp_type_dict)? obj: // Handle the case of dict for a struct + mp_get_callbacks(obj); // Handle the case of mp_lv_obj_t for an lv_obj_t +#else + return obj; +#endif + } + return NULL; +} + +typedef void *(*mp_lv_get_user_data)(void *); +typedef void (*mp_lv_set_user_data)(void *, void *); + +static void *mp_lv_callback(mp_obj_t mp_callback, void *lv_callback, qstr callback_name, + void **user_data_ptr, void *containing_struct, mp_lv_get_user_data get_user_data, mp_lv_set_user_data set_user_data) +{ + if (lv_callback && mp_obj_is_callable(mp_callback)) { + void *user_data = NULL; + if (user_data_ptr) { + // user_data is either a dict of callbacks in case of struct, or a pointer to mp_lv_obj_t in case of lv_obj_t + if (! (*user_data_ptr) ) *user_data_ptr = MP_OBJ_TO_PTR(mp_obj_new_dict(0)); // if it's NULL - it's a dict for a struct + user_data = *user_data_ptr; + } + else if (get_user_data && set_user_data) { + user_data = get_user_data(containing_struct); + if (!user_data) { + user_data = MP_OBJ_TO_PTR(mp_obj_new_dict(0)); + set_user_data(containing_struct, user_data); + } + } + + if (user_data) { + mp_obj_t callbacks = get_callback_dict_from_user_data(user_data); + mp_obj_dict_store(callbacks, MP_OBJ_NEW_QSTR(callback_name), mp_callback); + } + return lv_callback; + } else { + return mp_to_ptr(mp_callback); + } +} + +static int _nesting = 0; + +// Call a Python callback from LVGL C code without ever unwinding through +// the C frames that invoked it. A raising callback used to nlr-unwind past +// both the `_nesting--` (leaving the counter stuck nonzero, which silently +// disables every consumer gating on `lv._nesting.value == 0` until a hard +// reset, C statics surviving soft reset) and LVGL's own re-entrancy state +// (lv_timer_handler's already-running flag), which wedged timer handling +// even with the counter balanced. So: report the exception here and return +// a benign result (0 lowers safely to void/int/bool/enum/pointer returns); +// LVGL's C state stays consistent and the next callback runs normally. +static mp_obj_t mp_lv_nesting_call(mp_obj_t func, size_t n_args, const mp_obj_t *args) +{ + nlr_buf_t nlr; + mp_obj_t result; + _nesting++; + if (nlr_push(&nlr) == 0) { + result = mp_call_function_n_kw(func, n_args, 0, args); + nlr_pop(); + } else { + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + result = MP_OBJ_NEW_SMALL_INT(0); + } + _nesting--; + return result; +} + +// How many Python callbacks LVGL is inside right now. The MicroPython port's +// assert handler reads it: at zero, an exception raised from a failed LVGL +// assert unwinds out of every LVGL frame, so the handler first clears the +// state LVGL holds for the length of a pass; above zero, the callback's own +// nlr frame catches it and LVGL carries on, so that state must stay. +int mp_lv_nesting_depth(void); +int mp_lv_nesting_depth(void) +{ + return _nesting; +} + +// Function pointers wrapper + +static mp_obj_t mp_lv_funcptr(const mp_lv_obj_fun_builtin_var_t *mp_fun, void *lv_fun, void *lv_callback, qstr func_name, void *user_data) +{ + if (lv_fun == NULL) + return mp_const_none; + if (lv_fun == lv_callback) { + mp_obj_t callbacks = get_callback_dict_from_user_data(user_data); + if (callbacks) + return mp_obj_dict_get(callbacks, MP_OBJ_NEW_QSTR(func_name)); + } + mp_lv_obj_fun_builtin_var_t *funcptr = m_new_obj(mp_lv_obj_fun_builtin_var_t); + *funcptr = *mp_fun; + funcptr->lv_fun = lv_fun; + return MP_OBJ_FROM_PTR(funcptr); +} + +// Missing implementation for 64bit integer conversion + +static unsigned long long mp_obj_get_ull(mp_obj_t obj) +{ + if (mp_obj_is_small_int(obj)) + return MP_OBJ_SMALL_INT_VALUE(obj); + + unsigned long long val = 0; + bool big_endian = !(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__); + __MP_OBJ_GET_ULL_TO_BYTES__ + return val; +} + + +// Array of natives + +typedef struct mp_lv_array_t +{ + mp_lv_struct_t base; + size_t element_size; + bool is_signed; +} mp_lv_array_t; + +static void mp_lv_array_print(const mp_print_t *print, + mp_obj_t self_in, + mp_print_kind_t kind) +{ + mp_lv_array_t *self = MP_OBJ_TO_PTR(self_in); + size_t element_size = self->element_size; + bool is_signed = self->is_signed; + mp_printf(print, "C Array (%sint%d[])", is_signed? "": "u", element_size*8); +} + +static mp_obj_t lv_array_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) +{ + mp_lv_array_t *self = MP_OBJ_TO_PTR(self_in); + + if ((!self) || (!self->base.data)) + return NULL; + if (!mp_obj_is_int(index)) { + nlr_raise( + mp_obj_new_exception_msg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Subscript index must be an integer!"))); + } + + size_t element_size = self->element_size; + size_t element_index = mp_obj_get_int(index); + void *element_addr = (byte*)self->base.data + element_size*element_index; + bool is_signed = self->is_signed; + union { + long long val; + unsigned long long uval; + } element; + memset(&element, 0, sizeof(element)); + + if (value == MP_OBJ_NULL){ + memset(element_addr, 0, element_size); + } + else if (value == MP_OBJ_SENTINEL){ + memcpy(&element, element_addr, element_size); + return is_signed? mp_obj_new_int_from_ll(element.val): mp_obj_new_int_from_ull(element.uval); + } else { + if (!mp_obj_is_int(value)) { + nlr_raise( + mp_obj_new_exception_msg_varg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Value '%s' must be an integer!"), mp_obj_get_type_str(value))); + } + element.uval = mp_obj_get_ull(value); + memcpy(element_addr, &element, element_size); + } + + return self_in; +} + +static const mp_rom_map_elem_t mp_base_struct_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___cast__), MP_ROM_PTR(&mp_lv_cast_class_method) }, + { MP_ROM_QSTR(MP_QSTR___cast_instance__), MP_ROM_PTR(&mp_lv_cast_instance_obj) }, + { MP_ROM_QSTR(MP_QSTR___dereference__), MP_ROM_PTR(&mp_lv_dereference_obj) }, +}; + +static MP_DEFINE_CONST_DICT(mp_base_struct_locals_dict, mp_base_struct_locals_dict_table); + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_lv_base_struct_type, + MP_QSTR_Struct, + MP_TYPE_FLAG_NONE, + binary_op, lv_struct_binary_op, + subscr, lv_struct_subscr, + buffer, mp_blob_get_buffer, + locals_dict, &mp_base_struct_locals_dict +); + +// TODO: provide constructor +static MP_DEFINE_CONST_OBJ_TYPE( + mp_lv_array_type, + MP_QSTR_C_Array, + MP_TYPE_FLAG_NONE, + print, mp_lv_array_print, + binary_op, lv_struct_binary_op, + subscr, lv_array_subscr, + buffer, mp_blob_get_buffer, + locals_dict, &mp_base_struct_locals_dict +); + +/* + * Fixed-size struct arrays inside a struct (lv_point_precise_t p[3]). + * + * Reading the field gives a view over the parent struct's memory, so + * d.p[1].x = 7 and d.p[1] = point write through, and len(d.p) works. The view + * holds the parent so the memory stays alive. Assigning the field takes a + * sequence of exactly that many structs (or dicts), or a packed buffer of the + * array's size; anything else raises and leaves the field unchanged + * (lvgl-bindings#38). + */ + +typedef struct { + mp_obj_base_t base; + mp_obj_t owner; + char *data; + size_t len; + size_t elem_size; + mp_obj_t (*read)(void *elem); + void *(*write)(mp_obj_t value); +} mp_lv_struct_array_t; + +static mp_obj_t lv_struct_array_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) +{ + mp_lv_struct_array_t *self = MP_OBJ_TO_PTR(self_in); + if (value == MP_OBJ_NULL) { + mp_raise_TypeError(MP_ERROR_TEXT("can't delete struct array items")); + } + size_t i = mp_get_index(self->base.type, self->len, index, false); + char *elem = self->data + i * self->elem_size; + if (value == MP_OBJ_SENTINEL) { + return self->read(elem); + } + memcpy(elem, self->write(value), self->elem_size); + return mp_const_none; +} + +static mp_obj_t lv_struct_array_unary_op(mp_unary_op_t op, mp_obj_t self_in) +{ + mp_lv_struct_array_t *self = MP_OBJ_TO_PTR(self_in); + switch (op) { + case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len); + case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0); + default: return MP_OBJ_NULL; + } +} + +// Iterates views of the elements, the same objects indexing returns. +static mp_obj_t lv_struct_array_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) +{ + mp_lv_struct_array_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_t items = mp_obj_new_tuple(self->len, NULL); + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(items); + for (size_t i = 0; i < self->len; i++) { + t->items[i] = self->read(self->data + i * self->elem_size); + } + return mp_getiter(items, iter_buf); +} + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_lv_struct_array_type, + MP_QSTR_StructArray, + MP_TYPE_FLAG_ITER_IS_GETITER, + unary_op, lv_struct_array_unary_op, + subscr, lv_struct_array_subscr, + iter, lv_struct_array_getiter +); + +GENMPY_UNUSED static mp_obj_t mp_lv_struct_array_new(mp_obj_t owner, void *data, + size_t len, size_t elem_size, mp_obj_t (*read)(void *), void *(*write)(mp_obj_t)) +{ + mp_lv_struct_array_t *self = m_new_obj(mp_lv_struct_array_t); + self->base.type = &mp_lv_struct_array_type; + self->owner = owner; + self->data = (char *)data; + self->len = len; + self->elem_size = elem_size; + self->read = read; + self->write = write; + return MP_OBJ_FROM_PTR(self); +} + +GENMPY_UNUSED static void mp_lv_struct_array_assign(void *data, size_t len, + size_t elem_size, void *(*write)(mp_obj_t), mp_obj_t value) +{ + if (MP_OBJ_IS_STR_OR_BYTES(value) || + MP_OBJ_IS_TYPE(value, &mp_type_bytearray) || + MP_OBJ_IS_TYPE(value, &mp_type_memoryview)) { + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(value, &bufinfo, MP_BUFFER_READ); + if (bufinfo.len != len * elem_size) { + mp_raise_msg_varg(&mp_type_ValueError, + MP_ERROR_TEXT("expected a buffer of %d bytes, got %d"), + (int)(len * elem_size), (int)bufinfo.len); + } + memcpy(data, bufinfo.buf, bufinfo.len); + return; + } + mp_obj_t mp_len = mp_obj_len_maybe(value); + if (mp_len == MP_OBJ_NULL) { + mp_raise_msg_varg(&mp_type_TypeError, + MP_ERROR_TEXT("expected a sequence of %d structs, got '%s'"), + (int)len, mp_obj_get_type_str(value)); + } + if ((size_t)mp_obj_get_int(mp_len) != len) { + mp_raise_msg_varg(&mp_type_ValueError, + MP_ERROR_TEXT("expected %d items, got %d"), + (int)len, (int)mp_obj_get_int(mp_len)); + } + // Convert every item before writing any, so a bad item changes nothing. + char *tmp = m_new(char, len * elem_size); + for (size_t i = 0; i < len; i++) { + mp_obj_t item = mp_obj_subscr(value, MP_OBJ_NEW_SMALL_INT(i), MP_OBJ_SENTINEL); + memcpy(tmp + i * elem_size, write(item), elem_size); + } + memcpy(data, tmp, len * elem_size); + m_del(char, tmp, len * elem_size); +} + +GENMPY_UNUSED static mp_obj_t mp_array_from_ptr(void *lv_arr, size_t element_size, bool is_signed) +{ + mp_lv_array_t *self = m_new_obj(mp_lv_array_t); + *self = (mp_lv_array_t){ + { {&mp_lv_array_type}, lv_arr }, + element_size, + is_signed + }; + return MP_OBJ_FROM_PTR(self); +} + +GENMPY_UNUSED static void *mp_array_to_ptr(mp_obj_t *mp_arr, size_t element_size, GENMPY_UNUSED bool is_signed) +{ + if (MP_OBJ_IS_STR_OR_BYTES(mp_arr) || + MP_OBJ_IS_TYPE(mp_arr, &mp_type_bytearray) || + MP_OBJ_IS_TYPE(mp_arr, &mp_type_memoryview)){ + return mp_to_ptr(mp_arr); + } + + mp_obj_t mp_len = mp_obj_len_maybe(mp_arr); + if (mp_len == MP_OBJ_NULL) return mp_to_ptr(mp_arr); + mp_int_t len = mp_obj_get_int(mp_len); + void *lv_arr = m_malloc(len * element_size); + byte *element_addr = (byte*)lv_arr; + mp_obj_t iter = mp_getiter(mp_arr, NULL); + mp_obj_t item; + while ((item = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) { + union { + long long val; + unsigned long long uval; + } element; + if (!mp_obj_is_int(item)) { + nlr_raise( + mp_obj_new_exception_msg_varg( + &mp_type_SyntaxError, MP_ERROR_TEXT("Value '%s' must be an integer!"), mp_obj_get_type_str(item))); + } + element.uval = mp_obj_get_ull(item); + memcpy(element_addr, &element, element_size); + element_addr += element_size; + } + return lv_arr; +} + +#define MP_ARRAY_CONVERTOR(name, size, is_signed) \ +GENMPY_UNUSED static mp_obj_t mp_array_from_ ## name(void *lv_arr)\ +{\ + return mp_array_from_ptr(lv_arr, size, is_signed);\ +}\ +GENMPY_UNUSED static void *mp_array_to_ ## name(mp_obj_t mp_arr)\ +{\ + return mp_array_to_ptr(mp_arr, size, is_signed);\ +} + +MP_ARRAY_CONVERTOR(u8ptr, 1, false) +MP_ARRAY_CONVERTOR(i8ptr, 1, true) +MP_ARRAY_CONVERTOR(u16ptr, 2, false) +MP_ARRAY_CONVERTOR(i16ptr, 2, true) +MP_ARRAY_CONVERTOR(u32ptr, 4, false) +MP_ARRAY_CONVERTOR(i32ptr, 4, true) +MP_ARRAY_CONVERTOR(u64ptr, 8, false) +MP_ARRAY_CONVERTOR(i64ptr, 8, true) + +""" + .replace("__MP_OBJ_GET_ULL_TO_BYTES__", _mp_obj_get_ull_to_bytes) + ) + + # + # Add regular enums with integer values + # + + enums = collections.OrderedDict() + for enum_def in enum_defs: + # Skip stdatomic.h memory_order, no bindings needed. + if isinstance(enum_def, c_ast.TypeDecl) and enum_def.declname == "memory_order": + continue + + # eprint("--> %s" % enum_def) + while hasattr(enum_def.type, "name") and not enum_def.type.values: + enum_def = next( + e + for e in enum_defs + if hasattr(e.type, "name") + and e.type.name == enum_def.type.name + and e.type.values + ) + member_names = [ + member.name + for member in enum_def.type.values.enumerators + if not member.name.startswith("_") + ] + enum_name = commonprefix(member_names) + enum_name = "_".join(enum_name.split("_")[:-1]) # remove suffix + enum = collections.OrderedDict() + for member in enum_def.type.values.enumerators: + if member.name.startswith("_"): + continue + member_name = ( + member.name[len(enum_name) + 1 :] if len(enum_name) > 0 else member.name + ) + if member_name[0].isdigit(): + member_name = "_" + member_name + if len(enum_name) > 0 and get_enum_name(enum_name) != "ENUM": + enum[member_name] = "MP_ROM_INT(%s)" % member.name + else: + int_constants.append(member.name) + if len(enum) > 0: + if len(get_enum_name(enum_name)) > 0: + prev_enum = enums.get(enum_name) + if prev_enum: + prev_enum.update(enum) + else: + enums[enum_name] = enum + + for enum in [ + enum for enum in enums if len(enums[enum]) == 1 and enum.startswith("ENUM") + ]: + int_constants.append("%s_%s" % (enum, next(iter(enums[enum])))) + del enums[enum] + + # Add special string enums + + print( + """ +/* + * LVGL string constants + */ +""" + ) + + for enum_def in enum_defs: + if not enum_def.type.values: + continue + member_names = [ + str_enum_to_str(member.name) + for member in enum_def.type.values.enumerators + if lv_str_enum_pattern.match(member.name) + ] + enum_name = commonprefix(member_names) + enum_name = "_".join(enum_name.split("_")[:-1]) # remove suffix + enum = collections.OrderedDict() + if enum_name: + for member in enum_def.type.values.enumerators: + full_name = str_enum_to_str(member.name) + member_name = full_name[len(enum_name) + 1 :] + print("MP_DEFINE_STR_OBJ(mp_%s, %s);" % (full_name, full_name)) + enum[member_name] = "&mp_%s" % full_name + if len(enum) > 0: + if enum_name in enums: + enums[enum_name].update(enum) + else: + enums[enum_name] = enum + + + # eprint('--> enums: \n%s' % enums) + + runtime.set_("enums", enums) + + # eprint(',\n'.join(sorted('%s : %s' % (name, get_type(blobs[name])) for name in blobs))) + + # + # Callbacks helper functions + # + + + def decl_to_callback(decl): + # print('/* decl_to_callback %s */' % decl) + if not hasattr(decl, "type"): + return None + if isinstance(decl.type, c_ast.PtrDecl) and isinstance( + decl.type.type, c_ast.FuncDecl + ): + return (decl.name, decl.type.type) + # print('/* callback: ADDED CALLBACK: %s\n%s */' % (gen.visit(decl.type.type), decl.type.type)) + elif isinstance(decl.type, c_ast.FuncDecl): + return (decl.name, decl.type) + # print('/* callback: ADDED CALLBACK: %s\n%s */' % (gen.visit(decl.type.type), decl.type.type)) + elif isinstance(decl.type, c_ast.TypeDecl) and hasattr(decl.type.type, "names"): + func_typedef_name = decl.type.type.names[0] + while func_typedef_name in synonym: + # eprint('decl_to_callback: %s --> %s' % (func_typedef_name, synonym[func_typedef_name])) + func_typedef_name = synonym[func_typedef_name] + # print('/* --> callback: TYPEDEF CALLBACK: %s: %s */' % (decl.name if hasattr(decl, 'name') else None, func_typedef_name)) + if func_typedef_name in func_typedefs: + return (decl.name, func_typedefs[func_typedef_name].type.type) + # print('/* callback: ADDED CALLBACK: %s\n%s */' % (func_typedef_name, func_typedefs[func_typedef_name])) + else: + return None + + + def get_user_data_accessors(containing_struct, containing_struct_name=None): + if not containing_struct_name and containing_struct and containing_struct.name: + containing_struct_name = containing_struct.name + if not containing_struct_name: + return None, None + base_struct_name = get_base_struct_name(containing_struct_name) + getter_name = base_struct_name + "_get_user_data" + setter_name = base_struct_name + "_set_user_data" + # print('/* struct functions = %s */' % [s.name + ':' + str(len(s.type.args.params)) for s in get_struct_functions(containing_struct_name)]) + # print('/* getter_name = %s */' % getter_name) + struct_functions = get_struct_functions(containing_struct_name) + getters = [ + s + for s in struct_functions + if s.name == getter_name and len(s.type.args.params) == 1 + ] + setters = [ + s + for s in struct_functions + if s.name == setter_name and len(s.type.args.params) == 2 + ] + if getters and setters: + return getters[0], setters[0] + else: + return None, None + + + def get_user_data( + func, func_name=None, containing_struct=None, containing_struct_name=None + ): + args = func.args.params + if not func_name: + func_name = get_arg_name(func.type) + # print('/* --> callback: func_name = %s, args = %s */' % (func_name, repr(args))) + user_data_found = False + user_data = "None" + if len(args) > 0 and isinstance(args[0].type, c_ast.PtrDecl): + # if isinstance(args[0].type.type.type, c_ast.Struct): + # struct_arg_type_name = args[0].type.type.type.name # PtrDecl.TypeDecl.Struct. Needed to omit 'struct' keyword. + # else: + # struct_arg_type_name = get_type(args[0].type.type, remove_quals = True) + struct_arg_type_name = get_type(args[0].type.type, remove_quals=True) + # print('/* --> get_user_data: containing_struct_name = %s, struct_arg_type_name = %s */' % (containing_struct_name, struct_arg_type_name)) + if containing_struct_name and struct_arg_type_name != containing_struct_name: + return None, None, None + if not containing_struct: + try_generate_type(args[0].type) + if struct_arg_type_name in structs: + containing_struct = structs[struct_arg_type_name] + # print('/* --> containing_struct = %s */' % containing_struct) + # if struct_arg_type_name in mp_to_lv: + # print('/* --> callback: %s First argument is %s */' % (gen.visit(func), struct_arg_type_name)) + if containing_struct: + flatten_struct_decls = flatten_struct(containing_struct.decls) + user_data = "user_data" + user_data_found = user_data in [decl.name for decl in flatten_struct_decls] + # print('/* --> callback: user_data=%s user_data_found=%s containing_struct=%s */' % (user_data, user_data_found, containing_struct)) + if not user_data_found and lvgl_json is not None: + containing_struct_j = next( + ( + struct + for struct in lvgl_json["structures"] + if struct["name"] == struct_arg_type_name + ), + None, + ) + if ( + containing_struct_j is None + and struct_arg_type_name.startswith("lv_") + and None + is not next( + ( + fwd_decl + for fwd_decl in lvgl_json["forward_decls"] + if fwd_decl["name"] == struct_arg_type_name + ), + None, + ) + ): + struct_arg_type_name_with_underscore = "_" + struct_arg_type_name + containing_struct_j = next( + ( + struct + for struct in lvgl_json["structures"] + if struct["name"] == struct_arg_type_name_with_underscore + ), + None, + ) + if containing_struct_j is not None: + user_data_found = any( + user_data == field["name"] + for field in containing_struct_j["fields"] + ) + return (user_data if user_data_found else None), *get_user_data_accessors( + containing_struct, containing_struct_name + ) + + + # + # Generate structs when needed + # + + generated_structs = collections.OrderedDict() + generated_struct_functions = collections.OrderedDict() + struct_aliases = collections.OrderedDict() + callbacks_used_on_structs = [] + + + def flatten_struct(struct_decls): + result = [] + if not struct_decls: + return result + for decl in struct_decls: + if is_struct(decl.type): + result.extend(flatten_struct(decl.type.decls)) + else: + result.append(decl) + return result + + + def _struct_array_elem_rw(decl): + """(reader, writer) by pointer for a struct-element array field, else None.""" + elem_ast = decl.type.type + if not isinstance(elem_ast, c_ast.TypeDecl): + return None + ptr_type = "%s *" % get_type(elem_ast, remove_quals=True) + read = lv_to_mp.get(ptr_type) or "" + write = mp_to_lv.get(ptr_type) or "" + if read.startswith("mp_read_ptr_") and write.startswith("mp_write_ptr_"): + return read, write + return None + + def try_generate_struct(struct_name, struct): + if struct_name in generated_structs: + return None + sanitized_struct_name = sanitize(struct_name) + generated_structs[struct_name] = False # Starting generating a struct + # print("/* Starting generating %s */" % struct_name) + if struct_name in mp_to_lv: + return mp_to_lv[struct_name] + # print('/* --> try_generate_struct %s: %s\n%s */' % (struct_name, gen.visit(struct), struct)) + if struct.decls is None: + if struct_name == struct.name: + return None + if struct.name not in structs: + return None + return try_generate_type(structs[struct.name]) + flatten_struct_decls = flatten_struct(struct.decls) + # Go over fields and try to generate type convertors for each + # print('!! %s' % struct) + # print('!!! %s' % flatten_struct_decls) + write_cases = [] + read_cases = [] + for decl in flatten_struct_decls: + # print('/* ==> decl %s: %s */' % (gen.visit(decl), decl)) + converted = try_generate_type(decl.type) + type_name = get_type(decl.type, remove_quals=True) + # print('/* --> %s: %s (%s)*/' % (decl.name, type_name, mp_to_lv[type_name] if type_name in mp_to_lv else '---')) + # Handle the case of nested struct + if not converted and is_struct(decl.type.type): + parent_name = struct_name + child_name = decl.type.declname + type_name = "%s_%s_t" % (parent_name[:-2], child_name) + print( + "typedef __typeof__( (({parent}*)(0))->{child} ) {new_struct};".format( + parent=parent_name, child=child_name, new_struct=type_name + ) + ) + try_generate_struct(type_name, decl.type.type) + + # print('==> %s %s: %s' % (type_name, str(type_name in mp_to_lv), decl)) + + if (type_name not in mp_to_lv or not mp_to_lv[type_name]) or ( + type_name not in lv_to_mp or not lv_to_mp[type_name] + ): + # eprint("[%s] %s or %s : %s" % (isinstance(decl.type,c_ast.PtrDecl), type_name, get_type(decl.type), decl.type)) + if type_name in generated_structs: + print( + "/* Already started generating %s! skipping field '%s' */" + % (type_name, decl.name) + ) + continue + raise MissingConversionException( + "Missing conversion to %s when generating struct %s.%s" + % (type_name, struct_name, get_name(decl)) + ) + + mp_to_lv_convertor = mp_to_lv[type_name] + lv_to_mp_convertor = ( + lv_to_mp_byref[type_name] + if type_name in lv_to_mp_byref + else lv_to_mp[type_name] + ) + + cast = ( + "(void*)" if isinstance(decl.type, c_ast.PtrDecl) else "" + ) # needed when field is const. casting to void overrides it + + callback = decl_to_callback(decl) + + if callback: + if _emit_max_phase is not None and _emit_max_phase < 7: + continue + # print("/* %s callback %s */" % (gen.visit(decl), callback)) + func_name, arg_type = callback + user_data, _, _ = get_user_data( + arg_type, + func_name=func_name, + containing_struct=struct, + containing_struct_name=struct_name, + ) + if callback not in callbacks_used_on_structs: + callbacks_used_on_structs.append(callback + (struct_name,)) + # Emit callback forward decl. + if user_data in [ + user_data_decl.name for user_data_decl in flatten_struct_decls + ]: + full_user_data = "data->%s" % user_data + full_user_data_ptr = "&%s" % full_user_data + lv_callback = "%s_%s_callback" % (struct_name, func_name) + print( + "static %s %s_%s_callback(%s);" + % ( + get_type(arg_type.type, remove_quals=False), + struct_name, + func_name, + gen.visit(arg_type.args), + ) + ) + else: + full_user_data = "NULL" + full_user_data_ptr = full_user_data + lv_callback = "NULL" + if not user_data: + gen_func_error( + decl, + "Missing 'user_data' as a field of the first parameter of the callback function '%s_%s_callback'" + % (struct_name, func_name), + ) + else: + gen_func_error( + decl, "Missing 'user_data' member in struct '%s'" % struct_name + ) + write_cases.append( + "case MP_QSTR_{field}: data->{decl_name} = {cast}mp_lv_callback(dest[1], {lv_callback} ,MP_QSTR_{struct_name}_{field}, {user_data}, NULL, NULL, NULL); break; // converting to callback {type_name}".format( + struct_name=struct_name, + field=sanitize(decl.name), + decl_name=decl.name, + lv_callback=lv_callback, + user_data=full_user_data_ptr, + type_name=type_name, + cast=cast, + ) + ) + read_cases.append( + "case MP_QSTR_{field}: dest[0] = mp_lv_funcptr(&mp_{funcptr}_mpobj, {cast}data->{decl_name}, {lv_callback} ,MP_QSTR_{struct_name}_{field}, {user_data}); break; // converting from callback {type_name}".format( + struct_name=struct_name, + field=sanitize(decl.name), + decl_name=decl.name, + lv_callback=lv_callback, + funcptr=lv_to_mp_funcptr[type_name], + user_data=full_user_data, + type_name=type_name, + cast=cast, + ) + ) + else: + user_data = None + # Only allow write to non-const members + is_writeable = ( + not hasattr(decl.type, "quals") + ) or "const" not in decl.type.quals + # Arrays must be handled by memcpy, otherwise we would get "assignment to expression with array type" error + elem_rw = ( + _struct_array_elem_rw(decl) + if isinstance(decl.type, c_ast.ArrayDecl) + else None + ) + if elem_rw: + # A view, not a list of copies (lvgl-bindings#38). + elem_read, elem_write = elem_rw + shape = "data->{decl_name}, {dim}, sizeof({elem})".format( + decl_name=decl.name, + dim=gen.visit(decl.type.dim), + elem=gen.visit(decl.type.type), + ) + if is_writeable: + write_cases.append( + "case MP_QSTR_{field}: mp_lv_struct_array_assign({shape}, {write}, dest[1]); break; // converting to {type_name}".format( + field=sanitize(decl.name), + shape=shape, + write=elem_write, + type_name=type_name, + ) + ) + read_cases.append( + "case MP_QSTR_{field}: dest[0] = mp_lv_struct_array_new(self_in, {shape}, {read}, {write}); break; // converting from {type_name}".format( + field=sanitize(decl.name), + shape=shape, + read=elem_read, + write=elem_write, + type_name=type_name, + ) + ) + elif isinstance(decl.type, c_ast.ArrayDecl): + memcpy_size = "sizeof(%s)*%s" % ( + gen.visit(decl.type.type), + gen.visit(decl.type.dim), + ) + if is_writeable: + write_cases.append( + "case MP_QSTR_{field}: memcpy((void*)&data->{decl_name}, {cast}{convertor}(dest[1]), {size}); break; // converting to {type_name}".format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=mp_to_lv_convertor, + type_name=type_name, + cast=cast, + size=memcpy_size, + ) + ) + read_cases.append( + "case MP_QSTR_{field}: dest[0] = {convertor}({cast}data->{decl_name}); break; // converting from {type_name}".format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=lv_to_mp_convertor, + type_name=type_name, + cast=cast, + ) + ) + else: + if is_writeable: + write_cases.append( + "case MP_QSTR_{field}: data->{decl_name} = {cast}{convertor}(dest[1]); break; // converting to {type_name}".format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=mp_to_lv_convertor, + type_name=type_name, + cast=cast, + ) + ) + read_cases.append( + "case MP_QSTR_{field}: dest[0] = {convertor}({cast}data->{decl_name}); break; // converting from {type_name}".format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=lv_to_mp_convertor, + type_name=type_name, + cast=cast, + ) + ) + print( + """ +/* + * Struct {struct_name} + */ + +{pointer_helpers} + +#define mp_read_{sanitized_struct_name}(field) mp_read_ptr_{sanitized_struct_name}(copy_buffer(&field, sizeof({struct_tag}{struct_name}))) +#define mp_read_byref_{sanitized_struct_name}(field) mp_read_ptr_{sanitized_struct_name}(&field) + +static void mp_{sanitized_struct_name}_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) +{{ + mp_lv_struct_t *self = MP_OBJ_TO_PTR(self_in); + GENMPY_UNUSED {struct_tag}{struct_name} *data = ({struct_tag}{struct_name}*)self->data; + + if (dest[0] == MP_OBJ_NULL) {{ + // load attribute + switch(attr) + {{ + {read_cases}; + default: call_parent_methods(self_in, attr, dest); // fallback to locals_dict lookup + }} + }} else {{ + if (dest[1]) + {{ + // store attribute + switch(attr) + {{ + {write_cases}; + default: return; + }} + + dest[0] = MP_OBJ_NULL; // indicate success + }} + }} +}} + +static void mp_{sanitized_struct_name}_print(const mp_print_t *print, + mp_obj_t self_in, + mp_print_kind_t kind) +{{ + mp_printf(print, "struct {struct_name}"); +}} + +static const mp_obj_dict_t mp_{sanitized_struct_name}_locals_dict; + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_{sanitized_struct_name}_type, + MP_QSTR_{sanitized_struct_name}, + MP_TYPE_FLAG_NONE, + print, mp_{sanitized_struct_name}_print, + make_new, make_new_lv_struct, + binary_op, lv_struct_binary_op, + subscr, lv_struct_subscr, + attr, mp_{sanitized_struct_name}_attr, + locals_dict, &mp_{sanitized_struct_name}_locals_dict, + buffer, mp_blob_get_buffer, + parent, &mp_lv_base_struct_type +); + +static inline const mp_obj_type_t *get_mp_{sanitized_struct_name}_type(void) +{{ + return &mp_{sanitized_struct_name}_type; +}} + """.format( + sanitized_struct_name=sanitized_struct_name, + struct_name=struct_name, + struct_tag="struct " + if struct_name in structs_without_typedef.keys() + else "", + write_cases=";\n ".join(write_cases), + read_cases=";\n ".join(read_cases), + pointer_helpers=struct_pointer_helpers_source( + accept_none=False, + unused_qualifier="GENMPY_UNUSED ", + sanitized_struct_name=sanitized_struct_name, + struct_name=struct_name, + struct_tag="struct " + if struct_name in structs_without_typedef.keys() + else "", + ), + ) + ) + lv_to_mp[struct_name] = "mp_read_%s" % sanitized_struct_name + lv_to_mp_byref[struct_name] = "mp_read_byref_%s" % sanitized_struct_name + mp_to_lv[struct_name] = "mp_write_%s" % sanitized_struct_name + lv_to_mp["%s *" % struct_name] = "mp_read_ptr_%s" % sanitized_struct_name + mp_to_lv["%s *" % struct_name] = "mp_write_ptr_%s" % sanitized_struct_name + lv_to_mp["const %s *" % struct_name] = "mp_read_ptr_%s" % sanitized_struct_name + mp_to_lv["const %s *" % struct_name] = "mp_write_ptr_%s" % sanitized_struct_name + lv_mp_type[struct_name] = simplify_identifier(sanitized_struct_name) + lv_mp_type["%s *" % struct_name] = simplify_identifier(sanitized_struct_name) + lv_mp_type["const %s *" % struct_name] = simplify_identifier(sanitized_struct_name) + # print('/* --> struct "%s" generated! */' % (struct_name)) + generated_structs[struct_name] = True # Completed generating a struct + return struct_name + + + # + # Generate Array Types when needed + # + + + def try_generate_array_type(type_ast): + arr_name = get_name(type_ast) + if arr_name in mp_to_lv: + return mp_to_lv[arr_name] + # print('/* --> try_generate_array_type %s: %s */' % (arr_name, type_ast)) + dim = gen.visit(type_ast.dim) if hasattr(type_ast, "dim") and type_ast.dim else None + element_type = get_type(type_ast.type, remove_quals=True) + qualified_element_type = gen.visit(type_ast.type) + if element_type not in mp_to_lv or not mp_to_lv[element_type]: + try_generate_type(type_ast.type) + if element_type not in mp_to_lv or not mp_to_lv[element_type]: + raise MissingConversionException( + "Missing conversion to %s while generating array type conversion" + % element_type + ) + type_ptr_ast = c_ast.PtrDecl(quals=[], type=type_ast.type) + element_type_ptr = get_type(type_ptr_ast, remove_quals=True) + qualified_element_ptr_type = gen.visit(type_ptr_ast) + if element_type_ptr not in mp_to_lv or not mp_to_lv[element_type_ptr]: + try_generate_type(type_ptr_ast) + if element_type_ptr not in mp_to_lv or not mp_to_lv[element_type_ptr]: + raise MissingConversionException( + "Missing conversion to %s while generating array type conversion" + % element_type_ptr + ) + array_convertor_suffix = ( + arr_name.replace(" ", "_") + .replace("*", "ptr") + .replace("+", "plus") + .replace("-", "minus") + .replace("[", "__") + .replace("]", "__") + .replace("(", "__") + .replace(")", "__") + .replace("/", "_div_") + ) + arr_to_c_convertor_name = "mp_arr_to_%s" % array_convertor_suffix + arr_to_mp_convertor_name = "mp_arr_from_%s" % array_convertor_suffix + print( + ( + ( + """ +/* + * Array convertors for {arr_name} + */ + +GENMPY_UNUSED static {struct_tag}{type} *{arr_to_c_convertor_name}(mp_obj_t mp_arr) +{{ + // A packed buffer is already the C array (lvgl-bindings#37). + if (MP_OBJ_IS_STR_OR_BYTES(mp_arr) || + MP_OBJ_IS_TYPE(mp_arr, &mp_type_bytearray) || + MP_OBJ_IS_TYPE(mp_arr, &mp_type_memoryview)) + return mp_to_ptr(mp_arr); + mp_obj_t mp_len = mp_obj_len_maybe(mp_arr); + if (mp_len == MP_OBJ_NULL) return mp_to_ptr(mp_arr); + mp_int_t len = mp_obj_get_int(mp_len); + {check_dim} + {struct_tag}{type} *lv_arr = ({struct_tag}{type}*)m_malloc(len * sizeof({struct_tag}{type})); + mp_obj_t iter = mp_getiter(mp_arr, NULL); + mp_obj_t item; + size_t i = 0; + while ((item = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) {{ + lv_arr[i++] = {mp_to_lv_convertor}(item); + }} + return ({struct_tag}{type} *)lv_arr; +}} +""" + ) + + ( + """ +GENMPY_UNUSED static mp_obj_t {arr_to_mp_convertor_name}({qualified_type} *arr) +{{ + mp_obj_t obj_arr[{dim}]; + for (size_t i=0; i<{dim}; i++){{ + obj_arr[i] = {lv_to_mp_convertor}(arr[i]); + }} + return mp_obj_new_list({dim}, obj_arr); // TODO: return custom iterable object! +}} +""" + if dim + else """ +GENMPY_UNUSED static mp_obj_t {arr_to_mp_convertor_name}({qualified_type} *arr) +{{ + return {lv_to_mp_ptr_convertor}((void*)arr); +}} +""" + ) + ).format( + arr_to_c_convertor_name=arr_to_c_convertor_name, + arr_to_mp_convertor_name=arr_to_mp_convertor_name, + arr_name=arr_name, + type=element_type, + type_ptr=element_type_ptr, + struct_tag="struct " + if element_type in structs_without_typedef.keys() + else "", + qualified_type=qualified_element_type, + qualified_ptr_type=qualified_element_ptr_type, + check_dim="//TODO check dim!" if dim else "", + mp_to_lv_convertor=mp_to_lv[element_type], + lv_to_mp_convertor=lv_to_mp[element_type], + mp_to_lv_ptr_convertor=mp_to_lv[element_type_ptr], + lv_to_mp_ptr_convertor=lv_to_mp[element_type_ptr], + dim=dim if dim else 1, + ) + ) + mp_to_lv[arr_name] = arr_to_c_convertor_name + mp_to_lv["const %s" % arr_name] = arr_to_c_convertor_name + lv_to_mp[arr_name] = arr_to_mp_convertor_name + lv_to_mp["const %s" % arr_name] = arr_to_mp_convertor_name + lv_mp_type[arr_name] = arr_to_c_convertor_name + lv_mp_type["const %s" % arr_name] = "const %s" % arr_to_c_convertor_name + return arr_to_c_convertor_name + + + # + # Generate types from typedefs when needed + # + + generated_funcptr_helpers = collections.OrderedDict() + + + def emit_function_pointer(helper_name, func): + print("#define %s NULL\n" % helper_name) + if _emit_max_phase is not None and _emit_max_phase < 4: + return False + gen_mp_func(func, None) + print( + "GENMPY_UNUSED static inline mp_obj_t mp_lv_{f}(void *func){{ " + "return mp_lv_funcptr(&mp_{f}_mpobj, func, NULL, MP_QSTR_, NULL); }}\n".format( + f=helper_name + ) + ) + return True + + + type_discovery = TypeDiscovery( + get_name=get_name, + get_type=get_type, + structs=structs, + typedefs=typedefs, + struct_aliases=struct_aliases, + mp_to_lv=mp_to_lv, + lv_to_mp=lv_to_mp, + lv_mp_type=lv_mp_type, + lv_to_mp_byref=lv_to_mp_byref, + lv_to_mp_funcptr=lv_to_mp_funcptr, + generated_funcptr_helpers=generated_funcptr_helpers, + try_generate_struct=try_generate_struct, + try_generate_array=try_generate_array_type, + emit_function_pointer=emit_function_pointer, + missing_conversion=MissingConversionException, + report_error=lambda func, exp: gen_func_error(func, exp), + ) + get_arg_name = type_discovery.typedef_name + + + def try_generate_type(type_ast): + return type_discovery.generate(type_ast) + + + # + # Helper structs + # + + + def create_helper_struct(struct_str): + print(struct_str) + struct_str_ast = parser.parse(struct_str).ext[0].type + struct_name = get_name(struct_str_ast) + # print('/* --> %s: %s */' % (struct_name, struct_str_ast.type)) + structs[struct_name] = struct_str_ast.type + try: + try_generate_struct(struct_name, struct_str_ast.type) + except MissingConversionException as exp: + print("/* Helper structs NOT generated:\n %s\n*/" % (repr(exp))) + + + print( + """ +/* + * Helper Structs + */ + """ + ) + + create_helper_struct( + """ +typedef union { + void* ptr_val; + const char* str_val; + int int_val; + unsigned int uint_val; +} C_Pointer; +""" + ) + + # + # + # Emit C callback functions + # + + generated_callbacks = collections.OrderedDict() + generated_funcs = collections.OrderedDict() + + if _emit_max_phase is None or _emit_max_phase > 1: + + if _emit_target == "circuitpython" and _emit_max_phase is not None and _emit_max_phase >= 2: + from .emit_circuitpython_glue import emit_phase2_enums + + emit_phase2_enums() + + if _emit_max_phase is None or _emit_max_phase >= 4: + + def build_callback_func_arg(arg, index, func, func_name=None): + arg_type = get_type(arg.type, remove_quals=True) + cast = ( + "(void*)" if isinstance(arg.type, c_ast.PtrDecl) else "" + ) # needed when field is const. casting to void overrides it + if not conversion_available( + conversions=lv_to_mp, + type_name=arg_type, + generate_type=lambda: try_generate_type(arg.type), + ): + raise MissingConversionException( + "Callback: Missing conversion to %s" % arg_type + ) + arg_metadata = {"type": lv_mp_type[arg_type]} + if arg.name: + arg_metadata["name"] = arg.name + callback_metadata[func_name]["args"].append(arg_metadata) + return "mp_args[{i}] = {convertor}({cast}arg{i});".format( + convertor=lv_to_mp[arg_type], i=index, cast=cast + ) + + + def gen_callback_func(func, func_name=None, user_data_argument=False): + if func_name in generated_callbacks: + return + # print('/* --> callback: %s */' % (gen.visit(func))) + callback_metadata[func_name] = {"args": []} + args = func.args.params + enumerated_args = [] + for i, arg in enumerate(args): + arg_name = f"arg{i}" + new_arg = c_ast.Decl( + name=arg_name, + quals=arg.quals, + align=[], + storage=[], + funcspec=[], + type=copy.deepcopy(arg.type), + init=None, + bitsize=None, + ) + t = new_arg + while hasattr(t, "type"): + if hasattr(t.type, "declname"): + t.type.declname = arg_name + t = t.type + enumerated_args.append(new_arg) + # print(f'/* --> {gen.visit(new_arg)} */') + if not func_name: + func_name = get_arg_name(func.type) + # print('/* --> callback: func_name = %s */' % func_name) + if is_global_callback(func): + full_user_data = "MP_STATE_PORT(mp_lv_user_data)" + else: + user_data, user_data_getter, _ = get_user_data(func, func_name) + + if ( + user_data_argument + and len(args) > 0 + and gen.visit(args[-1].type) == "void *" + ): + full_user_data = "arg%d" % (len(args) - 1) + elif user_data: + full_user_data = "arg0->%s" % user_data + if ( + len(args) < 1 + or hasattr(args[0].type.type, "names") + and lv_base_obj_pattern.match(args[0].type.type.names[0]) + ): + raise MissingConversionException( + "Callback: First argument of callback function must be lv_obj_t" + ) + elif user_data_getter: + full_user_data = "%s(arg0)" % user_data_getter.name + else: + full_user_data = None + + # if full_user_data: print('/* --> callback: %s user_data found!! %s */' %(gen.visit(func), full_user_data)) + # else: print('/* --> callback: full_user_data NOT FOUND !! %s */' % (gen.visit(func))) + if not full_user_data: + raise MissingConversionException( + "Callback: user_data NOT FOUND! %s" % (gen.visit(func)) + ) + return_type = get_type(func.type, remove_quals=False) + if not callback_return_conversion_available( + return_type=return_type, + mp_to_lv=mp_to_lv, + generate_type=lambda: try_generate_type(func.type), + ): + raise MissingConversionException( + "Callback return value: Missing conversion to %s" % return_type + ) + + callback_metadata[func_name]["return_type"] = lv_mp_type[return_type] + return_lowering = callback_return_lowering( + return_type=return_type, + mp_to_lv=mp_to_lv, + ) + print( + """ +/* + * Callback function {func_name} + * {func_prototype} + */ + +GENMPY_UNUSED static {return_type} {func_name}_callback({func_args}) +{{ + mp_obj_t mp_args[{num_args}]; + {build_args} + mp_obj_t callbacks = get_callback_dict_from_user_data({user_data}); + {return_value_assignment}mp_lv_nesting_call(mp_obj_dict_get(callbacks, MP_OBJ_NEW_QSTR(MP_QSTR_{func_name})), {num_args}, mp_args); + return{return_value}; +}} +""".format( + func_prototype=gen.visit(func), + func_name=sanitize(func_name), + return_type=return_type, + func_args=", ".join([(gen.visit(arg)) for arg in enumerated_args]), + num_args=len(args), + build_args="\n ".join( + [ + build_callback_func_arg(arg, i, func, func_name=func_name) + for i, arg in enumerate(args) + ] + ), + user_data=full_user_data, + return_value_assignment=return_lowering.result_assignment, + return_value=return_lowering.return_value, + ) + ) + generated_callbacks[func_name] = True + + + # + # Emit Mpy function definitions + # + + generated_funcs = collections.OrderedDict() + + + def build_mp_func_arg(arg, index, func, obj_name): + if isinstance(arg, c_ast.EllipsisParam): + raise MissingConversionException("Cannot convert ellipsis param") + fixed_arg = copy.deepcopy(arg) + convert_array_to_ptr(fixed_arg) + if not fixed_arg.name: + fixed_arg.name = "arg%d" % index + add_default_declname(fixed_arg, fixed_arg.name) + # print('/* --> FIXED ARG: %s */' % repr(fixed_arg)) + callback = decl_to_callback(arg) + args = func.type.args.params if func.type.args else [] + # print('/* --> ARG: %s */' % arg) + # print('/* --> FIRST ARG: %s */' % first_arg) + if callback: + # Callback is supported in two modes: + # 1) last argument is a void* user_data which is passed to callback + # 2) first argument is a struct with user_data field, which is passed to callback + + callback_name, arg_type = callback + # print('/* --> callback %s ARG TYPE: %s */' % (callback_name, arg_type)) + + try: + user_data_argument = False + full_user_data = None + user_data_getter = None + user_data_setter = None + if ( + len(args) > 0 + and gen.visit(args[-1].type) == "void *" + and args[-1].name == "user_data" + ): + callback_name = "%s_%s" % (func.name, callback_name) + full_user_data = "&user_data" + user_data_argument = True + else: + first_arg = args[0] + struct_name = get_name( + first_arg.type.type.type + if hasattr(first_arg.type.type, "type") + else first_arg.type.type + ) + callback_name = "%s_%s" % (struct_name, callback_name) + user_data, user_data_getter, user_data_setter = get_user_data( + arg_type, callback_name + ) + if is_global_callback(arg_type): + full_user_data = "&MP_STATE_PORT(mp_lv_user_data)" + else: + if user_data: + full_user_data = "&%s->%s" % (first_arg.name, user_data) + elif user_data_getter and user_data_setter: + full_user_data = "NULL" # uses getter/setter instead + if index == 0: + raise MissingConversionException( + "Callback argument '%s' cannot be the first argument! We assume the first argument contains the user_data" + % gen.visit(arg) + ) + if not full_user_data: + raise MissingConversionException( + "Callback function '%s' must receive a struct pointer with user_data member as its first argument!" + % gen.visit(arg) + ) + # eprint("--> callback_metadata= %s_%s" % (struct_name, callback_name)) + gen_callback_func(arg_type, "%s" % callback_name, user_data_argument) + arg_metadata = { + "type": "callback", + "function": callback_metadata[callback_name], + } + if arg.name: + arg_metadata["name"] = arg.name + func_metadata[func.name]["args"].append(arg_metadata) + return "void *{arg_name} = mp_lv_callback(mp_args[{i}], &{callback_name}_callback, MP_QSTR_{callback_name}, {full_user_data}, {containing_struct}, (mp_lv_get_user_data){user_data_getter}, (mp_lv_set_user_data){user_data_setter});".format( + i=index, + arg_name=fixed_arg.name, + callback_name=sanitize(callback_name), + full_user_data=full_user_data, + containing_struct=first_arg.name + if user_data_getter and user_data_setter + else "NULL", + user_data_getter=user_data_getter.name if user_data_getter else "NULL", + user_data_setter=user_data_setter.name if user_data_setter else "NULL", + ) + except MissingConversionException as exp: + gen_func_error(arg, exp) + callback_name = "NULL" + full_user_data = "NULL" + if not hasattr(arg, "type"): + raise MissingConversionException( + "Cannot convert function argument %s" % repr(arg) + ) + arg_type = get_type(arg.type, remove_quals=True) + # print('/* --> arg = %s, arg_type = %s */' %(gen.visit(arg), arg_type)) + if not conversion_available( + conversions=mp_to_lv, + type_name=arg_type, + generate_type=lambda: try_generate_type(arg.type), + ): + raise MissingConversionException("Missing conversion to %s" % arg_type) + arg_metadata = {"type": lv_mp_type[arg_type]} + if arg.name: + arg_metadata["name"] = arg.name + func_metadata[func.name]["args"].append(arg_metadata) + cast = ( + ("(%s)" % gen.visit(fixed_arg.type)) if "const" in arg.quals else "" + ) # allow conversion from non const to const, sometimes requires cast + return "{var} = {cast}{convertor}(mp_args[{i}]);".format( + var=gen.visit(fixed_arg), cast=cast, convertor=mp_to_lv[arg_type], i=index + ) + + + def emit_func_obj(func_obj_name, func_name, param_count, func_ptr, is_static): + print( + """ +static {builtin_macro}(mp_{func_obj_name}_mpobj, {param_count}, mp_{func_name}, {func_ptr}); + """.format( + func_obj_name=func_obj_name, + func_name=func_name, + func_ptr=func_ptr, + param_count=param_count, + builtin_macro="MP_DEFINE_CONST_LV_FUN_OBJ_STATIC_VAR" + if is_static + else "MP_DEFINE_CONST_LV_FUN_OBJ_VAR", + ) + ) + + + def gen_mp_func(func, obj_name): + # print('/* gen_mp_func: %s : %s */' % (obj_name, func)) + if func.name in generated_funcs: + print( + """ +/* + * WARNING: %s was declared more than once! + */ + """ + % func.name + ) + return + # print("/* gen_mp_func %s */" % func.name) + generated_funcs[func.name] = False # starting to generate the function + func_metadata[func.name] = {"type": "function", "args": []} + + args = func.type.args.params if func.type.args else [] + enumerated_args = enumerate(args) + + # Handle the case of a single function argument which is "void" + if len(args) == 1 and get_type(args[0].type, remove_quals=True) == "void": + param_count = 0 + args = [] + else: + param_count = len(args) + + # If func prototype matches an already generated func, reuse it and only emit func obj that points to it. + prototype_str = gen.visit(function_prototype(func)) + if prototype_str in func_prototypes: + original_func = func_prototypes[prototype_str] + if function_reuse_allowed( + function_name=func.name, + original_name=original_func.name, + original_generated=generated_funcs[original_func.name] is True, + supports_dynamic_function_pointer=runtime.get( + "target_lowering_profile" + ).supports_dynamic_function_pointer, + ): + print("/* Reusing %s for %s */" % (original_func.name, func.name)) + emit_func_obj( + func.name, + original_func.name, + param_count, + func.name, + is_static_member(func, base_obj_type), + ) + func_metadata[func.name]["return_type"] = func_metadata[original_func.name][ + "return_type" + ] + func_metadata[func.name]["args"] = func_metadata[original_func.name]["args"] + generated_funcs[func.name] = True # completed generating the function + return + func_prototypes[prototype_str] = func + + # user_data argument must be handled first, if it exists + try: + i = [(arg.name if hasattr(arg, "name") else None) for arg in args].index( + "user_data" + ) + if i > 0: + enumerated_args = [ + (i, arg) for i, arg in enumerated_args + ] # convert enumerate to list + enumerated_args[0], enumerated_args[i] = ( + enumerated_args[i], + enumerated_args[0], + ) + except ValueError: + pass + + return_type = get_type(func.type.type, remove_quals=False) + qualified_return_type = gen.visit(func.type.type) + if isinstance(func.type.type, c_ast.PtrDecl) and lv_func_returns_array.match( + func.name + ): + try_generate_array_type(func.type.type) + # print('/* --> return_type = %s, qualified_return_type = %s\n%s */' % (return_type, qualified_return_type, func.type.type)) + if return_type != "void" and not conversion_available( + conversions=lv_to_mp, + type_name=return_type, + generate_type=lambda: try_generate_type(func.type.type), + ): + raise MissingConversionException( + "Missing conversion from %s" % return_type + ) + return_lowering = function_return_lowering( + return_type=return_type, + qualified_return_type=qualified_return_type, + is_pointer=isinstance(func.type.type, c_ast.PtrDecl), + lv_to_mp=lv_to_mp, + lv_mp_type=lv_mp_type, + ) + build_result = return_lowering.build_result + build_return_value = return_lowering.build_return_value + func_metadata[func.name]["return_type"] = ( + return_lowering.metadata_return_type + ) + if func.name == "lv_draw_buf_destroy" and _emit_target == "circuitpython": + print( + """ +/* + * {module_name} extension definition for: + * {print_func} + */ + +static mp_obj_t mp_{func}(size_t mp_n_args, const mp_obj_t *mp_args, void *lv_func_ptr) +{{ + mp_lv_struct_t *self = MP_OBJ_TO_PTR(mp_args[0]); + lv_draw_buf_t *buf = (lv_draw_buf_t *)self->data; + if (buf != NULL) {{ + ((void (*)(lv_draw_buf_t *))lv_func_ptr)(buf); + self->data = NULL; + }} + return mp_const_none; +}} + + """ + .format( + module_name=module_name, + func=func.name, + print_func=gen.visit(func), + ) + ) + else: + print( + """ +/* + * {module_name} extension definition for: + * {print_func} + */ + +static mp_obj_t mp_{func}(size_t mp_n_args, const mp_obj_t *mp_args, void *lv_func_ptr) +{{ + {build_args} + {build_result}(({func_ptr})lv_func_ptr)({send_args}); + return {build_return_value}; +}} + + """.format( + module_name=module_name, + func=func.name, + func_ptr=prototype_str, + print_func=gen.visit(func), + build_args="\n ".join( + [ + build_mp_func_arg(arg, i, func, obj_name) + for i, arg in enumerated_args + if isinstance(arg, c_ast.EllipsisParam) + or (not isinstance(arg.type, c_ast.TypeDecl)) + or (not isinstance(arg.type.type, c_ast.IdentifierType)) + or "void" not in arg.type.type.names + ] + ), # Handle the case of 'void' param which should be ignored + send_args=", ".join( + [ + (arg.name if (hasattr(arg, "name") and arg.name) else ("arg%d" % i)) + for i, arg in enumerate(args) + ] + ), + build_result=build_result, + build_return_value=build_return_value, + ) + ) + + emit_func_obj( + func.name, + func.name, + param_count, + func.name, + is_static_member(func, base_obj_type), + ) + generated_funcs[func.name] = True # completed generating the function + # print('/* is_struct_function() = %s, is_static_member() = %s, get_first_arg_type()=%s, obj_name = %s */' % ( + # is_struct_function(func), is_static_member(func, base_obj_type), get_first_arg_type(func), base_obj_type)) + + + def gen_func_error(method, exp): + diagnostic, funcs = failed_generation( + method=method, + problem=exp, + funcs=runtime.get("funcs"), + render_method=lambda value: ( + gen.visit(value) if isinstance(value, c_ast.Node) else value + ), + api_model=runtime.get("api_model"), + target=_emit_target, + ) + print(diagnostic) + runtime.set_("funcs", funcs) + + + # + # Emit Mpy objects definitions + # + + enum_referenced = collections.OrderedDict() + + + def gen_obj_methods(obj_name): + helper_members = ( + ["{ MP_ROM_QSTR(MP_QSTR___cast__), MP_ROM_PTR(&cast_obj_class_method) }"] + if len(obj_names) > 0 and obj_name == base_obj_name + else [] + ) + members = [ + "{{ MP_ROM_QSTR(MP_QSTR_{method_name}), MP_ROM_PTR(&mp_{method}_mpobj) }}".format( + method=method.name, + method_name=sanitize(method_name_from_func_name(method.name)), + ) + for method in get_methods(obj_name) + ] + obj_metadata[obj_name]["members"].update( + { + method_name_from_func_name(method.name): func_metadata[method.name] + for method in get_methods(obj_name) + } + ) + # add parent methods + parent_members = [] + if obj_name in parent_obj_names and parent_obj_names[obj_name] != None: + # parent_members += gen_obj_methods(parent_obj_names[obj_name]) + obj_metadata[obj_name]["members"].update( + obj_metadata[parent_obj_names[obj_name]]["members"] + ) + # add enum members + enum_members = [ + "{{ MP_ROM_QSTR(MP_QSTR_{enum_member}), MP_ROM_PTR({enum_member_value}) }}".format( + enum_member=export_name(enum_member_name, "enum_member"), + enum_member_value=get_enum_value(obj_name, enum_member_name), + ) + for enum_member_name in get_enum_members(obj_name) + ] + obj_metadata[obj_name]["members"].update( + { + get_enum_member_name(enum_member_name): {"type": "enum_member"} + for enum_member_name in get_enum_members(obj_name) + } + ) + # add enums that match object name + obj_enums = [ + enum_name for enum_name in enums.keys() if is_method_of(enum_name, obj_name) + ] + enum_types = [ + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_lv_{enum}_type_base) }}".format( + name=export_name(method_name_from_func_name(enum_name), "enum"), + enum=enum_name + ) + for enum_name in obj_enums + ] + obj_metadata[obj_name]["members"].update( + { + method_name_from_func_name(enum_name): {"type": "enum_type"} + for enum_name in obj_enums + } + ) + for enum_name in obj_enums: + obj_metadata[obj_name]["members"][method_name_from_func_name(enum_name)].update( + obj_metadata[enum_name] + ) + if is_widget_scoped_only_enum(enum_name): + enum_referenced[enum_name] = True + return members + parent_members + enum_members + enum_types + helper_members + + + def gen_obj(obj_name): + # eprint('Generating object %s...' % obj_name) + is_obj = has_ctor(obj_name) + should_add_base_methods = is_obj and obj_name != "obj" + obj_metadata[obj_name] = {"members": collections.OrderedDict()} + + # Generate object methods + for method in get_methods(obj_name): + try: + gen_mp_func(method, obj_name) + except MissingConversionException as exp: + gen_func_error(method, exp) + + # Generate object construction function, if needed + if is_obj: + ctor_func = get_ctor(obj_name) + try: + gen_mp_func(ctor_func, obj_name) + except MissingConversionException as exp: + gen_func_error(ctor_func, exp) + + # print([method.name for method in methods]) + ctor = """ +static mp_obj_t {obj}_make_new( + const mp_obj_type_t *type, + size_t n_args, + size_t n_kw, + const mp_obj_t *args) +{{ + return make_new(&mp_{ctor_name}_mpobj, type, n_args, n_kw, args); +}} +""" + + print( + """ +/* + * {module_name} {obj} object definitions + */ + """.format(module_name=module_name, obj=obj_name) + ) + + print( + """ +static const mp_rom_map_elem_t {obj}_locals_dict_table[] = {{ + {locals_dict_entries} +}}; + +static MP_DEFINE_CONST_DICT({obj}_locals_dict, {obj}_locals_dict_table); + +static void {obj}_print(const mp_print_t *print, + mp_obj_t self_in, + mp_print_kind_t kind) +{{ + mp_printf(print, "{module_name} {obj}"); +}} + +{ctor} + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_lv_{obj}_type_base, + MP_QSTR_{obj}, + MP_TYPE_FLAG_NONE, + print, {obj}_print, + {make_new} + {binary_op} + attr, call_parent_methods, + {buffer} + {parent} + locals_dict, &{obj}_locals_dict +); + +GENMPY_UNUSED static const mp_lv_obj_type_t mp_lv_{obj}_type = {{ +#ifdef LV_OBJ_T + .lv_obj_class = {lv_class}, +#endif + .mp_obj_type = &mp_lv_{obj}_type_base, +}}; + """.format( + module_name=module_name, + obj=sanitize(obj_name), + locals_dict_entries=",\n ".join(gen_obj_methods(obj_name)), + ctor=ctor.format(obj=obj_name, ctor_name=ctor_func.name) + if has_ctor(obj_name) + else "", + make_new="make_new, %s_make_new," % obj_name if is_obj else "", + binary_op="binary_op, mp_lv_obj_binary_op," if is_obj else "", + buffer="buffer, mp_lv_obj_get_buffer," if is_obj else "", + parent="parent, &mp_lv_%s_type_base," % parent_obj_names[obj_name] + if obj_name in parent_obj_names and parent_obj_names[obj_name] + else "", + lv_class="&lv_%s_class" % obj_name if is_obj else "NULL", + ) + ) + + + # + # Generate Enum objects + # + + if _emit_max_phase is None: + for enum_name in list(enums.keys()): + gen_obj(enum_name) + + # + # Generate all other objects. Generate parent objects first + # + + if _emit_max_phase is None or _emit_max_phase >= 5: + + generated_obj_names = collections.OrderedDict() + for obj_name in object_generation_order(obj_names, parent_obj_names): + gen_obj(obj_name) + generated_obj_names[obj_name] = True + + # + # Generate structs which contain function members + # First argument of a function could be it's parent struct + # Need to make sure these structs are generated *before* struct-functions are + # Otherwise we will not know of all the structs when generating struct-functions + # + + + def try_generate_structs_from_first_argument(): + for func in funcs: + if func.name in generated_funcs: + continue + args = func.type.args.params if func.type.args else [] + if len(args) < 1: + continue + arg_type = get_type(args[0].type, remove_quals=True) + if arg_type not in mp_to_lv or not mp_to_lv[arg_type]: + try: + try_generate_type(args[0].type) + except MissingConversionException as e: + print( + """ +/* + * {struct} not generated: {err} + */ + """.format(struct=arg_type, err=e) + ) + + + # + # Generate globals + # + + # eprint("/* Generating globals */") + + + def gen_func_error(method, exp): + diagnostic, funcs = failed_generation( + method=method, + problem=exp, + funcs=runtime.get("funcs"), + render_method=lambda value: ( + gen.visit(value) if isinstance(value, c_ast.Node) else value + ), + api_model=runtime.get("api_model"), + target=_emit_target, + ) + print(diagnostic) + runtime.set_("funcs", funcs) + + + def _emit_all_struct_types(): + print( + """ +/* + * CircuitPython phase-3 struct type generation + */ +""" + ) + for struct_name in list(structs.keys()): + if generated_structs.get(struct_name): + continue + try: + try_generate_struct(struct_name, structs[struct_name]) + except MissingConversionException as exp: + print( + """ +/* + * Struct NOT generated: {name} + * {problem} + */ +""".format( + name=struct_name, + problem=exp, + ) + ) + + + struct_locals_basic = collections.OrderedDict() + + + def _emit_struct_locals_dicts(include_methods=False, struct_list=None): + if struct_list is None: + struct_names = list(generated_structs.keys()) + else: + struct_names = struct_list + for struct_name in struct_names: + if not generated_structs.get(struct_name): + continue + if include_methods: + if generated_struct_functions.get(struct_name): + continue + else: + if struct_locals_basic.get(struct_name): + continue + sanitized_struct_name = sanitize(struct_name) + struct_funcs = ( + list(get_struct_functions(struct_name)) if include_methods else [] + ) + if include_methods: + for struct_func in struct_funcs[:]: + try: + if struct_func.name not in generated_funcs: + gen_mp_func(struct_func, struct_name) + except MissingConversionException as exp: + gen_func_error(struct_func, exp) + struct_funcs.remove(struct_func) + if struct_name not in structs or structs[struct_name].decls: + struct_size_attr = "{{ MP_ROM_QSTR(MP_QSTR___SIZE__), MP_ROM_PTR(MP_ROM_INT(sizeof({struct_tag}{struct_name}))) }},".format( + struct_name=struct_name, + struct_tag="struct " + if struct_name in structs_without_typedef.keys() + else "", + ) + else: + struct_size_attr = "" + print( + """ +static const mp_rom_map_elem_t mp_{sanitized_struct_name}_locals_dict_table[] = {{ + {struct_size} + {functions} +}}; + +static MP_DEFINE_CONST_DICT(mp_{sanitized_struct_name}_locals_dict, mp_{sanitized_struct_name}_locals_dict_table); + """.format( + struct_size=struct_size_attr, + sanitized_struct_name=sanitized_struct_name, + functions="".join( + [ + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_{func}_mpobj) }},\n ".format( + name=sanitize(noncommon_part(f.name, struct_name)), + func=f.name, + ) + for f in struct_funcs + ] + ), + ) + ) + if include_methods: + generated_struct_functions[struct_name] = True + else: + struct_locals_basic[struct_name] = True + + + def gen_global(global_name, global_type_ast): + global_type = get_type(global_type_ast, remove_quals=True) + generated_global = try_generate_type(global_type_ast) + # print("/* generated_global = %s */" % generated_global) + if global_type not in generated_structs: + wrapped_type = lv_mp_type[global_type] + if not wrapped_type: + raise MissingConversionException( + "Missing conversion to %s when generating global %s" + % (wrapped_type, global_name) + ) + global_type = sanitize("_lv_mp_%s_wrapper" % wrapped_type) + custom_struct_str = """ +typedef struct {{ + {type} value; +}} {name}; + """.format(type=wrapped_type, name=global_type) + if global_type not in generated_structs: + print("/* Global struct wrapper for %s */" % wrapped_type) + print(custom_struct_str) + # eprint("%s: %s\n" % (wrapped_type, custom_struct_str)) + try_generate_struct( + global_type, parser.parse(custom_struct_str).ext[0].type.type + ) + + print( + """ +/* + * {module_name} {global_name} global definitions + */ + +{definition} + """.format( + module_name=module_name, + global_name=global_name, + definition=guarded( + """static const mp_lv_struct_t mp_{global_name} = {{ + {{ &mp_{struct_name}_type }}, + ({cast}*)&{global_name} +}};""".format( + global_name=global_name, + struct_name=global_type, + cast=gen.visit(global_type_ast), + ), + global_name, + ), + ) + ) + + + generated_globals = [] + for global_name in blobs: + try: + gen_global(global_name, blobs[global_name]) + generated_globals.append(global_name) + except MissingConversionException as exp: + gen_func_error(global_name, exp) + + if _emit_max_phase is None or _emit_max_phase >= 4: + # + # Generate struct-functions + # + + # eprint("/* Generating struct-functions */") + try_generate_structs_from_first_argument() + _emit_struct_locals_dicts(include_methods=True) + + elif _emit_target == "circuitpython" and _emit_max_phase == 3: + _emit_all_struct_types() + _emit_struct_locals_dicts(include_methods=False) + + if _emit_max_phase is None or _emit_max_phase >= 6: + # + # Generate all module functions (not including method functions which were already generated) + # + + print( + """ +/* + * + * Global Module Functions + * + */ +""" + ) + + # eprint("/* Generating global module functions /*") + module_funcs = [func for func in funcs if func.name not in generated_funcs] + module_funcs = filter_module_funcs_for_target( + module_funcs, _emit_target, runtime.get("api_model") + ) + module_funcs = filter_registration_module_funcs(module_funcs) + for module_func in module_funcs[ + : + ]: # clone list because we are changing it in the loop. + if module_func.name in generated_funcs: + continue # generated_funcs could change inside the loop so need to recheck. + try: + gen_mp_func(module_func, None) + # A new function can create new struct with new function structs + new_structs = [ + s + for s in generated_structs + if generated_structs[s] and not generated_struct_functions.get(s) + ] + if new_structs: + _emit_struct_locals_dicts(include_methods=True, struct_list=new_structs) + except MissingConversionException as exp: + gen_func_error(module_func, exp) + module_funcs.remove(module_func) + + functions_not_generated = [ + func.name for func in funcs if func.name not in generated_funcs + ] + if len(functions_not_generated) > 0: + print( + """ +/* + * Functions not generated: + * {funcs} + * + */ + +""".format(funcs="\n * ".join(functions_not_generated)) + ) + + if _emit_max_phase is None or _emit_max_phase >= 7: + # + # Generate callback functions (struct field callbacks) + # + + # eprint("/* Generating callback functions */") + for func_name, func, struct_name in callbacks_used_on_structs: + try: + # print('/* --> gen_callback_func %s */' % func_name) + gen_callback_func(func, func_name="%s_%s" % (struct_name, func_name)) + except MissingConversionException as exp: + gen_func_error(func, exp) + + # + # Emit Mpy Module definition + # + + emit_target = _emit_target + if emit_target == "circuitpython": + from .emit_circuitpython_glue import emit_phase2_enums, finish_cp_fragment + + if _emit_max_phase is not None and _emit_max_phase >= 2: + emit_phase2_enums() + if _emit_max_phase is not None and _emit_max_phase < 6: + module_funcs = [] + runtime.set_("module_funcs", module_funcs) + runtime.set_("generated_globals", generated_globals) + runtime.set_("int_constants", int_constants) + runtime.set_("generated_structs", generated_structs) + runtime.set_("struct_aliases", struct_aliases) + runtime.set_("enums", runtime.get("enums")) + runtime.set_("enum_referenced", enum_referenced) + if len(obj_names) > 0 and (_emit_max_phase is None or _emit_max_phase >= 5): + print( + """ +static const mp_lv_obj_type_t *mp_lv_obj_types[] = {{ + {obj_types}, + NULL +}}; +""".format( + obj_types=",\n ".join( + ["&mp_lv_%s_type" % sanitize(o) for o in obj_names] + ) + ) + ) + finish_cp_fragment(_emit_max_phase or 7) + EmitterResult.capture(locals()).apply(ctx) + return + + # eprint("/* Generating module definition */") + public_struct_names = public_struct_c_names( + runtime.get("api_model"), _emit_target + ) + public_enum_names = public_enum_module_names( + runtime.get("api_model"), _emit_target + ) + print( + """ + +/* + * {module_name} module definitions + */ + +static const mp_rom_map_elem_t {module_name}_globals_table[] = {{ + {{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_{module_name}) }}, + {{ MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&lvgl_mod_init_obj) }}, + {{ MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&lvgl_mod_deinit_obj) }}, + {objects} + {functions} + {enums} + {structs} + {struct_aliases} + {blobs} + {int_constants} +#ifdef LV_OBJ_T + {{ MP_ROM_QSTR(MP_QSTR_LvReferenceError), MP_ROM_PTR(&mp_type_LvReferenceError) }}, +#endif // LV_OBJ_T +}}; +""".format( + module_name=sanitize(module_name), + objects="".join( + [ + "{{ MP_ROM_QSTR(MP_QSTR_{export_name}), MP_ROM_PTR(&mp_lv_{obj}_type_base) }},\n ".format( + export_name=export_name(o, "object"), + obj=sanitize(o), + ) + for o in obj_names + ] + ), + functions="".join( + [ + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_{func}_mpobj) }},\n ".format( + name=export_name(f.name, "function"), func=f.name + ) + for f in module_funcs + ] + ), + enums="".join( + [ + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_lv_{enum}_type_base) }},\n ".format( + name=export_name(enum_name, "enum"), enum=enum_name + ) + for enum_name in enums.keys() + if enum_name not in enum_referenced + and ( + public_enum_names is None + or export_name(enum_name, "enum") in public_enum_names + ) + ] + ), + structs="".join( + [ + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_{struct_name}_type) }},\n ".format( + name=export_name(struct_name, "struct"), + struct_name=sanitize(struct_name), + ) + for struct_name in generated_structs + if generated_structs[struct_name] + and ( + public_struct_names is None + or struct_name in public_struct_names + ) + ] + ), + struct_aliases="".join( + [ + "{{ MP_ROM_QSTR(MP_QSTR_{alias_name}), MP_ROM_PTR(&mp_{struct_name}_type) }},\n ".format( + struct_name=sanitize(struct_name), + alias_name=export_name( + struct_aliases[struct_name], "struct" + ), + ) + for struct_name in struct_aliases.keys() + if public_struct_names is None + or struct_aliases[struct_name] in public_struct_names + ] + ), + blobs="".join( + [ + guarded( + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_{global_name}) }},".format( + name=export_name(global_name, "blob"), + global_name=global_name, + ), + global_name, + indent=" ", + ) + + "\n " + # _nesting is deliberately kept here even though the + # canonical API model marks it private: see the + # comment in emit_backend.module_registration_plan and + # api_model.build_api_model. + for global_name in generated_globals + ] + ), + int_constants="".join( + [ + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(MP_ROM_INT({value})) }},\n ".format( + name=export_name(int_constant, "constant"), + value=int_constant, + ) + for int_constant in int_constants + ] + ), + ) + ) + + + print( + """ +static MP_DEFINE_CONST_DICT ( + mp_module_{module_name}_globals, + {module_name}_globals_table +); + +const mp_obj_module_t mp_module_{module_name} = {{ + .base = {{ &mp_type_module }}, + .globals = (mp_obj_dict_t*)&mp_module_{module_name}_globals +}}; + +MP_REGISTER_MODULE(MP_QSTR_{module_name}, mp_module_{module_name}); + +""".format( + module_name=module_name, + ) + ) + + # Add an array of all object types + + if len(obj_names) > 0: + print( + """ +static const mp_lv_obj_type_t *mp_lv_obj_types[] = {{ + {obj_types}, + NULL +}}; + """.format( + obj_types=",\n ".join( + ["&mp_lv_%s_type" % obj_name for obj_name in obj_names] + ) + ) + ) + + EmitterResult.capture(locals()).apply(ctx) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython.py new file mode 100644 index 00000000..7d01728e --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython.py @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""CircuitPython target entry: analyze → emit_c_micropython_style (target=circuitpython).""" + +from __future__ import print_function + +from . import emit_c_micropython_style as emit_c_mod +from . import runtime +from .analyze import analyze +from .emit_backend import prepare_target_lowering + + +def emit_circuitpython(ctx): + """Run shared analysis and emit CircuitPython C source to ctx.emit_print.""" + prepare_target_lowering(ctx, target="circuitpython", max_phase=7) + if not getattr(ctx, "_analysis_ready", False): + analyze(ctx) + runtime.activate(ctx) + emit_c_mod.emit_c(ctx) + + +def run(ctx): + ctx.init_patterns() + runtime.activate(ctx) + emit_circuitpython(ctx) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython_glue.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython_glue.py new file mode 100644 index 00000000..98b31f3c --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_circuitpython_glue.py @@ -0,0 +1,331 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""CircuitPython bookends: phase-2 enums and LVCP_MODULE_GLOBALS module table.""" +from __future__ import print_function + +import collections + +from . import runtime +from .util import guarded +from .emit_backend import enum_namespace_plan, module_registration_plan, public_enum_module_names, public_struct_c_names + + +# This module owns no mirrored emitter globals; generated output is routed +# through the active run context explicitly. +print = runtime.emit +from .analyze import get_enum_members, get_enum_member_name, get_enum_value +from .helpers import ( + export_name, + get_enum_name, + is_method_of, + is_widget_scoped_only_enum, + method_name_from_func_name, + sanitize, + simplify_identifier, +) + + +def _module_global_entries( + max_phase, + int_constants, + generated_globals, + enums, + enum_referenced, + generated_structs=None, + struct_aliases=None, + obj_names=None, + module_funcs=None, +): + canonical_enum_names = public_enum_module_names( + runtime.get("api_model"), "circuitpython" + ) + plan = module_registration_plan( + max_phase=max_phase, + int_constants=int_constants, + generated_globals=generated_globals, + enums=enums, + enum_referenced=enum_referenced, + generated_structs=generated_structs or {}, + struct_aliases=struct_aliases or {}, + obj_names=obj_names or (), + module_funcs=module_funcs or (), + public_struct_names=public_struct_c_names( + runtime.get("api_model"), "circuitpython" + ), + public_enum_names=( + frozenset( + name + for name in enums + if export_name(name, "enum") in canonical_enum_names + ) + if canonical_enum_names is not None + else None + ), + ) + entries = [] + if plan.int_constants or plan.generated_globals: + for int_constant in plan.int_constants: + entries.append( + " {{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(MP_ROM_INT({value})) }}".format( + name=export_name(int_constant, "constant"), + value=int_constant, + ) + ) + for global_name in plan.generated_globals: + entries.append( + guarded( + " {{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_{global_name}) }},".format( + name=export_name(global_name, "blob"), + global_name=global_name, + ), + global_name, + ) + ) + if plan.enum_names: + for enum_name in plan.enum_names: + entries.append( + " {{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_lv_{enum}_type_base) }}".format( + name=export_name(enum_name, "enum"), + enum=enum_name, + ) + ) + if plan.struct_names: + for struct_name in plan.struct_names: + entries.append( + " {{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_{struct_name}_type) }}".format( + name=export_name(struct_name, "struct"), + struct_name=sanitize(struct_name), + ) + ) + if plan.struct_alias_names: + for struct_name in plan.struct_alias_names: + entries.append( + " {{ MP_ROM_QSTR(MP_QSTR_{alias_name}), MP_ROM_PTR(&mp_{struct_name}_type) }}".format( + struct_name=sanitize(struct_name), + alias_name=export_name(struct_aliases[struct_name], "struct"), + ) + ) + if plan.object_names: + entries.append( + " { MP_ROM_QSTR(MP_QSTR_LvReferenceError), MP_ROM_PTR(&mp_type_LvReferenceError) }" + ) + for obj_name in plan.object_names: + entries.append( + " {{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_lv_{obj}_type_base) }}".format( + name=export_name(obj_name, "object"), + obj=sanitize(obj_name), + ) + ) + if plan.module_functions: + for func in plan.module_functions: + entries.append( + " {{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_{func}_mpobj) }}".format( + name=export_name(func.name, "function"), + func=func.name, + ) + ) + return entries + + +def _table(entries): + """Join table entries; an entry that already ends in its comma keeps it. + + Entries wrapped in ``#if``/``#endif`` carry their comma inside the guard. + """ + return "\n".join( + entry if entry.endswith(",") or entry.endswith("#endif") else entry + "," + for entry in entries + ) + + +def finish_cp_fragment(max_phase): + """Emit mergeable module entry table for shared-bindings/lvgl/__init__.c.""" + int_constants = runtime.get("int_constants", []) + generated_globals = runtime.get("generated_globals", []) + enums = runtime.get("enums", {}) + enum_referenced = runtime.get("enum_referenced", collections.OrderedDict()) + generated_structs = runtime.get("generated_structs", {}) + struct_aliases = runtime.get("struct_aliases", collections.OrderedDict()) + obj_names = runtime.get("obj_names", []) + module_funcs = runtime.get("module_funcs", []) + + entries = _module_global_entries( + max_phase, + int_constants, + generated_globals, + enums, + enum_referenced, + generated_structs=generated_structs, + struct_aliases=struct_aliases, + obj_names=obj_names, + module_funcs=module_funcs, + ) + + spike_entries = [ + " { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_lvgl) }", + " { MP_ROM_QSTR(MP_QSTR___version__), MP_ROM_QSTR(MP_QSTR_9) }", + " { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&lvgl_init_obj) }", + " { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&lvgl_deinit_obj) }", + ] + all_entries = spike_entries + entries + + print( + """ +/* + * CircuitPython module dict (generated; spike registers via MP_REGISTER_MODULE). + * Hand-written init/deinit callables live in shared-bindings/lvgl/__init.c. + */ + +#ifndef LVCP_MODULE_GLOBALS_H +#define LVCP_MODULE_GLOBALS_H + +#include "py/obj.h" + +extern const mp_obj_module_t lvgl_module; + +#endif /* LVCP_MODULE_GLOBALS_H */ + +extern const mp_obj_fun_builtin_fixed_t lvgl_init_obj; +extern const mp_obj_fun_builtin_fixed_t lvgl_deinit_obj; + +static const mp_rom_map_elem_t lvgl_module_globals_table[] = {{ +{table} +}}; + +static MP_DEFINE_CONST_DICT(lvgl_module_globals, lvgl_module_globals_table); + +const mp_obj_module_t lvgl_module = {{ + .base = {{ &mp_type_module }}, + .globals = (mp_obj_dict_t *)&lvgl_module_globals, +}}; + +const mp_rom_map_elem_t lvgl_module_entries[] = {{ +{table} +}}; + +const size_t lvgl_module_entry_count = sizeof(lvgl_module_entries) / sizeof(lvgl_module_entries[0]); +""".format( + table=_table(all_entries) if all_entries else " /* no module entries */" + ) + ) + + runtime.set_("generated_globals", generated_globals) + runtime.set_("int_constants", int_constants) + runtime.set_("enum_referenced", enum_referenced) + + +def finish_phase1_fragment(): + """Emit phase-1 module entry table (alias for finish_cp_fragment(1)).""" + finish_cp_fragment(1) + + +def emit_phase2_enums(): + """Emit enum type objects (same C shape as emit_c_micropython_style.gen_obj for enum keys).""" + if runtime.get("_cp_enums_emitted", False): + return + runtime.set_("_cp_enums_emitted", True) + enums = runtime.get("enums", {}) + obj_metadata = runtime.get("obj_metadata") + enum_referenced = collections.OrderedDict() + module_name = runtime.get("module_name", "lvgl") + + print( + """ +/* + * CircuitPython phase-2 enum type objects + */ +""" + ) + + for enum_plan in enum_namespace_plan( + enums=enums, + get_enum_members=get_enum_members, + is_method_of=is_method_of, + is_widget_scoped=is_widget_scoped_only_enum, + ): + obj_name = enum_plan.name + obj_metadata[obj_name] = {"members": collections.OrderedDict()} + + enum_members = [ + "{{ MP_ROM_QSTR(MP_QSTR_{enum_member}), MP_ROM_PTR({enum_member_value}) }}".format( + enum_member=export_name(enum_member_name, "enum_member"), + enum_member_value=get_enum_value(obj_name, enum_member_name), + ) + for enum_member_name in enum_plan.members + ] + obj_metadata[obj_name]["members"].update( + { + get_enum_member_name(enum_member_name): {"type": "enum_member"} + for enum_member_name in enum_plan.members + } + ) + + obj_enums = enum_plan.nested_names + enum_types = [ + "{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&mp_lv_{enum}_type_base) }}".format( + name=export_name(method_name_from_func_name(enum_name), "enum"), + enum=enum_name + ) + for enum_name in obj_enums + ] + obj_metadata[obj_name]["members"].update( + { + method_name_from_func_name(enum_name): {"type": "enum_type"} + for enum_name in obj_enums + } + ) + for enum_name in obj_enums: + if enum_name in obj_metadata: + obj_metadata[obj_name]["members"][ + method_name_from_func_name(enum_name) + ].update(obj_metadata[enum_name]) + if enum_name in enum_plan.widget_scoped_nested_names: + enum_referenced[enum_name] = True + + locals_dict_entries = ",\n ".join(enum_members + enum_types) + + print( + """ +/* + * {module_name} {obj} object definitions + */ + +static const mp_rom_map_elem_t {obj}_locals_dict_table[] = {{ + {locals_dict_entries} +}}; + +static MP_DEFINE_CONST_DICT({obj}_locals_dict, {obj}_locals_dict_table); + +static void {obj}_print(const mp_print_t *print, + mp_obj_t self_in, + mp_print_kind_t kind) +{{ + mp_printf(print, "{module_name} {obj}"); +}} + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_lv_{obj}_type_base, + MP_QSTR_{obj}, + MP_TYPE_FLAG_NONE, + print, {obj}_print, + attr, call_parent_methods, + locals_dict, &{obj}_locals_dict +); + +GENMPY_UNUSED static const mp_lv_obj_type_t mp_lv_{obj}_type = {{ +#ifdef LV_OBJ_T + .lv_obj_class = NULL, +#endif + .mp_obj_type = &mp_lv_{obj}_type_base, +}}; +""".format( + module_name=module_name, + obj=sanitize(obj_name), + locals_dict_entries=locals_dict_entries, + ) + ) + + runtime.set_("obj_metadata", obj_metadata) + runtime.set_("enum_referenced", enum_referenced) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython.py new file mode 100644 index 00000000..89be20a0 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython.py @@ -0,0 +1,32 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""CPython target entry: analyze → emit_c_cpython.""" + +from __future__ import print_function + +from . import emit_c_cpython as emit_c_mod +from . import runtime +from .analyze import analyze +from .emit_backend import prepare_target_lowering + + +def emit_cpython(ctx): + prepare_target_lowering(ctx, target="cpython", max_phase=7) + if not getattr(ctx, "_analysis_ready", False): + analyze(ctx) + runtime.activate(ctx) + emit_c_mod.emit_c(ctx) + + +def run(ctx): + from .emit_cpython_native import begin_emit_helpers, reset_emit_helpers + + ctx.init_patterns() + runtime.activate(ctx) + helper_token = begin_emit_helpers() + try: + emit_cpython(ctx) + finally: + reset_emit_helpers(helper_token) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_glue.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_glue.py new file mode 100644 index 00000000..2e81b243 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_glue.py @@ -0,0 +1,493 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""CPython bookends: phase-2 enum types and PyInit_lvgl / module registration.""" +from __future__ import print_function + +import collections + +from . import runtime +from .util import guarded +from .emit_backend import enum_namespace_plan, module_registration_plan, public_enum_module_names, public_struct_c_names + + +# This module owns no mirrored emitter globals; generated output is routed +# through the active run context explicitly. +print = runtime.emit +from .analyze import get_enum_member_name, get_enum_members, get_enum_value +from .emit_cpython_native import _resolved_py_func_name +from .helpers import export_name, get_enum_name, is_method_of, is_widget_scoped_only_enum, method_name_from_func_name, sanitize, simplify_identifier + + +def _member_c_value(value): + if value.startswith("MP_ROM_INT(") and value.endswith(")"): + return value[len("MP_ROM_INT(") : -1] + if value.startswith("&mp_"): + return value[len("&mp_") :] + return value + + +def emit_phase2_enums_cpython(): + """Emit read-only enum namespace types (native CPython API).""" + if runtime.get("_py_enums_emitted", False): + return + runtime.set_("_py_enums_emitted", True) + enums = runtime.get("enums", {}) + obj_metadata = runtime.get("obj_metadata") + enum_referenced = collections.OrderedDict() + module_name = runtime.get("module_name", "lvgl") + + print( + """ +/* + * CPython phase-2 enum namespace types + * + * Members resolve through each type's tp_getattro. __dir__ lists them from a + * static name table, so dir(), help() and REPL completion can find them. + */ + +static PyObject *lvpy_enum_dir(PyObject *self, const char *const *members) +{ + PyObject *base = PyObject_CallMethod((PyObject *)&PyBaseObject_Type, "__dir__", "O", self); + if (base == NULL) { + return NULL; + } + PyObject *names = PySequence_List(base); + Py_DECREF(base); + if (names == NULL) { + return NULL; + } + for (const char *const *m = members; *m != NULL; m++) { + PyObject *s = PyUnicode_FromString(*m); + if (s == NULL || PyList_Append(names, s) < 0) { + Py_XDECREF(s); + Py_DECREF(names); + return NULL; + } + Py_DECREF(s); + } + return names; +} +""" + ) + + for enum_plan in enum_namespace_plan( + enums=enums, + get_enum_members=get_enum_members, + is_method_of=is_method_of, + is_widget_scoped=is_widget_scoped_only_enum, + ): + enum_name = enum_plan.name + members = enums[enum_name] + if not members: + continue + obj_metadata[enum_name] = {"members": collections.OrderedDict()} + obj_metadata[enum_name]["members"].update( + { + get_enum_member_name(enum_member_name): {"type": "enum_member"} + for enum_member_name in enum_plan.members + } + ) + obj_enums = enum_plan.nested_names + obj_metadata[enum_name]["members"].update( + { + method_name_from_func_name(other): {"type": "enum_type"} + for other in obj_enums + } + ) + for other in obj_enums: + if other in obj_metadata: + obj_metadata[enum_name]["members"][ + method_name_from_func_name(other) + ].update(obj_metadata[other]) + if other in enum_plan.widget_scoped_nested_names: + enum_referenced[other] = True + safe = sanitize(enum_name) + py_name = export_name(enum_name, "enum") + + print( + """ +static PyObject *py_lv_{safe}_getattro(PyObject *self, PyObject *name) +{{ + (void)self; + if (!PyUnicode_Check(name)) {{ + PyErr_SetString(PyExc_TypeError, "attribute name must be string"); + return NULL; + }} + const char *attr = PyUnicode_AsUTF8(name); + if (attr == NULL) {{ + return NULL; + }} +""".format(safe=safe) + ) + + py_members = [] + for member_name, member_value in members.items(): + cval = _member_c_value(member_value) + py_member = export_name(member_name, "enum_member") + py_members.append(py_member) + if cval.startswith("LV_SYMBOL_"): + print( + ' if (strcmp(attr, "{member}") == 0) return PyUnicode_FromString({cval});'.format( + member=py_member, cval=cval + ) + ) + else: + print( + ' if (strcmp(attr, "{member}") == 0) return PyLong_FromLong({cval});'.format( + member=py_member, cval=cval + ) + ) + + print( + """ + return PyObject_GenericGetAttr(self, name); +}} + +static const char *const py_lv_{safe}_members[] = {{ +{member_list} NULL +}}; + +static PyObject *py_lv_{safe}_dir(PyObject *self, PyObject *Py_UNUSED(ignored)) +{{ + return lvpy_enum_dir(self, py_lv_{safe}_members); +}} + +static PyMethodDef py_lv_{safe}_methods[] = {{ + {{"__dir__", py_lv_{safe}_dir, METH_NOARGS, NULL}}, + {{NULL, NULL, 0, NULL}} +}}; + +static PyTypeObject py_lv_{safe}_type = {{ + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "{module}.{py_name}", + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_getattro = py_lv_{safe}_getattro, + .tp_methods = py_lv_{safe}_methods, + .tp_doc = "LVGL {py_name} enum namespace", +}}; +""".format( + module=module_name, + py_name=py_name, + safe=safe, + member_list="".join(' "{}",\n'.format(m) for m in py_members), + ) + ) + + runtime.set_("obj_metadata", obj_metadata) + runtime.set_("enum_referenced", enum_referenced) + + +def finish_py_module(max_phase): + """Emit PyInit_lvgl and module-level registration (native CPython API).""" + int_constants = runtime.get("int_constants", []) + generated_globals = runtime.get("generated_globals", []) + cpython_global_types = runtime.get("cpython_global_types", {}) + enums = runtime.get("enums", {}) + enum_referenced = runtime.get("enum_referenced", collections.OrderedDict()) + generated_structs = runtime.get("generated_structs", {}) + struct_aliases = runtime.get("struct_aliases", collections.OrderedDict()) + cpython_struct_sizes = runtime.get("cpython_struct_sizes", {}) + obj_names = runtime.get("obj_names", []) + module_funcs = runtime.get("module_funcs", []) + canonical_enum_names = public_enum_module_names( + runtime.get("api_model"), "cpython" + ) + registration = module_registration_plan( + max_phase=max_phase, + int_constants=int_constants, + generated_globals=generated_globals, + enums=enums, + enum_referenced=enum_referenced, + generated_structs=generated_structs, + struct_aliases=struct_aliases, + obj_names=obj_names, + module_funcs=module_funcs, + public_struct_names=public_struct_c_names(runtime.get("api_model"), "cpython"), + public_enum_names=( + frozenset( + name + for name in enums + if export_name(name, "enum") in canonical_enum_names + ) + if canonical_enum_names is not None + else None + ), + ) + + print( + """ +/* + * CPython module definition + */ + +static int lvgl_mod_initialized = 0; + +/* A build of this module can run its own setup right after lv_init() by + * defining LVPY_AFTER_LV_INIT as the name of a void(void) function: lvgl-python + * registers jpegio's JPEG decoder there. A macro rather than a weak symbol, so + * it works with every compiler a wheel is built with. */ +#ifdef LVPY_AFTER_LV_INIT +extern void LVPY_AFTER_LV_INIT(void); +#endif + +static PyObject *py_lvgl_init(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + lvpy_lock(); + if (!lvgl_mod_initialized) { + lv_init(); +#ifdef LVPY_AFTER_LV_INIT + LVPY_AFTER_LV_INIT(); +#endif + lvgl_mod_initialized = 1; + } + lvpy_unlock(); + Py_RETURN_NONE; +} + +static PyObject *py_lvgl_deinit(PyObject *self, PyObject *args) +{ + (void)self; + (void)args; + lvpy_lock(); + if (lvgl_mod_initialized) { + lv_deinit(); + lvgl_mod_initialized = 0; + } + lvpy_unlock(); + Py_RETURN_NONE; +} + +static PyMethodDef lvgl_methods[] = { + {"init", py_lvgl_init, METH_NOARGS, "Initialize LVGL"}, + {"deinit", py_lvgl_deinit, METH_NOARGS, "Deinitialize LVGL"}, + {NULL, NULL, 0, NULL} +}; + +static struct PyModuleDef lvgl_module_def = { + PyModuleDef_HEAD_INIT, + "lvgl", + "LVGL bindings for CPython (generated)", + -1, + lvgl_methods +}; +""" + ) + + print("PyMODINIT_FUNC PyInit_lvgl(void)") + print("{") + print(" PyObject *m = PyModule_Create(&lvgl_module_def);") + print(" if (m == NULL) {") + print(" return NULL;") + print(" }") + # Free-threaded builds re-enable the GIL on import unless the module + # says it doesn't need it. LVGL itself isn't thread-safe; the rule that + # makes this safe is one thread for every LVGL call and every LVGL + # object's release, which lvgl-python documents. + print("#ifdef Py_GIL_DISABLED") + print(" if (PyUnstable_Module_SetGIL(m, Py_MOD_GIL_NOT_USED) < 0) {") + print(" Py_DECREF(m);") + print(" return NULL;") + print(" }") + print("#endif") + + if registration.int_constants or registration.generated_globals: + for int_constant in registration.int_constants: + name = export_name(int_constant, "constant") + print( + ' if (PyModule_AddIntConstant(m, "{name}", {value}) < 0) return NULL;'.format( + name=name, value=int_constant + ) + ) + for global_name in registration.generated_globals: + if not global_name.startswith("LV_"): + continue + if global_name.startswith("LV_SYMBOL_"): + continue + py_name = simplify_identifier(global_name) + if py_name.startswith("LV_"): + py_name = py_name[3:] + print( + ' if (PyModule_AddStringConstant(m, "{name}", {value}) < 0) return NULL;'.format( + name=py_name, value=global_name + ) + ) + + if registration.enum_names: + for enum_name in registration.enum_names: + safe = sanitize(enum_name) + py_name = export_name(enum_name, "enum") + print( + ' if (PyType_Ready(&py_lv_{safe}_type) < 0) return NULL;'.format( + safe=safe + ) + ) + print( + ' {{ PyObject *ns = PyType_GenericNew(&py_lv_{safe}_type, NULL, NULL); if (ns == NULL) return NULL; if (PyModule_AddObject(m, "{name}", ns) < 0) return NULL; }}'.format( + name=py_name, safe=safe + ) + ) + + if max_phase >= 3: + print(" py_lv_runtime_init_types();") + print(" if (PyType_Ready(&py_blob_type) < 0) return NULL;") + print(" if (PyType_Ready(&py_lv_base_struct_type) < 0) return NULL;") + print(" if (PyType_Ready(&py_C_Pointer_type) < 0) return NULL;") + print(" Py_INCREF((PyObject *)&py_C_Pointer_type);") + print(' if (PyModule_AddObject(m, "C_Pointer", (PyObject *)&py_C_Pointer_type) < 0) return NULL;') + print(" if (PyLvReferenceError) {") + print(" Py_INCREF(PyLvReferenceError);") + print(' if (PyModule_AddObject(m, "LvReferenceError", PyLvReferenceError) < 0) return NULL;') + print(" }") + if registration.struct_names: + for struct_name in registration.struct_names: + san = sanitize(struct_name) + struct_tag = ( + "struct " + if struct_name in runtime.get("structs_without_typedef", {}) + else "" + ) + py_name = export_name(struct_name, "struct") + print( + ' if (PyType_Ready(&py_{san}_type) < 0) return NULL;'.format( + san=san + ) + ) + if struct_name in cpython_struct_sizes: + print( + ' lv_struct_register_size(&py_{san}_type, sizeof({tag}{name}));'.format( + san=san, tag=struct_tag, name=struct_name + ) + ) + print( + ' lv_struct_expose_size(&py_{san}_type);'.format(san=san) + ) + print( + ' Py_INCREF((PyObject *)&py_{san}_type);'.format(san=san) + ) + print( + ' if (PyModule_AddObject(m, "{name}", (PyObject *)&py_{san}_type) < 0) return NULL;'.format( + name=py_name, san=san + ) + ) + if registration.struct_alias_names: + for struct_name in registration.struct_alias_names: + san = sanitize(struct_name) + struct_tag = ( + "struct " + if struct_name in runtime.get("structs_without_typedef", {}) + else "" + ) + py_name = export_name(struct_aliases[struct_name], "struct") + print( + ' if (PyType_Ready(&py_{san}_type) < 0) return NULL;'.format( + san=san + ) + ) + if struct_name in cpython_struct_sizes: + print( + ' lv_struct_register_size(&py_{san}_type, sizeof({tag}{name}));'.format( + san=san, tag=struct_tag, name=struct_name + ) + ) + print( + ' lv_struct_expose_size(&py_{san}_type);'.format(san=san) + ) + print( + ' Py_INCREF((PyObject *)&py_{san}_type);'.format(san=san) + ) + print( + ' if (PyModule_AddObject(m, "{name}", (PyObject *)&py_{san}_type) < 0) return NULL;'.format( + name=py_name, san=san + ) + ) + if registration.struct_names: + # Structs that aren't exported, such as the type of an anonymous + # union field, are still returned by field reads, so their types + # must be ready (lvgl-bindings#39). + for struct_name, generated in generated_structs.items(): + if generated and struct_name not in registration.struct_names: + print( + ' if (PyType_Ready(&py_{san}_type) < 0) return NULL;'.format( + san=sanitize(struct_name) + ) + ) + + for global_name in cpython_global_types: + global_type = cpython_global_types.get(global_name) + type_object = ( + "&py_{san}_type".format(san=sanitize(global_type)) + if global_type + else "&py_blob_type" + ) + py_name = simplify_identifier(global_name) + print( + guarded( + ' {{ PyObject *obj = lv_to_mp_struct({type_object}, (void *)&{global_name});' + ' if (obj == NULL) return NULL;' + ' if (PyModule_AddObject(m, "{py_name}", obj) < 0) {{ Py_DECREF(obj); return NULL; }} }}'.format( + type_object=type_object, + global_name=global_name, + py_name=py_name, + ), + global_name, + ) + ) + + if registration.object_names: + enums = runtime.get("enums", {}) + for obj_name in registration.object_names: + san = sanitize(obj_name) + print( + ' if (PyType_Ready(&py_lv_{san}_type) < 0) return NULL;'.format( + san=san + ) + ) + obj_enums = [ + enum_name + for enum_name in enums.keys() + if is_method_of(enum_name, obj_name) + ] + for enum_name in obj_enums: + enum_safe = sanitize(enum_name) + attr_name = export_name(method_name_from_func_name(enum_name), "enum") + print( + ' {{ if (PyType_Ready(&py_lv_{enum_safe}_type) < 0) return NULL;' + ' PyObject *_enum_ns = (PyObject *)PyType_GenericNew(&py_lv_{enum_safe}_type, NULL, NULL);' + ' if (_enum_ns == NULL) return NULL;' + ' if (((PyTypeObject *)&py_lv_{san}_type)->tp_dict &&' + ' PyDict_SetItemString(((PyTypeObject *)&py_lv_{san}_type)->tp_dict, "{attr_name}", _enum_ns) < 0) {{ Py_DECREF(_enum_ns); return NULL; }}' + ' Py_DECREF(_enum_ns); }}'.format( + enum_safe=enum_safe, + san=san, + attr_name=attr_name, + ) + ) + print( + ' Py_INCREF((PyObject *)&py_lv_{san}_type);'.format(san=san) + ) + print( + ' if (PyModule_AddObject(m, "{name}", (PyObject *)&py_lv_{san}_type) < 0) return NULL;'.format( + name=export_name(obj_name, "object"), san=san + ) + ) + + if registration.module_functions: + generated_funcs = runtime.get("generated_funcs", {}) + for func in registration.module_functions: + py_func = _resolved_py_func_name(func.name, generated_funcs) + if not py_func: + continue + fname = sanitize(py_func) + py_name = export_name(func.name, "function") + print( + ' {{ PyObject *fn = PyCFunction_New(&py_{fname}_def, NULL); if (fn == NULL) return NULL; if (PyModule_AddObject(m, "{py_name}", fn) < 0) return NULL; }}'.format( + fname=fname, py_name=py_name + ) + ) + + print(" return m;") + print("}") diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_native.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_native.py new file mode 100644 index 00000000..b2fc5f47 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_cpython_native.py @@ -0,0 +1,1651 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""CPython body codegen (phases 3–7): funcs, objects, structs, and callbacks.""" + +from __future__ import print_function + +import re +import collections +import copy +from contextvars import ContextVar + +from pycparser import c_ast + +from . import runtime +from .emit_backend import ( + callback_return_conversion_available, + conversion_available, + function_reuse_allowed, +) +from .helpers import ( + is_global_callback, + is_method_of, + is_struct, + is_widget_scoped_only_enum, + method_name_from_func_name, + sanitize as helper_sanitize, + simplify_identifier, +) +from .parse import add_default_declname, convert_array_to_ptr, function_prototype, get_name, get_type + + +# This module owns no mirrored emitter globals; generated output is routed +# through the active run context explicitly. +print = runtime.emit + + +_EMIT_HELPERS = ContextVar("lvgl_cpython_emit_helpers", default=None) + + +def begin_emit_helpers(): + """Start an isolated helper scope and return its restoration token.""" + return _EMIT_HELPERS.set(None) + + +def bind_emit_helpers(local_ns): + """Bind AST-emitter helpers to the active CPython backend run.""" + from . import analyze as analyze_mod + + analyze_fns = ( + "get_methods", + "has_ctor", + "get_ctor", + "get_struct_functions", + "noncommon_part", + "get_enum_members", + "get_enum_value", + "get_enum_member_name", + "is_static_member", + "is_struct_function", + ) + bound = {k: getattr(analyze_mod, k) for k in analyze_fns} + bound["sanitize"] = helper_sanitize + bound["simplify_identifier"] = simplify_identifier + bound["method_name_from_func_name"] = method_name_from_func_name + bound["is_struct"] = is_struct + bound["is_global_callback"] = is_global_callback + bound["get_type"] = get_type + bound["function_prototype"] = function_prototype + bound["MissingConversionException"] = analyze_mod.MissingConversionException + keys = ( + "gen", + "parser", + "get_name", + "is_struct", + "structs", + "structs_without_typedef", + "decl_to_callback", + "flatten_struct", + "get_user_data", + "is_global_callback", + "get_arg_name", + "lv_base_obj_pattern", + "gen_func_error", + "try_generate_type", + "lv_to_mp_funcptr", + "function_prototype", + "is_static_member", + "is_struct_function", + "build_mp_func_arg", + "method_name_from_func_name", + "parent_obj_names", + "base_obj_type", + "lv_func_returns_array", + "try_generate_array_type", + "func_prototypes", + "func_metadata", + "obj_metadata", + "generated_funcs", + "generated_callbacks", + "callback_metadata", + "lv_to_mp", + "mp_to_lv", + "lv_to_mp_byref", + "lv_mp_type", + "generated_structs", + "generated_struct_functions", + "generated_struct_method_funcs", + "callbacks_used_on_structs", + "enum_referenced", + "enums", + ) + for k in keys: + if k in local_ns: + bound[k] = local_ns[k] + elif k in _STATE_KEYS: + value = runtime.get(k, None) + if value is not None: + bound[k] = value + _EMIT_HELPERS.set(bound) + return bound + + +_STATE_KEYS = ( + "generated_structs", + "generated_struct_functions", + "struct_aliases", + "callbacks_used_on_structs", + "generated_funcs", + "generated_callbacks", + "mp_to_lv", + "lv_to_mp", + "lv_to_mp_byref", + "lv_mp_type", + "func_prototypes", + "func_metadata", + "obj_metadata", + "enum_referenced", + "enums", +) + + +def _h(name): + helpers = _EMIT_HELPERS.get() + if helpers is None: + raise RuntimeError("CPython native emitter helpers are not bound") + if name in helpers: + return helpers[name] + if name in _STATE_KEYS: + return runtime.get(name) + try: + return runtime.get(name) + except NameError: + raise KeyError("Missing emit helper: %s" % name) + + +def bound_helper(name, default=None): + """Return a value from the active CPython native emitter binding.""" + helpers = _EMIT_HELPERS.get() + if helpers is None: + return default + return helpers.get(name, default) + + +def reset_emit_helpers(token=None): + """Release helper state, restoring an enclosing emitter when supplied.""" + if token is None: + _EMIT_HELPERS.set(None) + else: + _EMIT_HELPERS.reset(token) + + +def _emit_max_phase(): + return runtime.get("emit_options", {}).get("max_phase") + + +def emit_helper_struct_cpython(): + from pycparser import c_parser + + parser = c_parser.CParser() + ast = parser.parse( + """ +typedef union { + void* ptr_val; + const char* str_val; + int int_val; + unsigned int uint_val; +} C_Pointer; +""" + ) + try_generate_struct_cpython("C_Pointer", ast.ext[0].type.type) + + +def _struct_value_writer(struct_name, san, struct_tag, complete): + """C for ``mp_write_``: a Python value to a struct by value. + + The value form is dereferenced where it is used (``data->header = + mp_write_...(value)``), so it must never yield NULL. A dict builds the + struct the way the type's own constructor does, as MicroPython accepts; + anything else sets ``TypeError`` and yields a zeroed scratch copy, which + the caller discards when it sees the error (lvgl-bindings#21). + """ + ctype = "{tag}{name}".format(tag=struct_tag, name=struct_name) + if not complete: + return "#define mp_write_{san}(struct_obj) (*(({ctype}*)mp_write_ptr_{san}(struct_obj)))".format( + san=san, ctype=ctype + ) + return """static {ctype} mp_write_scratch_{san}; + +static inline void* mp_write_value_ptr_{san}(PyObject *value) +{{ + if (value != NULL && PyDict_Check(value)) {{ + PyObject *tmp = PyObject_CallOneArg((PyObject *)&py_{san}_type, value); + if (tmp != NULL) {{ + memcpy(&mp_write_scratch_{san}, ((py_lv_struct_t *)tmp)->data, sizeof({ctype})); + Py_DECREF(tmp); + return &mp_write_scratch_{san}; + }} + }} else if (value != NULL && value != Py_None) {{ + void *p = mp_write_ptr_{san}(value); + if (p != NULL) return p; + }} else {{ + PyErr_SetString(PyExc_TypeError, "Expected lvgl.{san} or dict, got None"); + }} + memset(&mp_write_scratch_{san}, 0, sizeof({ctype})); + return &mp_write_scratch_{san}; +}} + +#define mp_write_{san}(struct_obj) (*(({ctype}*)mp_write_value_ptr_{san}(struct_obj)))""".format( + san=san, ctype=ctype + ) + + +def try_generate_struct_cpython(struct_name, struct): + gen = _h("gen") + sanitize = _h("sanitize") + get_type_fn = _h("get_type") + mp_to_lv = _h("mp_to_lv") + lv_to_mp = _h("lv_to_mp") + lv_to_mp_byref = _h("lv_to_mp_byref") + lv_mp_type = _h("lv_mp_type") + generated_structs = _h("generated_structs") + structs_without_typedef = _h("structs_without_typedef") + flatten_struct = _h("flatten_struct") + try_generate_type = _h("try_generate_type") + decl_to_callback = _h("decl_to_callback") + get_user_data = _h("get_user_data") + callbacks_used_on_structs = _h("callbacks_used_on_structs") + MissingConversionException = _h("MissingConversionException") + gen_func_error = _h("gen_func_error") + max_phase = _emit_max_phase() + + if struct_name in generated_structs: + return None + sanitized_struct_name = sanitize(struct_name) + generated_structs[struct_name] = False + + if struct_name in mp_to_lv: + return mp_to_lv[struct_name] + + if struct.decls is None: + structs = _h("structs") + if struct_name == struct.name: + return None + if struct.name not in structs: + return None + return try_generate_type(structs[struct.name]) + + flatten_struct_decls = flatten_struct(struct.decls) + struct_tag = "struct " if struct_name in structs_without_typedef.keys() else "" + read_cases = [] + write_cases = [] + struct_has_fields = bool(flatten_struct_decls) + elem_size_expr = ( + "sizeof({struct_tag}{struct_name})".format( + struct_tag=struct_tag, struct_name=struct_name + ) + if struct_has_fields + else "0" + ) + + for decl in flatten_struct_decls: + converted = try_generate_type(decl.type) + type_name = get_type_fn(decl.type, remove_quals=True) + if ( + not converted + and ("\n" in type_name or "{" in type_name) + and isinstance(decl.type, c_ast.TypeDecl) + and is_struct(decl.type.type) + ): + # An anonymous struct or union member (lv_grad_dsc_t.params): + # name its type and bind it as a struct, as MicroPython does + # (lvgl-bindings#39). + type_name = "%s_%s_t" % (struct_name[:-2], decl.type.declname) + print( + "typedef __typeof__( (({tag}{parent}*)(0))->{child} ) {new};".format( + tag=struct_tag, + parent=struct_name, + child=decl.type.declname, + new=type_name, + ) + ) + try_generate_struct_cpython(type_name, decl.type.type) + if "\n" in type_name or "{" in type_name: + continue + if not is_struct(decl.type.type): + if (type_name not in mp_to_lv or not mp_to_lv[type_name]) or ( + type_name not in lv_to_mp or not lv_to_mp[type_name] + ): + if type_name in generated_structs: + continue + raise MissingConversionException( + "Missing conversion to %s when generating struct %s.%s" + % (type_name, struct_name, decl.name) + ) + + mp_to_lv_convertor = mp_to_lv[type_name] + lv_to_mp_convertor = ( + lv_to_mp_byref[type_name] + if type_name in lv_to_mp_byref + else lv_to_mp[type_name] + ) + cast = "(void*)" if isinstance(decl.type, c_ast.PtrDecl) else "" + callback = decl_to_callback(decl) + + if callback: + if max_phase is not None and max_phase < 7: + continue + func_name, arg_type = callback + user_data, _, _ = get_user_data( + arg_type, + func_name=func_name, + containing_struct=struct, + containing_struct_name=struct_name, + ) + if callback not in callbacks_used_on_structs: + callbacks_used_on_structs.append(callback + (struct_name,)) + if user_data in [d.name for d in flatten_struct_decls]: + full_user_data = "data->%s" % user_data + full_user_data_ptr = "&%s" % full_user_data + lv_callback = "%s_%s_callback" % (struct_name, func_name) + print( + "static %s %s_%s_callback(%s);" + % ( + get_type_fn(arg_type.type, remove_quals=False), + struct_name, + func_name, + gen.visit(arg_type.args), + ) + ) + else: + full_user_data = "NULL" + full_user_data_ptr = full_user_data + lv_callback = "NULL" + if not user_data: + gen_func_error( + decl, + "Missing 'user_data' field for callback '%s_%s'" + % (struct_name, func_name), + ) + else: + gen_func_error( + decl, "Missing 'user_data' member in struct '%s'" % struct_name + ) + write_cases.append( + 'if (strcmp(attr, "{field}") == 0) {{ data->{decl_name} = {cast}mp_lv_callback(value, {lv_callback}, "{struct_name}_{field}", {user_data}, {holder}, NULL, NULL); result = 0; }}'.format( + struct_name=struct_name, + field=sanitize(decl.name), + decl_name=decl.name, + lv_callback=lv_callback, + user_data=full_user_data_ptr, + holder="data" if full_user_data_ptr.startswith("&data->") else "NULL", + cast=cast, + ) + ) + read_cases.append( + 'if (strcmp(attr, "{field}") == 0) return mp_lv_funcptr(NULL, {cast}data->{decl_name}, {lv_callback}, "{struct_name}_{field}", {user_data});'.format( + struct_name=struct_name, + field=sanitize(decl.name), + decl_name=decl.name, + lv_callback=lv_callback, + user_data=full_user_data, + cast=cast, + ) + ) + else: + is_writeable = (not hasattr(decl.type, "quals")) or "const" not in decl.type.quals + elem = ( + _struct_array_elem(decl, get_type_fn, lv_to_mp) + if isinstance(decl.type, c_ast.ArrayDecl) + else None + ) + if elem: + # A view, not a raw Blob, and a checked whole-array write + # instead of a memcpy from whatever mp_to_ptr returned + # (lvgl-bindings#38). + shape = "data->{decl_name}, {dim}, sizeof({ctype})".format( + decl_name=decl.name, + dim=gen.visit(decl.type.dim), + ctype=gen.visit(decl.type.type), + ) + san = sanitize(elem) + if is_writeable: + write_cases.append( + 'if (strcmp(attr, "{field}") == 0) {{ lvpy_struct_array_assign({shape}, mp_write_value_ptr_{san}, value); result = 0; }}'.format( + field=sanitize(decl.name), shape=shape, san=san + ) + ) + read_cases.append( + 'if (strcmp(attr, "{field}") == 0) return lvpy_struct_array_new(self, {shape}, mp_read_ptr_{san}, mp_write_value_ptr_{san});'.format( + field=sanitize(decl.name), shape=shape, san=san + ) + ) + elif isinstance(decl.type, c_ast.ArrayDecl): + memcpy_size = "sizeof(%s)*%s" % ( + gen.visit(decl.type.type), + gen.visit(decl.type.dim), + ) + if is_writeable: + write_cases.append( + 'if (strcmp(attr, "{field}") == 0) {{ memcpy((void*)&data->{decl_name}, {cast}{convertor}(value), {size}); result = 0; }}'.format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=mp_to_lv_convertor, + cast=cast, + size=memcpy_size, + ) + ) + read_cases.append( + 'if (strcmp(attr, "{field}") == 0) return {convertor}({cast}data->{decl_name});'.format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=lv_to_mp_convertor, + cast=cast, + ) + ) + else: + if is_writeable: + write_cases.append( + 'if (strcmp(attr, "{field}") == 0) {{ data->{decl_name} = {cast}{convertor}(value); result = 0; }}'.format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=mp_to_lv_convertor, + cast=cast, + ) + ) + read_cases.append( + 'if (strcmp(attr, "{field}") == 0) return {convertor}({cast}data->{decl_name});'.format( + field=sanitize(decl.name), + decl_name=decl.name, + convertor=lv_to_mp_convertor, + cast=cast, + ) + ) + + print( + """ +/* + * Struct {struct_name} (CPython) + */ + +extern PyMethodDef py_{san}_methods[]; + +static PyObject *py_{san}_getattro(PyObject *self, PyObject *name) +{{ + py_lv_struct_t *inst = (py_lv_struct_t *)self; + {struct_tag}{struct_name} *data = ({struct_tag}{struct_name}*)inst->data; + if (data == NULL) {{ + PyErr_SetString(PyLvReferenceError, "struct data is NULL"); + return NULL; + }} + const char *attr = PyUnicode_AsUTF8(name); + if (attr == NULL) return NULL; + {read_cases} + for (PyMethodDef *m = py_{san}_methods; m->ml_name != NULL; m++) {{ + if (strcmp(attr, m->ml_name) == 0) + return PyCFunction_NewEx(m, self, NULL); + }} + return PyObject_GenericGetAttr((PyObject *)self, name); +}} + +static const char *const py_{san}_field_names[] = {{{field_names}NULL}}; + +static PyObject *py_{san}_dir(PyObject *self, PyObject *unused) +{{ + (void)unused; + return lvpy_struct_dir(self, py_{san}_field_names, py_{san}_methods); +}} + +static PyMethodDef py_{san}_type_methods[] = {{ + {{"__dir__", py_{san}_dir, METH_NOARGS, NULL}}, + {{NULL}} +}}; + +static int py_{san}_setattro(PyObject *self, PyObject *name, PyObject *value) +{{ + if (value == NULL) {{ + PyErr_SetString(PyExc_AttributeError, "cannot delete struct fields"); + return -1; + }} + py_lv_struct_t *inst = (py_lv_struct_t *)self; + {struct_tag}{struct_name} *data = ({struct_tag}{struct_name}*)inst->data; + if (data == NULL) {{ + PyErr_SetString(PyLvReferenceError, "struct data is NULL"); + return -1; + }} + const char *attr = PyUnicode_AsUTF8(name); + if (attr == NULL) return -1; + int result = -1; + {save_fields} + {write_cases} + if (PyErr_Occurred()) {{ + {restore_fields} + return -1; + }} + if (result < 0) {{ + PyErr_Format(PyExc_AttributeError, "'{struct_name}' object has no attribute '%s'", attr); + }} + return result; +}} + +static PyObject *py_{san}_new(PyTypeObject *type, PyObject *args, PyObject *kwds) +{{ + return make_new_lv_struct(type, args, kwds, {elem_size}); +}} + +static void py_{san}_dealloc(py_lv_struct_t *self) +{{ + py_lv_struct_dealloc(self); +}} + +PyTypeObject py_{san}_type = {{ + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "lvgl.{san}", + .tp_basicsize = sizeof(py_lv_struct_t), + .tp_dealloc = (destructor)py_{san}_dealloc, + .tp_getattro = (getter)py_{san}_getattro, + .tp_setattro = (setter)py_{san}_setattro, + .tp_new = py_{san}_new, + .tp_methods = py_{san}_type_methods, + .tp_base = &py_lv_base_struct_type, + .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, +}}; + +static inline void* mp_write_ptr_{san}(PyObject *self_in) +{{ + if (!self_in || self_in == Py_None) return NULL; + if (!PyObject_TypeCheck(self_in, &py_{san}_type)) {{ + PyErr_Format(PyExc_TypeError, "Expected lvgl.{san}, got '%s'", Py_TYPE(self_in)->tp_name); + return NULL; + }} + py_lv_struct_t *self = (py_lv_struct_t *)self_in; + return ({struct_tag}{struct_name}*)self->data; +}} + +{write_value} + +static inline PyObject *mp_read_ptr_{san}(void *field) +{{ + return lv_to_mp_struct(&py_{san}_type, field); +}} + +#define mp_read_{san}(field) lv_to_mp_struct_own(&py_{san}_type, copy_buffer(&field, sizeof({struct_tag}{struct_name}))) +#define mp_read_byref_{san}(field) mp_read_ptr_{san}(&field) +""".format( + struct_name=struct_name, + san=sanitized_struct_name, + struct_tag=struct_tag, + read_cases="\n ".join(read_cases) if read_cases else "(void)attr;", + field_names="".join( + '"%s", ' % name + for name in dict.fromkeys( + re.findall(r'strcmp\(attr, "([^"]+)"\)', "".join(read_cases)) + ) + ), + write_cases="\n ".join(write_cases) if write_cases else "(void)value;", + elem_size=elem_size_expr, + # A conversion that fails has already stored its placeholder, so + # the field is put back as it was (lvgl-bindings#21). + save_fields=( + "{t}{n} saved;\n memcpy(&saved, data, sizeof(saved));".format( + t=struct_tag, n=struct_name + ) + if struct_has_fields and write_cases + else "" + ), + restore_fields=( + "memcpy(data, &saved, sizeof(saved));" + if struct_has_fields and write_cases + else "" + ), + write_value=_struct_value_writer( + struct_name, sanitized_struct_name, struct_tag, struct_has_fields + ), + ) + ) + + if struct_has_fields: + cpython_struct_sizes = runtime.get("cpython_struct_sizes", {}) + cpython_struct_sizes[struct_name] = True + runtime.set_("cpython_struct_sizes", cpython_struct_sizes) + + lv_to_mp[struct_name] = "mp_read_%s" % sanitized_struct_name + lv_to_mp_byref[struct_name] = "mp_read_byref_%s" % sanitized_struct_name + mp_to_lv[struct_name] = "mp_write_%s" % sanitized_struct_name + lv_to_mp["%s *" % struct_name] = "mp_read_ptr_%s" % sanitized_struct_name + mp_to_lv["%s *" % struct_name] = "mp_write_ptr_%s" % sanitized_struct_name + lv_to_mp["const %s *" % struct_name] = "mp_read_ptr_%s" % sanitized_struct_name + mp_to_lv["const %s *" % struct_name] = "mp_write_ptr_%s" % sanitized_struct_name + lv_mp_type[struct_name] = simplify_identifier(sanitized_struct_name) + lv_mp_type["%s *" % struct_name] = simplify_identifier(sanitized_struct_name) + lv_mp_type["const %s *" % struct_name] = simplify_identifier(sanitized_struct_name) + generated_structs[struct_name] = True + return struct_name + + +def emit_struct_methods_cpython(struct_name, method_entries): + sanitize = _h("sanitize") + if not method_entries: + print( + "PyMethodDef py_{san}_methods[] = {{{{NULL}}}};".format( + san=sanitize(struct_name) + ) + ) + return + lines = [] + for func_name, method_name in method_entries: + lines.append( + ' {{"{method}", (PyCFunction)py_{func}, METH_VARARGS | METH_KEYWORDS, NULL}}'.format( + method=method_name, + func=func_name, + ) + ) + print( + """ +PyMethodDef py_{san}_methods[] = {{ +{entries}, + {{NULL}} +}}; +""".format( + san=sanitize(struct_name), + entries=",\n".join(lines), + ) + ) + + +PY_INT_TYPES = frozenset( + { + "int", + "int8_t", + "int16_t", + "int32_t", + "int64_t", + "char", + "short", + "long", + "unsigned", + "unsigned int", + "unsigned char", + "unsigned short", + "unsigned long", + "uint8_t", + "uint16_t", + "uint32_t", + "uint64_t", + "size_t", + "long long", + "unsigned long long", + "unsigned long long int", + "long long int", + "long int", + "bool", + "lv_coord_t", + "lv_opa_t", + } +) +PY_FLOAT_TYPES = frozenset({"float", "double"}) + + +def _skip_func_arg(arg, get_type_fn): + if isinstance(arg, c_ast.EllipsisParam): + return True + if isinstance(arg.type, c_ast.TypeDecl) and isinstance( + arg.type.type, c_ast.IdentifierType + ): + if "void" in arg.type.type.names: + return True + return False + + +def _c_param_name(arg, index): + if hasattr(arg, "name") and arg.name: + return arg.name + return "arg%d" % index + + +def _c_param_type(arg, gen): + full = gen.visit(arg) + name = _c_param_name(arg, 0) + if full.endswith(" " + name): + return full[: -len(name) - 1] + return full.rsplit(" ", 1)[0] + + +def _callback_c_args(func): + gen = _h("gen") + args = func.args.params + enumerated_args = [] + for i, arg in enumerate(args): + arg_name = "arg%d" % i + new_arg = c_ast.Decl( + name=arg_name, + quals=arg.quals, + align=[], + storage=[], + funcspec=[], + type=copy.deepcopy(arg.type), + init=None, + bitsize=None, + ) + t = new_arg + while hasattr(t, "type"): + if hasattr(t.type, "declname"): + t.type.declname = arg_name + t = t.type + enumerated_args.append(new_arg) + return args, enumerated_args, ", ".join(gen.visit(a) for a in enumerated_args) + + +def gen_callback_func_cpython(func, func_name=None, user_data_argument=False): + gen = _h("gen") + sanitize = _h("sanitize") + get_type_fn = _h("get_type") + lv_to_mp = _h("lv_to_mp") + mp_to_lv = _h("mp_to_lv") + lv_mp_type = _h("lv_mp_type") + get_user_data = _h("get_user_data") + lv_base_obj_pattern = _h("lv_base_obj_pattern") + generated_callbacks = _h("generated_callbacks") + callback_metadata = _h("callback_metadata") + try_generate_type = _h("try_generate_type") + MissingConversionException = _h("MissingConversionException") + get_arg_name = _h("get_arg_name") + + if func_name in generated_callbacks: + return + callback_metadata[func_name] = {"args": []} + args, enumerated_args, func_args = _callback_c_args(func) + if not func_name: + func_name = get_arg_name(func.type) + + if is_global_callback(func): + full_user_data = "(void *)mp_lv_global_user_data" + else: + user_data, user_data_getter, _ = get_user_data(func, func_name) + if ( + user_data_argument + and len(args) > 0 + and gen.visit(args[-1].type) == "void *" + ): + full_user_data = "arg%d" % (len(args) - 1) + elif user_data: + full_user_data = "arg0->%s" % user_data + if len(args) < 1 or ( + hasattr(args[0].type.type, "names") + and lv_base_obj_pattern.match(args[0].type.type.names[0]) + ): + raise MissingConversionException( + "Callback: first argument must be lv_obj_t" + ) + elif user_data_getter: + full_user_data = "%s(arg0)" % user_data_getter.name + else: + raise MissingConversionException( + "Callback: user_data NOT FOUND! %s" % gen.visit(func) + ) + + return_type = get_type_fn(func.type, remove_quals=False) + if not callback_return_conversion_available( + return_type=return_type, + mp_to_lv=mp_to_lv, + generate_type=lambda: try_generate_type(func.type), + ): + raise MissingConversionException( + "Callback return value: Missing conversion to %s" % return_type + ) + + callback_metadata[func_name]["return_type"] = lv_mp_type[return_type] + build_arg_lines = [] + tuple_items = [] + for i, arg in enumerate(args): + arg_type = get_type_fn(arg.type, remove_quals=True) + cast = "(void*)" if isinstance(arg.type, c_ast.PtrDecl) else "" + if not conversion_available( + conversions=lv_to_mp, + type_name=arg_type, + generate_type=lambda: try_generate_type(arg.type), + ): + raise MissingConversionException( + "Callback: Missing conversion to %s" % arg_type + ) + convertor = lv_to_mp[arg_type] + build_arg_lines.append( + "PyObject *py_arg%d = %s(%sarg%d);" + % (i, convertor, cast, i) + ) + tuple_items.append("py_arg%d" % i) + callback_metadata[func_name]["args"].append({"type": lv_mp_type[arg_type]}) + + safe_name = sanitize(func_name) + if return_type == "void": + void_default = "" + elif "*" in return_type: + void_default = " NULL" + else: + void_default = " (%s){0}" % return_type + + if return_type == "void": + tail = ( + " lvpy_release_lock_for_python();\n" + " lvpy_nesting_inc();\n" + " PyObject *result = PyObject_CallObject(py_cb, py_args);\n" + " Py_DECREF(py_args);\n" + " Py_DECREF(py_cb);\n" + " lvpy_nesting_dec();\n" + " lvpy_reacquire_lock_after_python();\n" + " if (result) Py_DECREF(result);\n" + " else PyErr_Clear();\n" + " PyGILState_Release(gstate);" + ) + else: + tail = ( + " lvpy_release_lock_for_python();\n" + " lvpy_nesting_inc();\n" + " PyObject *result = PyObject_CallObject(py_cb, py_args);\n" + " Py_DECREF(py_args);\n" + " Py_DECREF(py_cb);\n" + " lvpy_nesting_dec();\n" + " lvpy_reacquire_lock_after_python();\n" + " if (!result) { PyErr_Clear(); PyGILState_Release(gstate); return%s; }\n" + " %s _c_res = %s(result);\n" + " Py_DECREF(result);\n" + " PyGILState_Release(gstate);\n" + " return _c_res;" + % (void_default, return_type, mp_to_lv[return_type]) + ) + + print( + """ +/* + * Callback function {func_name} (CPython) + * {func_prototype} + */ +static {return_type} {safe_name}_callback({func_args}) +{{ + PyGILState_STATE gstate = PyGILState_Ensure(); + PyObject *callbacks = get_callback_dict_from_user_data({user_data}); + if (!callbacks) {{ PyGILState_Release(gstate); return{void_default}; }} + PyObject *py_cb = PyDict_GetItemString(callbacks, "{func_name}"); + if (!py_cb || !PyCallable_Check(py_cb)) {{ PyGILState_Release(gstate); return{void_default}; }} + /* Hold the callback for the whole call: it may replace or remove its + * own registration while it runs. */ + Py_INCREF(py_cb); + {build_args} + PyObject *py_args = ({args_ok}) ? PyTuple_Pack({num_args}{tuple_args}) : NULL; + {release_args} + if (!py_args) {{ PyErr_Clear(); Py_DECREF(py_cb); PyGILState_Release(gstate); return{void_default}; }} +{tail} +}} +""".format( + func_name=func_name, + func_prototype=gen.visit(func), + safe_name=safe_name, + return_type=return_type, + func_args=func_args, + user_data=full_user_data, + build_args="\n ".join(build_arg_lines), + num_args=len(args), + tuple_args="".join(", " + item for item in tuple_items), + args_ok=" && ".join(tuple_items) if tuple_items else "1", + release_args="\n ".join( + "Py_XDECREF(%s);" % item for item in tuple_items + ), + tail=tail, + void_default=void_default, + ) + ) + generated_callbacks[func_name] = True + + +def build_py_callback_arg(arg, index, func, py_var): + gen = _h("gen") + decl_to_callback = _h("decl_to_callback") + get_user_data = _h("get_user_data") + sanitize = _h("sanitize") + func_metadata = _h("func_metadata") + callback_metadata = _h("callback_metadata") + gen_func_error = _h("gen_func_error") + MissingConversionException = _h("MissingConversionException") + + fixed_arg = copy.deepcopy(arg) + convert_array_to_ptr(fixed_arg) + if not fixed_arg.name: + fixed_arg.name = _c_param_name(arg, index) + add_default_declname(fixed_arg, fixed_arg.name) + + callback = decl_to_callback(arg) + if not callback: + raise MissingConversionException("Not a callback argument") + + callback_name, arg_type = callback + args = func.type.args.params if func.type.args else [] + try: + user_data_argument = False + full_user_data = "NULL" + user_data_getter = "NULL" + user_data_setter = "NULL" + containing_struct = "NULL" + if ( + len(args) > 0 + and gen.visit(args[-1].type) == "void *" + and args[-1].name == "user_data" + ): + callback_name = "%s_%s" % (func.name, callback_name) + full_user_data = "&user_data" + user_data_argument = True + else: + first_arg = args[0] + struct_name = get_name( + first_arg.type.type.type + if hasattr(first_arg.type.type, "type") + else first_arg.type.type + ) + callback_name = "%s_%s" % (struct_name, callback_name) + user_data, user_data_getter_fn, user_data_setter_fn = get_user_data( + arg_type, callback_name + ) + if is_global_callback(arg_type): + full_user_data = "&mp_lv_global_user_data" + else: + if user_data: + full_user_data = "&%s->%s" % (first_arg.name, user_data) + # The struct holds the dict: every callback set on it + # shares one reference, released with the struct. + containing_struct = first_arg.name + elif user_data_getter_fn and user_data_setter_fn: + full_user_data = "NULL" + containing_struct = first_arg.name + user_data_getter = user_data_getter_fn.name + user_data_setter = user_data_setter_fn.name + if index == 0: + raise MissingConversionException( + "Callback cannot be the first argument" + ) + if not full_user_data and not user_data_getter_fn: + raise MissingConversionException( + "Callback needs user_data on struct" + ) + + gen_callback_func_cpython(arg_type, callback_name, user_data_argument) + safe_cb = sanitize(callback_name) + arg_metadata = { + "type": "callback", + "function": callback_metadata[callback_name], + } + if fixed_arg.name: + arg_metadata["name"] = fixed_arg.name + func_metadata[func.name]["args"].append(arg_metadata) + return ( + "void *{arg_name} = mp_lv_callback({py_var}, &{safe_cb}_callback, " + '"{callback_name}", {full_user_data}, {containing_struct}, ' + "({user_data_getter}), ({user_data_setter}));" + ).format( + arg_name=fixed_arg.name, + py_var=py_var, + safe_cb=safe_cb, + callback_name=callback_name, + full_user_data=full_user_data, + containing_struct=containing_struct, + user_data_getter=user_data_getter, + user_data_setter=user_data_setter, + ) + except MissingConversionException as exp: + gen_func_error(arg, exp) + return "void *%s = NULL;" % fixed_arg.name + + +def _is_char_ptr_array_arg(arg): + """True for a parameter declared as an array of char pointers.""" + t = getattr(arg, "type", None) + if not isinstance(t, c_ast.ArrayDecl) or not isinstance(t.type, c_ast.PtrDecl): + return False + inner = t.type.type + return ( + isinstance(inner, c_ast.TypeDecl) + and isinstance(inner.type, c_ast.IdentifierType) + and inner.type.names == ["char"] + ) + + +def _struct_array_elem(decl, get_type_fn, lv_to_mp): + """Element struct name for a fixed-size struct array field, else None. + + Only complete structs qualify: their mp_write_value_ptr_* writer and + mp_read_ptr_* reader exist. + """ + elem_ast = decl.type.type + if not isinstance(elem_ast, c_ast.TypeDecl): + return None + elem = get_type_fn(elem_ast, remove_quals=True) + if not runtime.get("cpython_struct_sizes", {}).get(elem): + return None + if elem in (_h("structs_without_typedef") or {}): + return None + if not (lv_to_mp.get("%s *" % elem) or "").startswith("mp_read_ptr_"): + return None + return elem + + +def _const_struct_array_elem(arg, get_type_fn): + """Element struct name for a ``const T name[]`` parameter, else None. + + Only const arrays qualify: LVGL reads them, so a list copied into a C + array means the same thing as the caller's buffer. A non-const array may + be written by LVGL (lv_obj_transform_point_array), and a copy would drop + those writes, so it keeps the buffer-only lowering. + """ + t = getattr(arg, "type", None) + if not isinstance(t, c_ast.ArrayDecl) or not isinstance(t.type, c_ast.TypeDecl): + return None + if "const" not in (t.type.quals or []): + return None + elem = get_type_fn(t.type, remove_quals=True) + if not runtime.get("cpython_struct_sizes", {}).get(elem): + return None + if elem in (_h("structs_without_typedef") or {}): + return None + return elem + + +def build_py_func_arg_line(arg, index, func, py_var): + gen = _h("gen") + get_type_fn = _h("get_type") + mp_to_lv = _h("mp_to_lv") + lv_mp_type = _h("lv_mp_type") + func_metadata = _h("func_metadata") + try_generate_type = _h("try_generate_type") + decl_to_callback = _h("decl_to_callback") + MissingConversionException = _h("MissingConversionException") + max_phase = _emit_max_phase() + + if decl_to_callback(arg): + if max_phase is not None and max_phase < 7: + raise MissingConversionException( + "Callbacks require emit phase 7 (function %s)" % func.name + ) + return build_py_callback_arg(arg, index, func, py_var) + + if _is_char_ptr_array_arg(arg): + # const char * const map[] and friends: LVGL stores the pointer, so + # the generic mp_to_ptr lowering both rejected str sequences and, + # had it worked, would have dangled. lvpy_str_arr_arg (emitted in + # the file preamble) converts a sequence of str and retains the + # array + strings on the widget under a per-function key. + fixed_arg = copy.deepcopy(arg) + convert_array_to_ptr(fixed_arg) + cname = _c_param_name(arg, index) + if not fixed_arg.name: + fixed_arg.name = cname + add_default_declname(fixed_arg, cname) + arg_type = get_type_fn(arg.type, remove_quals=True) + # Same lazy registration as the generic path: populates lv_mp_type + # (and the conversion tables) for this array type on first sight. + conversion_available( + conversions=mp_to_lv, + type_name=arg_type, + generate_type=lambda: try_generate_type(arg.type), + ) + arg_metadata = {"type": lv_mp_type[arg_type]} + if cname: + arg_metadata["name"] = cname + func_metadata[func.name]["args"].append(arg_metadata) + return '{var} = ({cast})lvpy_str_arr_arg(self, {py_var}, "{key}");'.format( + var=gen.visit(fixed_arg), + cast=gen.visit(fixed_arg.type), + py_var=py_var, + key="%s:%s" % (func.name, cname or index), + ) + + fixed_arg = copy.deepcopy(arg) + convert_array_to_ptr(fixed_arg) + cname = _c_param_name(arg, index) + if not fixed_arg.name: + fixed_arg.name = cname + add_default_declname(fixed_arg, cname) + + arg_type = get_type_fn(arg.type, remove_quals=True) + elem = _const_struct_array_elem(arg, get_type_fn) + if elem is not None and conversion_available( + conversions=mp_to_lv, + type_name=arg_type, + generate_type=lambda: try_generate_type(arg.type), + ): + # const lv_point_precise_t points[] and friends: a list of structs + # (or dicts) becomes a C array, as on MicroPython; a buffer passes + # through. Either way it is retained on the widget, because LVGL + # keeps the pointer (lv_line_set_points never copies; + # lvgl-bindings#37). + arg_metadata = {"type": lv_mp_type[arg_type]} + if cname: + arg_metadata["name"] = cname + func_metadata[func.name]["args"].append(arg_metadata) + return ( + '{var} = ({cast})lvpy_struct_arr_arg(self, {py_var}, "{key}", ' + "sizeof({elem}), mp_write_value_ptr_{san});" + ).format( + var=gen.visit(fixed_arg), + cast=gen.visit(fixed_arg.type), + py_var=py_var, + key="%s:%s" % (func.name, cname or index), + elem=elem, + san=_h("sanitize")(elem), + ) + + if not conversion_available( + conversions=mp_to_lv, + type_name=arg_type, + generate_type=lambda: try_generate_type(arg.type), + ): + raise MissingConversionException("Missing conversion to %s" % arg_type) + + convertor = mp_to_lv[arg_type] + cast = "" + if hasattr(arg, "quals") and "const" in arg.quals: + # const pointer: cast the converted pointer. const struct by value: the + # lhs is already const; mp_write_* returns an lvalue — do not cast to struct. + if isinstance(fixed_arg.type, c_ast.PtrDecl): + cast = "(%s)" % gen.visit(fixed_arg.type) + arg_metadata = {"type": lv_mp_type[arg_type]} + if cname: + arg_metadata["name"] = cname + func_metadata[func.name]["args"].append(arg_metadata) + return "{var} = {cast}{convertor}({py_var});".format( + var=gen.visit(fixed_arg), + cast=cast, + convertor=convertor, + py_var=py_var, + ) + + +def _struct_receiver_kind(func, obj_name, get_type_fn): + """How a struct method takes its struct: "ptr", "array" (``T name[]``), + "value", or None when the first argument isn't the struct. MicroPython + binds all three as methods (lvgl-bindings#46).""" + generated_structs = _h("generated_structs") + if not obj_name or obj_name not in generated_structs: + return None + args = func.type.args.params if func.type.args else [] + if not args: + return None + first = args[0].type + first_type = get_type_fn(first, remove_quals=True) + if first_type in (obj_name + " *", "const " + obj_name + " *"): + return "array" if isinstance(first, c_ast.ArrayDecl) else "ptr" + if isinstance(first, c_ast.ArrayDecl): + return "array" if get_type_fn(first.type, remove_quals=True) == obj_name else None + if isinstance(first, c_ast.TypeDecl) and first_type == obj_name: + return "value" + return None + + +def _is_struct_method(func, obj_name, get_type_fn): + return _struct_receiver_kind(func, obj_name, get_type_fn) is not None + + +def gen_py_func(func, obj_name): + gen = _h("gen") + sanitize = _h("sanitize") + get_type_fn = _h("get_type") + lv_to_mp = _h("lv_to_mp") + generated_funcs = _h("generated_funcs") + generated_struct_method_funcs = _h("generated_struct_method_funcs") + func_prototypes = _h("func_prototypes") + func_metadata = _h("func_metadata") + function_prototype = _h("function_prototype") + is_static_member = _h("is_static_member") + is_struct_function = _h("is_struct_function") + base_obj_type = _h("base_obj_type") + module_name = _h("module_name") + try_generate_type = _h("try_generate_type") + lv_func_returns_array = _h("lv_func_returns_array") + try_generate_array_type = _h("try_generate_array_type") + + args = func.type.args.params if func.type.args else [] + if len(args) == 1 and get_type_fn(args[0].type, remove_quals=True) == "void": + args = [] + + struct_method = bool(obj_name and _is_struct_method(func, obj_name, get_type_fn)) + emit_name = func.name + "_struct_method" if struct_method else func.name + + if struct_method: + if generated_struct_method_funcs.get(emit_name) is True: + return + generated_struct_method_funcs[emit_name] = False + else: + if func.name in generated_funcs: + return + generated_funcs[func.name] = False + func_metadata[func.name] = {"type": "function", "args": []} + + prototype_str = gen.visit(function_prototype(func)) + if not struct_method: + if prototype_str in func_prototypes: + original = func_prototypes[prototype_str] + if function_reuse_allowed( + function_name=func.name, + original_name=original.name, + original_generated=generated_funcs.get(original.name) is True, + supports_dynamic_function_pointer=runtime.get( + "target_lowering_profile" + ).supports_dynamic_function_pointer, + ): + generated_funcs[func.name] = original.name + return + func_prototypes[prototype_str] = func + + return_type = get_type_fn(func.type.type, remove_quals=False) + if isinstance(func.type.type, c_ast.PtrDecl) and lv_func_returns_array.match(func.name): + try_generate_array_type(func.type.type) + + if return_type == "void": + result_decl = "" + c_call = "(({func_ptr}){c_func})({send_args});" + build_return = "Py_RETURN_NONE;" + allow_threads = func.name in ("lv_task_handler", "lv_tick_inc") + else: + if not conversion_available( + conversions=lv_to_mp, + type_name=return_type, + generate_type=lambda: try_generate_type(func.type.type), + ): + raise _h("MissingConversionException")( + "Missing conversion from %s" % return_type + ) + result_decl = "%s _res;\n " % gen.visit(func.type.type) + c_call = "_res = (({func_ptr}){c_func})({send_args});" + cast = "(void*)" if isinstance(func.type.type, c_ast.PtrDecl) else "" + build_return = "return %s(%s_res);" % (lv_to_mp[return_type], cast) + allow_threads = func.name in ("lv_task_handler", "lv_tick_inc") + + is_method = ( + obj_name + and not is_static_member(func, base_obj_type) + and ( + is_method_of(func.name, obj_name) + or _is_struct_method(func, obj_name, get_type_fn) + ) + ) + struct_method = _is_struct_method(func, obj_name, get_type_fn) + + is_factory = obj_name is None and func.name.endswith("_create") + decl_to_callback = _h("decl_to_callback") + + parse_fmt = [] + parse_decls = [] + parse_names = [] + body_items = [] + send_args = [] + decl_to_callback = _h("decl_to_callback") + + def _arg_sort_key(index, param): + if ( + hasattr(param, "name") + and param.name == "user_data" + and gen.visit(param.type) == "void *" + ): + return 0 + if decl_to_callback(param): + return 2 + return 1 + + indexed_args = [ + (i, arg) + for i, arg in enumerate(args) + if not _skip_func_arg(arg, get_type_fn) + ] + + for i, arg in indexed_args: + send_args.append(_c_param_name(arg, i)) + + for i, arg in indexed_args: + cname = _c_param_name(arg, i) + if is_method and i == 0: + if struct_method: + san = sanitize(obj_name) + kind = _struct_receiver_kind(func, obj_name, get_type_fn) + if kind == "value": + # A wrong type leaves the zeroed value and an exception set, + # which the PyErr_Occurred check after the arguments reports. + line = ( + "%s %s = {0}; { %s *p_ = (%s *)mp_write_ptr_%s(self);" + " if (p_) %s = *p_; }" + % (obj_name, cname, obj_name, obj_name, san, cname) + ) + elif kind == "array": + line = "%s *%s = (%s *)mp_write_ptr_%s(self);" % ( + obj_name, cname, obj_name, san) + else: + line = "%s = (%s *)mp_write_ptr_%s(self);" % ( + gen.visit(arg), obj_name, san) + body_items.append((0, line)) + else: + body_items.append( + (0, "lv_obj_t *%s = mp_to_lv(self);" % (cname or "obj")) + ) + if not cname and not struct_method: + send_args[0] = "obj" + continue + + arg_type = get_type_fn(arg.type, remove_quals=True) + if is_factory and i == 0 and arg_type == ("%s *" % base_obj_type): + py_var = "parent_py" + parse_fmt.append("|O") + parse_decls.append("PyObject *%s" % py_var) + parse_names.append(py_var) + body_items.append( + ( + 1, + "lv_obj_t *%s = NULL;\n" + " if (%s && %s != Py_None) {\n" + " %s = mp_to_lv(%s);\n" + " if (!%s) {{ PyGILState_Release(gstate); return NULL; }}\n" + " }" + % (cname, py_var, py_var, cname, py_var, cname), + ) + ) + continue + + c_type = _c_param_type(arg, gen) + full_decl = gen.visit(arg) + if arg_type in PY_INT_TYPES: + pvar = "%s_val" % cname + parse_fmt.append("l") + parse_decls.append("long %s" % pvar) + parse_names.append(pvar) + if arg_type == "bool": + line = "bool %s = (%s != 0);" % (cname, pvar) + else: + line = "%s = (%s)%s;" % (full_decl, c_type, pvar) + body_items.append((_arg_sort_key(i, arg), line)) + elif arg_type in PY_FLOAT_TYPES: + pvar = "%s_val" % cname + parse_fmt.append("d") + parse_decls.append("double %s" % pvar) + parse_names.append(pvar) + body_items.append( + (_arg_sort_key(i, arg), "%s = (%s)%s;" % (full_decl, c_type, pvar)) + ) + else: + py_var = "%s_py" % cname + parse_fmt.append("O") + parse_decls.append("PyObject *%s" % py_var) + parse_names.append(py_var) + body_items.append( + ( + _arg_sort_key(i, arg), + build_py_func_arg_line(arg, i, func, py_var), + ) + ) + + # NOTE: do not point a NULL user_data at the wrapper object (self/obj). + # Functions like lv_obj_add_event_cb register multiple callbacks on the same + # object, distinguished only by their event filter and per-registration + # user_data. Reusing the object as user_data makes every registration share + # one callback dict under a single fixed key, so each call clobbers the + # previous and only the last-registered callback ever fires. Leaving + # user_data NULL matches the MicroPython/CircuitPython emitters: mp_lv_callback + # then allocates a fresh dict per registration, which LVGL stores as that + # event descriptor's user_data and the trampoline reads back correctly. + + body_lines = [line for _, line in sorted(body_items, key=lambda t: t[0])] + + parse_block = "" + if parse_fmt: + parse_block = ( + ' {decls};\n if (!PyArg_ParseTuple(py_args, "{fmt}", {names})) {{ PyGILState_Release(gstate); return NULL; }}' + ).format( + decls="; ".join(parse_decls), + fmt="".join(parse_fmt), + names=", ".join("&" + n for n in parse_names), + ) + + void_self = "" if is_method else " (void)self;\n" + + pre_lv_call = "" + post_lv_call = "" + fname = func.name + # A timer or a started animation holds its callback dict through LVGL's + # ext_data free_cb (lvpy_runtime.c): LVGL releases it on every path that + # frees the timer or the animation copy. + if fname == "lv_timer_create": + post_lv_call = " lvpy_timer_bind(_res);" + elif fname == "lv_timer_set_cb": + post_lv_call = " lvpy_timer_bind(timer);" + elif fname == "lv_anim_start": + post_lv_call = " lvpy_anim_bind(_res);" + elif fname.endswith("_remove_event_cb_with_user_data"): + post_lv_call = " if (_res > 0) lvpy_release_callback_user_data(user_data);" + elif fname == "lv_obj_remove_event_cb": + pre_lv_call = ( + " void *_lvpy_release_ud = lvpy_peek_obj_event_cb_user_data(obj, event_cb, NULL);" + ) + post_lv_call = " if (_res) lvpy_release_callback_user_data(_lvpy_release_ud);" + elif fname == "lv_obj_remove_event_dsc": + pre_lv_call = " void *_lvpy_release_ud = lv_event_dsc_get_user_data(dsc);" + post_lv_call = " if (_res) lvpy_release_callback_user_data(_lvpy_release_ud);" + elif fname == "lv_obj_remove_event": + pre_lv_call = ( + " lv_event_dsc_t *_lvpy_release_dsc = lv_obj_get_event_dsc(obj, index);\n" + " void *_lvpy_release_ud = _lvpy_release_dsc ? lv_event_dsc_get_user_data(_lvpy_release_dsc) : NULL;" + ) + post_lv_call = " if (_res) lvpy_release_callback_user_data(_lvpy_release_ud);" + elif fname == "lv_indev_remove_event": + pre_lv_call = ( + " lv_event_dsc_t *_lvpy_release_dsc = lv_indev_get_event_dsc(indev, index);\n" + " void *_lvpy_release_ud = _lvpy_release_dsc ? lv_event_dsc_get_user_data(_lvpy_release_dsc) : NULL;" + ) + post_lv_call = " if (_res) lvpy_release_callback_user_data(_lvpy_release_ud);" + + if allow_threads: + lv_call_block = """ {result_decl}lvpy_lock(); + Py_BEGIN_ALLOW_THREADS + {c_call} + Py_END_ALLOW_THREADS + lvpy_unlock();""" + else: + lv_call_block = """ {result_decl}lvpy_lock(); + {c_call} + lvpy_unlock();""" + + print( + """ +/* + * {module_name} extension definition for: + * {print_func} + */ +static PyObject *py_{func}(PyObject *self, PyObject *py_args, PyObject *py_kwds) +{{ + PyGILState_STATE gstate = PyGILState_Ensure(); +{void_self} (void)py_kwds; +{parse} + {body} + if (PyErr_Occurred()) {{ PyGILState_Release(gstate); return NULL; }} + {pre_lv_call} +{lv_call_block} + {post_lv_call} + PyGILState_Release(gstate); + {build_return} +}} + +static PyMethodDef py_{func}_def = {{ + "{py_name}", + (PyCFunction)py_{func}, + METH_VARARGS | METH_KEYWORDS, + NULL +}}; +""".format( + module_name=module_name, + func=emit_name, + c_func=func.name, + py_name=sanitize(func.name), + print_func=gen.visit(func), + void_self=void_self, + parse=parse_block, + body="\n ".join(body_lines), + pre_lv_call=pre_lv_call, + post_lv_call=post_lv_call, + result_decl=result_decl, + lv_call_block=lv_call_block.format( + result_decl=result_decl, + c_call=c_call.format( + func_ptr=prototype_str, + c_func=func.name, + send_args=", ".join(send_args), + ), + ), + build_return=build_return, + ) + ) + if struct_method: + generated_struct_method_funcs[emit_name] = True + generated_struct_method_funcs[func.name] = emit_name + else: + generated_funcs[func.name] = True + + +def _resolved_struct_method_py_func_name(func_name, generated_struct_method_funcs): + emit_name = func_name + "_struct_method" + target = generated_struct_method_funcs.get(emit_name) + if target is True: + return emit_name + if isinstance(target, str): + return target + target = generated_struct_method_funcs.get(func_name) + if target is True: + return emit_name + if isinstance(target, str): + return target + return None + + +def _resolved_py_func_name(func_name, generated_funcs): + target = generated_funcs.get(func_name) + if target is True: + return func_name + if isinstance(target, str): + return target + return None + + +def gen_py_obj(obj_name): + sanitize = _h("sanitize") + module_name = _h("module_name") + get_methods = _h("get_methods") + has_ctor = _h("has_ctor") + get_ctor = _h("get_ctor") + parent_obj_names = _h("parent_obj_names") + generated_funcs = _h("generated_funcs") + method_name_from_func_name = _h("method_name_from_func_name") + obj_metadata = _h("obj_metadata") + func_metadata = _h("func_metadata") + get_enum_members = _h("get_enum_members") + get_enum_member_name = _h("get_enum_member_name") + enums = _h("enums") + enum_referenced = _h("enum_referenced") + + obj_metadata[obj_name] = {"members": collections.OrderedDict()} + + for method in get_methods(obj_name): + try: + gen_py_func(method, obj_name) + except Exception as exp: + _h("gen_func_error")(method, exp) + + obj_metadata[obj_name]["members"].update( + { + method_name_from_func_name(method.name): func_metadata[method.name] + for method in get_methods(obj_name) + if method.name in func_metadata + } + ) + parent = parent_obj_names.get(obj_name) + if parent and parent in obj_metadata: + obj_metadata[obj_name]["members"].update(obj_metadata[parent]["members"]) + obj_metadata[obj_name]["members"].update( + { + get_enum_member_name(enum_member_name): {"type": "enum_member"} + for enum_member_name in get_enum_members(obj_name) + } + ) + for enum_name in enums.keys(): + if not is_method_of(enum_name, obj_name): + continue + member_name = method_name_from_func_name(enum_name) + obj_metadata[obj_name]["members"][member_name] = {"type": "enum_type"} + if enum_name in obj_metadata: + obj_metadata[obj_name]["members"][member_name].update(obj_metadata[enum_name]) + if is_widget_scoped_only_enum(enum_name): + enum_referenced[enum_name] = True + + ctor_name = "lv_obj_create" + if has_ctor(obj_name): + ctor = get_ctor(obj_name) + ctor_name = ctor.name + try: + gen_py_func(ctor, None) + except Exception as exp: + _h("gen_func_error")(ctor, exp) + + ctor_py = _resolved_py_func_name(ctor_name, generated_funcs) or ctor_name + + method_defs = [] + for method in get_methods(obj_name): + py_func = _resolved_py_func_name(method.name, generated_funcs) + if py_func: + method_defs.append( + ' {{"{name}", (PyCFunction)py_{func}, METH_VARARGS | METH_KEYWORDS, NULL}},'.format( + name=sanitize(method_name_from_func_name(method.name)), + func=py_func, + ) + ) + + parent = parent_obj_names.get(obj_name) + if parent: + parent_base = "&py_lv_%s_type" % sanitize(parent) + elif sanitize(obj_name) == "obj": + parent_base = "NULL" + else: + parent_base = "&py_lv_obj_type" + + print( + """ +/* + * {module_name} {obj} object definitions (CPython) + */ +static PyObject *py_lv_{obj}_call(PyObject *type, PyObject *py_args, PyObject *py_kwds) +{{ + (void)type; + return py_{ctor}(type, py_args, py_kwds); +}} + +static PyObject *py_lv_{obj}_new(PyTypeObject *type, PyObject *py_args, PyObject *py_kwds) +{{ + return py_{ctor}((PyObject *)type, py_args, py_kwds); +}} + +static void py_lv_{obj}_dealloc(py_lv_obj_t *self) +{{ + lvpy_dealloc_obj(self); +}} + +static PyMethodDef py_lv_{obj}_methods[] = {{ +{methods} + {{NULL, NULL, 0, NULL}} +}}; + +PyTypeObject py_lv_{obj}_type = {{ + PyVarObject_HEAD_INIT(NULL, 0) + .tp_name = "lvgl.{obj}", + .tp_basicsize = sizeof(py_lv_obj_t), + .tp_dealloc = (destructor)py_lv_{obj}_dealloc, + .tp_flags = Py_TPFLAGS_DEFAULT, + .tp_base = {parent_base}, + .tp_new = (newfunc)py_lv_{obj}_new, + .tp_methods = py_lv_{obj}_methods, + .tp_call = (ternaryfunc)py_lv_{obj}_call, +}}; + +static py_lv_obj_type_t py_lv_{obj}_mapping = {{ + .lv_obj_class = &lv_{obj}_class, + .py_type = &py_lv_{obj}_type, +}}; +""".format( + module_name=module_name, + obj=sanitize(obj_name), + ctor=ctor_py, + methods="\n".join(method_defs) if method_defs else "", + parent_base=parent_base, + ) + ) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_micropython.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_micropython.py new file mode 100644 index 00000000..1deebb70 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_micropython.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""MicroPython target entry: analyze → emit_c_micropython_style.""" +from __future__ import print_function + +import builtins + +from . import emit_c_micropython_style as emit_c_mod +from . import runtime +from .analyze import analyze +from .emit_backend import prepare_target_lowering + +print = builtins.print + + +def run(ctx): + ctx.init_patterns() + runtime.activate(ctx) + # The MP-style object/enum pass has a full-generation dependency that is + # intentionally represented by an unbounded phase. CircuitPython and + # CPython use their finite lifecycle phases below. + prepare_target_lowering(ctx, target="micropython", max_phase=None) + if not getattr(ctx, "_analysis_ready", False): + analyze(ctx) + runtime.activate(ctx) + emit_c_mod.emit_c(ctx) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi.py new file mode 100644 index 00000000..35c155a2 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi.py @@ -0,0 +1,156 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Generate the shared lvgl.pyi from the canonical API model.""" + +from __future__ import annotations + +import re +from pathlib import Path +from typing import Optional, Sequence + +from .emit_pyi_canonical import CanonicalPyiEmitter, load_canonical_api + +ALL_TARGETS = ("cpython", "micropython", "circuitpython") + +_LV_VERSION_DEFINE_RE = re.compile( + r"^#define\s+(LVGL_VERSION_MAJOR|LVGL_VERSION_MINOR|LVGL_VERSION_PATCH)\s+(\d+)", + re.MULTILINE, +) + + +def read_lvgl_version_major_minor(repo_root: Optional[Path] = None) -> str: + """Read the major/minor version from the pinned LVGL submodule.""" + + repo_root = (repo_root or Path(__file__).resolve().parent.parent).resolve() + for version_file in ( + repo_root / "lvgl" / "lv_version.h", + repo_root / "lvgl" / "lvgl.h", + ): + if not version_file.is_file(): + continue + text = version_file.read_text(encoding="utf-8") + parts = { + name: int(value) + for name, value in _LV_VERSION_DEFINE_RE.findall(text) + } + if "LVGL_VERSION_MAJOR" in parts and "LVGL_VERSION_MINOR" in parts: + return "{}.{}".format( + parts["LVGL_VERSION_MAJOR"], + parts["LVGL_VERSION_MINOR"], + ) + raise FileNotFoundError( + "could not read LVGL version from lvgl/lv_version.h under {}".format(repo_root) + ) + + +def default_api_path(generated_dir: Path) -> Path: + return generated_dir.resolve() / "api.json" + + +def default_output_path(generated_dir: Path) -> Path: + return generated_dir.resolve() / "lvgl.pyi" + + +def write_pyi( + api_path: Path, + output_path: Path, + *, + target: str = "all", + lvgl_version: Optional[str] = None, + repo_root: Optional[Path] = None, +) -> None: + """Render one common or target-specific stub from ``api.json``.""" + + data = load_canonical_api(api_path) + repo_root = repo_root or api_path.resolve().parent.parent + emitter = CanonicalPyiEmitter( + data, + target=target, + lvgl_version=lvgl_version or read_lvgl_version_major_minor(repo_root), + ) + output_path.parent.mkdir(parents=True, exist_ok=True) + with output_path.open("w", encoding="utf-8") as handle: + emitter.emit(handle) + + +def generate_pyi( + generated_dir: Path, + *, + api_path: Optional[Path] = None, + output_path: Optional[Path] = None, +) -> Path: + api_path = api_path or default_api_path(generated_dir) + output_path = output_path or default_output_path(generated_dir) + if not api_path.is_file(): + raise FileNotFoundError("canonical API file not found: {}".format(api_path)) + write_pyi(api_path, output_path, target="all") + return output_path + + +def generate_all_pyis( + generated_dir: Path, + *, + api_path: Optional[Path] = None, +) -> list[Path]: + return [generate_pyi(generated_dir, api_path=api_path)] + + +def generate_pyi_for_target( + generated_dir: Path, + target: str, + *, + api_path: Optional[Path] = None, + output_path: Optional[Path] = None, +) -> Path: + api_path = api_path or default_api_path(generated_dir) + output_path = output_path or default_output_path(generated_dir) + if not api_path.is_file(): + raise FileNotFoundError("canonical API file not found: {}".format(api_path)) + write_pyi(api_path, output_path, target=target) + return output_path + + +def main(argv: Optional[Sequence[str]] = None) -> int: + import argparse + + parser = argparse.ArgumentParser( + description="Generate lvgl.pyi stubs from the canonical api.json." + ) + parser.add_argument( + "--target", + choices=list(ALL_TARGETS) + ["all"], + default="all", + help="Emit the common API or one target's available symbols", + ) + parser.add_argument( + "--api", + type=Path, + help="Canonical API JSON (default: generated/api.json)", + ) + parser.add_argument( + "--output", + type=Path, + help="Output .pyi path (default: generated/lvgl.pyi)", + ) + parser.add_argument( + "--generated-dir", + type=Path, + default=Path(__file__).resolve().parent.parent / "generated", + help="Directory containing canonical API artifacts", + ) + args = parser.parse_args(argv) + api_path = args.api or default_api_path(args.generated_dir) + output_path = args.output or default_output_path(args.generated_dir) + write_pyi( + api_path, + output_path, + target=args.target, + ) + print("Wrote {}".format(output_path)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi_canonical.py b/maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi_canonical.py new file mode 100644 index 00000000..7d9d0d86 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/emit_pyi_canonical.py @@ -0,0 +1,549 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Emit the shared ``lvgl.pyi`` from the canonical API model.""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any, Mapping, TextIO + +from .api_model import API_SCHEMA_VERSION, TARGETS +from .verify_api import validate_api_data + +_PY_KEYWORDS = frozenset( + { + "False", + "None", + "True", + "and", + "as", + "assert", + "async", + "await", + "break", + "case", + "class", + "continue", + "def", + "del", + "elif", + "else", + "except", + "finally", + "for", + "from", + "global", + "if", + "import", + "in", + "is", + "lambda", + "match", + "nonlocal", + "not", + "or", + "pass", + "raise", + "return", + "try", + "type", + "while", + "with", + "yield", + } +) + + +def _identifier(name: str) -> str: + if name in _PY_KEYWORDS: + return "_" + name + if name and name[0].isdigit(): + return "_" + name + return name.replace(" ", "_").replace("*", "_ptr") + + +class CanonicalPyiEmitter: + """Render one common or target-specific stub from ``api.json``.""" + + def __init__( + self, + data: Mapping[str, Any], + *, + target: str = "all", + lvgl_version: str, + ) -> None: + if data.get("schema_version") != API_SCHEMA_VERSION: + raise ValueError("unsupported canonical API schema") + if target not in TARGETS + ("all",): + raise ValueError("unsupported stub target: %s" % target) + self.data = data + self.target = target + self.lvgl_version = lvgl_version + self.lines: list[str] = [] + self.functions = tuple(data.get("functions", ())) + self.objects = tuple(data.get("objects", ())) + self.structs = tuple(data.get("structs", ())) + self.enums = tuple(data.get("enums", ())) + self.variables = tuple(data.get("variables", ())) + self.constants = tuple(data.get("constants", ())) + self._type_names = frozenset( + _identifier(item["python_name"]) + for section in ("objects", "structs", "enums") + for item in data.get(section, ()) + if item.get("python_name") + ) + + def _available(self, item: Mapping[str, Any]) -> bool: + available = set(item.get("available_on", ())) + if self.target == "all": + return set(TARGETS) <= available + return self.target in available + + def _public(self, item: Mapping[str, Any]) -> bool: + return item.get("visibility") == "public" and self._available(item) + + def _view_type( + self, + item: Mapping[str, Any], + *, + type_aliases: Mapping[str, str] | None = None, + ) -> str: + view = item.get("view") + if not isinstance(view, Mapping): + raise ValueError("canonical API item is missing a type view") + python_type = view.get("python_type") + if not isinstance(python_type, str) or not python_type: + raise ValueError("canonical API type view has no Python type") + for type_name, alias in (type_aliases or {}).items(): + python_type = re.sub(r"\b%s\b" % re.escape(type_name), alias, python_type) + return python_type + + def _shadowed_type_aliases( + self, field_names: set[str], referenced_types: tuple[str, ...] + ) -> dict[str, str]: + return { + type_name: "__lv_type_%s" % type_name + for type_name in sorted(field_names & self._type_names) + if any( + re.search(r"\b%s\b" % re.escape(type_name), reference) + for reference in referenced_types + ) + } + + def _inherited_method_names(self, object_name: str) -> set[str]: + objects = {item["python_name"]: item for item in self.objects} + names: set[str] = set() + parent = objects.get(object_name, {}).get("parent") + while parent is not None: + names.update( + function["python_name"] + for function in self.functions + if function.get("role") == "object_method" + and function.get("receiver") == parent + and function.get("visibility") == "public" + and self._available(function) + ) + parent = objects.get(parent, {}).get("parent") + return names + + def emit(self, out: TextIO) -> None: + self.lines = [] + self._header() + self._emit_helpers() + self._emit_module_enums() + self._emit_structs() + self._emit_objects() + self._emit_variables() + self._emit_functions() + self._emit_constants() + out.write("\n".join(self.lines) + "\n") + + def _add(self, line: str = "", indent: int = 0) -> None: + self.lines.append((" " * indent) + line if line else "") + + def _header(self) -> None: + self._add("# LVGL %s" % self.lvgl_version) + self._add("# Naming: upstream-compatible") + self._add('"""Type stubs for LVGL Python bindings (auto-generated)."""') + self._add("from __future__ import annotations") + self._add("from collections.abc import Callable, Sequence") + self._add("from typing import Any, ClassVar, TypeAlias, TypeVar, overload") + self._add() + # These intentionally stay private: they describe only the generic + # runtime helpers below, not LVGL declarations in the public API. + self._add('_StructT = TypeVar("_StructT", bound="_Struct")') + self._add('_BlobT = TypeVar("_BlobT")') + self._add() + + def _emit_helpers(self) -> None: + self._add("class LvReferenceError(Exception): ...") + self._add() + self._add("class _Struct:") + self._add("__SIZE__: ClassVar[int]", 1) + self._add( + "def __init__(self, fields: dict[str, Any] | None = None, /, **kwargs: Any) -> None: ...", + 1, + ) + self._add("@classmethod", 1) + self._add( + "def __cast__(cls, target_type: type[_StructT], pointer: Any, /) -> _StructT: ...", + 1, + ) + self._add( + "def __cast_instance__(self: _StructT, pointer: Any, /) -> _StructT: ...", + 1, + ) + self._add( + "def __dereference__(self, size: int | None = ..., /) -> memoryview | None: ...", + 1, + ) + self._add() + self._add("class C_Pointer(_Struct):") + self._add("__SIZE__: ClassVar[int]", 1) + self._add("ptr_val: Any", 1) + self._add("str_val: str | None", 1) + self._add("int_val: int", 1) + self._add("uint_val: int", 1) + self._add() + self._add("class _Blob:") + self._add( + "def __dereference__(self, size: int | None = ..., /) -> memoryview | None: ...", + 1, + ) + self._add("@overload", 1) + self._add("def __cast__(self, /) -> Any: ...", 1) + self._add("@overload", 1) + self._add( + "def __cast__(self, target_type: type[_BlobT], /) -> _BlobT: ...", + 1, + ) + self._add() + # _nesting is deliberately private in the canonical API model (see + # api_model.build_api_model) but still stubbed here: it is a real + # runtime attribute on MicroPython/CircuitPython, and + # PyDevices' display_driver.py (pydevices lib/) depends on its + # public shape (`.value: int`). + self._add("class _Nesting:") + self._add("value: int", 1) + self._add() + + def _module_enums(self) -> list[Mapping[str, Any]]: + return sorted( + ( + enum + for enum in self.enums + if self._public(enum) and enum.get("module_name") + ), + key=lambda enum: (enum["module_name"], enum.get("python_name", "")), + ) + + def _emit_module_enums(self) -> None: + for enum in self._module_enums(): + self._emit_enum(enum["module_name"], enum) + + def _emit_enum(self, name: str, enum: Mapping[str, Any], indent: int = 0) -> None: + self._add("class %s:" % _identifier(name), indent) + member_type = enum.get("member_type", "int") + members = enum.get("members", ()) + if not members: + self._add("...", indent + 1) + for member in members: + member_name = _identifier(member["name"]) + self._add("%s: %s" % (member_name, member_type), indent + 1) + if indent == 0: + self._add() + + def _emit_structs(self) -> None: + functions = [ + function + for function in self.functions + if function.get("role") == "struct_method" + and function.get("visibility") == "public" + and self._available(function) + ] + for struct in sorted( + (struct for struct in self.structs if self._public(struct)), + key=lambda item: item["python_name"], + ): + name = _identifier(struct["python_name"]) + self._add("class %s(_Struct):" % name) + emitted = False + field_names = set() + for field in struct.get("fields", ()): + field_name = _identifier(field.get("name") or "field") + if field_name in field_names: + raise ValueError("duplicate struct field %s.%s" % (name, field_name)) + field_names.add(field_name) + referenced_types = tuple( + field.get("view", {}).get("python_type", "") + for field in struct.get("fields", ()) + ) + referenced_types += tuple( + parameter.get("view", {}).get("python_type", "") + for function in functions + if function.get("receiver") == struct["python_name"] + for parameter in function.get("parameters", ()) + ) + referenced_types += tuple( + function.get("return_view", {}).get("python_type", "") + for function in functions + if function.get("receiver") == struct["python_name"] + ) + type_aliases = self._shadowed_type_aliases( + field_names, referenced_types + ) + for type_name, alias in type_aliases.items(): + self._add('%s: TypeAlias = "%s"' % (alias, type_name), 1) + if type_aliases: + emitted = True + for field in struct.get("fields", ()): + field_name = _identifier(field.get("name") or "field") + self._add( + "%s: %s" % ( + field_name, + self._view_type(field, type_aliases=type_aliases), + ), + 1, + ) + emitted = True + for function in sorted( + ( + function + for function in functions + if function.get("receiver") == struct["python_name"] + ), + key=lambda item: (item["python_name"], item["c_name"]), + ): + if _identifier(function["python_name"]) in field_names: + # The generated struct attr handler checks fields before + # falling back to its method dictionary. A colliding + # method is therefore not callable through the Python + # object and must not be emitted as a duplicate member. + continue + if function.get("static"): + self._add("@staticmethod", 1) + signature = self._signature( + function, instance=False, type_aliases=type_aliases + ) + else: + signature = self._signature( + function, + instance=True, + skip_receiver=True, + type_aliases=type_aliases, + ) + self._add("def %s" % signature, 1) + emitted = True + if not emitted: + self._add("...", 1) + self._add() + + def _nested_enums(self, object_name: str) -> list[tuple[str, Mapping[str, Any]]]: + result = [] + for enum in self.enums: + if not self._public(enum): + continue + for owner_info in enum.get("owners", ()): + owner = owner_info["object"] + nested_name = owner_info["name"] + if owner == object_name: + result.append((nested_name, enum)) + return sorted(result, key=lambda item: item[0]) + + def _emit_objects(self) -> None: + functions = [ + function + for function in self.functions + if function.get("role") in {"constructor", "object_method"} + and function.get("visibility") == "public" + and self._available(function) + ] + object_names = { + object_["python_name"] + for object_ in self.objects + if self._public(object_) + } + for object_ in sorted( + (object_ for object_ in self.objects if self._public(object_)), + key=lambda item: item["python_name"], + ): + object_name = object_["python_name"] + parent = object_.get("parent") + parent_type = ( + _identifier(parent) + if parent in object_names + else "_Struct" + ) + self._add("class %s(%s):" % (_identifier(object_name), parent_type)) + emitted = False + for nested_name, enum in self._nested_enums(object_name): + self._emit_enum(nested_name, enum, indent=1) + emitted = True + constructor = next( + ( + function + for function in functions + if function.get("role") == "constructor" + and function.get("receiver") == object_name + ), + None, + ) + if constructor is not None: + params = self._parameters(constructor, skip_receiver=False, constructor=True) + params = "self" + (", " + params if params else "") + self._add("def __init__(%s) -> None: ..." % params, 1) + emitted = True + for function in sorted( + ( + function + for function in functions + if function.get("role") == "object_method" + and function.get("receiver") == object_name + ), + key=lambda item: (item["python_name"], item["c_name"]), + ): + if function.get("static"): + self._add("@staticmethod", 1) + signature = self._signature(function, instance=False) + else: + signature = self._signature(function, instance=True, skip_receiver=True) + override_note = "" + if function["python_name"] in self._inherited_method_names(object_name): + override_note = " # type: ignore[override]" + self._add("def %s%s" % (signature, override_note), 1) + emitted = True + if not emitted: + self._add("...", 1) + self._add() + + def _emit_variables(self) -> None: + for variable in sorted( + ( + variable + for variable in self.variables + if self._available(variable) + and ( + variable.get("visibility") == "public" + and variable.get("c_name") != "_nesting" + ) + ), + key=lambda item: item.get("python_name") or item["c_name"], + ): + name = _identifier(variable.get("python_name") or variable["c_name"]) + self._add("%s: %s" % (name, self._view_type(variable))) + if any(variable.get("c_name") == "_nesting" for variable in self.variables): + self._add("_nesting: _Nesting") + self._add() + + def _emit_functions(self) -> None: + for function in sorted( + ( + function + for function in self.functions + if function.get("role") == "module" and self._public(function) + ), + key=lambda item: (item["python_name"], item["c_name"]), + ): + self._add("def %s" % self._signature(function, instance=False)) + self._add() + + def _emit_constants(self) -> None: + for constant in sorted( + (constant for constant in self.constants if self._public(constant)), + key=lambda item: item["python_name"], + ): + self._add("%s: int" % _identifier(constant["python_name"])) + + def _signature( + self, + function: Mapping[str, Any], + *, + instance: bool, + skip_receiver: bool = False, + type_aliases: Mapping[str, str] | None = None, + ) -> str: + params = self._parameters( + function, skip_receiver=skip_receiver, type_aliases=type_aliases + ) + if instance: + params = "self" + (", " + params if params else "") + return "%s(%s) -> %s: ..." % ( + _identifier(function["python_name"]), + params, + self._return_type(function, type_aliases=type_aliases), + ) + + def _parameters( + self, + function: Mapping[str, Any], + *, + skip_receiver: bool, + constructor: bool = False, + type_aliases: Mapping[str, str] | None = None, + ) -> str: + parameters = list(function.get("parameters", ())) + if skip_receiver and not function.get("static"): + parameters = parameters[1:] + used = {"self"} if not constructor and not function.get("static") else set() + result = [] + for index, parameter in enumerate(parameters): + name = _identifier(parameter.get("name") or "arg") + original = name + suffix = 2 + while name in used: + name = "%s%d" % (original, suffix) + suffix += 1 + used.add(name) + if parameter.get("type", {}).get("kind") == "ellipsis": + result.append("*%s: Any" % name) + continue + default = "" + if ( + constructor + and index == 0 + and parameter.get("name") == "parent" + and parameter.get("view", {}).get("category") == "object_pointer" + ): + parameter_type = ( + self._view_type(parameter, type_aliases=type_aliases) + " | None" + ) + default = " = ..." + else: + parameter_type = self._view_type( + parameter, type_aliases=type_aliases + ) + result.append("%s: %s%s" % (name, parameter_type, default)) + if function.get("variadic"): + result.append("*args: Any") + return ", ".join(result) + + def _return_type( + self, + function: Mapping[str, Any], + *, + type_aliases: Mapping[str, str] | None = None, + ) -> str: + view = function.get("return_view") + if not isinstance(view, Mapping): + raise ValueError("canonical API function is missing a return view") + python_type = view.get("python_type") + if not isinstance(python_type, str) or not python_type: + raise ValueError("canonical API function has no return Python type") + for type_name, alias in (type_aliases or {}).items(): + python_type = re.sub(r"\b%s\b" % re.escape(type_name), alias, python_type) + return python_type + + +def load_canonical_api(path: Path) -> Mapping[str, Any]: + with path.open(encoding="utf-8") as handle: + data = json.load(handle) + if data.get("schema_version") != API_SCHEMA_VERSION: + raise ValueError("unsupported canonical API schema") + errors = validate_api_data(data) + if errors: + raise ValueError("invalid canonical API model: %s" % "; ".join(errors)) + return data diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/generate.py b/maix_lvgl/tools/omnipython_lvgl/binding/generate.py new file mode 100644 index 00000000..476afe0f --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/generate.py @@ -0,0 +1,319 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Unified command for generating all LVGL binding artifacts.""" + +from __future__ import annotations + +import argparse +import io +import json +import shutil +import sys +import tempfile +from pathlib import Path +from types import SimpleNamespace + +from .artifacts import manifest_for_directory +from .api_model import write_api_model +from .api_policy import ApiPolicy, validate_policy_against_declarations +from .emit_pyi import write_pyi +from .generator import ( + analysis_snapshot, + prepare_analysis, + run_backend, +) +from .preprocess import preprocess + + +TARGETS = ("micropython", "circuitpython", "cpython") +TARGET_OUTPUTS = { + "micropython": "lvgl_micropython.c", + "circuitpython": "lvgl_circuitpython.c", + "cpython": "lvgl_python.c", +} + + +def _repo_root(): + return Path(__file__).resolve().parent.parent + + +def _target_command_line(target): + return " ".join( + [ + "python", + "-m", + "binding.generate", + "--target", + target, + ] + ) + + +def _generation_args(root, output_dir): + return SimpleNamespace( + include=[str(root / "fake_libc_include")], + define=[], + ep=str(output_dir / "lvgl.pp"), + json=None, + module_name="lvgl", + module_prefix="lv", + input=["lvgl/lvgl.h"], + ) + + +def _extract_circuitpython_header(source): + start_marker = "#ifndef LVCP_MODULE_GLOBALS_H" + end_marker = "#endif /* LVCP_MODULE_GLOBALS_H */" + start = source.find(start_marker) + end = source.find(end_marker) + if start < 0 or end < 0: + raise RuntimeError("LVCP_MODULE_GLOBALS block not found in generated C") + end += len(end_marker) + return source[start:end] + "\n" + + +def _preprocess_to(output_dir, root): + args = SimpleNamespace( + ep=None, + include=[str(root / "fake_libc_include")], + define=[], + input=[str(root / "lvgl" / "lvgl.h")], + ) + source, command = preprocess(args) + output_dir.mkdir(parents=True, exist_ok=True) + (output_dir / "lvgl.pp").write_text(source, encoding="utf-8") + return command + + +def generate( + *, + root=None, + output_dir=None, + target="all", + pyi_only=False, +): + """Generate selected targets into *output_dir* and return artifact metadata.""" + + root = Path(root or _repo_root()).resolve() + output_dir = Path(output_dir or root / "generated").resolve() + output_dir.mkdir(parents=True, exist_ok=True) + + api_path = output_dir / "api.json" + pp_path = output_dir / "lvgl.pp" + pyi_path = output_dir / "lvgl.pyi" + + if pyi_only: + if not api_path.is_file(): + raise FileNotFoundError( + "pyi-only requires existing %s" % api_path + ) + write_pyi( + api_path, + pyi_path, + target="all", + repo_root=root, + ) + return manifest_for_directory(output_dir, ("lvgl.pyi",)) + + _preprocess_to(output_dir, root) + selected = TARGETS if target == "all" else (target,) + + args = _generation_args(root, output_dir) + source = pp_path.read_text(encoding="utf-8") + prepared = prepare_analysis( + args, + source, + "Preprocessing was disabled.", + _target_command_line("all"), + lambda *unused_args, **unused_kwargs: None, + ) + shared_analysis = analysis_snapshot(prepared) + validate_policy_against_declarations( + ApiPolicy.default(module_prefix=prepared.module_prefix), + prepared.declaration_ir, + ) + model_errors = prepared.api_model.validation_errors() + if model_errors: + raise ValueError("invalid canonical API model: %s" % "; ".join(model_errors)) + write_api_model(prepared.api_model, api_path) + + if "micropython" in selected: + output = io.StringIO() + run_backend( + "micropython", + args, + source, + "Preprocessing was disabled.", + output, + _target_command_line("micropython"), + analysis_state=shared_analysis, + ) + (output_dir / TARGET_OUTPUTS["micropython"]).write_text( + output.getvalue(), encoding="utf-8" + ) + + if "circuitpython" in selected: + output = io.StringIO() + circuitpython_run = run_backend( + "circuitpython", + args, + source, + "Preprocessing was disabled.", + output, + _target_command_line("circuitpython"), + analysis_state=shared_analysis, + ) + circuitpython_source = output.getvalue() + (output_dir / "lvgl_circuitpython.h").write_text( + _extract_circuitpython_header(circuitpython_source), encoding="utf-8" + ) + (output_dir / TARGET_OUTPUTS["circuitpython"]).write_text( + circuitpython_source, encoding="utf-8" + ) + + if "cpython" in selected: + output = io.StringIO() + run_backend( + "cpython", + args, + source, + "Preprocessing was disabled.", + output, + _target_command_line("cpython"), + analysis_state=shared_analysis, + ) + (output_dir / TARGET_OUTPUTS["cpython"]).write_text( + output.getvalue(), encoding="utf-8" + ) + + write_pyi( + api_path, + pyi_path, + target="all", + repo_root=root, + ) + return manifest_for_directory(output_dir) + + +def _normalized_for_check(path, data): + """Normalize generated C command banners before read-only comparison.""" + + if not path.endswith((".c", ".h")): + return data + lines = data.splitlines(True) + normalized = [] + skip_command = False + for line in lines: + if line.rstrip().endswith("Command line:"): + normalized.append(line) + skip_command = True + continue + if skip_command: + normalized.append(" * \n") + skip_command = False + continue + normalized.append(line) + return "".join(normalized) + + +def _compare_directories(expected_dir, actual_dir, filenames): + differences = [] + for filename in filenames: + expected = Path(expected_dir) / filename + actual = Path(actual_dir) / filename + if not expected.is_file(): + differences.append("missing expected %s" % filename) + continue + if not actual.is_file(): + differences.append("missing generated %s" % filename) + continue + expected_data = _normalized_for_check(filename, expected.read_text(encoding="utf-8")) + actual_data = _normalized_for_check(filename, actual.read_text(encoding="utf-8")) + if expected_data != actual_data: + differences.append("changed %s" % filename) + return differences + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", type=Path, default=_repo_root(), help="lvgl-bindings repository root" + ) + parser.add_argument( + "--output-dir", + type=Path, + help="artifact directory (default: /generated)", + ) + parser.add_argument( + "--target", choices=TARGETS + ("all",), default="all" + ) + parser.add_argument( + "--pyi-only", action="store_true", help="regenerate only lvgl.pyi" + ) + parser.add_argument( + "--check", action="store_true", help="generate in a temporary directory and compare" + ) + parser.add_argument( + "--hash", action="store_true", help="print the generated artifact manifest" + ) + args = parser.parse_args(argv) + root = args.root.resolve() + output_dir = (args.output_dir or root / "generated").resolve() + + if not args.check: + manifest = generate( + root=root, + output_dir=output_dir, + target=args.target, + pyi_only=args.pyi_only, + ) + if args.hash: + print(json.dumps(manifest, indent=2, sort_keys=True)) + return 0 + + if args.target != "all": + selected = ( + TARGET_OUTPUTS[args.target], + "api.json", + "lvgl.pp", + "lvgl.pyi", + ) + if args.target == "circuitpython": + selected += ("lvgl_circuitpython.h",) + elif args.pyi_only: + selected = ("lvgl.pyi",) + else: + selected = ( + "api.json", + "lvgl.pp", + "lvgl.pyi", + "lvgl_micropython.c", + "lvgl_circuitpython.c", + "lvgl_circuitpython.h", + "lvgl_python.c", + ) + + with tempfile.TemporaryDirectory(prefix="lvgl-bindings-check-") as temporary: + temporary_dir = Path(temporary) + if args.pyi_only: + for filename in ("api.json",): + shutil.copy2(output_dir / filename, temporary_dir / filename) + generate( + root=root, + output_dir=temporary_dir, + target=args.target, + pyi_only=args.pyi_only, + ) + differences = _compare_directories(output_dir, temporary, selected) + if differences: + for difference in differences: + print(difference, file=sys.stderr) + return 1 + print("generated artifacts match %s" % output_dir) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/generator.py b/maix_lvgl/tools/omnipython_lvgl/binding/generator.py new file mode 100644 index 00000000..c21c8c25 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/generator.py @@ -0,0 +1,163 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Shared analysis and target-backend orchestration.""" + +from __future__ import print_function + +import copy +from dataclasses import dataclass +from importlib import import_module + +from .context import BindingContext + + +@dataclass(frozen=True) +class Backend: + """Target-specific lowering entry point behind the common generator flow.""" + + name: str + emitter_module: str + + +@dataclass +class BackendRun: + """Completed lowering run for one target.""" + + context: BindingContext + emitted: bool = True + + +BACKENDS = { + "micropython": Backend("micropython", "binding.emit_micropython"), + "circuitpython": Backend("circuitpython", "binding.emit_circuitpython"), + "cpython": Backend("cpython", "binding.emit_cpython"), +} + + +_ANALYSIS_STATE_NAMES = ( + "obj_metadata", + "func_metadata", + "callback_metadata", + "func_prototypes", + "parser", + "gen", + "parsed_ast", + "ast", + "declaration_ir", + "declaration_index", + "api_model", + "lvgl_json", + "forward_struct_decls", + "typedefs", + "synonym", + "struct_typedefs", + "structs_without_typedef", + "structs", + "explicit_structs", + "opaque_structs", + "func_defs", + "func_decls", + "all_funcs", + "funcs", + "obj_ctors", + "obj_names", + "parent_obj_names", + "enum_defs", + "func_typedefs", + "blobs", + "int_constants", + "mp_to_lv", + "lv_to_mp", + "lv_mp_type", + "lv_to_mp_byref", + "lv_to_mp_funcptr", +) + + +def prepare_analysis(args, source, pp_cmd, cmd_line, emit_print): + """Parse and analyze one translation unit for reuse by every target.""" + from pycparser import c_generator, c_parser + + from . import runtime + from .api_model import build_api_model + from .api_policy import ApiPolicy + from .analyze import analyze + + runtime.reset() + ctx = BindingContext(args, source, pp_cmd, cmd_line, emit_print) + ctx.init_patterns() + ctx.parser = c_parser.CParser() + ctx.gen = c_generator.CGenerator() + ctx.parsed_ast = ctx.parser.parse(source, filename="") + runtime.activate(ctx) + analyze(ctx) + runtime.activate(ctx) + policy = ApiPolicy.default(module_prefix=ctx.module_prefix) + ctx.api_model = build_api_model( + ctx.declaration_ir, + module_prefix=ctx.module_prefix, + base_obj_type=ctx.base_obj_type, + policy=policy, + ) + runtime.set_("api_model", ctx.api_model) + return ctx + + +def analysis_snapshot(ctx): + """Return an isolated, internally consistent copy of analysis state.""" + values = { + name: getattr(ctx, name) + for name in _ANALYSIS_STATE_NAMES + if hasattr(ctx, name) + } + snapshot = copy.deepcopy(values) + # DeclarationIR is frozen and target-neutral. Preserve the same object so + # every backend receives the exact canonical declaration set, not a copy. + if hasattr(ctx, "declaration_ir"): + snapshot["declaration_ir"] = ctx.declaration_ir + if hasattr(ctx, "api_model"): + snapshot["api_model"] = ctx.api_model + return snapshot + + +def _new_context(args, source, pp_cmd, cmd_line, emit_print, analysis_state=None): + from .util import clear_memoized + + clear_memoized() + ctx = BindingContext(args, source, pp_cmd, cmd_line, emit_print) + ctx.init_patterns() + if analysis_state is not None: + values = copy.deepcopy(analysis_state) + if "declaration_ir" in analysis_state: + values["declaration_ir"] = analysis_state["declaration_ir"] + if "api_model" in analysis_state: + values["api_model"] = analysis_state["api_model"] + for name, value in values.items(): + setattr(ctx, name, value) + ctx._analysis_ready = True + return ctx + + +def run_backend(target, args, source, pp_cmd, out, cmd_line, analysis_state=None): + """Lower one shared analysis snapshot through a named target backend.""" + import builtins + + try: + backend = BACKENDS[target] + except KeyError: + raise ValueError("unsupported backend: %s" % target) + + def emit_print(*a, **k): + k.setdefault("file", out) + builtins.print(*a, **k) + + ctx = _new_context( + args, source, pp_cmd, cmd_line, emit_print, analysis_state=analysis_state + ) + from . import runtime + + with runtime.scoped(ctx): + import_module(backend.emitter_module).run(ctx) + return BackendRun(ctx) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/helpers.py b/maix_lvgl/tools/omnipython_lvgl/binding/helpers.py new file mode 100644 index 00000000..c591cfcb --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/helpers.py @@ -0,0 +1,167 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Shared identifier sanitization, LVGL patterns, and export_name helpers.""" +from __future__ import print_function + +import collections + +from pycparser import c_ast + +from . import runtime +from .parse import get_name, get_type +from .util import memoize + +# Prevent identifier names which are Python reserved words (add underscore in such case) +def export_name(name, kind): + """Delegate to `binding.naming` for Python export identifiers.""" + from .naming import export_name as _export_name + + return _export_name(name, kind) + + +def sanitize( + id, + kwlist=[ + "False", + "None", + "True", + "and", + "as", + "assert", + "break", + "class", + "continue", + "def", + "del", + "elif", + "else", + "except", + "finally", + "for", + "from", + "global", + "if", + "import", + "in", + "is", + "lambda", + "nonlocal", + "not", + "or", + "pass", + "raise", + "return", + "try", + "while", + "with", + "yield", + ], +): + if id in kwlist: + result = "_%s" % id + else: + result = id + result = result.strip() + result = result.replace(" ", "_") + result = result.replace("*", "_ptr") + return result + + +@memoize +def simplify_identifier(id): + match_result = runtime.current_context().lv_func_pattern.match(id) + return match_result.group(1) if match_result else id + + +def obj_name_from_ext_name(ext_name): + return runtime.current_context().lv_ext_pattern.match(ext_name).group(1) + + +def obj_name_from_func_name(func_name): + return runtime.current_context().lv_obj_pattern.match(func_name).group(1) + + +def ctor_name_from_obj_name(obj_name): + return "{prefix}_{obj}_create".format( + prefix=runtime.current_context().module_prefix, obj=obj_name + ) + + +def is_method_of(func_name, obj_name): + return func_name.lower().startswith( + "{prefix}_{obj}_".format( + prefix=runtime.current_context().module_prefix, obj=obj_name + ).lower() + ) + + +def method_name_from_func_name(func_name): + res = runtime.current_context().lv_method_pattern.match(func_name).group(1) + return res if res != "del" else "delete" # del is a reserved name, don't use it + + +def get_enum_name(enum): + match_result = runtime.current_context().lv_enum_name_pattern.match(enum) + return match_result.group(3) if match_result else enum + + +# C enum names that are nested on widget types (e.g. obj.FLAG) and also lv.OBJ_FLAG. +MODULE_LEVEL_DUPLEX_ENUMS = frozenset({"LV_OBJ_FLAG"}) + + +def is_widget_scoped_only_enum(enum_name): + """True when enum must not appear on the module (widget nested only).""" + return enum_name not in MODULE_LEVEL_DUPLEX_ENUMS + + +def collect_enum_referenced(enums, obj_names): + """Return enum names attached to widget types in the shared API contract.""" + enum_referenced = collections.OrderedDict() + for obj_name in obj_names: + for enum_name in enums.keys(): + if is_method_of(enum_name, obj_name) and is_widget_scoped_only_enum(enum_name): + enum_referenced[enum_name] = True + return enum_referenced + + +def str_enum_to_str(str_enum): + ctx = runtime.current_context() + res = ctx.lv_str_enum_pattern.match(str_enum).group(1) + return ("%s_" % ctx.module_prefix.upper()) + res + + +def is_obj_ctor(func): + ctx = runtime.current_context() + # ctor name must match pattern + if not ctx.create_obj_pattern.match(func.name): + return False + # ctor must return a base_obj type + if not ctx.lv_base_obj_pattern.match(get_type(func.type.type, remove_quals=True)): + return False + # ctor must receive (at least) one base obj parameters + args = func.type.args.params + if len(args) < 1: + return False + if not ctx.lv_base_obj_pattern.match(get_type(args[0].type, remove_quals=True)): + return False + return True + + +def is_global_callback(arg_type): + ctx = runtime.current_context() + arg_type_str = get_name(arg_type.type) + # print('/* --> is_global_callback %s: %s */' % (lv_global_callback_pattern.match(arg_type_str), arg_type_str)) + result = ctx.lv_global_callback_pattern.match(arg_type_str) + return result + + +# +# Initialization, data structures, helper functions +# + + +# We consider union as a struct, for simplicity +def is_struct(type): + return isinstance(type, c_ast.Struct) or isinstance(type, c_ast.Union) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/ir.py b/maix_lvgl/tools/omnipython_lvgl/binding/ir.py new file mode 100644 index 00000000..efc0e873 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/ir.py @@ -0,0 +1,641 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Target-neutral C declaration intermediate representation. + +The IR deliberately contains declarations only. Target runtime policy, +argument conversion, public-export decisions, and C emission belong to later +pipeline stages. This module has no dependency on any binding target. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Mapping, Optional, Sequence, Tuple + +from pycparser import c_ast, c_generator, c_parser + + +@dataclass(frozen=True) +class SourceLocation: + file: Optional[str] = None + line: Optional[int] = None + column: Optional[int] = None + + @classmethod + def from_coord(cls, coord: Any) -> "SourceLocation": + if coord is None: + return cls() + return cls( + file=getattr(coord, "file", None), + line=getattr(coord, "line", None), + column=getattr(coord, "column", None), + ) + + +@dataclass(frozen=True) +class CType: + """A normalized C type expression.""" + + kind: str + name: Optional[str] = None + qualifiers: Tuple[str, ...] = () + target: Optional["CType"] = None + element: Optional["CType"] = None + dimensions: Tuple[str, ...] = () + return_type: Optional["CType"] = None + parameters: Tuple["CParameter", ...] = () + variadic: bool = False + + def canonical(self) -> str: + qualifiers = " ".join(self.qualifiers) + prefix = (qualifiers + " ") if qualifiers else "" + if self.kind in {"primitive", "identifier"}: + return prefix + (self.name or "") + if self.kind in {"struct", "union", "enum"}: + return prefix + self.kind + " " + (self.name or "") + if self.kind == "pointer": + target = self.target.canonical() if self.target else "void" + pointer_qualifiers = " ".join(self.qualifiers) + suffix = " *" + if pointer_qualifiers: + suffix += " " + pointer_qualifiers + return target + suffix + if self.kind == "array": + suffix = "".join("[" + dimension + "]" for dimension in self.dimensions) + return (self.element.canonical() if self.element else "") + suffix + if self.kind == "function": + args = ", ".join(parameter.type.canonical() for parameter in self.parameters) + if self.variadic: + args = (args + ", ") if args else "" + args += "..." + return "{} ({})".format( + self.return_type.canonical() if self.return_type else "void", + args, + ) + if self.kind == "ellipsis": + return "..." + return prefix + (self.name or "") + + +@dataclass(frozen=True) +class CParameter: + name: Optional[str] + type: CType + location: SourceLocation = field(default_factory=SourceLocation) + + +@dataclass(frozen=True) +class CField: + name: Optional[str] + type: CType + location: SourceLocation = field(default_factory=SourceLocation) + bit_width: Optional[str] = None + + +@dataclass(frozen=True) +class CFunction: + name: str + return_type: CType + parameters: Tuple[CParameter, ...] + variadic: bool = False + storage: Tuple[str, ...] = () + function_specifiers: Tuple[str, ...] = () + is_definition: bool = False + location: SourceLocation = field(default_factory=SourceLocation) + + @property + def signature(self) -> str: + args = ", ".join(parameter.type.canonical() for parameter in self.parameters) + if self.variadic: + args = (args + ", ") if args else "" + args += "..." + return "{} {}({})".format(self.return_type.canonical(), self.name, args) + + +@dataclass(frozen=True) +class CStruct: + name: Optional[str] + kind: str + fields: Tuple[CField, ...] = () + typedef_names: Tuple[str, ...] = () + complete: bool = False + location: SourceLocation = field(default_factory=SourceLocation) + + +@dataclass(frozen=True) +class CEnum: + name: Optional[str] + members: Tuple[str, ...] = () + typedef_names: Tuple[str, ...] = () + complete: bool = False + values: Tuple[Tuple[str, Optional[str]], ...] = () + location: SourceLocation = field(default_factory=SourceLocation) + + +@dataclass(frozen=True) +class CTypedef: + name: str + type: CType + location: SourceLocation = field(default_factory=SourceLocation) + + +@dataclass(frozen=True) +class CVariable: + name: str + type: CType + storage: Tuple[str, ...] = () + location: SourceLocation = field(default_factory=SourceLocation) + + +@dataclass(frozen=True) +class DeclarationIR: + """All declarations from one preprocessed translation unit.""" + + functions: Tuple[CFunction, ...] = () + structs: Tuple[CStruct, ...] = () + enums: Tuple[CEnum, ...] = () + typedefs: Tuple[CTypedef, ...] = () + variables: Tuple[CVariable, ...] = () + + @property + def functions_by_name(self) -> Mapping[str, CFunction]: + return {function.name: function for function in self.functions} + + @property + def typedefs_by_name(self) -> Mapping[str, CTypedef]: + return {typedef.name: typedef for typedef in self.typedefs} + + @property + def callback_typedefs(self) -> Mapping[str, CType]: + return { + typedef.name: typedef.type + for typedef in self.typedefs + if typedef.type.kind == "pointer" + and typedef.type.target is not None + and typedef.type.target.kind == "function" + } + + +@dataclass(frozen=True) +class DeclarationIndex: + """Read-only indexes and relationship queries over `DeclarationIR`.""" + + ir: DeclarationIR + functions_by_name: Mapping[str, CFunction] + structs_by_name: Mapping[str, CStruct] + enums_by_name: Mapping[str, CEnum] + typedefs_by_name: Mapping[str, CTypedef] + struct_aliases: Mapping[str, str] + struct_tag_aliases: Mapping[str, str] + module_prefix: str = "lv" + + @classmethod + def from_ir(cls, ir: DeclarationIR, module_prefix: str = "lv") -> "DeclarationIndex": + structs = {} + aliases = {} + tag_aliases = {} + for struct in ir.structs: + if struct.name: + structs[struct.name] = struct + for alias in struct.typedef_names: + structs[alias] = struct + if struct.name: + aliases[alias] = struct.name + tag_aliases.setdefault(struct.name, alias) + enums = {} + for enum in ir.enums: + if enum.name: + enums[enum.name] = enum + for alias in enum.typedef_names: + enums[alias] = enum + return cls( + ir=ir, + functions_by_name={function.name: function for function in ir.functions}, + structs_by_name=structs, + enums_by_name=enums, + typedefs_by_name={typedef.name: typedef for typedef in ir.typedefs}, + struct_aliases=aliases, + struct_tag_aliases=tag_aliases, + module_prefix=module_prefix, + ) + + @staticmethod + def _without_qualifiers(type_: CType) -> str: + if type_.kind in {"identifier", "primitive", "struct", "union", "enum"}: + return type_.name or type_.canonical() + if type_.kind == "pointer": + target = ( + DeclarationIndex._without_qualifiers(type_.target) + if type_.target is not None + else "void" + ) + return target + " *" + if type_.kind == "array": + element = ( + DeclarationIndex._without_qualifiers(type_.element) + if type_.element is not None + else "" + ) + return element + "".join("[" + dim + "]" for dim in type_.dimensions) + return type_.canonical() + + @classmethod + def _first_argument_type_name(cls, type_: CType) -> Optional[str]: + # Inspect one pointer/array layer, but + # retain a second pointer layer (T ** is not a T struct receiver). + if type_.kind in {"pointer", "array"}: + type_ = type_.target or type_.element + if type_ is None: + return None + return cls._without_qualifiers(type_) + + def first_argument_type_name(self, function_name: str) -> Optional[str]: + function = self.functions_by_name.get(function_name) + if function is None or not function.parameters: + return None + name = self._first_argument_type_name(function.parameters[0].type) + return self.struct_tag_aliases.get(name, name) + + def _struct_identity(self, name: Optional[str]) -> Optional[str]: + if not name: + return None + struct = self.structs_by_name.get(name) + if struct is not None and struct.name: + return struct.name + return self.struct_aliases.get(name, name) + + @staticmethod + def _struct_stems(name: Optional[str]) -> Tuple[str, ...]: + if not name: + return () + names = {name} + if name.endswith("_t"): + names.add(name[:-2]) + return tuple(names) + + def is_struct_function(self, function_name: str, struct_name: str) -> bool: + if struct_name not in self.structs_by_name: + return False + first_type = self.first_argument_type_name(function_name) + if self._struct_identity(first_type) != self._struct_identity(struct_name): + return False + # Preserve the established relationship rule: a common identifier + # prefix is enough, even when the first argument's struct tag has a + # longer suffix (for example lv_obj_class_t/lv_obj_event_base). + function_name = self._simplify(function_name) + struct_name = self._simplify(struct_name) + common_length = 0 + for left, right in zip(function_name, struct_name): + if left != right: + break + common_length += 1 + if common_length == 0: + return False + index = common_length - 1 + while index > 0 and function_name[index] != "_": + index -= 1 + return function_name[index + 1 :] != function_name + + def _simplify(self, name: str) -> str: + prefix = self.module_prefix + "_" + return name[len(prefix) :] if name.startswith(prefix) else name + + def struct_functions(self, struct_name: str) -> Tuple[CFunction, ...]: + return tuple( + function + for function in self.ir.functions + if self.is_struct_function(function.name, struct_name) + ) + + +class _Converter: + def __init__(self) -> None: + self.generator = c_generator.CGenerator() + + def location(self, node: Any) -> SourceLocation: + return SourceLocation.from_coord(getattr(node, "coord", None)) + + def expression(self, node: Any) -> str: + if node is None: + return "" + return self.generator.visit(node) + + def type(self, node: Any) -> CType: + if isinstance(node, c_ast.TypeDecl): + result = self.type(node.type) + if node.quals: + result = CType( + kind=result.kind, + name=result.name, + qualifiers=tuple(node.quals) + result.qualifiers, + target=result.target, + element=result.element, + dimensions=result.dimensions, + return_type=result.return_type, + parameters=result.parameters, + variadic=result.variadic, + ) + return result + if isinstance(node, c_ast.IdentifierType): + names = tuple(node.names) + primitive_names = { + "_Bool", + "bool", + "char", + "double", + "float", + "int", + "long", + "short", + "signed", + "unsigned", + "void", + } + kind = "primitive" if set(names) <= primitive_names else "identifier" + return CType(kind=kind, name=" ".join(names)) + if isinstance(node, c_ast.PtrDecl): + return CType( + kind="pointer", + qualifiers=tuple(node.quals or ()), + target=self.type(node.type), + ) + if isinstance(node, c_ast.ArrayDecl): + dimension = self.expression(node.dim) + return CType( + kind="array", + element=self.type(node.type), + dimensions=(dimension,), + ) + if isinstance(node, c_ast.FuncDecl): + parameters, variadic = self.parameters(node.args) + return CType( + kind="function", + return_type=self.type(node.type), + parameters=parameters, + variadic=variadic, + ) + if isinstance(node, c_ast.Struct): + return CType(kind="struct", name=node.name) + if isinstance(node, c_ast.Union): + return CType(kind="union", name=node.name) + if isinstance(node, c_ast.Enum): + return CType(kind="enum", name=node.name) + if isinstance(node, c_ast.EllipsisParam): + return CType(kind="ellipsis", name="...") + if isinstance(node, c_ast.Typename): + return self.type(node.type) + return CType(kind="unknown", name=self.generator.visit(node)) + + def parameter(self, node: Any) -> CParameter: + if isinstance(node, c_ast.EllipsisParam): + return CParameter(name=None, type=CType(kind="ellipsis", name="...")) + return CParameter( + name=getattr(node, "name", None), + type=self.type(node.type), + location=self.location(node), + ) + + def parameters(self, node: Any) -> Tuple[Tuple[CParameter, ...], bool]: + if node is None or not node.params: + return (), False + variadic = any(isinstance(parameter, c_ast.EllipsisParam) for parameter in node.params) + parameters = tuple( + self.parameter(parameter) + for parameter in node.params + if not isinstance(parameter, c_ast.EllipsisParam) + ) + # In a C prototype, ``(void)`` means no parameters. pycparser keeps + # the ``void`` Typename node, so normalize it here rather than making + # every target backend special-case a phantom argument. + if ( + not variadic + and len(parameters) == 1 + and parameters[0].name is None + and parameters[0].type.kind == "primitive" + and parameters[0].type.name == "void" + and not parameters[0].type.qualifiers + ): + parameters = () + return parameters, variadic + + def fields(self, node: Any) -> Tuple[CField, ...]: + if not node.decls: + return () + result = [] + for declaration in node.decls: + result.append( + CField( + name=declaration.name, + type=self.type(declaration.type), + location=self.location(declaration), + bit_width=self.expression(declaration.bitsize) + if declaration.bitsize is not None + else None, + ) + ) + return tuple(result) + + def struct(self, node: Any, typedef_names: Sequence[str] = ()) -> CStruct: + kind = "union" if isinstance(node, c_ast.Union) else "struct" + return CStruct( + name=node.name, + kind=kind, + fields=self.fields(node), + typedef_names=tuple(typedef_names), + complete=node.decls is not None, + location=self.location(node), + ) + + def enum(self, node: c_ast.Enum, typedef_names: Sequence[str] = ()) -> CEnum: + members = () + values = () + if node.values is not None: + enumerators = node.values.enumerators or () + members = tuple(enumerator.name for enumerator in enumerators) + values = tuple( + ( + enumerator.name, + self.expression(enumerator.value) + if enumerator.value is not None + else None, + ) + for enumerator in enumerators + ) + return CEnum( + name=node.name, + members=members, + typedef_names=tuple(typedef_names), + complete=node.values is not None, + values=values, + location=self.location(node), + ) + + +def _function_from_decl(converter: _Converter, declaration: Any, is_definition=False): + function_type = declaration.type + parameters, variadic = converter.parameters(function_type.args) + return CFunction( + name=declaration.name, + return_type=converter.type(function_type.type), + parameters=parameters, + variadic=variadic, + storage=tuple(declaration.storage or ()), + function_specifiers=tuple(declaration.funcspec or ()), + is_definition=is_definition, + location=converter.location(declaration), + ) + + +def parse_ast(ast: c_ast.FileAST) -> DeclarationIR: + """Convert a pycparser AST to target-neutral declarations.""" + + converter = _Converter() + functions = [] + structs = [] + enums = [] + typedefs = [] + variables = [] + struct_positions = {} + enum_positions = {} + + def add_struct(node, typedef_names=()): + kind = "union" if isinstance(node, c_ast.Union) else "struct" + key = (kind, node.name) if node.name else (kind, id(node)) + declaration = converter.struct(node, typedef_names) + if key not in struct_positions: + struct_positions[key] = len(structs) + structs.append(declaration) + return + position = struct_positions[key] + previous = structs[position] + typedefs = tuple(dict.fromkeys(previous.typedef_names + declaration.typedef_names)) + complete = previous.complete or declaration.complete + fields = declaration.fields if declaration.complete else previous.fields + location = ( + declaration.location + if declaration.complete and not previous.complete + else previous.location + ) + structs[position] = CStruct( + name=previous.name or declaration.name, + kind=previous.kind, + fields=fields, + typedef_names=typedefs, + complete=complete, + location=location, + ) + + def add_enum(node, typedef_names=()): + key = ("named", node.name) if node.name else ("anonymous", id(node)) + declaration = converter.enum(node, typedef_names) + if key not in enum_positions: + enum_positions[key] = len(enums) + enums.append(declaration) + return + position = enum_positions[key] + previous = enums[position] + typedefs = tuple(dict.fromkeys(previous.typedef_names + declaration.typedef_names)) + complete = previous.complete or declaration.complete + members = declaration.members if declaration.complete else previous.members + values = declaration.values if declaration.complete else previous.values + location = ( + declaration.location + if declaration.complete and not previous.complete + else previous.location + ) + enums[position] = CEnum( + name=previous.name or declaration.name, + members=members, + typedef_names=typedefs, + complete=complete, + values=values, + location=location, + ) + + def typedef_composite(node): + """Return a composite directly named by a typedef, if present.""" + + if isinstance(node, c_ast.TypeDecl) and isinstance( + node.type, (c_ast.Struct, c_ast.Union, c_ast.Enum) + ): + return node.type + return None + + for external in ast.ext: + if isinstance(external, c_ast.FuncDef): + functions.append(_function_from_decl(converter, external.decl, True)) + continue + if isinstance(external, c_ast.Typedef): + typedefs.append( + CTypedef( + name=external.name, + type=converter.type(external.type), + location=converter.location(external), + ) + ) + composite = typedef_composite(external.type) + if isinstance(composite, (c_ast.Struct, c_ast.Union)): + add_struct(composite, (external.name,)) + elif isinstance(composite, c_ast.Enum): + add_enum(composite, (external.name,)) + continue + if not isinstance(external, c_ast.Decl): + continue + if isinstance(external.type, c_ast.FuncDecl): + functions.append(_function_from_decl(converter, external)) + elif isinstance(external.type, (c_ast.Struct, c_ast.Union)): + add_struct(external.type) + if external.name: + variables.append( + CVariable( + name=external.name, + type=converter.type(external.type), + storage=tuple(external.storage or ()), + location=converter.location(external), + ) + ) + elif isinstance(external.type, c_ast.Enum): + add_enum(external.type) + elif external.name: + variables.append( + CVariable( + name=external.name, + type=converter.type(external.type), + storage=tuple(external.storage or ()), + location=converter.location(external), + ) + ) + + unique_functions = [] + function_positions = {} + for function in functions: + previous_position = function_positions.get(function.name) + if previous_position is None: + function_positions[function.name] = len(unique_functions) + unique_functions.append(function) + continue + previous = unique_functions[previous_position] + if previous.signature != function.signature: + raise ValueError( + "conflicting declarations for %s: %s / %s" + % (function.name, previous.signature, function.signature) + ) + if function.is_definition and not previous.is_definition: + unique_functions[previous_position] = function + + return DeclarationIR( + functions=tuple(unique_functions), + structs=tuple(structs), + enums=tuple(enums), + typedefs=tuple(typedefs), + variables=tuple(variables), + ) + + +def parse_source(source: str, filename: str = "", parser=None) -> DeclarationIR: + """Parse C source and return a target-neutral declaration IR.""" + + parser = parser or c_parser.CParser() + return parse_ast(parser.parse(source, filename=filename)) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/naming.py b/maix_lvgl/tools/omnipython_lvgl/binding/naming.py new file mode 100644 index 00000000..9d0d495a --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/naming.py @@ -0,0 +1,45 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Established upstream-compatible Python export names.""" + +from __future__ import annotations + +def _established_name(name: str, kind: str) -> str: + from .analyze import get_enum_member_name + from . import helpers + from .helpers import get_enum_name, sanitize + + def _simplify(name: str) -> str: + try: + return helpers.simplify_identifier(name) + except RuntimeError: + return name + + def _enum_name(name: str) -> str: + try: + return sanitize(get_enum_name(name)) + except RuntimeError: + return sanitize(name) + + if kind == "object": + return sanitize(name) + if kind == "enum": + return _enum_name(name) + if kind == "enum_member": + return sanitize(get_enum_member_name(name)) + if kind == "function": + return sanitize(_simplify(name)) + if kind == "struct": + return sanitize(_simplify(name)) + if kind == "blob": + return sanitize(_simplify(name)) + if kind == "constant": + return _enum_name(name) + return sanitize(name) + + +def export_name(name: str, kind: str) -> str: + """Return the Python-facing export identifier for ``name``.""" + return _established_name(name, kind) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/parse.py b/maix_lvgl/tools/omnipython_lvgl/binding/parse.py new file mode 100644 index 00000000..a242fb66 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/parse.py @@ -0,0 +1,155 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Low-level pycparser AST helpers used by analyze and emit.""" +from __future__ import print_function + +import copy + +from pycparser import c_ast, c_generator + +from .util import memoize + +@memoize +def remove_declname(ast): + if hasattr(ast, "declname"): + ast.declname = None + if isinstance(ast, tuple): + remove_declname(ast[1]) + return + for i, c1 in enumerate(ast.children()): + child = ast.children()[i] + remove_declname(child) + + +@memoize +def add_default_declname(ast, name): + if hasattr(ast, "declname"): + if ast.declname == None: + ast.declname = name + if isinstance(ast, tuple): + add_default_declname(ast[1], name) + return + for i, c1 in enumerate(ast.children()): + child = ast.children()[i] + add_default_declname(child, name) + + +@memoize +def convert_array_to_ptr(ast): + if hasattr(ast, "type") and isinstance(ast.type, c_ast.ArrayDecl): + ast.type = c_ast.PtrDecl( + ast.type.quals if hasattr(ast.type, "quals") else [], ast.type.type + ) + if isinstance(ast, tuple): + return convert_array_to_ptr(ast[1]) + for i, c1 in enumerate(ast.children()): + child = ast.children()[i] + convert_array_to_ptr(child) + + +@memoize +def remove_quals(ast): + if hasattr(ast, "quals"): + ast.quals = [] + if hasattr(ast, "dim_quals"): + ast.dim_quals = [] + if isinstance(ast, tuple): + return remove_quals(ast[1]) + for i, c1 in enumerate(ast.children()): + child = ast.children()[i] + if not isinstance( + child, c_ast.FuncDecl + ): # Don't remove quals which change function prototype + remove_quals(child) + + +from .util import memoize + + +def _emit(): + from . import runtime + + return runtime.current_context() + + +@memoize +def remove_explicit_struct(ast): + em = _emit() + if isinstance(ast, c_ast.TypeDecl) and isinstance(ast.type, c_ast.Struct): + explicit_struct_name = ast.type.name + if explicit_struct_name: + if explicit_struct_name in em.explicit_structs: + ast.type = c_ast.IdentifierType( + [em.explicit_structs[explicit_struct_name]] + ) + elif explicit_struct_name in em.structs: + ast.type = c_ast.IdentifierType([explicit_struct_name]) + if isinstance(ast, tuple): + return remove_explicit_struct(ast[1]) + for i, c1 in enumerate(ast.children()): + child = ast.children()[i] + remove_explicit_struct(child) + + +@memoize +def get_type(arg, **kwargs): + if isinstance(arg, str): + return arg + remove_quals_arg = "remove_quals" in kwargs and kwargs["remove_quals"] + arg_ast = copy.deepcopy(arg) + remove_explicit_struct(arg_ast) + if remove_quals_arg: + remove_quals(arg_ast) + return _emit().gen.visit(arg_ast) + + +@memoize +def get_name(type): + em = _emit() + if isinstance(type, c_ast.Decl): + return type.name + if isinstance(type, c_ast.Struct) and type.name and type.name in em.explicit_structs: + return em.explicit_structs[type.name] + if isinstance(type, c_ast.Struct): + return type.name + if isinstance(type, c_ast.TypeDecl): + return type.declname + if isinstance(type, c_ast.IdentifierType): + return type.names[0] + if isinstance(type, c_ast.FuncDecl): + return type.type.declname + # if isinstance(type, (c_ast.PtrDecl, c_ast.ArrayDecl)) and hasattr(type.type, 'declname'): + # return type.type.declname + if isinstance(type, (c_ast.PtrDecl, c_ast.ArrayDecl)): + return get_type(type, remove_quals=True) + else: + return em.gen.visit(type) + + +@memoize +def remove_arg_names(ast): + if isinstance(ast, c_ast.TypeDecl): + ast.declname = None + remove_arg_names(ast.type) + elif isinstance(ast, c_ast.Decl): + remove_arg_names(ast.type) + elif isinstance(ast, c_ast.FuncDecl): + remove_arg_names(ast.args) + elif isinstance(ast, c_ast.ParamList): + for param in ast.params: + remove_arg_names(param) + + +# Create a function prototype AST from a function AST +@memoize +def function_prototype(func): + bare_func = copy.deepcopy(func) + remove_declname(bare_func) + + ptr_decl = c_ast.PtrDecl(quals=[], type=bare_func.type) + + func_proto = c_ast.Typename(name=None, quals=[], align=[], type=ptr_decl) + + return func_proto diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/preprocess.py b/maix_lvgl/tools/omnipython_lvgl/binding/preprocess.py new file mode 100644 index 00000000..de8b21d1 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/preprocess.py @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Deterministic C preprocessing used by the binding generator.""" + +from __future__ import print_function + +import os +import shlex +import subprocess + + +def _preprocessor_command(args): + compiler = shlex.split(os.environ.get("CPP", "gcc")) + if "-E" not in compiler: + compiler.append("-E") + if "-P" not in compiler: + compiler.append("-P") + if not any(flag.startswith("-std=") for flag in compiler): + compiler.append("-std=c99") + compiler.append("-DPYCPARSER") + for define in args.define or []: + compiler.append("-D%s" % define) + for include in args.include or []: + compiler.extend(["-I", include]) + for input_file in args.input[1:]: + compiler.extend(["-include", input_file]) + compiler.append(args.input[0]) + return compiler + + +def preprocess(args): + """Return preprocessed source text and a description of how it was produced.""" + if not args.ep: + command = _preprocessor_command(args) + pp_cmd = " ".join(shlex.quote(part) for part in command) + source = subprocess.check_output(command).decode("utf-8") + else: + pp_cmd = "Preprocessing was disabled." + with open(args.ep, "r", encoding="utf-8") as f: + source = f.read() + return source, pp_cmd diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/runtime.py b/maix_lvgl/tools/omnipython_lvgl/binding/runtime.py new file mode 100644 index 00000000..a2011484 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/runtime.py @@ -0,0 +1,106 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Context-local state access for one binding generation run.""" +from __future__ import print_function + +from contextlib import contextmanager +from contextvars import ContextVar + +from .context import BindingContext + + +_ACTIVE_CONTEXT = ContextVar("lvgl_binding_context", default=None) +_RUN_VALUES = ContextVar("lvgl_binding_run_values", default=None) + + +def current_context(): + """Return the context for the active generation run.""" + ctx = _ACTIVE_CONTEXT.get() + if ctx is None: + raise RuntimeError("no active binding generation context") + return ctx + +def export_names(): + return BindingContext.EXPORT_NAMES + + +def set_(name, value): + """Assign state on the active context, or to run-local extra values.""" + ctx = _ACTIVE_CONTEXT.get() + if ctx is not None: + setattr(ctx, name, value) + return + values = _RUN_VALUES.get() + if values is None: + values = {} + _RUN_VALUES.set(values) + values[name] = value + + +def activate(ctx): + """Activate a context for the current generation flow.""" + _ACTIVE_CONTEXT.set(ctx) + _RUN_VALUES.set({}) + + +@contextmanager +def scoped(ctx): + """Activate one run and restore an enclosing run when it completes.""" + context_token = _ACTIVE_CONTEXT.set(ctx) + values_token = _RUN_VALUES.set({}) + try: + yield ctx + finally: + _RUN_VALUES.reset(values_token) + _ACTIVE_CONTEXT.reset(context_token) + + +def reset(): + """Clear context-local generation state before an in-process run.""" + from .util import clear_memoized + + clear_memoized() + + _ACTIVE_CONTEXT.set(None) + _RUN_VALUES.set({}) + + +_MISSING = object() + + +def get(name, default=_MISSING): + """Return state from the active context or run-local extra values.""" + ctx = _ACTIVE_CONTEXT.get() + if ctx is not None and hasattr(ctx, name): + return getattr(ctx, name) + values = _RUN_VALUES.get() or {} + if name in values: + return values[name] + if default is not _MISSING: + return default + raise NameError(name) + + +def emit(*args, **kwargs): + """Write generated output through the active binding context explicitly.""" + ctx = _ACTIVE_CONTEXT.get() + writer = ctx.emit_print if ctx is not None else get("print") + return writer(*args, **kwargs) + + +class _Namespace(object): + """Attribute access to binding globals (read/write through runtime).""" + + def __getattr__(self, name): + try: + return get(name) + except NameError: + raise AttributeError(name) + + def __setattr__(self, name, value): + set_(name, value) + + +ns = _Namespace() diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/runtime_exports.py b/maix_lvgl/tools/omnipython_lvgl/binding/runtime_exports.py new file mode 100644 index 00000000..05ca206a --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/runtime_exports.py @@ -0,0 +1,69 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Select the canonical module-function surface for native registration.""" + +from __future__ import print_function + +# C function names (parser names, not simplified Python names) +# LV_USE_TJPGD is 0 on every target (lv_conf.h): the JPEG decoder is jpegio's, +# registered through lv_image_decoder_create by displayif, the CircuitPython +# port and the CPython port. +RUNTIME_SKIP_MODULE_FUNCS = { + "micropython": frozenset( + { + "lv_tjpgd_init", + "lv_tjpgd_deinit", + } + ), + "circuitpython": frozenset( + { + "lv_tjpgd_init", + "lv_tjpgd_deinit", + } + ), + "cpython": frozenset( + { + "lv_tjpgd_init", + "lv_tjpgd_deinit", + "mp_lv_init_gc", + "mp_lv_deinit_gc", + "mp_lv_get_roots", + } + ), +} + +LIFECYCLE_MODULE_FUNCS = frozenset({"lv_init", "lv_deinit"}) + + +def skip_module_func(func_name, target): + return func_name in RUNTIME_SKIP_MODULE_FUNCS.get(target, frozenset()) + + +def filter_module_funcs_for_target(module_funcs, target, api_model=None): + """Return public canonical module functions available on ``target``. + + Native lowering discovers functions while generating wrappers. + Registration follows the canonical API roles so a struct or + object method can never leak into one target's module namespace. + """ + if api_model is None: + return [ + func + for func in module_funcs + if not skip_module_func(func.name, target) + ] + public = { + function.c_name + for function in api_model.functions + if function.visibility == "public" + and function.role == "module" + and target in function.available_on + } + return [func for func in module_funcs if func.name in public] + + +def filter_registration_module_funcs(module_funcs): + """Exclude lifecycle functions supplied by each target's module glue.""" + return [func for func in module_funcs if func.name not in LIFECYCLE_MODULE_FUNCS] diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/util.py b/maix_lvgl/tools/omnipython_lvgl/binding/util.py new file mode 100644 index 00000000..bdd49299 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/util.py @@ -0,0 +1,60 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Small utilities: memoize and stderr logging for analyze/emit.""" +from __future__ import print_function + +import re +import sys +from functools import lru_cache + + +_MEMOIZED_FUNCTIONS = [] + + +def memoize(func): + @lru_cache(maxsize=1000000) + def memoized(*args, **kwargs): + return func(*args, **kwargs) + + _MEMOIZED_FUNCTIONS.append(memoized) + return memoized + + +def clear_memoized(): + """Clear caches whose values may refer to a previous translation unit.""" + for memoized in _MEMOIZED_FUNCTIONS: + memoized.cache_clear() + + +def eprint(*args, **kwargs): + print(*args, file=sys.stderr, **kwargs) + + +_MONTSERRAT_FONT = re.compile(r"lv_font_montserrat_(\d+)$") + + +def config_guard(global_name): + """Return the ``lv_conf.h`` switch a generated global depends on, or None. + + A build can turn a built-in Montserrat size off (``-DLV_FONT_MONTSERRAT_40=0``) + without regenerating the binding, so the font's wrapper and its module entry + are emitted inside ``#if`` on that switch. + """ + match = _MONTSERRAT_FONT.match(global_name) + if match is None: + return None + return "LV_FONT_MONTSERRAT_%s" % match.group(1) + + +def guarded(text, global_name, indent=""): + """Wrap ``text`` in ``#if``/``#endif`` on `config_guard` when it has one. + + ``indent`` goes before ``text`` and ``#endif``, for a line that the caller's + template has already indented. + """ + guard = config_guard(global_name) + if guard is None: + return text + return "#if %s\n%s%s\n%s#endif" % (guard, indent, text, indent) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/verify_api.py b/maix_lvgl/tools/omnipython_lvgl/binding/verify_api.py new file mode 100644 index 00000000..d51398ec --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/verify_api.py @@ -0,0 +1,197 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Validate the generated target-neutral API model and its content hash.""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path + +from .api_model import API_SCHEMA_VERSION, TARGETS, api_hash_for_dict + + +def _validate_type_view(view, label, errors): + if not isinstance(view, dict): + errors.append("%s must be an object" % label) + return + for key in ("python_type", "category", "conversion"): + if not isinstance(view.get(key), str) or not view[key]: + errors.append("%s.%s must be a non-empty string" % (label, key)) + if "nullable" in view and not isinstance(view["nullable"], bool): + errors.append("%s.nullable must be boolean" % label) + if "lifetime" in view and ( + not isinstance(view["lifetime"], str) or not view["lifetime"] + ): + errors.append("%s.lifetime must be a non-empty string" % label) + + +def validate_api_data(data): + errors = [] + if data.get("schema_version") != API_SCHEMA_VERSION: + errors.append("unsupported API schema version") + if not isinstance(data.get("api_hash"), str): + errors.append("missing api_hash") + elif data["api_hash"] != api_hash_for_dict(data): + errors.append("api_hash does not match canonical content") + if data.get("module_prefix") != "lv": + errors.append("unexpected module prefix") + sections = ( + "functions", + "objects", + "structs", + "enums", + "typedefs", + "variables", + "constants", + ) + for section in sections: + if not isinstance(data.get(section), list): + errors.append("section %s must be a list" % section) + function_exports = {} + for function in data.get("functions", ()): + parameters = function.get("parameters") + if isinstance(parameters, list): + for index, parameter in enumerate(parameters): + _validate_type_view( + parameter.get("view"), + "function %s parameter %d view" + % (function.get("c_name"), index), + errors, + ) + else: + errors.append( + "function %s parameters must be a list" % function.get("c_name") + ) + _validate_type_view( + function.get("return_view"), + "function %s return view" % function.get("c_name"), + errors, + ) + available = function.get("available_on", ()) + if not set(available) <= set(TARGETS): + errors.append("function %s has an unknown target" % function.get("c_name")) + if function.get("visibility") == "public" and not available: + errors.append("public function %s has no targets" % function.get("c_name")) + if function.get("visibility") == "public": + key = ( + function.get("role"), + function.get("receiver"), + function.get("python_name"), + ) + if key in function_exports: + errors.append( + "duplicate function export %s (%s and %s)" + % ( + function.get("python_name"), + function_exports[key], + function.get("c_name"), + ) + ) + else: + function_exports[key] = function.get("c_name") + for section in ( + "objects", + "structs", + "enums", + "typedefs", + "variables", + "constants", + ): + for item in data.get(section, ()): + if section == "enums" and item.get("member_type") not in {"int", "str"}: + errors.append( + "enum %s has an unsupported member type" + % (item.get("python_name") or item.get("c_name")) + ) + if section == "structs": + fields = item.get("fields") + if isinstance(fields, list): + for index, field in enumerate(fields): + _validate_type_view( + field.get("view"), + "struct %s field %d view" + % (item.get("python_name"), index), + errors, + ) + else: + errors.append( + "struct %s fields must be a list" % item.get("python_name") + ) + elif section in {"typedefs", "variables"}: + _validate_type_view( + item.get("view"), + "%s %s view" % (section[:-1], item.get("python_name")), + errors, + ) + available = item.get("available_on", ()) + if not set(available) <= set(TARGETS): + name = item.get("python_name") or item.get("name") or item.get("c_name") + errors.append("%s %s has an unknown target" % (section, name)) + if item.get("visibility") == "public" and not available: + name = item.get("python_name") or item.get("name") or item.get("c_name") + errors.append("public %s %s has no targets" % (section, name)) + names = {} + for function in data.get("functions", ()): + if function.get("visibility") != "public" or function.get("role") != "module": + continue + name = function.get("python_name") + if name in names: + errors.append( + "duplicate module export %s (function and %s)" % (name, names[name]) + ) + else: + names[name] = "function" + type_names = { + item.get("python_name") + for section in ("structs", "enums") + for item in data.get(section, ()) + if item.get("visibility") == "public" + } + for section in ("objects", "structs", "enums", "typedefs", "variables", "constants"): + for item in data.get(section, ()): + if item.get("visibility") != "public": + continue + name = item.get("python_name") or item.get("name") + if ( + section == "typedefs" + and name in type_names + and item.get("type", {}).get("kind") in {"struct", "union", "enum"} + ): + continue + if name in names: + errors.append( + "duplicate module export %s (%s and %s)" + % (name, names[name], section) + ) + else: + names[name] = section + members = item.get("members") + if isinstance(members, list): + member_names = [member.get("name") for member in members] + if len(member_names) != len(set(member_names)): + errors.append("duplicate enum members: %s" % name) + methods = item.get("methods") if section == "objects" else None + if isinstance(methods, list) and len(methods) != len(set(methods)): + errors.append("duplicate object methods: %s" % name) + return errors + + +def main(argv=None): + path = Path((argv or sys.argv)[1]) + with path.open(encoding="utf-8") as handle: + data = json.load(handle) + errors = validate_api_data(data) + if errors: + for error in errors: + print("FAIL: " + error) + return 1 + print("OK: %s (%s)" % (path, data["api_hash"])) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/verify_namespace.py b/maix_lvgl/tools/omnipython_lvgl/binding/verify_namespace.py new file mode 100755 index 00000000..ecbf4a41 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/verify_namespace.py @@ -0,0 +1,202 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Verify every native module namespace against the canonical API model.""" +from __future__ import print_function + +import json +import re +import sys +from pathlib import Path + +# Also exported at module level (lv.OBJ_FLAG) while nested on obj.FLAG. +MODULE_LEVEL_DUPLEX_ENUMS = frozenset(["OBJ_FLAG"]) + +WIDGET_SCOPED_MODULE_ENUMS = frozenset( + [ + "IMAGE_FLAGS", + "IMAGE_SRC", + "IMAGE_ALIGN", + "IMAGE_COMPRESS", + "BAR_MODE", + "SLIDER_MODE", + "ARC_MODE", + "ROLLER_MODE", + "KEYBOARD_MODE", + "LABEL_LONG_MODE", + "CHART_UPDATE_MODE", + "CHART_AXIS", + "CHART_TYPE", + "IMAGEBUTTON_STATE", + "OBJ_POINT_TRANSFORM_FLAG", + "OBJ_TREE_WALK", + "OBJ_CLASS_EDITABLE", + "OBJ_CLASS_GROUP_DEF", + "OBJ_CLASS_THEME_INHERITABLE", + "BUTTONMATRIX_CTRL", + "TABLE_CELL_CTRL", + "MENU_HEADER", + "MENU_ROOT_BACK_BUTTON", + "SCALE_MODE", + ] +) + +WIDGET_ENUM_ATTRS = { + "obj": ["FLAG"], + "image": ["FLAGS"], + "label": ["LONG_MODE"], + "bar": ["MODE"], +} + + +def mp_module_names(text): + m = re.search( + r"(?:lvgl_globals_table|lvgl_module_globals_table)\[\] = \{(.*?)\n\};", + text, + re.S, + ) + if not m: + return set() + names = set() + for line in m.group(1).splitlines(): + match = re.search(r"MP_ROM_QSTR\(MP_QSTR_(\w+)\)", line) + if match: + names.add(match.group(1)) + return names + + +def py_module_names(text): + names = set( + re.findall( + r'PyModule_Add(?:Object|StringConstant|IntConstant)\(m,\s*"([^"]+)"', + text, + ) + ) + methods = re.search(r"static PyMethodDef lvgl_methods\[\] = \{(.*?)\n\};", text, re.S) + if methods: + names.update(re.findall(r'\{"([^"]+)"\s*,', methods.group(1))) + return names + + +def mp_obj_enum_attrs(text, obj): + m = re.search( + rf"static const mp_rom_map_elem_t {obj}_locals_dict_table\[\] = \{{(.*?)\}};", + text, + re.S, + ) + if not m: + return set() + attrs = set() + for line in m.group(1).splitlines(): + if "_type_base" not in line: + continue + q = re.search(r"MP_ROM_QSTR\(MP_QSTR_(\w+)\)", line) + if q: + attrs.add(q.group(1)) + return attrs + + +def py_obj_enum_attrs(text, obj): + block = re.search(r"PyInit_lvgl\(void\).*?return m;", text, re.S) + if not block: + return set() + attrs = set() + for m in re.finditer( + rf'py_lv_{obj}_type\)->tp_dict,\s*"([^"]+)"', + block.group(0), + ): + attrs.add(m.group(1)) + return attrs + + +def canonical_module_names(data, target): + names = {"C_Pointer", "LvReferenceError"} + names.update( + item["python_name"] + for item in data.get("functions", ()) + if item.get("visibility") == "public" + and item.get("role") == "module" + and target in item.get("available_on", ()) + ) + for section in ("objects", "structs", "variables", "constants"): + names.update( + item.get("python_name") or item.get("name") + for item in data.get(section, ()) + if item.get("visibility") == "public" + and target in item.get("available_on", ()) + and item.get("c_name") != "_nesting" + ) + names.update( + item["module_name"] + for item in data.get("enums", ()) + if item.get("visibility") == "public" + and target in item.get("available_on", ()) + and item.get("module_name") + ) + return names + + +def verify(target, text, expected_names): + errors = [] + names = mp_module_names(text) if target == "CircuitPython" else py_module_names(text) + if target == "MicroPython": + names = mp_module_names(text) + # _nesting is deliberately private in the canonical API model (it is + # not an LVGL declaration) yet is still emitted for MicroPython and + # CircuitPython; see api_model.build_api_model and emit_backend's + # module_registration_plan. Treat it like the other non-canonical but + # expected infrastructure exports rather than flagging it as unexpected. + integration_names = {"__name__", "__version__", "_nesting"} + missing = expected_names - names + unexpected = names - expected_names - integration_names + if missing: + errors.append("module missing exports: %s" % ", ".join(sorted(missing))) + if unexpected: + errors.append("module has unexpected exports: %s" % ", ".join(sorted(unexpected))) + + obj_enum_fn = mp_obj_enum_attrs if target != "CPython" else py_obj_enum_attrs + for obj, expected in WIDGET_ENUM_ATTRS.items(): + attrs = obj_enum_fn(text, obj) + for attr in expected: + if attr not in attrs: + errors.append("%s missing enum attr %s" % (obj, attr)) + + return errors + + +def main(argv): + generated = Path(argv[1]) if len(argv) > 1 else Path(__file__).resolve().parent.parent / "generated" + files = { + "MicroPython": generated / "lvgl_micropython.c", + "CircuitPython": generated / "lvgl_circuitpython.c", + "CPython": generated / "lvgl_python.c", + } + api = json.loads((generated / "api.json").read_text()) + + failed = False + for target, path in files.items(): + if not path.is_file(): + print("FAIL: missing %s" % path) + failed = True + continue + canonical_target = target.lower() + errors = verify( + target, + path.read_text(), + canonical_module_names(api, canonical_target), + ) + if errors: + failed = True + print("FAIL %s:" % target) + for err in errors: + print(" - %s" % err) + else: + print("OK: %s namespace parity" % target) + + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/maix_lvgl/tools/omnipython_lvgl/binding/verify_pyi.py b/maix_lvgl/tools/omnipython_lvgl/binding/verify_pyi.py new file mode 100644 index 00000000..658e1526 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/binding/verify_pyi.py @@ -0,0 +1,533 @@ +# SPDX-FileCopyrightText: 2026 Brad Barnett +# +# SPDX-License-Identifier: MIT + +"""Validate a generated pyi against the canonical API manifest.""" + +from __future__ import annotations + +import argparse +import ast +import json +import re +import sys +from pathlib import Path +from typing import Any, Mapping + +from .api_model import API_SCHEMA_VERSION, TARGETS +from .emit_pyi_canonical import _identifier +from .verify_api import validate_api_data + +_ALL_TARGETS = frozenset(TARGETS) +_HELPER_NAMES = frozenset({"C_Pointer", "LvReferenceError"}) +_PRIVATE_HELPER_NAMES = frozenset({"_Blob", "_BlobT", "_Struct", "_StructT", "_Nesting"}) + + +def _available(item: Mapping[str, Any], target: str) -> bool: + available = set(item.get("available_on", ())) + return _ALL_TARGETS <= available if target == "all" else target in available + + +def _public(item: Mapping[str, Any], target: str) -> bool: + return item.get("visibility") == "public" and _available(item, target) + + +def _top_level_nodes(tree: ast.Module) -> dict[str, ast.AST]: + nodes: dict[str, ast.AST] = {} + for node in tree.body: + names = [] + if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + names.append(node.name) + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + names.append(node.target.id) + elif isinstance(node, ast.Assign): + names.extend( + target.id for target in node.targets if isinstance(target, ast.Name) + ) + for name in names: + nodes[name] = node + return nodes + + +def _class_nodes(tree: ast.Module) -> dict[str, ast.ClassDef]: + return { + node.name: node + for node in tree.body + if isinstance(node, ast.ClassDef) + } + + +def _member_nodes(class_node: ast.ClassDef) -> dict[str, ast.AST]: + nodes: dict[str, ast.AST] = {} + for node in class_node.body: + if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)): + nodes[node.name] = node + elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): + nodes[node.target.id] = node + return nodes + + +def _annotation_text(node: ast.AST | None) -> str | None: + return ast.unparse(node) if node is not None else None + + +def _class_type_aliases(class_node: ast.ClassDef) -> dict[str, str]: + aliases = {} + for node in class_node.body: + if not ( + isinstance(node, ast.AnnAssign) + and isinstance(node.target, ast.Name) + and isinstance(node.annotation, ast.Name) + and node.annotation.id == "TypeAlias" + and isinstance(node.value, ast.Constant) + and isinstance(node.value.value, str) + ): + continue + aliases[node.value.value] = node.target.id + return aliases + + +def _apply_type_aliases( + python_type: str, type_aliases: Mapping[str, str] +) -> str: + for type_name, alias in type_aliases.items(): + python_type = re.sub(r"\b%s\b" % re.escape(type_name), alias, python_type) + return python_type + + +def _expected_parameters( + function: Mapping[str, Any], + *, + skip_receiver: bool, + constructor: bool, + type_aliases: Mapping[str, str] | None = None, +) -> list[tuple[str, str, bool]]: + parameters = list(function.get("parameters", ())) + if skip_receiver and not function.get("static"): + parameters = parameters[1:] + used = {"self"} if not constructor and not function.get("static") else set() + result = [] + for index, parameter in enumerate(parameters): + name = _identifier(parameter.get("name") or "arg") + original = name + suffix = 2 + while name in used: + name = "%s%d" % (original, suffix) + suffix += 1 + used.add(name) + if parameter.get("type", {}).get("kind") == "ellipsis": + result.append(("*" + name, "Any", False)) + continue + parameter_type = parameter.get("view", {}).get("python_type") + if not isinstance(parameter_type, str) or not parameter_type: + parameter_type = "Any" + parameter_type = _apply_type_aliases(parameter_type, type_aliases or {}) + default = ( + constructor + and index == 0 + and parameter.get("name") == "parent" + and parameter.get("view", {}).get("category") == "object_pointer" + ) + if default: + parameter_type += " | None" + result.append((name, parameter_type, default)) + if function.get("variadic"): + result.append(("*args", "Any", False)) + return result + + +def _expected_function_signature( + function: Mapping[str, Any], + *, + instance: bool, + skip_receiver: bool = False, + type_aliases: Mapping[str, str] | None = None, +) -> tuple[list[tuple[str, str, bool]], str, bool]: + constructor = function.get("role") == "constructor" + parameters = _expected_parameters( + function, + skip_receiver=skip_receiver, + constructor=constructor, + type_aliases=type_aliases, + ) + if instance or constructor: + parameters.insert(0, ("self", "", False)) + return_type = "None" if constructor else function.get("return_view", {}).get("python_type") + if not isinstance(return_type, str) or not return_type: + return_type = "Any" + return_type = _apply_type_aliases(return_type, type_aliases or {}) + return parameters, return_type, bool(function.get("static")) + + +def _actual_function_signature(node: ast.FunctionDef) -> tuple[list[tuple[str, str | None]], str | None, bool]: + parameters = [] + for argument in node.args.posonlyargs + node.args.args: + parameters.append((argument.arg, _annotation_text(argument.annotation))) + if node.args.vararg is not None: + parameters.append(("*" + node.args.vararg.arg, _annotation_text(node.args.vararg.annotation))) + for argument in node.args.kwonlyargs: + parameters.append((argument.arg, _annotation_text(argument.annotation))) + if node.args.kwarg is not None: + parameters.append(("**" + node.args.kwarg.arg, _annotation_text(node.args.kwarg.annotation))) + static = any( + isinstance(decorator, ast.Name) and decorator.id == "staticmethod" + for decorator in node.decorator_list + ) + return parameters, _annotation_text(node.returns), static + + +def _default_parameter_indexes(node: ast.FunctionDef) -> set[int]: + first_default = len(node.args.args) - len(node.args.defaults) + return set(range(first_default, len(node.args.args))) + + +def _expected_top_level(data: Mapping[str, Any], target: str) -> set[str]: + expected = set(_HELPER_NAMES | _PRIVATE_HELPER_NAMES) + for section in ("objects", "structs"): + expected.update( + _identifier(item["python_name"]) + for item in data.get(section, ()) + if _public(item, target) + ) + expected.update( + _identifier(item["module_name"]) + for item in data.get("enums", ()) + if _public(item, target) and item.get("module_name") + ) + expected.update( + _identifier(item["python_name"]) + for item in data.get("functions", ()) + if _public(item, target) and item.get("role") == "module" + ) + expected.update( + _identifier(item["python_name"]) + for item in data.get("variables", ()) + if _public(item, target) and item.get("c_name") != "_nesting" + ) + # _nesting is private in the canonical model but still deliberately + # stubbed (as `_Nesting`, see CanonicalPyiEmitter) for the targets that + # emit it; see api_model.build_api_model for the rationale. + if any(item.get("c_name") == "_nesting" for item in data.get("variables", ())): + expected.add("_nesting") + expected.update( + _identifier(item["python_name"]) + for item in data.get("constants", ()) + if _public(item, target) + ) + return expected + + +def _expected_enum_members(enum: Mapping[str, Any]) -> set[str]: + return {_identifier(member["name"]) for member in enum.get("members", ())} + + +def _expected_class_members( + data: Mapping[str, Any], class_name: str, target: str +) -> set[str]: + expected: set[str] = set() + struct = next( + ( + item + for item in data.get("structs", ()) + if item.get("python_name") == class_name and _public(item, target) + ), + None, + ) + if struct is not None: + field_names = { + _identifier(field.get("name") or "field") + for field in struct.get("fields", ()) + } + expected.update(field_names) + expected.update( + _identifier(function["python_name"]) + for function in data.get("functions", ()) + if function.get("role") == "struct_method" + and function.get("receiver") == class_name + and _public(function, target) + and _identifier(function["python_name"]) not in field_names + ) + + object_ = next( + ( + item + for item in data.get("objects", ()) + if item.get("python_name") == class_name and _public(item, target) + ), + None, + ) + if object_ is not None: + expected.update( + owner["name"] + for enum in data.get("enums", ()) + if _public(enum, target) + for owner in enum.get("owners", ()) + if owner.get("object") == class_name + ) + if any( + function.get("role") == "constructor" + and function.get("receiver") == class_name + and _public(function, target) + for function in data.get("functions", ()) + ): + expected.add("__init__") + expected.update( + _identifier(function["python_name"]) + for function in data.get("functions", ()) + if function.get("role") == "object_method" + and function.get("receiver") == class_name + and _public(function, target) + ) + return expected + + +def validate_pyi_data( + data: Mapping[str, Any], source: str, *, target: str = "all" +) -> list[str]: + """Return manifest discrepancies for one generated stub source.""" + + errors = [] + if data.get("schema_version") != API_SCHEMA_VERSION: + return ["unsupported API schema version"] + if target not in TARGETS + ("all",): + return ["unsupported stub target: %s" % target] + api_errors = validate_api_data(data) + if api_errors: + return ["invalid API model: %s" % error for error in api_errors] + try: + tree = ast.parse(source) + except SyntaxError as error: + return ["stub is not valid Python: %s" % error] + + actual_top = set(_top_level_nodes(tree)) + expected_top = _expected_top_level(data, target) + for name in sorted(expected_top - actual_top): + errors.append("missing top-level export: %s" % name) + for name in sorted(actual_top - expected_top): + errors.append("unexpected top-level export: %s" % name) + + classes = _class_nodes(tree) + for item in data.get("enums", ()): + if not (_public(item, target) and item.get("module_name")): + continue + name = _identifier(item["module_name"]) + class_node = classes.get(name) + if class_node is None: + continue + actual_members = set(_member_nodes(class_node)) + expected_members = _expected_enum_members(item) + for member in sorted(expected_members - actual_members): + errors.append("missing enum member: %s.%s" % (name, member)) + for member in sorted(actual_members - expected_members): + errors.append("unexpected enum member: %s.%s" % (name, member)) + + for item in data.get("objects", ()): + if not _public(item, target): + continue + name = _identifier(item["python_name"]) + class_node = classes.get(name) + if class_node is None: + continue + actual_members = set(_member_nodes(class_node)) + expected_members = _expected_class_members(data, item["python_name"], target) + for member in sorted(expected_members - actual_members): + errors.append("missing member: %s.%s" % (name, member)) + for member in sorted(actual_members - expected_members): + if not member.startswith("__"): + errors.append("unexpected member: %s.%s" % (name, member)) + + for item in data.get("structs", ()): + if not _public(item, target): + continue + name = _identifier(item["python_name"]) + class_node = classes.get(name) + if class_node is None: + continue + actual_members = set(_member_nodes(class_node)) + expected_members = _expected_class_members(data, item["python_name"], target) + for member in sorted(expected_members - actual_members): + errors.append("missing member: %s.%s" % (name, member)) + for member in sorted(actual_members - expected_members): + if not member.startswith("__"): + errors.append("unexpected member: %s.%s" % (name, member)) + + top_nodes = _top_level_nodes(tree) + + def check_function( + function: Mapping[str, Any], + node: ast.FunctionDef, + *, + label: str, + instance: bool, + skip_receiver: bool = False, + type_aliases: Mapping[str, str] | None = None, + ) -> None: + expected, return_type, expected_static = _expected_function_signature( + function, + instance=instance, + skip_receiver=skip_receiver, + type_aliases=type_aliases, + ) + actual, actual_return, actual_static = _actual_function_signature(node) + expected_shape = [(name, annotation or None) for name, annotation, _ in expected] + if actual != expected_shape or actual_return != return_type: + errors.append( + "signature mismatch: %s (expected %s -> %s, got %s -> %s)" + % (label, expected_shape, return_type, actual, actual_return) + ) + expected_defaults = { + index + for index, (_name, _annotation, has_default) in enumerate(expected) + if has_default and not _name.startswith("*") + } + if _default_parameter_indexes(node) != expected_defaults: + errors.append("default mismatch: %s" % label) + if actual_static != expected_static: + errors.append("staticmethod mismatch: %s" % label) + + for function in data.get("functions", ()): + if not _public(function, target): + continue + role = function.get("role") + if role == "module": + node = top_nodes.get(_identifier(function["python_name"])) + if isinstance(node, ast.FunctionDef): + check_function(function, node, label=function["python_name"], instance=False) + continue + receiver = function.get("receiver") + if not receiver: + continue + receiver_node = classes.get(_identifier(receiver)) + if receiver_node is None: + continue + members = _member_nodes(receiver_node) + if role == "constructor": + node_name = "__init__" + instance = True + skip_receiver = False + elif role in {"object_method", "struct_method"}: + node_name = _identifier(function["python_name"]) + instance = not function.get("static") + skip_receiver = instance + else: + continue + node = members.get(node_name) + if isinstance(node, ast.FunctionDef): + check_function( + function, + node, + label="%s.%s" % (receiver, node_name), + instance=instance, + skip_receiver=skip_receiver, + type_aliases=( + _class_type_aliases(receiver_node) + if role == "struct_method" + else None + ), + ) + + for item in data.get("enums", ()): + if not _public(item, target): + continue + enum_type = item.get("member_type", "int") + targets = [] + if item.get("module_name"): + targets.append((_identifier(item["module_name"]), classes.get(_identifier(item["module_name"])))) + for owner in item.get("owners", ()): + owner_node = classes.get(_identifier(owner["object"])) + nested = _member_nodes(owner_node).get(owner["name"]) if owner_node else None + targets.append(("%s.%s" % (owner["object"], owner["name"]), nested)) + for enum_label, enum_node in targets: + if not isinstance(enum_node, ast.ClassDef): + continue + for member in item.get("members", ()): + member_node = _member_nodes(enum_node).get(_identifier(member["name"])) + if isinstance(member_node, ast.AnnAssign): + actual_type = _annotation_text(member_node.annotation) + if actual_type != enum_type: + errors.append( + "enum member type mismatch: %s.%s (expected %s, got %s)" + % (enum_label, member["name"], enum_type, actual_type) + ) + + for item in data.get("structs", ()): + if not _public(item, target): + continue + class_node = classes.get(_identifier(item["python_name"])) + if class_node is None: + continue + members = _member_nodes(class_node) + type_aliases = _class_type_aliases(class_node) + for field in item.get("fields", ()): + field_node = members.get(_identifier(field.get("name") or "field")) + if isinstance(field_node, ast.AnnAssign): + expected_type = field.get("view", {}).get("python_type") + if isinstance(expected_type, str): + expected_type = _apply_type_aliases(expected_type, type_aliases) + actual_type = _annotation_text(field_node.annotation) + if actual_type != expected_type: + errors.append( + "field type mismatch: %s.%s (expected %s, got %s)" + % ( + item["python_name"], + field.get("name"), + expected_type, + actual_type, + ) + ) + + for variable in data.get("variables", ()): + if not _public(variable, target) or variable.get("c_name") == "_nesting": + continue + node = top_nodes.get(_identifier(variable["python_name"])) + if isinstance(node, ast.AnnAssign): + expected_type = variable.get("view", {}).get("python_type") + actual_type = _annotation_text(node.annotation) + if actual_type != expected_type: + errors.append( + "variable type mismatch: %s (expected %s, got %s)" + % (variable["python_name"], expected_type, actual_type) + ) + + for constant in data.get("constants", ()): + if not _public(constant, target): + continue + node = top_nodes.get(_identifier(constant["python_name"])) + if isinstance(node, ast.AnnAssign) and _annotation_text(node.annotation) != "int": + errors.append("constant type mismatch: %s" % constant["python_name"]) + + return errors + + +def validate_pyi_file(api_path: Path, pyi_path: Path, *, target: str = "all") -> list[str]: + with api_path.open(encoding="utf-8") as handle: + data = json.load(handle) + return validate_pyi_data( + data, + pyi_path.read_text(encoding="utf-8"), + target=target, + ) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("api", type=Path, help="canonical generated/api.json") + parser.add_argument("pyi", type=Path, help="generated/lvgl.pyi") + parser.add_argument( + "--target", + choices=list(TARGETS) + ["all"], + default="all", + help="stub target represented by the pyi", + ) + args = parser.parse_args(argv) + errors = validate_pyi_file(args.api, args.pyi, target=args.target) + if errors: + for error in errors: + print("FAIL: %s" % error, file=sys.stderr) + return 1 + print("OK: %s matches canonical API manifest" % args.pyi) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Intrinsic.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Intrinsic.h new file mode 100644 index 00000000..ab7ebb36 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Intrinsic.h @@ -0,0 +1,4 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" +#include "_X11_fake_defines.h" +#include "_X11_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Xlib.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Xlib.h new file mode 100644 index 00000000..ab7ebb36 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/Xlib.h @@ -0,0 +1,4 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" +#include "_X11_fake_defines.h" +#include "_X11_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_defines.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_defines.h new file mode 100644 index 00000000..c88774bb --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_defines.h @@ -0,0 +1,16 @@ +#ifndef _X11_FAKE_DEFINES_H +#define _X11_FAKE_DEFINES_H + +#define Atom CARD32 +#define Bool int +#define KeySym CARD32 +#define Pixmap CARD32 +#define Time CARD32 +#define _XFUNCPROTOBEGIN +#define _XFUNCPROTOEND +#define _Xconst const + +#define _X_RESTRICT_KYWD +#define Cardinal unsigned int +#define Boolean int +#endif diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_typedefs.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_typedefs.h new file mode 100644 index 00000000..39011421 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/X11/_X11_fake_typedefs.h @@ -0,0 +1,38 @@ +#ifndef _X11_FAKE_TYPEDEFS_H +#define _X11_FAKE_TYPEDEFS_H + +typedef char* XPointer; +typedef unsigned char KeyCode; +typedef unsigned int CARD32; +typedef unsigned long VisualID; +typedef unsigned long XIMResetState; +typedef unsigned long XID; +typedef XID Window; +typedef XID Colormap; +typedef XID Cursor; +typedef XID Drawable; +typedef void* XtPointer; +typedef XtPointer XtRequestId; +typedef struct Display Display; +typedef struct Screen Screen; +typedef struct Status Status; +typedef struct Visual Visual; +typedef struct Widget *Widget; +typedef struct XColor XColor; +typedef struct XClassHint XClassHint; +typedef struct XEvent XEvent; +typedef struct XFontStruct XFontStruct; +typedef struct XGCValues XGCValues; +typedef struct XKeyEvent XKeyEvent; +typedef struct XKeyPressedEvent XKeyPressedEvent; +typedef struct XPoint XPoint; +typedef struct XRectangle XRectangle; +typedef struct XSelectionRequestEvent XSelectionRequestEvent; +typedef struct XWindowChanges XWindowChanges; +typedef struct _XGC _XCG; +typedef struct _XGC *GC; +typedef struct _XIC *XIC; +typedef struct _XIM *XIM; +typedef struct _XImage XImage; + +#endif diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_ansi.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_ansi.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_ansi.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_defines.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_defines.h new file mode 100644 index 00000000..852744a6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_defines.h @@ -0,0 +1,262 @@ +#ifndef _FAKE_DEFINES_H +#define _FAKE_DEFINES_H + +#define NULL 0 +#define BUFSIZ 1024 +#define FOPEN_MAX 20 +#define FILENAME_MAX 1024 + +#ifndef SEEK_SET +#define SEEK_SET 0 /* set file offset to offset */ +#endif +#ifndef SEEK_CUR +#define SEEK_CUR 1 /* set file offset to current plus offset */ +#endif +#ifndef SEEK_END +#define SEEK_END 2 /* set file offset to EOF plus offset */ +#endif + +#define __LITTLE_ENDIAN 1234 +#define LITTLE_ENDIAN __LITTLE_ENDIAN +#define __BIG_ENDIAN 4321 +#define BIG_ENDIAN __BIG_ENDIAN +#define __BYTE_ORDER __LITTLE_ENDIAN +#define BYTE_ORDER __BYTE_ORDER + +#define EXIT_FAILURE 1 +#define EXIT_SUCCESS 0 + +#define SCHAR_MIN -128 +#define SCHAR_MAX 127 +#define CHAR_MIN -128 +#define CHAR_MAX 127 +#define UCHAR_MAX 255 +#define SHRT_MIN -32768 +#define SHRT_MAX 32767 +#define USHRT_MAX 65535 +#define INT_MIN -2147483648 +#define INT_MAX 2147483647 +#define UINT_MAX 4294967295U +#define LONG_MIN -9223372036854775808L +#define LONG_MAX 9223372036854775807L +#define ULONG_MAX 18446744073709551615UL +#define RAND_MAX 32767 + +/* C99 inttypes.h defines */ +#define PRId8 "d" +#define PRIi8 "i" +#define PRIo8 "o" +#define PRIu8 "u" +#define PRIx8 "x" +#define PRIX8 "X" +#define PRId16 "d" +#define PRIi16 "i" +#define PRIo16 "o" +#define PRIu16 "u" +#define PRIx16 "x" +#define PRIX16 "X" +#define PRId32 "d" +#define PRIi32 "i" +#define PRIo32 "o" +#define PRIu32 "u" +#define PRIx32 "x" +#define PRIX32 "X" +#define PRId64 "d" +#define PRIi64 "i" +#define PRIo64 "o" +#define PRIu64 "u" +#define PRIx64 "x" +#define PRIX64 "X" +#define PRIdLEAST8 "d" +#define PRIiLEAST8 "i" +#define PRIoLEAST8 "o" +#define PRIuLEAST8 "u" +#define PRIxLEAST8 "x" +#define PRIXLEAST8 "X" +#define PRIdLEAST16 "d" +#define PRIiLEAST16 "i" +#define PRIoLEAST16 "o" +#define PRIuLEAST16 "u" +#define PRIxLEAST16 "x" +#define PRIXLEAST16 "X" +#define PRIdLEAST32 "d" +#define PRIiLEAST32 "i" +#define PRIoLEAST32 "o" +#define PRIuLEAST32 "u" +#define PRIxLEAST32 "x" +#define PRIXLEAST32 "X" +#define PRIdLEAST64 "d" +#define PRIiLEAST64 "i" +#define PRIoLEAST64 "o" +#define PRIuLEAST64 "u" +#define PRIxLEAST64 "x" +#define PRIXLEAST64 "X" +#define PRIdFAST8 "d" +#define PRIiFAST8 "i" +#define PRIoFAST8 "o" +#define PRIuFAST8 "u" +#define PRIxFAST8 "x" +#define PRIXFAST8 "X" +#define PRIdFAST16 "d" +#define PRIiFAST16 "i" +#define PRIoFAST16 "o" +#define PRIuFAST16 "u" +#define PRIxFAST16 "x" +#define PRIXFAST16 "X" +#define PRIdFAST32 "d" +#define PRIiFAST32 "i" +#define PRIoFAST32 "o" +#define PRIuFAST32 "u" +#define PRIxFAST32 "x" +#define PRIXFAST32 "X" +#define PRIdFAST64 "d" +#define PRIiFAST64 "i" +#define PRIoFAST64 "o" +#define PRIuFAST64 "u" +#define PRIxFAST64 "x" +#define PRIXFAST64 "X" +#define PRIdPTR "d" +#define PRIiPTR "i" +#define PRIoPTR "o" +#define PRIuPTR "u" +#define PRIxPTR "x" +#define PRIXPTR "X" +#define PRIdMAX "d" +#define PRIiMAX "i" +#define PRIoMAX "o" +#define PRIuMAX "u" +#define PRIxMAX "x" +#define PRIXMAX "X" +#define SCNd8 "d" +#define SCNi8 "i" +#define SCNo8 "o" +#define SCNu8 "u" +#define SCNx8 "x" +#define SCNd16 "d" +#define SCNi16 "i" +#define SCNo16 "o" +#define SCNu16 "u" +#define SCNx16 "x" +#define SCNd32 "d" +#define SCNi32 "i" +#define SCNo32 "o" +#define SCNu32 "u" +#define SCNx32 "x" +#define SCNd64 "d" +#define SCNi64 "i" +#define SCNo64 "o" +#define SCNu64 "u" +#define SCNx64 "x" +#define SCNdLEAST8 "d" +#define SCNiLEAST8 "i" +#define SCNoLEAST8 "o" +#define SCNuLEAST8 "u" +#define SCNxLEAST8 "x" +#define SCNdLEAST16 "d" +#define SCNiLEAST16 "i" +#define SCNoLEAST16 "o" +#define SCNuLEAST16 "u" +#define SCNxLEAST16 "x" +#define SCNdLEAST32 "d" +#define SCNiLEAST32 "i" +#define SCNoLEAST32 "o" +#define SCNuLEAST32 "u" +#define SCNxLEAST32 "x" +#define SCNdLEAST64 "d" +#define SCNiLEAST64 "i" +#define SCNoLEAST64 "o" +#define SCNuLEAST64 "u" +#define SCNxLEAST64 "x" +#define SCNdFAST8 "d" +#define SCNiFAST8 "i" +#define SCNoFAST8 "o" +#define SCNuFAST8 "u" +#define SCNxFAST8 "x" +#define SCNdFAST16 "d" +#define SCNiFAST16 "i" +#define SCNoFAST16 "o" +#define SCNuFAST16 "u" +#define SCNxFAST16 "x" +#define SCNdFAST32 "d" +#define SCNiFAST32 "i" +#define SCNoFAST32 "o" +#define SCNuFAST32 "u" +#define SCNxFAST32 "x" +#define SCNdFAST64 "d" +#define SCNiFAST64 "i" +#define SCNoFAST64 "o" +#define SCNuFAST64 "u" +#define SCNxFAST64 "x" +#define SCNdPTR "d" +#define SCNiPTR "i" +#define SCNoPTR "o" +#define SCNuPTR "u" +#define SCNxPTR "x" +#define SCNdMAX "d" +#define SCNiMAX "i" +#define SCNoMAX "o" +#define SCNuMAX "u" +#define SCNxMAX "x" + +/* C99 stdbool.h defines */ +#define __bool_true_false_are_defined 1 +#define false 0 +#define true 1 + +/* va_arg macros and type*/ +#define va_start(_ap, _type) __builtin_va_start((_ap)) +#define va_arg(_ap, _type) __builtin_va_arg((_ap)) +#define va_end(_list) + +/* Vectors */ +#define __m128 int +#define __m128_u int +#define __m128d int +#define __m128d_u int +#define __m128i int +#define __m128i_u int +#define __m256 int +#define __m256_u int +#define __m256d int +#define __m256d_u int +#define __m256i int +#define __m256i_u int +#define __m512 int +#define __m512_u int +#define __m512d int +#define __m512d_u int +#define __m512i int +#define __m512i_u int + +/* C11 stdnoreturn.h defines */ +#define __noreturn_is_defined 1 +#define noreturn _Noreturn + +/* C11 threads.h defines */ +#define thread_local _Thread_local + +/* C11 assert.h defines */ +#define static_assert _Static_assert + +/* C11 stdatomic.h defines */ +#define ATOMIC_BOOL_LOCK_FREE 0 +#define ATOMIC_CHAR_LOCK_FREE 0 +#define ATOMIC_CHAR16_T_LOCK_FREE 0 +#define ATOMIC_CHAR32_T_LOCK_FREE 0 +#define ATOMIC_WCHAR_T_LOCK_FREE 0 +#define ATOMIC_SHORT_LOCK_FREE 0 +#define ATOMIC_INT_LOCK_FREE 0 +#define ATOMIC_LONG_LOCK_FREE 0 +#define ATOMIC_LLONG_LOCK_FREE 0 +#define ATOMIC_POINTER_LOCK_FREE 0 +#define ATOMIC_VAR_INIT(value) (value) +#define ATOMIC_FLAG_INIT { 0 } +#define kill_dependency(y) (y) + +/* C11 stdalign.h defines */ +#define alignas _Alignas +#define alignof _Alignof +#define __alignas_is_defined 1 +#define __alignof_is_defined 1 + +#endif diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_typedefs.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_typedefs.h new file mode 100644 index 00000000..b52d93ba --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_fake_typedefs.h @@ -0,0 +1,236 @@ +#ifndef _FAKE_TYPEDEFS_H +#define _FAKE_TYPEDEFS_H + +typedef int size_t; +typedef int __builtin_va_list; +typedef int __gnuc_va_list; +typedef int va_list; +typedef int __int8_t; +typedef int __uint8_t; +typedef int __int16_t; +typedef int __uint16_t; +typedef int __int_least16_t; +typedef int __uint_least16_t; +typedef int __int32_t; +typedef int __uint32_t; +typedef int __int64_t; +typedef int __uint64_t; +typedef int __int_least32_t; +typedef int __uint_least32_t; +typedef int __s8; +typedef int __u8; +typedef int __s16; +typedef int __u16; +typedef int __s32; +typedef int __u32; +typedef int __s64; +typedef int __u64; +typedef int _LOCK_T; +typedef int _LOCK_RECURSIVE_T; +typedef int _off_t; +typedef int __dev_t; +typedef int __uid_t; +typedef int __gid_t; +typedef int _off64_t; +typedef int _fpos_t; +typedef int _ssize_t; +typedef int wint_t; +typedef int _mbstate_t; +typedef int _flock_t; +typedef int _iconv_t; +typedef int __ULong; +typedef int __FILE; +typedef int ptrdiff_t; +typedef int wchar_t; +typedef int char16_t; +typedef int char32_t; +typedef int __off_t; +typedef int __pid_t; +typedef int __loff_t; +typedef int u_char; +typedef int u_short; +typedef int u_int; +typedef int u_long; +typedef int ushort; +typedef int uint; +typedef int clock_t; +typedef int time_t; +typedef int daddr_t; +typedef int caddr_t; +typedef int ino_t; +typedef int off_t; +typedef int dev_t; +typedef int uid_t; +typedef int gid_t; +typedef int pid_t; +typedef int key_t; +typedef int ssize_t; +typedef int mode_t; +typedef int nlink_t; +typedef int fd_mask; +typedef int _types_fd_set; +typedef int clockid_t; +typedef int timer_t; +typedef int useconds_t; +typedef int suseconds_t; +typedef int FILE; +typedef int fpos_t; +typedef int cookie_read_function_t; +typedef int cookie_write_function_t; +typedef int cookie_seek_function_t; +typedef int cookie_close_function_t; +typedef int cookie_io_functions_t; +typedef int div_t; +typedef int ldiv_t; +typedef int lldiv_t; +typedef int sigset_t; +typedef int __sigset_t; +typedef int _sig_func_ptr; +typedef int sig_atomic_t; +typedef int __tzrule_type; +typedef int __tzinfo_type; +typedef int mbstate_t; +typedef int sem_t; +typedef int pthread_t; +typedef int pthread_attr_t; +typedef int pthread_mutex_t; +typedef int pthread_mutexattr_t; +typedef int pthread_cond_t; +typedef int pthread_condattr_t; +typedef int pthread_key_t; +typedef int pthread_once_t; +typedef int pthread_rwlock_t; +typedef int pthread_rwlockattr_t; +typedef int pthread_spinlock_t; +typedef int pthread_barrier_t; +typedef int pthread_barrierattr_t; +typedef int jmp_buf; +typedef int rlim_t; +typedef int sa_family_t; +typedef int sigjmp_buf; +typedef int stack_t; +typedef int siginfo_t; +typedef int z_stream; + +/* C99 exact-width integer types */ +typedef int int8_t; +typedef int uint8_t; +typedef int int16_t; +typedef int uint16_t; +typedef int int32_t; +typedef int uint32_t; +typedef int int64_t; +typedef int uint64_t; + +/* C99 minimum-width integer types */ +typedef int int_least8_t; +typedef int uint_least8_t; +typedef int int_least16_t; +typedef int uint_least16_t; +typedef int int_least32_t; +typedef int uint_least32_t; +typedef int int_least64_t; +typedef int uint_least64_t; + +/* C99 fastest minimum-width integer types */ +typedef int int_fast8_t; +typedef int uint_fast8_t; +typedef int int_fast16_t; +typedef int uint_fast16_t; +typedef int int_fast32_t; +typedef int uint_fast32_t; +typedef int int_fast64_t; +typedef int uint_fast64_t; + +/* C99 integer types capable of holding object pointers */ +typedef int intptr_t; +typedef int uintptr_t; + +/* C99 greatest-width integer types */ +typedef int intmax_t; +typedef int uintmax_t; + +/* C99 stdbool.h bool type. _Bool is built-in in C99 */ +typedef _Bool bool; + +/* GNU Extension for 64-bit targets */ +#ifdef __SIZEOF_INT128__ +typedef int __int128_t; +typedef int __uint128_t; +#endif /* __SIZEOF_INT128__ */ + +/* Mir typedefs */ +typedef void* MirEGLNativeWindowType; +typedef void* MirEGLNativeDisplayType; +typedef struct MirConnection MirConnection; +typedef struct MirSurface MirSurface; +typedef struct MirSurfaceSpec MirSurfaceSpec; +typedef struct MirScreencast MirScreencast; +typedef struct MirPromptSession MirPromptSession; +typedef struct MirBufferStream MirBufferStream; +typedef struct MirPersistentId MirPersistentId; +typedef struct MirBlob MirBlob; +typedef struct MirDisplayConfig MirDisplayConfig; + +/* xcb typedefs */ +typedef struct xcb_connection_t xcb_connection_t; +typedef uint32_t xcb_window_t; +typedef uint32_t xcb_visualid_t; + +/* dirent typedef */ +typedef void* DIR; + +/* socket typedefs */ +typedef __uint32_t __socklen_t; +typedef __socklen_t socklen_t; +typedef unsigned short __kernel_sa_family_t; + +/* C11 stdatomic.h types */ +typedef _Atomic(_Bool) atomic_bool; +typedef _Atomic(char) atomic_char; +typedef _Atomic(signed char) atomic_schar; +typedef _Atomic(unsigned char) atomic_uchar; +typedef _Atomic(short) atomic_short; +typedef _Atomic(unsigned short) atomic_ushort; +typedef _Atomic(int) atomic_int; +typedef _Atomic(unsigned int) atomic_uint; +typedef _Atomic(long) atomic_long; +typedef _Atomic(unsigned long) atomic_ulong; +typedef _Atomic(long long) atomic_llong; +typedef _Atomic(unsigned long long) atomic_ullong; +typedef _Atomic(uint_least16_t) atomic_char16_t; +typedef _Atomic(uint_least32_t) atomic_char32_t; +typedef _Atomic(wchar_t) atomic_wchar_t; +typedef _Atomic(int_least8_t) atomic_int_least8_t; +typedef _Atomic(uint_least8_t) atomic_uint_least8_t; +typedef _Atomic(int_least16_t) atomic_int_least16_t; +typedef _Atomic(uint_least16_t) atomic_uint_least16_t; +typedef _Atomic(int_least32_t) atomic_int_least32_t; +typedef _Atomic(uint_least32_t) atomic_uint_least32_t; +typedef _Atomic(int_least64_t) atomic_int_least64_t; +typedef _Atomic(uint_least64_t) atomic_uint_least64_t; +typedef _Atomic(int_fast8_t) atomic_int_fast8_t; +typedef _Atomic(uint_fast8_t) atomic_uint_fast8_t; +typedef _Atomic(int_fast16_t) atomic_int_fast16_t; +typedef _Atomic(uint_fast16_t) atomic_uint_fast16_t; +typedef _Atomic(int_fast32_t) atomic_int_fast32_t; +typedef _Atomic(uint_fast32_t) atomic_uint_fast32_t; +typedef _Atomic(int_fast64_t) atomic_int_fast64_t; +typedef _Atomic(uint_fast64_t) atomic_uint_fast64_t; +typedef _Atomic(intptr_t) atomic_intptr_t; +typedef _Atomic(uintptr_t) atomic_uintptr_t; +typedef _Atomic(size_t) atomic_size_t; +typedef _Atomic(ptrdiff_t) atomic_ptrdiff_t; +typedef _Atomic(intmax_t) atomic_intmax_t; +typedef _Atomic(uintmax_t) atomic_uintmax_t; +typedef struct atomic_flag { atomic_bool _Value; } atomic_flag; +typedef enum memory_order { + memory_order_relaxed, + memory_order_consume, + memory_order_acquire, + memory_order_release, + memory_order_acq_rel, + memory_order_seq_cst +} memory_order; + +#endif diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_syslist.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_syslist.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/_syslist.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/aio.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/aio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/aio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/alloca.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/alloca.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/alloca.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ar.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ar.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ar.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/argz.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/argz.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/argz.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/arpa/inet.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/arpa/inet.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/arpa/inet.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/asm-generic/int-ll64.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/asm-generic/int-ll64.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/asm-generic/int-ll64.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/assert.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/assert.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/assert.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/complex.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/complex.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/complex.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/cpio.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/cpio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/cpio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ctype.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ctype.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ctype.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dirent.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dirent.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dirent.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dlfcn.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dlfcn.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/dlfcn.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/emmintrin.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/emmintrin.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/emmintrin.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/endian.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/endian.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/endian.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/envz.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/envz.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/envz.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/errno.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/errno.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/errno.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fastmath.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fastmath.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fastmath.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fcntl.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fcntl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fcntl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/features.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/features.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/features.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fenv.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fenv.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fenv.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/float.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/float.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/float.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fmtmsg.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fmtmsg.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fmtmsg.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fnmatch.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fnmatch.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/fnmatch.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ftw.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ftw.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ftw.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/getopt.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/getopt.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/getopt.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/glob.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/glob.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/glob.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/grp.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/grp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/grp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iconv.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iconv.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iconv.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ieeefp.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ieeefp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ieeefp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/immintrin.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/immintrin.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/immintrin.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/inttypes.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/inttypes.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/inttypes.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iso646.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iso646.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/iso646.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/langinfo.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/langinfo.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/langinfo.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libgen.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libgen.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libgen.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libintl.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libintl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/libintl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/limits.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/limits.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/limits.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/socket.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/socket.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/socket.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/version.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/version.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/linux/version.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/locale.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/locale.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/locale.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/malloc.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/malloc.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/malloc.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/math.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/math.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/math.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mir_toolkit/client_types.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mir_toolkit/client_types.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mir_toolkit/client_types.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/monetary.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/monetary.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/monetary.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mqueue.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mqueue.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/mqueue.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ndbm.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ndbm.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ndbm.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/net/if.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/net/if.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/net/if.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netdb.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netdb.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netdb.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/in.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/in.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/in.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/tcp.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/tcp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/netinet/tcp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/newlib.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/newlib.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/newlib.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/nl_types.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/nl_types.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/nl_types.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/err.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/err.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/err.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/evp.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/evp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/evp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/hmac.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/hmac.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/hmac.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/ssl.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/ssl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/ssl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/x509v3.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/x509v3.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/openssl/x509v3.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/paths.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/paths.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/paths.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/poll.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/poll.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/poll.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/process.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/process.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/process.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pthread.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pthread.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pthread.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pwd.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pwd.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/pwd.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/reent.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/reent.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/reent.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regdef.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regdef.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regdef.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regex.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regex.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/regex.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sched.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sched.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sched.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/search.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/search.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/search.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/semaphore.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/semaphore.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/semaphore.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/setjmp.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/setjmp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/setjmp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/signal.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/signal.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/signal.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/smmintrin.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/smmintrin.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/smmintrin.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/spawn.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/spawn.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/spawn.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdalign.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdalign.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdalign.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdarg.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdarg.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdarg.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdatomic.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdatomic.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdatomic.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdbool.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdbool.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdbool.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stddef.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stddef.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stddef.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdint.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdint.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdint.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdio.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdlib.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdlib.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdlib.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdnoreturn.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdnoreturn.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stdnoreturn.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/string.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/string.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/string.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/strings.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/strings.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/strings.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stropts.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stropts.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/stropts.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ioctl.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ioctl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ioctl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ipc.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ipc.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/ipc.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/mman.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/mman.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/mman.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/msg.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/msg.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/msg.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/poll.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/poll.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/poll.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/resource.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/resource.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/resource.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/select.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/select.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/select.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sem.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sem.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sem.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/shm.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/shm.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/shm.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/socket.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/socket.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/socket.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/stat.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/stat.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/stat.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/statvfs.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/statvfs.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/statvfs.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sysctl.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sysctl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/sysctl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/time.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/time.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/time.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/times.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/times.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/times.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/types.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/types.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/types.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/uio.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/uio.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/uio.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/un.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/un.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/un.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/utsname.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/utsname.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/utsname.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/wait.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/wait.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/sys/wait.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/syslog.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/syslog.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/syslog.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tar.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tar.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tar.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/termios.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/termios.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/termios.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tgmath.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tgmath.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/tgmath.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/threads.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/threads.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/threads.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/time.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/time.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/time.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/trace.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/trace.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/trace.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ulimit.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ulimit.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/ulimit.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unctrl.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unctrl.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unctrl.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unistd.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unistd.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/unistd.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utime.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utime.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utime.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmp.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmpx.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmpx.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/utmpx.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wchar.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wchar.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wchar.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wctype.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wctype.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wctype.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wordexp.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wordexp.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/wordexp.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/xcb/xcb.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/xcb/xcb.h new file mode 100644 index 00000000..f952c1d6 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/xcb/xcb.h @@ -0,0 +1,2 @@ +#include "_fake_defines.h" +#include "_fake_typedefs.h" diff --git a/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/zlib.h b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/zlib.h new file mode 100644 index 00000000..af326008 --- /dev/null +++ b/maix_lvgl/tools/omnipython_lvgl/fake_libc_include/zlib.h @@ -0,0 +1,33 @@ +#ifndef ZLIB_H +#define ZLIB_H + +#include "_fake_defines.h" +#include "_fake_typedefs.h" + +typedef int uInt; +typedef int uLong; +#if !defined(__MACTYPES__) +typedef int Byte; +#endif + +typedef int Bytef; +typedef int charf; +typedef int intf; +typedef int uIntf; +typedef int uLongf; + +typedef int voidpc; +typedef int voidpf; +typedef int voidp; + +#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC) +typedef int Z_U4; +#endif + +typedef int z_crc_t; +typedef int z_size_t; + +typedef int alloc_func; +typedef int free_func; + +#endif diff --git a/maix_lvgl/tools/regenerate_binding.py b/maix_lvgl/tools/regenerate_binding.py new file mode 100644 index 00000000..0d677b93 --- /dev/null +++ b/maix_lvgl/tools/regenerate_binding.py @@ -0,0 +1,227 @@ +"""Regenerate the CPython binding from MaixCDK's LVGL source. + +Called automatically by setup.py. The binding is only regenerated when the +LVGL source, MaixCDK's lv_conf.h or the bundled generator changes (tracked in +``binding/.binding_stamp.json``). +""" +from __future__ import annotations + +import json +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import maixcdk_lvgl as mk + +PROJECT_ROOT = Path(__file__).resolve().parent.parent +TOOLS_DIR = PROJECT_ROOT / "tools" / "omnipython_lvgl" +BINDING_DIR = PROJECT_ROOT / "binding" +WORK_DIR = PROJECT_ROOT / ".build" / "bindgen" +STAMP_FILE = BINDING_DIR / ".binding_stamp.json" + +_PRUNE_KEYS = { + "function": ["private_functions", "unsupported_functions"], + "enum": ["private_enums"], + "struct": ["private_structs"], + "variable": ["private_variables"], +} + + +def adjust_lv_conf(text: str) -> str: + """Adapt MaixCDK's lv_conf.h for a single-threaded CPython binding.""" + text = text.replace('#include "global_config.h"\n', "") + text = re.sub(r"extern bool lv_ui_mutex_lock\(int timeout\);\n?", "", text) + text = re.sub(r"extern void lv_ui_mutex_unlock\(\);\n?", "", text) + # Keep LV_USE_OS / LV_USE_RLOTTIE as MaixCDK configures them: the binding + # links against the LVGL library that MaixCDK's lvgl component builds, so + # both sides must agree on struct layouts (pthread mutex fields, rlottie). + return text + + + +def _hide_pthread_structs(policy_path: Path) -> None: + """Hide structs whose pthread fields cannot be represented in Python.""" + data = json.loads(policy_path.read_text(encoding="utf-8")) + existing = {item.get("name") for item in data.get("private_structs", [])} + changed = False + for name in ("lv_thread_sync_t", "lv_draw_global_info_t"): + if name not in existing: + data.setdefault("private_structs", []).append( + { + "name": name, + "reason": ( + "Contains pthread_mutex_t/cond fields, which have no " + "Python representation; the binding links against the " + "LVGL library built by MaixCDK (LV_USE_OS=PTHREAD)." + ), + "test": "tools/regenerate_binding.py::_hide_pthread_structs", + } + ) + changed = True + if changed: + policy_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + + + +def _patch_generated_c(path: Path) -> None: + """Drop getattro/setattro branches for pthread-typed struct fields.""" + text = path.read_text(encoding="utf-8") + functions = ( + "py_lv_thread_sync_t_getattro", + "py_lv_thread_sync_t_setattro", + "py_lv_draw_global_info_t_getattro", + "py_lv_draw_global_info_t_setattro", + "py_lv_cache_t_getattro", + "py_lv_cache_t_setattro", + ) + for func in functions: + start = text.find(func + "(") + if start < 0: + continue + end = text.find("\n}\n", start) + if end < 0: + continue + block = text[start:end] + block = re.sub( + r'^\s*if \(strcmp\(attr, "(?:mutex|cond|circle_cache_mutex|lock)"\) == 0\).*$\n', + "", + block, + flags=re.M, + ) + text = text[:start] + block + text[end:] + # Field name lists: remove the pthread-typed names. + text = re.sub( + r'(py_lv_thread_sync_t_field_names\[\] = \{)[^}]*?(\};)', + r'\1NULL\2', + text, + flags=re.S, + ) + text = re.sub( + r'(py_lv_draw_global_info_t_field_names\[\] = \{[^}]*?)"circle_cache_mutex",\s*', + r'\1', + text, + ) + text = re.sub( + r'(py_lv_cache_t_field_names\[\] = \{[^}]*?)"lock",\s*', + r'\1', + text, + ) + path.write_text(text, encoding="utf-8") + + +def _prune_policy(policy_path: Path, missing: str) -> int: + keymap = _PRUNE_KEYS + data = json.loads(policy_path.read_text(encoding="utf-8")) + entries = re.findall(r"(enum|function|struct|variable) ([A-Za-z0-9_]+)", missing) + removed = 0 + for kind, name in entries: + for key in keymap[kind]: + items = data.get(key, []) + before = len(items) + data[key] = [item for item in items if item.get("name") != name] + removed += before - len(data[key]) + policy_path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8") + return removed + + +def _run_generator(work: Path) -> None: + env = os.environ.copy() + env["PYTHONPATH"] = str(work) + for attempt in range(40): + proc = subprocess.run( + [sys.executable, "-m", "binding.generate", "--target", "cpython"], + cwd=work, + env=env, + capture_output=True, + text=True, + ) + out = proc.stdout + proc.stderr + if proc.returncode == 0: + return + # Match the exception line, not the traceback's source line that also + # contains "API policy names missing declarations: %s". + matches = re.findall( + r"ValueError: API policy names missing declarations: (.*)", out + ) + if not matches: + raise RuntimeError( + "omnipython-lvgl binding generation failed:\n" + out[-6000:] + ) + removed = _prune_policy(work / "binding" / "api_policy.json", matches[-1]) + print( + f" binding policy: pruned {removed} entries (round {attempt + 1})", + flush=True, + ) + raise RuntimeError("binding generation did not converge after 40 prune rounds") + + +def _generate(lvgl_dir: Path, conf: Path, inputs: dict, log=print) -> None: + try: + import pycparser # noqa: F401 + except ImportError as exc: + raise RuntimeError( + "pycparser is required to regenerate the LVGL binding. " + "Install it with: python3 -m pip install 'pycparser>=3.0'" + ) from exc + + if WORK_DIR.exists(): + shutil.rmtree(WORK_DIR) + WORK_DIR.mkdir(parents=True) + + shutil.copytree(TOOLS_DIR / "binding", WORK_DIR / "binding") + shutil.copytree(TOOLS_DIR / "fake_libc_include", WORK_DIR / "fake_libc_include") + # Copy rather than symlink: lv_conf_internal.h includes "../../lv_conf.h" + # relative to lvgl/src, so the LVGL tree must physically sit next to the + # adjusted lv_conf.h inside the work directory. + shutil.copytree(lvgl_dir, WORK_DIR / "lvgl") + + adjusted = adjust_lv_conf(conf.read_text(encoding="utf-8")) + (WORK_DIR / "lv_conf.h").write_text(adjusted, encoding="utf-8") + _hide_pthread_structs(WORK_DIR / "binding" / "api_policy.json") + + log("generating CPython binding from MaixCDK's LVGL sources ...") + _run_generator(WORK_DIR) + _patch_generated_c(WORK_DIR / "generated" / "lvgl_python.c") + + BINDING_DIR.mkdir(parents=True, exist_ok=True) + shutil.copy2(WORK_DIR / "generated" / "lvgl_python.c", BINDING_DIR / "lvgl_python.c") + shutil.copy2(WORK_DIR / "generated" / "lvgl.pyi", BINDING_DIR / "lvgl.pyi") + shutil.copy2(WORK_DIR / "lv_conf.h", BINDING_DIR / "lv_conf.h") + STAMP_FILE.write_text(json.dumps(inputs, indent=2) + "\n", encoding="utf-8") + log("binding updated: binding/lvgl_python.c") + + +def ensure_binding(force: bool = False, log=print, sdk_path=None): + """Return (lvgl_source_dir, lv_conf_for_build), regenerating if stale.""" + sdk = Path(sdk_path).resolve() if sdk_path else mk.find_maixcdk() + version = mk.lvgl_version(sdk) + lvgl_dir = mk.ensure_lvgl_source(sdk, version, log) + conf = mk.lv_conf_path(sdk) + inputs = mk.stamp(sdk, version, lvgl_dir, conf) + + current = None + if STAMP_FILE.is_file() and (BINDING_DIR / "lvgl_python.c").is_file(): + try: + current = json.loads(STAMP_FILE.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + current = None + + if not force and current == inputs: + log(f"binding is up to date (LVGL {version})") + return lvgl_dir, BINDING_DIR / "lv_conf.h" + + _generate(lvgl_dir, conf, inputs, log) + return lvgl_dir, BINDING_DIR / "lv_conf.h" + + +if __name__ == "__main__": + force = "--force" in sys.argv + sdk_path = None + if "--sdk-path" in sys.argv: + index = sys.argv.index("--sdk-path") + if index + 1 < len(sys.argv): + sdk_path = sys.argv[index + 1] + ensure_binding(force=force, sdk_path=sdk_path) diff --git a/setup.py b/setup.py index 26ae3ece..aec66e35 100644 --- a/setup.py +++ b/setup.py @@ -3,6 +3,7 @@ import os import platform import shutil +import subprocess #################################################################### # supported platforms @@ -97,9 +98,35 @@ def print_py_version_err(build_py_version): if ret != 0: print("-- Build cpp modules failed!") sys.exit(1) + + # Build the maix_lvgl sub-project (LVGL CPython bindings) + if board == "maixcam2": + print("-- Building maix_lvgl ...") + lvgl_cmd = [ + sys.executable, "project.py", "build", "-p", board, release_str, + "--config-file", os.path.join("configs", "config_platform_%s.mk" % board), + ] + ret = subprocess.call(lvgl_cmd, cwd="maix_lvgl") + if ret != 0: + print("-- Build maix_lvgl failed!") + sys.exit(1) else: sys.argv.remove("--skip-build") +# Stage maix_lvgl built files into its Python package (for the wheel) +if board == "maixcam2": + lvgl_pkg = os.path.join("maix_lvgl", "maix_lvgl") + lvgl_so = os.path.join("maix_lvgl", "build", "lvgl_binding", "liblvgl_binding.so") + if os.path.exists(lvgl_so): + shutil.copy2(lvgl_so, os.path.join(lvgl_pkg, "lvgl.cpython-313-aarch64-linux-gnu.so")) + dl_src = os.path.join("maix_lvgl", "build", "dl_lib", "libdatachannel.so") + if os.path.exists(dl_src): + dl_dst = os.path.join(lvgl_pkg, "dl_lib") + os.makedirs(dl_dst, exist_ok=True) + shutil.copy2(dl_src, os.path.join(dl_dst, "libdatachannel.so")) + else: + print("-- WARNING: maix_lvgl extension not found, package will not include it") + # check python version build_py_version = get_build_python_version() print("-- Build Python version: {}.{}.{}".format(build_py_version[0], build_py_version[1], build_py_version[2])) @@ -147,6 +174,17 @@ def print_py_version_err(build_py_version): if ret != 0: raise Exception("Generate doc file failed") +if board == "maixcam2": + print("-- Merging maix_lvgl API documentation into docs/api ...") + doc_cmd = [ + sys.executable, os.path.join("maix_lvgl", "tools", "gen_api_docs.py"), + "--pyi", os.path.join("maix_lvgl", "binding", "lvgl.pyi"), + "--out", "docs/api", "--merge", + ] + ret = subprocess.call(doc_cmd) + if ret != 0: + raise Exception("Generate maix_lvgl API doc failed") + # requirement packages requirements = [] @@ -166,6 +204,9 @@ def has_ext_modules(foo): return True pkgs = find_packages() +pkgs = [p for p in pkgs if not p.startswith("maix_lvgl")] +if os.path.isdir(os.path.join("maix_lvgl", "maix_lvgl")): + pkgs.append("maix_lvgl") print("-- found packages: {}".format(pkgs)) print("\n=================================") @@ -222,6 +263,7 @@ def has_ext_modules(foo): # You can just specify the packages manually here if your project is # simple. Or you can use find_packages(). packages=pkgs, + package_dir={"maix_lvgl": "maix_lvgl/maix_lvgl"}, # Alternatively, if you want to distribute just a my_module.py, uncomment # this: @@ -246,7 +288,8 @@ def has_ext_modules(foo): # installed, specify them here. If using Python 2.6 or less, then these # have to be included in MANIFEST.in as well. package_data={ - 'maix': ['*.so', "dl_lib/*.so*", "*.pyi", "**/*.pyi", "**/**/*.pyi"] + 'maix': ['*.so', "dl_lib/*.so*", "*.pyi", "**/*.pyi", "**/**/*.pyi"], + 'maix_lvgl': ['*.so', "dl_lib/*.so*"], }, # Although 'package_data' is the preferred approach, in some case you may