Add Chromium-only Blender WebEngine parity work

This commit is contained in:
mes123456
2026-08-12 04:47:48 -04:00
commit 9fd26010f6
18225 changed files with 11622124 additions and 0 deletions

View File

@@ -0,0 +1,52 @@
# SPDX-FileCopyrightText: 2023 Blender Authors
#
# SPDX-License-Identifier: GPL-2.0-or-later
set(INC
.
../../makesrna
)
set(INC_SYS
)
set(SRC
bl_math_py_api.cc
blf_py_api.cc
bpy_threads.cc
idprop_py_api.cc
idprop_py_ui_api.cc
imbuf_py_api.cc
py_capi_rna.cc
py_capi_utils.cc
python_compat.cc
bl_math_py_api.hh
blf_py_api.hh
idprop_py_api.hh
idprop_py_ui_api.hh
imbuf_py_api.hh
py_capi_rna.hh
py_capi_utils.hh
python_compat.hh
# header-only
python_utildefines.hh
)
set(LIB
PRIVATE bf::blenkernel
PRIVATE bf::blenlib
PRIVATE bf::dna
PRIVATE bf::gpu
PRIVATE bf::intern::clog
PRIVATE bf::intern::guardedalloc
PRIVATE bf::dependencies::optional::python
PRIVATE bf::dependencies::epoxy
)
if(WITH_PYTHON_MODULE)
add_definitions(-DWITH_PYTHON_MODULE)
endif()
blender_add_lib(bf_python_ext "${SRC}" "${INC}" "${INC_SYS}" "${LIB}")

View File

@@ -0,0 +1,156 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/**
* \file
* \ingroup pygen
*
* This file defines the 'bl_math' module, a module for math utilities.
*/
#include <Python.h>
#include "BLI_utildefines.h"
#include "bl_math_py_api.hh"
namespace blender {
/* -------------------------------------------------------------------- */
/** \name Python Functions
* \{ */
PyDoc_STRVAR(
/* Wrap. */
py_bl_math_clamp_doc,
".. function:: clamp(value, min=0, max=1)\n"
"\n"
" Clamps the float value between minimum and maximum. To avoid\n"
" confusion, any call must use either one or all three arguments.\n"
"\n"
" :param value: The value to clamp.\n"
" :type value: float\n"
" :param min: The minimum value, defaults to 0.\n"
" :type min: float\n"
" :param max: The maximum value, defaults to 1.\n"
" :type max: float\n"
" :return: The clamped value.\n"
" :rtype: float\n");
static PyObject *py_bl_math_clamp(PyObject * /*self*/, PyObject *args)
{
double x, minv = 0.0, maxv = 1.0;
if (PyTuple_Size(args) <= 1) {
if (!PyArg_ParseTuple(args, "d:clamp", &x)) {
return nullptr;
}
}
else {
if (!PyArg_ParseTuple(args, "ddd:clamp", &x, &minv, &maxv)) {
return nullptr;
}
}
CLAMP(x, minv, maxv);
return PyFloat_FromDouble(x);
}
PyDoc_STRVAR(
/* Wrap. */
py_bl_math_lerp_doc,
".. function:: lerp(from_value, to_value, factor)\n"
"\n"
" Linearly interpolate between two float values based on factor.\n"
"\n"
" :param from_value: The value to return when factor is 0.\n"
" :type from_value: float\n"
" :param to_value: The value to return when factor is 1.\n"
" :type to_value: float\n"
" :param factor: The interpolation value, normally in [0.0, 1.0].\n"
" :type factor: float\n"
" :return: The interpolated value.\n"
" :rtype: float\n");
static PyObject *py_bl_math_lerp(PyObject * /*self*/, PyObject *args)
{
double a, b, x;
if (!PyArg_ParseTuple(args, "ddd:lerp", &a, &b, &x)) {
return nullptr;
}
return PyFloat_FromDouble(a * (1.0 - x) + b * x);
}
PyDoc_STRVAR(
/* Wrap. */
py_bl_math_smoothstep_doc,
".. function:: smoothstep(from_value, to_value, value)\n"
"\n"
" Performs smooth interpolation between 0 and 1 as value changes between from and "
"to values.\n"
" Outside the range the function returns the same value as the nearest edge.\n"
"\n"
" :param from_value: The edge value where the result is 0.\n"
" :type from_value: float\n"
" :param to_value: The edge value where the result is 1.\n"
" :type to_value: float\n"
" :param value: The interpolation value.\n"
" :type value: float\n"
" :return: The interpolated value in [0.0, 1.0].\n"
" :rtype: float\n");
static PyObject *py_bl_math_smoothstep(PyObject * /*self*/, PyObject *args)
{
double a, b, x;
if (!PyArg_ParseTuple(args, "ddd:smoothstep", &a, &b, &x)) {
return nullptr;
}
double t = (x - a) / (b - a);
CLAMP(t, 0.0, 1.0);
return PyFloat_FromDouble(t * t * (3.0 - 2.0 * t));
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Module Definition
* \{ */
static PyMethodDef M_bl_math_methods[] = {
{"clamp", static_cast<PyCFunction>(py_bl_math_clamp), METH_VARARGS, py_bl_math_clamp_doc},
{"lerp", static_cast<PyCFunction>(py_bl_math_lerp), METH_VARARGS, py_bl_math_lerp_doc},
{"smoothstep",
static_cast<PyCFunction>(py_bl_math_smoothstep),
METH_VARARGS,
py_bl_math_smoothstep_doc},
{nullptr, nullptr, 0, nullptr},
};
PyDoc_STRVAR(
/* Wrap. */
M_bl_math_doc,
"Miscellaneous math utilities module.");
static PyModuleDef M_bl_math_module_def = {
/*m_base*/ PyModuleDef_HEAD_INIT,
/*m_name*/ "bl_math",
/*m_doc*/ M_bl_math_doc,
/*m_size*/ 0,
/*m_methods*/ M_bl_math_methods,
/*m_slots*/ nullptr,
/*m_traverse*/ nullptr,
/*m_clear*/ nullptr,
/*m_free*/ nullptr,
};
PyMODINIT_FUNC BPyInit_bl_math()
{
PyObject *submodule = PyModule_Create(&M_bl_math_module_def);
return submodule;
}
/** \} */
} // namespace blender

View File

@@ -0,0 +1,18 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/**
* \file
* \ingroup pygen
*/
#pragma once
#include <Python.h>
namespace blender {
PyMODINIT_FUNC BPyInit_bl_math();
} // namespace blender

View File

@@ -0,0 +1,852 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
*
* This file defines the `blf` module, used for drawing text to the GPU or image buffers.
*/
/* Future-proof, See https://docs.python.org/3/c-api/arg.html#strings-and-buffers */
#define PY_SSIZE_T_CLEAN
#include "blf_py_api.hh"
#include "py_capi_utils.hh"
#include <Python.h>
#include "../../blenfont/BLF_api.hh"
#include "BLI_utildefines.h"
#include "../../imbuf/IMB_colormanagement.hh"
#include "../../imbuf/IMB_imbuf.hh"
#include "../../imbuf/IMB_imbuf_types.hh"
#include "python_compat.hh" /* IWYU pragma: keep. */
#include "python_utildefines.hh"
#include "imbuf_py_api.hh"
namespace blender {
struct BPyBLFImBufContext {
PyObject_HEAD /* Required Python macro. */
PyObject *py_imbuf;
int fontid;
BLFBufferState *buffer_state;
};
PyDoc_STRVAR(
/* Wrap. */
py_blf_position_doc,
".. function:: position(fontid, x, y, z)\n"
"\n"
" Set the position for drawing text.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param x: X axis position to draw the text.\n"
" :type x: float\n"
" :param y: Y axis position to draw the text.\n"
" :type y: float\n"
" :param z: Z axis position to draw the text (typically 0).\n"
" :type z: float\n");
static PyObject *py_blf_position(PyObject * /*self*/, PyObject *args)
{
int fontid;
float x, y, z;
if (!PyArg_ParseTuple(args, "ifff:blf.position", &fontid, &x, &y, &z)) {
return nullptr;
}
BLF_position(fontid, x, y, z);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_size_doc,
".. function:: size(fontid, size)\n"
"\n"
" Set the size for drawing text.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param size: Point size of the font.\n"
" :type size: float\n");
static PyObject *py_blf_size(PyObject * /*self*/, PyObject *args)
{
int fontid;
float size;
if (!PyArg_ParseTuple(args, "if:blf.size", &fontid, &size)) {
return nullptr;
}
BLF_size(fontid, size);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_aspect_doc,
".. function:: aspect(fontid, aspect)\n"
"\n"
" Set the aspect for drawing text.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param aspect: The aspect ratio for non-uniform scaling of text.\n"
" :type aspect: float\n");
static PyObject *py_blf_aspect(PyObject * /*self*/, PyObject *args)
{
float aspect;
int fontid;
if (!PyArg_ParseTuple(args, "if:blf.aspect", &fontid, &aspect)) {
return nullptr;
}
BLF_aspect(fontid, aspect, aspect, 1.0);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_color_doc,
".. function:: color(fontid, r, g, b, a)\n"
"\n"
" Set the color for drawing text.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param r: Red channel 0.0 - 1.0.\n"
" :type r: float\n"
" :param g: Green channel 0.0 - 1.0.\n"
" :type g: float\n"
" :param b: Blue channel 0.0 - 1.0.\n"
" :type b: float\n"
" :param a: Alpha channel 0.0 - 1.0.\n"
" :type a: float\n");
static PyObject *py_blf_color(PyObject * /*self*/, PyObject *args)
{
int fontid;
float rgba[4];
if (!PyArg_ParseTuple(args, "iffff:blf.color", &fontid, &rgba[0], &rgba[1], &rgba[2], &rgba[3]))
{
return nullptr;
}
BLF_color4fv(fontid, rgba);
/* NOTE(@ideasman42): that storing these colors separately looks like something that could
* be refactored away if the font's internal color format was changed from `uint8` to `float`. */
BLF_buffer_col(fontid, rgba);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_draw_doc,
".. function:: draw(fontid, text)\n"
"\n"
" Draw text in the current context.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param text: The text to draw.\n"
" :type text: str\n");
static PyObject *py_blf_draw(PyObject * /*self*/, PyObject *args)
{
const char *text;
Py_ssize_t text_length;
int fontid;
if (!PyArg_ParseTuple(args, "is#:blf.draw", &fontid, &text, &text_length)) {
return nullptr;
}
BLF_draw(fontid, text, uint(text_length));
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_draw_buffer_doc,
".. function:: draw_buffer(fontid, text)\n"
"\n"
" Draw text into the image buffer bound via :func:`blf.bind_imbuf`.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param text: The text to draw into the bound image buffer.\n"
" :type text: str\n");
static PyObject *py_blf_draw_buffer(PyObject * /*self*/, PyObject *args)
{
const char *text;
Py_ssize_t text_length;
int fontid;
if (!PyArg_ParseTuple(args, "is#:blf.draw_buffer", &fontid, &text, &text_length)) {
return nullptr;
}
BLF_draw_buffer(fontid, text, uint(text_length));
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_dimensions_doc,
".. function:: dimensions(fontid, text)\n"
"\n"
" Return the width and height of the text.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param text: The text to measure.\n"
" :type text: str\n"
" :return: The width and height of the text.\n"
" :rtype: tuple[float, float]\n");
static PyObject *py_blf_dimensions(PyObject * /*self*/, PyObject *args)
{
const char *text;
float width, height;
PyObject *ret;
int fontid;
if (!PyArg_ParseTuple(args, "is:blf.dimensions", &fontid, &text)) {
return nullptr;
}
BLF_width_and_height(fontid, text, INT_MAX, &width, &height);
ret = PyTuple_New(2);
PyTuple_SET_ITEMS(ret, PyFloat_FromDouble(width), PyFloat_FromDouble(height));
return ret;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_clipping_doc,
".. function:: clipping(fontid, xmin, ymin, xmax, ymax)\n"
"\n"
" Set the clipping, enable/disable using :data:`CLIPPING`.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param xmin: Left edge of the clipping rectangle.\n"
" :type xmin: float\n"
" :param ymin: Bottom edge of the clipping rectangle.\n"
" :type ymin: float\n"
" :param xmax: Right edge of the clipping rectangle.\n"
" :type xmax: float\n"
" :param ymax: Top edge of the clipping rectangle.\n"
" :type ymax: float\n");
static PyObject *py_blf_clipping(PyObject * /*self*/, PyObject *args)
{
float xmin, ymin, xmax, ymax;
int fontid;
if (!PyArg_ParseTuple(args, "iffff:blf.clipping", &fontid, &xmin, &ymin, &xmax, &ymax)) {
return nullptr;
}
BLF_clipping(fontid, xmin, ymin, xmax, ymax);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_word_wrap_doc,
".. function:: word_wrap(fontid, wrap_width)\n"
"\n"
" Set the wrap width, enable/disable using :data:`WORD_WRAP`.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param wrap_width: The width (in pixels) to wrap words at.\n"
" :type wrap_width: int\n");
static PyObject *py_blf_word_wrap(PyObject * /*self*/, PyObject *args)
{
int wrap_width;
int fontid;
if (!PyArg_ParseTuple(args, "ii:blf.word_wrap", &fontid, &wrap_width)) {
return nullptr;
}
BLF_wordwrap(fontid, wrap_width);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_disable_doc,
".. function:: disable(fontid, option)\n"
"\n"
" Disable a font drawing option.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param option: One of :data:`ROTATION`, :data:`CLIPPING`, "
":data:`SHADOW`, :data:`MONOCHROME` or :data:`WORD_WRAP`.\n"
" :type option: int\n");
static PyObject *py_blf_disable(PyObject * /*self*/, PyObject *args)
{
int option, fontid;
if (!PyArg_ParseTuple(args, "ii:blf.disable", &fontid, &option)) {
return nullptr;
}
BLF_disable(fontid, FontFlags(option));
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_enable_doc,
".. function:: enable(fontid, option)\n"
"\n"
" Enable a font drawing option.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param option: One of :data:`ROTATION`, :data:`CLIPPING`, "
":data:`SHADOW`, :data:`MONOCHROME` or :data:`WORD_WRAP`.\n"
" :type option: int\n");
static PyObject *py_blf_enable(PyObject * /*self*/, PyObject *args)
{
int option, fontid;
if (!PyArg_ParseTuple(args, "ii:blf.enable", &fontid, &option)) {
return nullptr;
}
BLF_enable(fontid, FontFlags(option));
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_rotation_doc,
".. function:: rotation(fontid, angle)\n"
"\n"
" Set the text rotation angle, enable/disable using :data:`ROTATION`.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param angle: The angle for text drawing to use (in radians).\n"
" :type angle: float\n");
static PyObject *py_blf_rotation(PyObject * /*self*/, PyObject *args)
{
float angle;
int fontid;
if (!PyArg_ParseTuple(args, "if:blf.rotation", &fontid, &angle)) {
return nullptr;
}
BLF_rotation(fontid, angle);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_shadow_doc,
".. function:: shadow(fontid, level, r, g, b, a)\n"
"\n"
" Shadow options, enable/disable using :data:`SHADOW`.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param level: The shadow type: 0 for none, 3 for 3x3 blur, 5 for 5x5 blur "
"or 6 for outline. Other values raise a :exc:`TypeError`.\n"
" :type level: int\n"
" :param r: Shadow color (red channel 0.0 - 1.0).\n"
" :type r: float\n"
" :param g: Shadow color (green channel 0.0 - 1.0).\n"
" :type g: float\n"
" :param b: Shadow color (blue channel 0.0 - 1.0).\n"
" :type b: float\n"
" :param a: Shadow color (alpha channel 0.0 - 1.0).\n"
" :type a: float\n");
static PyObject *py_blf_shadow(PyObject * /*self*/, PyObject *args)
{
int level, fontid;
float rgba[4];
if (!PyArg_ParseTuple(
args, "iiffff:blf.shadow", &fontid, &level, &rgba[0], &rgba[1], &rgba[2], &rgba[3]))
{
return nullptr;
}
if (!ELEM(level, 0, 3, 5, 6)) {
PyErr_SetString(PyExc_TypeError, "blf.shadow expected arg to be in (0, 3, 5, 6)");
return nullptr;
}
BLF_shadow(fontid, FontShadowType(level), rgba);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_shadow_offset_doc,
".. function:: shadow_offset(fontid, x, y)\n"
"\n"
" Set the offset for shadow text, enable/disable using :data:`SHADOW`.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param x: Horizontal shadow offset value in pixels.\n"
" :type x: int\n"
" :param y: Vertical shadow offset value in pixels.\n"
" :type y: int\n");
static PyObject *py_blf_shadow_offset(PyObject * /*self*/, PyObject *args)
{
int x, y, fontid;
if (!PyArg_ParseTuple(args, "iii:blf.shadow_offset", &fontid, &x, &y)) {
return nullptr;
}
BLF_shadow_offset(fontid, x, y);
Py_RETURN_NONE;
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_load_doc,
".. function:: load(filepath)\n"
"\n"
" Load a new font.\n"
"\n"
" :param filepath: The filepath of the font.\n"
" :type filepath: str | bytes\n"
" :return: The new font's fontid or -1 if there was an error.\n"
" :rtype: int\n");
static PyObject *py_blf_load(PyObject * /*self*/, PyObject *args)
{
PyC_UnicodeAsBytesAndSize_Data filepath_data = {nullptr};
if (!PyArg_ParseTuple(args,
"O&" /* `filepath` */
":blf.load",
PyC_ParseUnicodeAsBytesAndSize,
&filepath_data))
{
return nullptr;
}
const int font_id = BLF_load(filepath_data.value);
Py_XDECREF(filepath_data.value_coerce);
return PyLong_FromLong(font_id);
}
PyDoc_STRVAR(
/* Wrap. */
py_blf_unload_doc,
".. function:: unload(filepath)\n"
"\n"
" Unload an existing font.\n"
"\n"
" :param filepath: The filepath of the font.\n"
" :type filepath: str | bytes\n");
static PyObject *py_blf_unload(PyObject * /*self*/, PyObject *args)
{
PyC_UnicodeAsBytesAndSize_Data filepath_data = {nullptr};
if (!PyArg_ParseTuple(args,
"O&" /* `filepath` */
":blf.unload",
PyC_ParseUnicodeAsBytesAndSize,
&filepath_data))
{
return nullptr;
}
BLF_unload(filepath_data.value);
Py_XDECREF(filepath_data.value_coerce);
Py_RETURN_NONE;
}
/* -------------------------------------------------------------------- */
/** \name Image Buffer Access
*
* Context manager for #ImBuf.
* \{ */
static PyObject *py_blf_bind_imbuf_enter(BPyBLFImBufContext *self)
{
if (UNLIKELY(self->buffer_state)) {
PyErr_SetString(PyExc_ValueError,
"BLFImBufContext.__enter__: unable to enter the same context more than once");
return nullptr;
}
ImBuf *ibuf = BPy_ImBuf_FromPyObject(self->py_imbuf);
if (ibuf == nullptr) {
/* The error will have been set. */
return nullptr;
}
BLFBufferState *buffer_state = BLF_buffer_state_push(self->fontid);
if (buffer_state == nullptr) {
PyErr_Format(PyExc_ValueError, "bind_imbuf: unknown fontid %d", self->fontid);
return nullptr;
}
BLF_buffer(self->fontid,
ibuf->float_data_for_write(),
ibuf->byte_data_for_write(),
ibuf->x,
ibuf->y,
4,
ibuf->byte_buffer.colorspace);
self->buffer_state = buffer_state;
Py_RETURN_NONE;
}
static PyObject *py_blf_bind_imbuf_exit(BPyBLFImBufContext *self, PyObject * /*args*/)
{
BLF_buffer_state_pop(self->buffer_state);
self->buffer_state = nullptr;
Py_RETURN_NONE;
}
static void py_blf_bind_imbuf_dealloc(BPyBLFImBufContext *self)
{
if (self->buffer_state) {
/* This should practically never happen since it implies
* `__enter__` is called without a matching `__exit__`.
* Do this mainly for correctness:
* if the process somehow exits before exiting the context manager. */
BLF_buffer_state_free(self->buffer_state);
}
PyObject_GC_UnTrack(self);
Py_CLEAR(self->py_imbuf);
PyObject_GC_Del(self);
}
static int py_blf_bind_imbuf_traverse(BPyBLFImBufContext *self, visitproc visit, void *arg)
{
Py_VISIT(self->py_imbuf);
return 0;
}
static int py_blf_bind_imbuf_clear(BPyBLFImBufContext *self)
{
Py_CLEAR(self->py_imbuf);
return 0;
}
#ifdef __GNUC__
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wcast-function-type"
# else
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-function-type"
# endif
#endif
static PyMethodDef py_blf_bind_imbuf_methods[] = {
{"__enter__", reinterpret_cast<PyCFunction>(py_blf_bind_imbuf_enter), METH_NOARGS},
{"__exit__", reinterpret_cast<PyCFunction>(py_blf_bind_imbuf_exit), METH_VARARGS},
{nullptr},
};
#ifdef __GNUC__
# ifdef __clang__
# pragma clang diagnostic pop
# else
# pragma GCC diagnostic pop
# endif
#endif
PyDoc_STRVAR(
/* Wrap. */
BPyBLFImBufContext_Type_doc,
"Context manager returned by :func:`blf.bind_imbuf` that binds an image buffer\n"
"as the destination for text drawing.");
static PyTypeObject BPyBLFImBufContext_Type = {
/*ob_base*/ PyVarObject_HEAD_INIT(nullptr, 0)
/*tp_name*/ "BLFImBufContext",
/*tp_basicsize*/ sizeof(BPyBLFImBufContext),
/*tp_itemsize*/ 0,
/*tp_dealloc*/ reinterpret_cast<destructor>(py_blf_bind_imbuf_dealloc),
/*tp_vectorcall_offset*/ 0,
/*tp_getattr*/ nullptr,
/*tp_setattr*/ nullptr,
/*tp_as_async*/ nullptr,
/*tp_repr*/ nullptr,
/*tp_as_number*/ nullptr,
/*tp_as_sequence*/ nullptr,
/*tp_as_mapping*/ nullptr,
/*tp_hash*/ nullptr,
/*tp_call*/ nullptr,
/*tp_str*/ nullptr,
/*tp_getattro*/ nullptr,
/*tp_setattro*/ nullptr,
/*tp_as_buffer*/ nullptr,
/*tp_flags*/ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,
/*tp_doc*/ BPyBLFImBufContext_Type_doc,
/*tp_traverse*/ reinterpret_cast<traverseproc>(py_blf_bind_imbuf_traverse),
/*tp_clear*/ reinterpret_cast<inquiry>(py_blf_bind_imbuf_clear),
/*tp_richcompare*/ nullptr,
/*tp_weaklistoffset*/ 0,
/*tp_iter*/ nullptr,
/*tp_iternext*/ nullptr,
/*tp_methods*/ py_blf_bind_imbuf_methods,
/*tp_members*/ nullptr,
/*tp_getset*/ nullptr,
/*tp_base*/ nullptr,
/*tp_dict*/ nullptr,
/*tp_descr_get*/ nullptr,
/*tp_descr_set*/ nullptr,
/*tp_dictoffset*/ 0,
/*tp_init*/ nullptr,
/*tp_alloc*/ nullptr,
/*tp_new*/ nullptr,
/*tp_free*/ nullptr,
/*tp_is_gc*/ nullptr,
/*tp_bases*/ nullptr,
/*tp_mro*/ nullptr,
/*tp_cache*/ nullptr,
/*tp_subclasses*/ nullptr,
/*tp_weaklist*/ nullptr,
/*tp_del*/ nullptr,
/*tp_version_tag*/ 0,
/*tp_finalize*/ nullptr,
/*tp_vectorcall*/ nullptr,
};
PyDoc_STRVAR(
/* Wrap. */
py_blf_bind_imbuf_doc,
".. function:: bind_imbuf(fontid, imbuf, *, display_name=None)\n"
"\n"
" Context manager to draw text into an image buffer instead of the GPU's context.\n"
"\n"
" :param fontid: The id of the typeface as returned by :func:`blf.load`, for default "
"font use 0.\n"
" :type fontid: int\n"
" :param imbuf: The image to draw into.\n"
" :type imbuf: :class:`imbuf.types.ImBuf`\n"
" :param display_name: Ignored (formerly a color-space transform name), "
"kept for backwards compatibility.\n"
" :type display_name: str | None\n"
" :return: The BLF ImBuf context manager.\n"
" :rtype: :class:`blf.types.BLFImBufContext`\n");
static PyObject *py_blf_bind_imbuf(PyObject * /*self*/, PyObject *args, PyObject *kwds)
{
int fontid;
PyObject *py_imbuf = nullptr;
const char *display_name = nullptr;
static const char *_keywords[] = {
"",
"",
"display_name",
nullptr,
};
static _PyArg_Parser _parser = {
"i" /* `fontid` */
"O!" /* `image` */
"|" /* Optional arguments. */
"z" /* `display_name` */
":bind_imbuf",
_keywords,
nullptr,
};
if (!_PyArg_ParseTupleAndKeywordsFast(
args, kwds, &_parser, &fontid, &Py_ImBuf_Type, &py_imbuf, &display_name))
{
return nullptr;
}
/* Display name is ignored, it is only kept for backwards compatibility. This should
* always have been the image buffer byte colorspace rather than a display. */
BPyBLFImBufContext *ret = PyObject_GC_New(BPyBLFImBufContext, &BPyBLFImBufContext_Type);
ret->py_imbuf = Py_NewRef(py_imbuf);
ret->fontid = fontid;
ret->buffer_state = nullptr;
PyObject_GC_Track(ret);
return reinterpret_cast<PyObject *>(ret);
}
/** \} */
#ifdef __GNUC__
# ifdef __clang__
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wcast-function-type"
# else
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wcast-function-type"
# endif
#endif
/*----------------------------MODULE INIT-------------------------*/
static PyMethodDef BLF_methods[] = {
{"aspect", static_cast<PyCFunction>(py_blf_aspect), METH_VARARGS, py_blf_aspect_doc},
{"clipping", static_cast<PyCFunction>(py_blf_clipping), METH_VARARGS, py_blf_clipping_doc},
{"word_wrap", static_cast<PyCFunction>(py_blf_word_wrap), METH_VARARGS, py_blf_word_wrap_doc},
{"disable", static_cast<PyCFunction>(py_blf_disable), METH_VARARGS, py_blf_disable_doc},
{"dimensions",
static_cast<PyCFunction>(py_blf_dimensions),
METH_VARARGS,
py_blf_dimensions_doc},
{"draw", static_cast<PyCFunction>(py_blf_draw), METH_VARARGS, py_blf_draw_doc},
{"draw_buffer",
static_cast<PyCFunction>(py_blf_draw_buffer),
METH_VARARGS,
py_blf_draw_buffer_doc},
{"enable", static_cast<PyCFunction>(py_blf_enable), METH_VARARGS, py_blf_enable_doc},
{"position", static_cast<PyCFunction>(py_blf_position), METH_VARARGS, py_blf_position_doc},
{"rotation", static_cast<PyCFunction>(py_blf_rotation), METH_VARARGS, py_blf_rotation_doc},
{"shadow", static_cast<PyCFunction>(py_blf_shadow), METH_VARARGS, py_blf_shadow_doc},
{"shadow_offset",
static_cast<PyCFunction>(py_blf_shadow_offset),
METH_VARARGS,
py_blf_shadow_offset_doc},
{"size", static_cast<PyCFunction>(py_blf_size), METH_VARARGS, py_blf_size_doc},
{"color", static_cast<PyCFunction>(py_blf_color), METH_VARARGS, py_blf_color_doc},
{"load", static_cast<PyCFunction>(py_blf_load), METH_VARARGS, py_blf_load_doc},
{"unload", static_cast<PyCFunction>(py_blf_unload), METH_VARARGS, py_blf_unload_doc},
{"bind_imbuf",
reinterpret_cast<PyCFunction>(py_blf_bind_imbuf),
METH_VARARGS | METH_KEYWORDS,
py_blf_bind_imbuf_doc},
{nullptr, nullptr, 0, nullptr},
};
#ifdef __GNUC__
# ifdef __clang__
# pragma clang diagnostic pop
# else
# pragma GCC diagnostic pop
# endif
#endif
PyDoc_STRVAR(
/* Wrap. */
BLF_doc,
"This module provides access to Blender's text drawing functions.");
static PyModuleDef BLF_module_def = {
/*m_base*/ PyModuleDef_HEAD_INIT,
/*m_name*/ "blf",
/*m_doc*/ BLF_doc,
/*m_size*/ 0,
/*m_methods*/ BLF_methods,
/*m_slots*/ nullptr,
/*m_traverse*/ nullptr,
/*m_clear*/ nullptr,
/*m_free*/ nullptr,
};
/* -------------------------------------------------------------------- */
/** \name Module Definition (`blf.types`)
* \{ */
PyDoc_STRVAR(
/* Wrap. */
BLF_types_doc,
"This module provides access to font drawing types.");
static PyModuleDef BLF_types_module_def = {
/*m_base*/ PyModuleDef_HEAD_INIT,
/*m_name*/ "blf.types",
/*m_doc*/ BLF_types_doc,
/*m_size*/ 0,
/*m_methods*/ nullptr,
/*m_slots*/ nullptr,
/*m_traverse*/ nullptr,
/*m_clear*/ nullptr,
/*m_free*/ nullptr,
};
static PyObject *BPyInit_blf_types()
{
PyObject *submodule = PyModule_Create(&BLF_types_module_def);
if (PyType_Ready(&BPyBLFImBufContext_Type) < 0) {
return nullptr;
}
PyModule_AddType(submodule, &BPyBLFImBufContext_Type);
return submodule;
}
/** \} */
PyObject *BPyInit_blf()
{
PyObject *mod;
PyObject *submodule;
PyObject *sys_modules = PyImport_GetModuleDict();
mod = PyModule_Create(&BLF_module_def);
PyModule_AddIntConstant(mod, "ROTATION", BLF_ROTATION);
PyModule_AddIntConstant(mod, "CLIPPING", BLF_CLIPPING);
PyModule_AddIntConstant(mod, "SHADOW", BLF_SHADOW);
PyModule_AddIntConstant(mod, "WORD_WRAP", BLF_WORD_WRAP);
PyModule_AddIntConstant(mod, "MONOCHROME", BLF_MONOCHROME);
PyModule_AddIntConstant(mod, "NO_FALLBACK", BLF_NO_FALLBACK);
/* `blf.types` */
PyModule_AddObject(mod, "types", (submodule = BPyInit_blf_types()));
PyC_Module_AddToSysModules(sys_modules, submodule);
return mod;
}
} // namespace blender

View File

@@ -0,0 +1,17 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
/** \file
* \ingroup pygen
*/
#include <Python.h>
namespace blender {
[[nodiscard]] PyObject *BPyInit_blf();
} // namespace blender

View File

@@ -0,0 +1,67 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
*
* This file contains wrapper functions related to global interpreter lock.
* these functions are slightly different from the original Python API,
* don't throw SIGABRT even if the thread state is nullptr. */
#include <Python.h>
#include "python_compat.hh" /* IWYU pragma: keep. */
#include "../BPY_extern.hh"
namespace blender {
BPy_ThreadStatePtr BPY_thread_save()
{
/* Use `_PyThreadState_UncheckedGet()` instead of `PyThreadState_Get()`, to avoid a fatal error
* issued when a thread state is nullptr (the thread state can be nullptr when quitting Blender).
*
* `PyEval_SaveThread()` will release the GIL, so this thread has to have the GIL to begin with
* or badness will ensue. */
if (PyThreadState_GetUnchecked() && PyGILState_Check()) {
return static_cast<BPy_ThreadStatePtr>(PyEval_SaveThread());
}
return nullptr;
}
void BPY_thread_restore(BPy_ThreadStatePtr tstate)
{
if (tstate) {
PyEval_RestoreThread(static_cast<PyThreadState *>(tstate));
}
}
void BPY_thread_backtrace_print()
{
PyThreadState *tstate = PyGILState_GetThisThreadState();
if (tstate) {
PyFrameObject *frame = PyThreadState_GetFrame(tstate);
printf(frame ? "Python stack trace:\n" : "No Python stack trace available.\n");
while (frame) {
PyCodeObject *frame_co = PyFrame_GetCode(frame);
int line = PyFrame_GetLineNumber(frame);
const char *filename = PyUnicode_AsUTF8(frame_co->co_filename);
const char *funcname = PyUnicode_AsUTF8(frame_co->co_name);
printf(" %s:%d %s\n", filename, line, funcname);
Py_DECREF(frame_co);
PyFrameObject *frame_back = PyFrame_GetBack(frame);
Py_DECREF(frame);
frame = frame_back;
}
printf("\n");
}
else {
printf("No Python thread state available.\n");
}
}
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,125 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
*/
#pragma once
#include <Python.h>
namespace blender {
struct BPy_IDGroup_Iter;
struct ID;
struct IDProperty;
extern PyTypeObject BPy_IDArray_Type;
extern PyTypeObject BPy_IDGroup_Type;
extern PyTypeObject BPy_IDGroup_ViewKeys_Type;
extern PyTypeObject BPy_IDGroup_ViewValues_Type;
extern PyTypeObject BPy_IDGroup_ViewItems_Type;
extern PyTypeObject BPy_IDGroup_IterKeys_Type;
extern PyTypeObject BPy_IDGroup_IterValues_Type;
extern PyTypeObject BPy_IDGroup_IterItems_Type;
#define BPy_IDArray_Check(v) (PyObject_TypeCheck(v, &BPy_IDArray_Type))
#define BPy_IDArray_CheckExact(v) (Py_TYPE(v) == &BPy_IDArray_Type)
#define BPy_IDGroup_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_Type))
#define BPy_IDGroup_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_Type)
#define BPy_IDGroup_ViewKeys_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_ViewKeys_Type))
#define BPy_IDGroup_ViewKeys_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_ViewKeys_Type)
#define BPy_IDGroup_ViewValues_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_ViewValues_Type))
#define BPy_IDGroup_ViewValues_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_ViewValues_Type)
#define BPy_IDGroup_ViewItems_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_ViewItems_Type))
#define BPy_IDGroup_ViewItems_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_ViewItems_Type)
#define BPy_IDGroup_IterKeys_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_IterKeys_Type))
#define BPy_IDGroup_IterKeys_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_IterKeys_Type)
#define BPy_IDGroup_IterValues_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_IterValues_Type))
#define BPy_IDGroup_IterValues_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_IterValues_Type)
#define BPy_IDGroup_IterItems_Check(v) (PyObject_TypeCheck(v, &BPy_IDGroup_IterItems_Type))
#define BPy_IDGroup_IterItems_CheckExact(v) (Py_TYPE(v) == &BPy_IDGroup_IterItems_Type)
struct BPy_IDProperty {
PyObject_HEAD
struct ID *owner_id; /* can be NULL */
struct IDProperty *prop; /* must be second member */
struct IDProperty *parent;
};
struct BPy_IDArray {
PyObject_HEAD
struct ID *owner_id; /* can be NULL */
struct IDProperty *prop; /* must be second member */
};
struct BPy_IDGroup_Iter {
PyObject_HEAD
BPy_IDProperty *group;
struct IDProperty *cur;
/** Use for detecting manipulation during iteration (which is not allowed). */
int len_init;
/** Iterate in the reverse direction. */
bool reversed;
};
/** Use to implement `IDPropertyGroup.keys/values/items` */
struct BPy_IDGroup_View {
PyObject_HEAD
/** This will be NULL when accessing keys on data that has no ID properties. */
BPy_IDProperty *group;
bool reversed;
};
[[nodiscard]] PyObject *BPy_Wrap_GetKeys(IDProperty *prop);
[[nodiscard]] PyObject *BPy_Wrap_GetValues(ID *id, IDProperty *prop);
[[nodiscard]] PyObject *BPy_Wrap_GetItems(ID *id, IDProperty *prop);
[[nodiscard]] PyObject *BPy_Wrap_GetKeys_View_WithID(ID *id, IDProperty *prop);
[[nodiscard]] PyObject *BPy_Wrap_GetValues_View_WithID(ID *id, IDProperty *prop);
[[nodiscard]] PyObject *BPy_Wrap_GetItems_View_WithID(ID *id, IDProperty *prop);
[[nodiscard]] int BPy_Wrap_SetMapItem(IDProperty *prop, PyObject *key, PyObject *val);
/**
* For simple, non nested types this is the same as #BPy_IDGroup_WrapData.
*/
[[nodiscard]] PyObject *BPy_IDGroup_MapDataToPy(IDProperty *prop);
[[nodiscard]] PyObject *BPy_IDGroup_WrapData(ID *id, IDProperty *prop, IDProperty *parent);
/**
* \note group can be a pointer array or a group.
* assume we already checked key is a string.
*
* \return success.
*/
[[nodiscard]] bool BPy_IDProperty_Map_ValidateAndCreate(PyObject *key,
IDProperty *group,
PyObject *ob);
void IDProp_Init_Types();
[[nodiscard]] PyObject *BPyInit_idprop();
/**
* Create an IDProperty from a Python object.
*
* \param prop_exist: pre-existing IDProperty to populate with the value. Can be `nullptr` to
* allocate a new IDProperty.
* \param name: the name of the IDProperty. Only used when creating a new IDProperty.
* \param ob: the Python object to convert.
* \param do_conversion: when there is a pre-existing IDProperty, whether the Python object's value
* should be converted to its type (if not the same type already).
* \param can_create: whether the function is allowed to create a new property. If this is `false`
* and `prop_exists` is `nullptr`, this function is a no-op.
*
* \return the existing/created IDProperty if the value was set on it, and `nullptr` otherwise.
*/
IDProperty *BPy_IDProperty_FromPyObject(
IDProperty *prop_exist, const char *name, PyObject *ob, bool do_conversion, bool can_create);
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
*/
#pragma once
#include <Python.h>
namespace blender {
struct IDProperty;
extern PyTypeObject BPy_IDPropertyUIManager_Type;
struct BPy_IDPropertyUIManager {
PyObject_HEAD
IDProperty *property;
};
void IDPropertyUIData_Init_Types();
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,24 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
#pragma once
/** \file
* \ingroup pygen
*/
#include <Python.h>
namespace blender {
struct ImBuf;
[[nodiscard]] PyObject *BPyInit_imbuf();
extern PyTypeObject Py_ImBuf_Type;
/** Return the #ImBuf or null with an error set. */
[[nodiscard]] ImBuf *BPy_ImBuf_FromPyObject(PyObject *py_imbuf);
} // namespace blender

View File

@@ -0,0 +1,250 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
*
* Python/RNA utilities.
*
* RNA functions that aren't part of the `bpy_rna.cc` API.
*/
/* Future-proof, See https://docs.python.org/3/c-api/arg.html#strings-and-buffers */
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "py_capi_rna.hh"
#include "BLI_bitmap.h"
#include "BLI_dynstr.h"
#include "RNA_access.hh"
#include "MEM_guardedalloc.h"
namespace blender {
/* -------------------------------------------------------------------- */
/** \name Enum Utilities
* \{ */
char *pyrna_enum_repr(const EnumPropertyItem *item)
{
DynStr *dynstr = BLI_dynstr_new();
/* We can't compare with the first element in the array
* since it may be a category (without an identifier). */
for (bool is_first = true; item->identifier; item++) {
if (item->identifier[0]) {
BLI_dynstr_appendf(dynstr, is_first ? "'%s'" : ", '%s'", item->identifier);
is_first = false;
}
}
char *cstring = BLI_dynstr_get_cstring(dynstr);
BLI_dynstr_free(dynstr);
return cstring;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Enum Conversion Utilities
* \{ */
int pyrna_enum_value_from_id(const EnumPropertyItem *item,
const char *identifier,
int *r_value,
const char *error_prefix)
{
if (RNA_enum_value_from_id(item, identifier, r_value) == 0) {
const char *enum_str = pyrna_enum_repr(item);
PyErr_Format(
PyExc_ValueError, "%s: '%.200s' not found in (%s)", error_prefix, identifier, enum_str);
MEM_delete(enum_str);
return -1;
}
return 0;
}
BLI_bitmap *pyrna_enum_bitmap_from_set(const EnumPropertyItem *items,
PyObject *value,
int type_size,
bool type_convert_sign,
int bitmap_size,
const char *error_prefix)
{
BLI_assert(PySet_Check(value));
BLI_bitmap *bitmap = BLI_BITMAP_NEW(bitmap_size, __func__);
if (PySet_GET_SIZE(value) > 0) {
/* Set looping. */
PyObject *it = PyObject_GetIter(value);
PyObject *key;
while ((key = PyIter_Next(it))) {
/* Borrow from the set. */
Py_DECREF(key);
const char *param = PyUnicode_AsUTF8(key);
if (param == nullptr) {
PyErr_Format(PyExc_TypeError,
"%.200s expected a string, not %.200s",
error_prefix,
Py_TYPE(key)->tp_name);
break;
}
int ret;
if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) == -1) {
break;
}
int index = ret;
if (type_convert_sign) {
if (type_size == 2) {
union {
signed short as_signed;
ushort as_unsigned;
} ret_convert;
ret_convert.as_signed = short(ret);
index = int(ret_convert.as_unsigned);
}
else if (type_size == 1) {
union {
signed char as_signed;
uchar as_unsigned;
} ret_convert;
ret_convert.as_signed = static_cast<signed char>(ret);
index = int(ret_convert.as_unsigned);
}
else {
BLI_assert_unreachable();
}
}
BLI_assert(index < bitmap_size);
BLI_BITMAP_ENABLE(bitmap, index);
}
Py_DECREF(it);
if (key) {
MEM_delete(bitmap);
bitmap = nullptr;
}
}
return bitmap;
}
int pyrna_enum_bitfield_from_set(const EnumPropertyItem *items,
PyObject *value,
int *r_value,
const char *error_prefix)
{
BLI_assert(PySet_Check(value));
/* Set of enum items, concatenate all values with OR. */
int flag = 0;
*r_value = 0;
PyObject *key = nullptr;
if (PySet_GET_SIZE(value) > 0) {
/* Set looping. */
PyObject *it = PyObject_GetIter(value);
while ((key = PyIter_Next(it))) {
/* Borrow from the set. */
Py_DECREF(key);
const char *param = PyUnicode_AsUTF8(key);
if (param == nullptr) {
PyErr_Format(PyExc_TypeError,
"%.200s expected a string, not %.200s",
error_prefix,
Py_TYPE(key)->tp_name);
break;
}
int ret;
if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) == -1) {
break;
}
flag |= ret;
}
Py_DECREF(it);
if (key) {
return -1;
}
}
*r_value = flag;
return 0;
}
PyObject *pyrna_enum_bitfield_as_set(const EnumPropertyItem *items, int value)
{
PyObject *ret = PySet_New(nullptr);
const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
if (RNA_enum_bitflag_identifiers(items, value, identifier)) {
PyObject *item;
int index;
for (index = 0; identifier[index]; index++) {
item = PyUnicode_FromString(identifier[index]);
PySet_Add(ret, item);
Py_DECREF(item);
}
}
return ret;
}
/** \} */
/* -------------------------------------------------------------------- */
/** \name Argument Parsing Helpers
* \{ */
int pyrna_enum_value_parse_string(PyObject *o, void *p)
{
const char *identifier = PyUnicode_AsUTF8(o);
if (identifier == nullptr) {
PyErr_Format(PyExc_TypeError, "expected a string enum, not %.200s", Py_TYPE(o)->tp_name);
return 0;
}
BPy_EnumProperty_Parse *parse_data = static_cast<BPy_EnumProperty_Parse *>(p);
if (pyrna_enum_value_from_id(
parse_data->items, identifier, &parse_data->value, "enum identifier") == -1)
{
return 0;
}
parse_data->value_orig = o;
parse_data->is_set = true;
return 1;
}
int pyrna_enum_bitfield_parse_set(PyObject *o, void *p)
{
if (!PySet_Check(o)) {
PyErr_Format(PyExc_TypeError, "expected a set, not %.200s", Py_TYPE(o)->tp_name);
return 0;
}
BPy_EnumProperty_Parse *parse_data = static_cast<BPy_EnumProperty_Parse *>(p);
if (pyrna_enum_bitfield_from_set(
parse_data->items, o, &parse_data->value, "enum identifier set") == -1)
{
return 0;
}
parse_data->value_orig = o;
parse_data->is_set = true;
return 1;
}
/** \} */
} // namespace blender

View File

@@ -0,0 +1,82 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/**
* \file
* \ingroup pygen
*/
#pragma once
#include <Python.h>
namespace blender {
struct EnumPropertyItem;
/**
* Convert all items into a single comma separated string.
* Use for creating useful error messages.
*/
[[nodiscard]] char *pyrna_enum_repr(const EnumPropertyItem *item);
/**
* Same as #RNA_enum_value_from_id, but raises an exception.
*/
[[nodiscard]] int pyrna_enum_value_from_id(const EnumPropertyItem *item,
const char *identifier,
int *r_value,
const char *error_prefix);
/**
* Takes a set of strings and map it to and array of booleans.
*
* Useful when the values aren't flags.
*
* \param type_convert_sign: Maps signed to unsigned range,
* needed when we want to use the full range of a signed short/char.
*/
[[nodiscard]] unsigned int *pyrna_enum_bitmap_from_set(const EnumPropertyItem *items,
PyObject *value,
int type_size,
bool type_convert_sign,
int bitmap_size,
const char *error_prefix);
/**
* 'value' _must_ be a set type, error check before calling.
*/
[[nodiscard]] int pyrna_enum_bitfield_from_set(const EnumPropertyItem *items,
PyObject *value,
int *r_value,
const char *error_prefix);
[[nodiscard]] PyObject *pyrna_enum_bitfield_as_set(const EnumPropertyItem *items, int value);
/**
* Data for #pyrna_enum_value_parse_string & #pyrna_enum_bitfield_parse_set parsing utilities.
* Use with #PyArg_ParseTuple's `O&` formatting.
*/
struct BPy_EnumProperty_Parse {
const EnumPropertyItem *items;
/**
* Set when the value was successfully parsed.
* Useful if the input ever needs to be included in an error message.
* (if the value is not supported under certain conditions).
*/
PyObject *value_orig;
int value;
bool is_set;
};
/**
* Use with #PyArg_ParseTuple's `O&` formatting.
*/
[[nodiscard]] int pyrna_enum_value_parse_string(PyObject *o, void *p);
/**
* Use with #PyArg_ParseTuple's `O&` formatting.
*/
[[nodiscard]] int pyrna_enum_bitfield_parse_set(PyObject *o, void *p);
} // namespace blender

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,545 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
*/
#pragma once
#include <Python.h>
#include <optional>
#include <string>
#include <type_traits>
#include "BLI_compiler_attrs.h"
#include "BLI_span.hh"
#include "BLI_sys_types.h"
#include "DNA_vec_types.h"
namespace blender {
/** Useful to print Python objects while debugging. */
void PyC_ObSpit(const char *name, PyObject *var);
/**
* A version of #PyC_ObSpit that writes into a string (and doesn't take a name argument).
* Use for logging.
*/
void PyC_ObSpitStr(char *result, size_t result_maxncpy, PyObject *var);
void PyC_LineSpit();
void PyC_StackSpit();
/**
* Return a string containing the full stack trace.
*
* - Only call when `PyErr_Occurred() != 0` .
* - The exception is left in place without being manipulated,
* although they will be normalized in order to display them (`PyErr_Print` also does this).
* - `SystemExit` exceptions will exit (so `sys.exit(..)` works, matching `PyErr_Print` behavior).
* - The always returns a Python string (unless exiting where the function doesn't return).
*/
[[nodiscard]] PyObject *PyC_ExceptionBuffer() ATTR_RETURNS_NONNULL;
/**
* A version of #PyC_ExceptionBuffer that returns the last exception only.
*
* Useful for error messages from evaluating numeric expressions for example
* where a full multi-line stack-trace isn't needed and doesn't format well in the status-bar.
*/
[[nodiscard]] PyObject *PyC_ExceptionBuffer_Simple() ATTR_RETURNS_NONNULL;
/**
* Get exit code `sys.exit(..)` was called with.
*/
[[nodiscard]] std::optional<int> PyC_ExceptionSystemExitCode();
/**
* Capture exit code from current python exception.
*
* If the current exception is `SystemExit`, capture the exit code and return true.
* Otherwise return false;
*/
bool PyC_Err_CaptureSystemExitCode();
[[nodiscard]] PyObject *PyC_Object_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...);
[[nodiscard]] PyObject *PyC_FrozenSetFromStrings(const char **strings);
/**
* Similar to #PyErr_Format(),
*
* Implementation - we can't actually prepend the existing exception,
* because it could have _any_ arguments given to it, so instead we get its
* `__str__` output and raise our own exception including it.
*/
PyObject *PyC_Err_Format_Prefix(PyObject *exception_type_prefix, const char *format, ...);
PyObject *PyC_Err_SetString_Prefix(PyObject *exception_type_prefix, const char *str);
/**
* Use for Python callbacks run directly from C,
* when we can't use normal methods of raising exceptions.
*/
void PyC_Err_PrintWithFunc(PyObject *py_func);
void PyC_FileAndNum(const char **r_filename, int *r_lineno);
/**
* The "safe" version checks Python is running first.
* Typically the caller should know this but there are times it's impractical.
*/
void PyC_FileAndNum_Safe(const char **r_filename, int *r_lineno);
[[nodiscard]] int PyC_AsArray_FAST(void *array,
size_t array_item_size,
PyObject *value_fast,
Py_ssize_t length,
const PyTypeObject *type,
const char *error_prefix);
[[nodiscard]] int PyC_AsArray(void *array,
size_t array_item_size,
PyObject *value,
Py_ssize_t length,
const PyTypeObject *type,
const char *error_prefix);
[[nodiscard]] int PyC_AsArray_Multi_FAST(void *array,
size_t array_item_size,
PyObject *value_fast,
const int *dims,
int dims_len,
const PyTypeObject *type,
const char *error_prefix);
[[nodiscard]] int PyC_AsArray_Multi(void *array,
size_t array_item_size,
PyObject *value,
const int *dims,
int dims_len,
const PyTypeObject *type,
const char *error_prefix);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_F32(const float *array, uint len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_F64(const double *array, uint len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_I32(const int *array, uint len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_I32FromBool(const int *array, uint len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_Bool(const bool *array, uint len);
/**
* \note Any errors converting strings will return null with the error left as-is.
*/
[[nodiscard]] PyObject *PyC_Tuple_PackArray_String(const char **array, uint len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_Multi_F32(const float *array,
const int dims[],
int dims_len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_Multi_F64(const double *array,
const int dims[],
int dims_len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_Multi_I32(const int *array,
const int dims[],
int dims_len);
[[nodiscard]] PyObject *PyC_Tuple_PackArray_Multi_Bool(const bool *array,
const int dims[],
int dims_len);
/**
* Caller needs to ensure tuple is uninitialized.
* Handy for filling a tuple with None for eg.
*/
void PyC_Tuple_Fill(PyObject *tuple, PyObject *value);
void PyC_List_Fill(PyObject *list, PyObject *value);
/**
* Create a `str` from bytes in a way which is compatible with non UTF8 encoded file-system paths,
* see: #111033.
* Follow http://www.python.org/dev/peps/pep-0383/
*/
[[nodiscard]] PyObject *PyC_UnicodeFromBytes(const char *str);
/**
* \param size: The length of the string: `strlen(str)`.
*/
[[nodiscard]] PyObject *PyC_UnicodeFromBytesAndSize(const char *str, Py_ssize_t size);
[[nodiscard]] const char *PyC_UnicodeAsBytes(PyObject *py_str,
PyObject **r_coerce); /* coerce must be NULL */
/**
* String conversion, escape non-unicode chars
* \param r_size: The string length (not including the null terminator).
* \note By convention Blender API's use len/length however Python API's use the term size,
* as this is an alternative to Python's #PyUnicode_AsUTF8AndSize, follow it's naming.
* \param r_coerce: must reference a pointer set to NULL.
*/
[[nodiscard]] const char *PyC_UnicodeAsBytesAndSize(PyObject *py_str,
Py_ssize_t *r_size,
PyObject **r_coerce);
/**
* Notes on using this structure:
* - Always initialize to `{nullptr}`.
* - Always `Py_XDECREF(value_coerce)` before returning,
* after this `value` must not be accessed.
*/
struct PyC_UnicodeAsBytesAndSize_Data {
PyObject *value_coerce;
const char *value;
Py_ssize_t value_len;
};
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* Expose #PyC_UnicodeAsBytes in a way which is useful to the argument parser.
* \param o: An argument parsed to #PyC_UnicodeAsBytes.
* \param p: Pointer to #PyC_UnicodeAsBytes_Data.
*
* \note The Python API docs reference `PyUnicode_FSConverter` however this does not support
* paths which non UTF8 encoding, see: #111033.
*/
int PyC_ParseUnicodeAsBytesAndSize(PyObject *o, void *p);
/** A version of #PyC_ParseUnicodeAsBytesAndSize that accepts None. */
int PyC_ParseUnicodeAsBytesAndSize_OrNone(PyObject *o, void *p);
/**
* Description: This function creates a new Python dictionary object.
* NOTE: dict is owned by sys.modules["__main__"] module, reference is borrowed
* NOTE: important we use the dict from __main__, this is what python expects
* for 'pickle' to work as well as strings like this...
* >> foo = 10
* >> print(__import__("__main__").foo)
*
* NOTE: this overwrites __main__ which gives problems with nested calls.
* be sure to run #PyC_MainModule_Backup & #PyC_MainModule_Restore if there is
* any chance that python is in the call stack.
*/
[[nodiscard]] PyObject *PyC_DefaultNameSpace(const char *filename) ATTR_NONNULL(1);
void PyC_RunQuicky(const char *filepath, int n, ...) ATTR_NONNULL(1);
/**
* Import `imports` into `py_dict`.
*
* \param py_dict: A Python dictionary, typically used as a name-space for script execution.
* \param imports: A NULL terminated array of strings.
* \return true when all modules import without errors, otherwise return false.
* The caller is expected to handle the exception.
*/
[[nodiscard]] bool PyC_NameSpace_ImportArray(PyObject *py_dict, const char *imports[]);
/**
* #PyC_MainModule_Restore MUST be called after #PyC_MainModule_Backup.
*/
[[nodiscard]] PyObject *PyC_MainModule_Backup();
void PyC_MainModule_Restore(PyObject *main_mod);
/**
* Add a module to `sys.modules` using the module's `__name__` as the key.
*
* Equivalent to: `sys.modules[module.__name__] = module`.
*
* \param sys_modules: The result of #PyImport_GetModuleDict().
* \param module: The module to add.
* \return 0 on success, -1 on error.
*/
int PyC_Module_AddToSysModules(PyObject *sys_modules, PyObject *module);
[[nodiscard]] bool PyC_IsInterpreterActive();
/**
* Generic function to avoid depending on RNA.
*/
[[nodiscard]] void *PyC_RNA_AsPointer(PyObject *value, const char *type_name);
/* flag / set --- interchange */
struct PyC_FlagSet {
int value;
const char *identifier;
};
[[nodiscard]] PyObject *PyC_FlagSet_AsString(const PyC_FlagSet *item);
[[nodiscard]] int PyC_FlagSet_ValueFromID_int(const PyC_FlagSet *item,
const char *identifier,
int *r_value);
[[nodiscard]] int PyC_FlagSet_ValueFromID(const PyC_FlagSet *item,
const char *identifier,
int *r_value,
const char *error_prefix);
[[nodiscard]] int PyC_FlagSet_ToBitfield(const PyC_FlagSet *items,
PyObject *value,
int *r_value,
const char *error_prefix);
[[nodiscard]] PyObject *PyC_FlagSet_FromBitfield(PyC_FlagSet *items, int flag);
/**
* \return success
*
* \note it is caller's responsibility to acquire & release GIL!
*/
[[nodiscard]] bool PyC_RunString_AsNumber(const char **imports,
const char *expr,
const char *filename,
double *r_value) ATTR_NONNULL(2, 3, 4);
[[nodiscard]] bool PyC_RunString_AsIntPtr(const char **imports,
const char *expr,
const char *filename,
intptr_t *r_value) ATTR_NONNULL(2, 3, 4);
/**
* \param r_value_size: The length of the string assigned: `strlen(*r_value)`.
*/
[[nodiscard]] bool PyC_RunString_AsStringAndSize(const char **imports,
const char *expr,
const char *filename,
char **r_value,
size_t *r_value_size) ATTR_NONNULL(2, 3, 4, 5);
[[nodiscard]] bool PyC_RunString_AsString(const char **imports,
const char *expr,
const char *filename,
char **r_value) ATTR_NONNULL(2, 3, 4);
/**
* \param r_value_size: The length of the string assigned: `strlen(*r_value)`.
*/
[[nodiscard]] bool PyC_RunString_AsStringAndSizeOrNone(const char **imports,
const char *expr,
const char *filename,
char **r_value,
size_t *r_value_size) ATTR_NONNULL(2, 3, 4);
[[nodiscard]] bool PyC_RunString_AsStringOrNone(const char **imports,
const char *expr,
const char *filename,
char **r_value) ATTR_NONNULL(2, 3, 4);
/**
* Flush Python's `sys.stdout` and `sys.stderr`. Errors are ignored.
*/
void PyC_StdFilesFlush();
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* \see #PyC_Long_AsBool for a similar function to use outside of argument parsing.
*/
[[nodiscard]] int PyC_ParseBool(PyObject *o, void *p);
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* A version of `O!` that also accepts None (setting the pointer to nullptr).
*/
struct PyC_TypeOrNone {
PyTypeObject *type;
PyObject **value_p;
};
[[nodiscard]] int PyC_ParseTypeOrNone(PyObject *o, void *p);
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* A version of `i` that also accepts None (leaving the `std::optional<int>` empty).
*/
[[nodiscard]] int PyC_ParseOptionalInt(PyObject *o, void *p);
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* A version of `d` that also accepts None (leaving the `std::optional<double>` empty).
*/
[[nodiscard]] int PyC_ParseOptionalDouble(PyObject *o, void *p);
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* A version of `f` that also accepts None (leaving the `std::optional<float>` empty).
*/
[[nodiscard]] int PyC_ParseOptionalFloat(PyObject *o, void *p);
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* A version of `I` that also accepts None (leaving the `std::optional<uint>` empty).
*/
[[nodiscard]] int PyC_ParseOptionalUInt(PyObject *o, void *p);
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* A version of #PyC_ParseBool that also accepts None
* (leaving the `std::optional<bool>` empty).
*/
[[nodiscard]] int PyC_ParseOptionalBool(PyObject *o, void *p);
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*
* Parse `((x1, y1), (x2, y2))` into an `rcti`.
*/
[[nodiscard]] int PyC_ParseRectI(PyObject *o, void *p);
/**
* A version of #PyC_ParseRectI that accepts None
* (leaving the `std::optional<rcti>` empty).
*/
[[nodiscard]] int PyC_ParseOptionalRectI(PyObject *o, void *p);
/**
* Cast a pointer of a PyObject-derived type to `PyObject *`.
*
* A type-safe alternative to the C/Python API's `_PyObject_CAST` which is
* a plain C-style cast without any validation. This verifies at compile time
* that `T::ob_base` is `PyObject` or `PyVarObject` (from `PyObject_HEAD`
* or `PyObject_VAR_HEAD`).
*/
template<typename T> inline PyObject *PyC_Object_CAST(T *value)
{
static_assert(std::is_same_v<decltype(T::ob_base), PyObject> ||
std::is_same_v<decltype(T::ob_base), PyVarObject>,
"Type must use PyObject_HEAD or PyObject_VAR_HEAD");
return reinterpret_cast<PyObject *>(value);
}
/** A version of #PyC_Object_CAST that casts `T**` to `PyObject **`. */
template<typename T> inline PyObject **PyC_Object_ptr_CAST(T **value_p)
{
static_assert(std::is_same_v<decltype(T::ob_base), PyObject> ||
std::is_same_v<decltype(T::ob_base), PyVarObject>,
"Type must use PyObject_HEAD or PyObject_VAR_HEAD");
return reinterpret_cast<PyObject **>(value_p);
}
/** Initializer for #PyC_TypeOrNone, validates PyObject compatibility at compile time. */
#define PyC_TYPE_OR_NONE_INIT(py_type, value_p) {(py_type), PyC_Object_ptr_CAST(value_p)}
struct PyC_StringEnumItems {
int value;
const char *id;
};
struct PyC_StringEnum {
const struct PyC_StringEnumItems *items;
int value_found;
};
/**
* Use with PyArg_ParseTuple's "O&" formatting.
*/
[[nodiscard]] int PyC_ParseStringEnum(PyObject *o, void *p);
[[nodiscard]] const char *PyC_StringEnum_FindIDFromValue(const struct PyC_StringEnumItems *items,
int value);
/**
* Silly function, we don't use arg. just check its compatible with `__deepcopy__`.
*/
[[nodiscard]] int PyC_CheckArgs_DeepCopy(PyObject *args);
/* Integer parsing (with overflow checks), -1 on error. */
/**
* Comparison with #PyObject_IsTrue
* ================================
*
* Even though Python provides a way to retrieve the boolean value for an object,
* in many cases it's far too relaxed, with the following examples coercing values.
*
* \code{.py}
* data.value = "Text" # True.
* data.value = "" # False.
* data.value = {1, 2} # True
* data.value = {} # False.
* data.value = None # False.
* \endcode
*
* In practice this is often a mistake by the script author that doesn't behave as they expect.
* So it's better to be more strict for attribute assignment and function arguments,
* only accepting True/False 0/1.
*
* If coercing a value is desired, it can be done explicitly: `data.value = bool(value)`
*
* \see #PyC_ParseBool for use with #PyArg_ParseTuple and related functions.
*
* \note Don't use `bool` return type, so -1 can be used as an error value.
*/
[[nodiscard]] int PyC_Long_AsBool(PyObject *value);
[[nodiscard]] int8_t PyC_Long_AsI8(PyObject *value);
[[nodiscard]] int16_t PyC_Long_AsI16(PyObject *value);
#if 0 /* inline */
[[nodiscard]] int32_t PyC_Long_AsI32(PyObject *value);
[[nodiscard]] int64_t PyC_Long_AsI64(PyObject *value);
#endif
/**
* Unlike Python's #PyLong_AsUnsignedLong and #PyLong_AsUnsignedLongLong, these unsigned integer
* parsing functions fall back to calling #PyNumber_Index when their argument is not a
* `PyLongObject`. This matches Python's signed integer parsing functions which also fall back to
* calling #PyNumber_Index.
*/
[[nodiscard]] uint8_t PyC_Long_AsU8(PyObject *value);
[[nodiscard]] uint16_t PyC_Long_AsU16(PyObject *value);
[[nodiscard]] uint32_t PyC_Long_AsU32(PyObject *value);
/**
* #PyLong_AsUnsignedLongLong, unlike #PyLong_AsLongLong, does not fall back to calling
* #PyNumber_Index when its argument is not a `PyLongObject` instance. To match parsing signed
* integer types with #PyLong_AsLongLong, this function performs the #PyNumber_Index fallback, if
* necessary, before calling #PyLong_AsUnsignedLongLong.
*/
[[nodiscard]] uint64_t PyC_Long_AsU64(PyObject *value);
/** Inline so type signatures match as expected. */
[[nodiscard]] Py_LOCAL_INLINE(int32_t) PyC_Long_AsI32(PyObject *value)
{
return int32_t(PyLong_AsInt(value));
}
[[nodiscard]] Py_LOCAL_INLINE(int64_t) PyC_Long_AsI64(PyObject *value)
{
return int64_t(PyLong_AsLongLong(value));
}
/* Utils for format string in `struct` module style syntax. */
[[nodiscard]] char PyC_StructFmt_type_from_str(const char *typestr);
[[nodiscard]] bool PyC_StructFmt_type_is_float_any(char format);
[[nodiscard]] bool PyC_StructFmt_type_is_int_any(char format);
[[nodiscard]] bool PyC_StructFmt_type_is_byte(char format);
[[nodiscard]] bool PyC_StructFmt_type_is_bool(char format);
/**
* Create a `str` from `std::string`, wraps #PyC_UnicodeFromBytesAndSize.
*/
[[nodiscard]] PyObject *PyC_UnicodeFromStdStr(const std::string &str);
[[nodiscard]] inline PyObject *PyC_Tuple_Pack_F32(const Span<float> values)
{
return PyC_Tuple_PackArray_F32(values.data(), values.size());
}
[[nodiscard]] inline PyObject *PyC_Tuple_Pack_F64(const Span<double> values)
{
return PyC_Tuple_PackArray_F64(values.data(), values.size());
}
[[nodiscard]] inline PyObject *PyC_Tuple_Pack_I32(const Span<int> values)
{
return PyC_Tuple_PackArray_I32(values.data(), values.size());
}
[[nodiscard]] inline PyObject *PyC_Tuple_Pack_I32FromBool(const Span<int> values)
{
return PyC_Tuple_PackArray_I32FromBool(values.data(), values.size());
}
[[nodiscard]] inline PyObject *PyC_Tuple_Pack_Bool(const Span<bool> values)
{
return PyC_Tuple_PackArray_Bool(values.data(), values.size());
}
/**
* Check that all keys in `dict` are Python strings.
*
* Use this to validate keyword arguments from `tp_call` which,
* unlike regular Python function calls, does not enforce string keys.
*/
[[nodiscard]] bool PyC_Dict_CheckKeysAreStrings(PyObject *dict);
/**
* Create a `memoryview` from the contents of `info`,
* similar to #PyMemoryView_FromBuffer.
*
* Unlike #PyMemoryView_FromBuffer the returned `memoryview` takes ownership of `info->buf`:
* when the last reference to the `memoryview`
* (or any `memoryview` derived from it via `cast()` / slicing) is released,
* the buffer is freed with #MEM_delete_void.
*
* \return A new `memoryview` reference, or null with an exception set on failure.
* `info->buf` is freed even when the function returns null.
*/
[[nodiscard]] PyObject *PyC_MemoryView_FromBufferOwned(const Py_buffer *info);
} // namespace blender

View File

@@ -0,0 +1,70 @@
/* SPDX-FileCopyrightText: 2025 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
*
* Functions relating to compatibility across Python versions.
*/
#include <Python.h> /* IWYU pragma: keep. */
#include "BLI_utildefines.h" /* IWYU pragma: keep. */
#include "python_compat.hh" /* IWYU pragma: keep. */
int _PyArg_CheckPositional(const char *name, Py_ssize_t nargs, Py_ssize_t min, Py_ssize_t max)
{
BLI_assert(min >= 0);
BLI_assert(min <= max);
if (nargs < min) {
if (name != nullptr) {
PyErr_Format(PyExc_TypeError,
"%.200s expected %s%zd argument%s, got %zd",
name,
(min == max ? "" : "at least "),
min,
min == 1 ? "" : "s",
nargs);
}
else {
PyErr_Format(PyExc_TypeError,
"unpacked tuple should have %s%zd element%s,"
" but has %zd",
(min == max ? "" : "at least "),
min,
min == 1 ? "" : "s",
nargs);
}
return 0;
}
if (nargs == 0) {
return 1;
}
if (nargs > max) {
if (name != nullptr) {
PyErr_Format(PyExc_TypeError,
"%.200s expected %s%zd argument%s, got %zd",
name,
(min == max ? "" : "at most "),
max,
max == 1 ? "" : "s",
nargs);
}
else {
PyErr_Format(PyExc_TypeError,
"unpacked tuple should have %s%zd element%s,"
" but has %zd",
(min == max ? "" : "at most "),
max,
max == 1 ? "" : "s",
nargs);
}
return 0;
}
return 1;
}

View File

@@ -0,0 +1,28 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
* \brief header-only compatibility defines.
*
* \note this header should not be removed/cleaned where Python is used.
* Because its required for Blender to build against different versions of Python.
*/
#pragma once
#include <Python.h>
/* This code is not placed in the blender namespace, as it is meant to replace Python functions
* in the global namespace. */
/* Python 3.14 made some changes, use the "new" names. */
#if PY_VERSION_HEX < 0x030e0000
# define Py_HashPointer _Py_HashPointer
# define PyThreadState_GetUnchecked _PyThreadState_UncheckedGet
/* TODO: Support: `PyDict_Pop`, it has different arguments. */
#endif
/** Removed in Python 3.13. */
int _PyArg_CheckPositional(const char *name, Py_ssize_t nargs, Py_ssize_t min, Py_ssize_t max);

View File

@@ -0,0 +1,38 @@
/* SPDX-FileCopyrightText: 2023 Blender Authors
*
* SPDX-License-Identifier: GPL-2.0-or-later */
/** \file
* \ingroup pygen
* \brief header-only utilities
* \note light addition to Python.h, use py_capi_utils.hh for larger features.
*/
#pragma once
#include <Python.h>
namespace blender {
#define PyTuple_SET_ITEMS(op_arg, ...) \
{ \
PyTupleObject *op = (PyTupleObject *)op_arg; \
PyObject **ob_items = op->ob_item; \
CHECK_TYPE_ANY(op_arg, PyObject *, PyTupleObject *); \
BLI_assert(VA_NARGS_COUNT(__VA_ARGS__) == PyTuple_GET_SIZE(op)); \
ARRAY_SET_ITEMS(ob_items, __VA_ARGS__); \
} \
(void)0
/**
* Append & transfer ownership to the list,
* avoids inline #Py_DECREF all over (which is quite a large macro).
*/
Py_LOCAL_INLINE(int) PyList_APPEND(PyObject *op, PyObject *v)
{
int ret = PyList_Append(op, v);
Py_DecRef(v);
return ret;
}
} // namespace blender