Blender V5.3
bpy_rna_wm.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2026 Blender Authors
2 *
3 * SPDX-License-Identifier: GPL-2.0-or-later */
4
10
11#define PY_SSIZE_T_CLEAN
12
13#include <Python.h>
14
15#include <cstring>
16#include <optional>
17
18#include "MEM_guardedalloc.h"
19
20#include "DNA_vec_types.h"
22
23#include "BLI_math_base_c.hh"
25#include "BLI_rect.hh"
26#include "BLI_utildefines.hh"
27
28#include "BKE_global.hh"
29
30#include "WM_api.hh"
31
33#include "../generic/python_compat.hh" /* IWYU pragma: keep. */
34
35#include "bpy_capi_utils.hh"
36#include "bpy_rna.hh"
37#include "bpy_rna_callback.hh"
38#include "bpy_rna_wm.hh"
39
40namespace blender {
41
42/* -------------------------------------------------------------------- */
48
50 /* Wrap. */
51 pyrna_WindowManager_clipboard_doc,
52 "Clipboard text storage.\n"
53 "\n"
54 ":type: str\n");
55static PyObject *pyrna_WindowManager_clipboard_get(PyObject * /*self*/, void * /*flag*/)
56{
57 int text_len = 0;
58 /* No need for UTF8 validation as #PyC_UnicodeFromBytesAndSize handles invalid byte sequences. */
59 char *text = WM_clipboard_text_get(false, false, &text_len);
60 PyObject *result = PyC_UnicodeFromBytesAndSize(text ? text : "", text_len);
61 if (text != nullptr) {
62 MEM_delete(text);
63 }
64 return result;
65}
66
67static int pyrna_WindowManager_clipboard_set(PyObject * /*self*/, PyObject *value, void * /*flag*/)
68{
69 PyObject *value_coerce = nullptr;
70 const char *text = PyC_UnicodeAsBytes(value, &value_coerce);
71 if (text == nullptr) {
72 return -1;
73 }
74 WM_clipboard_text_set(text, false);
75 Py_XDECREF(value_coerce);
76 return 0;
77}
78
80
81/* -------------------------------------------------------------------- */
84
86 /* Wrap. */
87 pyrna_draw_cursor_add_doc,
88 ".. classmethod:: draw_cursor_add(callback, args, space_type, region_type)\n"
89 "\n"
90 " Add a new draw cursor handler to this space type.\n"
91 " It will be called every time the cursor for the specified region in the space "
92 "type will be drawn.\n"
93 " Note: All arguments are positional only for now.\n"
94 "\n"
95 " :param callback:\n"
96 " A function that will be called when the cursor is drawn.\n"
97 " It gets the specified arguments as input with the mouse position "
98 "(``tuple[int, int]``) as last argument.\n"
99 " :type callback: Callable[..., Any]\n"
100 " :param args: Arguments that will be passed to the callback.\n"
101 " :type args: tuple[Any, ...]\n"
102 " :param space_type: The space type the callback draws in; for example ``VIEW_3D``. "
103 "(:class:`bpy.types.Space.type`)\n"
104 " :type space_type: str\n"
105 " :param region_type: The region type the callback draws in; usually ``WINDOW``. "
106 "(:class:`bpy.types.Region.type`)\n"
107 " :type region_type: str\n"
108 " :return: Handler that can be removed later on.\n"
109 " :rtype: object\n");
111 /* Wrap. */
112 pyrna_draw_cursor_remove_doc,
113 ".. classmethod:: draw_cursor_remove(handler)\n"
114 "\n"
115 " Remove a draw cursor handler that was added previously.\n"
116 "\n"
117 " :param handler: The draw cursor handler that should be removed.\n"
118 " :type handler: object\n");
119
121 "draw_cursor_add",
122 static_cast<PyCFunction>(pyrna_callback_classmethod_add),
123 METH_VARARGS | METH_CLASS,
124 pyrna_draw_cursor_add_doc,
125};
126
128 "draw_cursor_remove",
129 static_cast<PyCFunction>(pyrna_callback_classmethod_remove),
130 METH_VARARGS | METH_CLASS,
131 pyrna_draw_cursor_remove_doc,
132};
133
135 "clipboard",
138 pyrna_WindowManager_clipboard_doc,
139 nullptr,
140};
141
143
144/* -------------------------------------------------------------------- */
147
149 /* Wrap. */
150 bpy_rna_window_screenshot_doc,
151 ".. method:: screenshot(*, region=None, use_alpha=False)\n"
152 "\n"
153 " Capture the windows pixel data.\n"
154 "\n"
155 " :param region: The region to capture, or ``None`` to capture all.\n"
156 " Each int pair represents a pixel coordinate "
157 "(the end value is not inclusive, matching Python slicing): "
158 "((min_x, min_y), (max_x, max_y))\n"
159 " :type region: tuple[tuple[int, int], tuple[int, int]] | None\n"
160 " :param use_alpha: When false the alpha channel is fully opaque. "
161 "Otherwise alpha values from the window's frame-buffer are returned as-is.\n"
162 " :type use_alpha: bool\n"
163 " :return: A read-only :class:`memoryview` of shape ``(height, width, 4)`` "
164 "and format ``'B'``, viewing the captured RGBA pixels (rows ordered from bottom to top).\n"
165 " :rtype: memoryview\n");
166static PyObject *bpy_rna_window_screenshot(PyObject *self, PyObject *args, PyObject *kwds)
167{
168 BPy_StructRNA *pyrna = reinterpret_cast<BPy_StructRNA *>(self);
169 wmWindow *win = static_cast<wmWindow *>(pyrna->ptr->data);
170
171 std::optional<rcti> region;
172 bool use_alpha = false;
173
174 static const char *_keywords[] = {"region", "use_alpha", nullptr};
175 static _PyArg_Parser _parser = {
176 "|$" /* Optional, keyword only arguments. */
177 "O&" /* `region` */
178 "O&" /* `use_alpha` */
179 ":screenshot",
180 _keywords,
181 nullptr,
182 };
183 if (!_PyArg_ParseTupleAndKeywordsFast(
184 args, kwds, &_parser, PyC_ParseOptionalRectI, &region, PyC_ParseBool, &use_alpha))
185 {
186 return nullptr;
187 }
188
189 if (G.background) {
190 PyErr_SetString(PyExc_RuntimeError, "Window.screenshot() is not available in background mode");
191 return nullptr;
192 }
193
195
196 int dumprect_size[2];
197 uint8_t *dumprect = WM_window_pixels_read(C, win, dumprect_size);
198 if (dumprect == nullptr) {
199 PyErr_SetString(PyExc_RuntimeError, "Failed to read window pixels");
200 return nullptr;
201 }
202
203 if (region) {
204 /* `xmax` / `ymax` are end-exclusive (Python slicing); clamp to `[0, dim]`,
205 * keeping `max >= min` so an inverted/out-of-range region collapses to a
206 * zero-sized rect rather than a negative one. */
207 rcti safe = {
208 .xmin = max_ii(0, region->xmin),
209 .xmax = min_ii(dumprect_size[0], region->xmax),
210 .ymin = max_ii(0, region->ymin),
211 .ymax = min_ii(dumprect_size[1], region->ymax),
212 };
213 safe.xmax = max_ii(safe.xmin, safe.xmax);
214 safe.ymax = max_ii(safe.ymin, safe.ymax);
215
216 const int2 crop_size = {BLI_rcti_size_x(&safe), BLI_rcti_size_y(&safe)};
217 if (crop_size.x > 0 && crop_size.y > 0) {
218 const size_t row_bytes = size_t(crop_size.x) * 4;
219 const size_t src_stride = size_t(dumprect_size[0]) * 4;
220
221 uint8_t *cropped = MEM_new_array_uninitialized<uint8_t>(row_bytes * crop_size.y, __func__);
222 for (int y = 0; y < crop_size.y; y++) {
223 const uint8_t *src = dumprect + (size_t(safe.ymin + y) * src_stride) +
224 (size_t(safe.xmin) * 4);
225 memcpy(cropped + size_t(y) * row_bytes, src, row_bytes);
226 }
227 MEM_delete(dumprect);
228 dumprect = cropped;
229 dumprect_size[0] = crop_size.x;
230 dumprect_size[1] = crop_size.y;
231 }
232 else {
233 /* Empty region: free the full-window buffer and substitute a 1-byte
234 * placeholder so #PyC_MemoryView_FromBufferOwned still receives a
235 * non-null `info->buf`; the resulting memoryview has shape (0, 0, 4)
236 * and zero length, so the placeholder is never accessed. */
237 MEM_delete(dumprect);
238 dumprect = MEM_new_array_uninitialized<uint8_t>(1, __func__);
239 dumprect_size[0] = 0;
240 dumprect_size[1] = 0;
241 }
242 }
243
244 /* Force alpha to fully opaque unless the caller asked for raw alpha values. */
245 if (!use_alpha) {
246 const size_t total_bytes = size_t(dumprect_size[0]) * dumprect_size[1] * 4;
247 for (size_t i = 3; i < total_bytes; i += 4) {
248 dumprect[i] = 0xff;
249 }
250 }
251
252 Py_ssize_t shape[3] = {dumprect_size[1], dumprect_size[0], 4};
253 Py_ssize_t strides[3] = {Py_ssize_t(dumprect_size[0]) * 4, 4, 1};
254 Py_buffer info;
255 memset(&info, 0, sizeof(info));
256 info.buf = dumprect;
257 info.len = shape[0] * shape[1] * shape[2];
258 info.itemsize = 1;
259 info.readonly = 1;
260 info.format = const_cast<char *>("B");
261 info.ndim = 3;
262 info.shape = shape;
263 info.strides = strides;
264 return PyC_MemoryView_FromBufferOwned(&info);
265}
266
267#ifdef __GNUC__
268# ifdef __clang__
269# pragma clang diagnostic push
270# pragma clang diagnostic ignored "-Wcast-function-type"
271# else
272# pragma GCC diagnostic push
273# pragma GCC diagnostic ignored "-Wcast-function-type"
274# endif
275#endif
276
278 "screenshot",
279 reinterpret_cast<PyCFunction>(bpy_rna_window_screenshot),
280 METH_VARARGS | METH_KEYWORDS,
281 bpy_rna_window_screenshot_doc,
282};
283
284#ifdef __GNUC__
285# ifdef __clang__
286# pragma clang diagnostic pop
287# else
288# pragma GCC diagnostic pop
289# endif
290#endif
291
293
294} // namespace blender
Read Blender memory allocation and freeing.
#define C
Definition RandGen.cpp:29
BMesh Iterators.
static PyObject * bpy_rna_window_screenshot(PyObject *self, PyObject *args, PyObject *kwds)
PyGetSetDef BPY_rna_windowmanager_clipboard_getset_def
PyMethodDef BPY_rna_window_screenshot_method_def
int PyC_ParseBool(PyObject *o, void *p)
PyObject * PyC_MemoryView_FromBufferOwned(const Py_buffer *info)
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
PyMethodDef BPY_rna_windowmanager_draw_cursor_remove_method_def
PyDoc_STRVAR(bpy_bm_new_doc, ".. function:: new(*, use_operators=True)\n" "\n" " :param use_operators: Support calling operators in :mod:`bmesh.ops` (uses some " "extra memory per vert/edge/face).\n" " :type use_operators: bool\n" " :return: Return a new, empty BMesh.\n" " :rtype: :class:`bmesh.types.BMesh`\n")
uint8_t * WM_window_pixels_read(bContext *C, wmWindow *win, int r_size[2])
Definition wm_draw.cc:1575
MINLINE int max_ii(int a, int b)
Global G
Definition blender.cc:57
BLI_INLINE int BLI_rcti_size_y(const struct rcti *rct)
Definition BLI_rect.hh:207
static PyObject * pyrna_WindowManager_clipboard_get(PyObject *, void *)
Definition bpy_rna_wm.cc:55
PyMethodDef BPY_rna_windowmanager_draw_cursor_add_method_def
VecBase< int32_t, 2 > int2
struct bContext * BPY_context_get()
PyObject * pyrna_callback_classmethod_add(PyObject *, PyObject *args)
unsigned char uint8_t
Definition BKE_text.h:79
BLI_INLINE int BLI_rcti_size_x(const struct rcti *rct)
Definition BLI_rect.hh:203
PyObject * pyrna_callback_classmethod_remove(PyObject *, PyObject *args)
const char * PyC_UnicodeAsBytes(PyObject *py_str, PyObject **r_coerce)
char * WM_clipboard_text_get(bool selection, bool ensure_utf8, int *r_len)
static int pyrna_WindowManager_clipboard_set(PyObject *, PyObject *value, void *)
Definition bpy_rna_wm.cc:67
void WM_clipboard_text_set(const char *buf, bool selection)
int PyC_ParseOptionalRectI(PyObject *o, void *p)
PyObject * PyC_UnicodeFromBytesAndSize(const char *str, Py_ssize_t size)
MINLINE int min_ii(int a, int b)
header-only compatibility defines.
PyObject_HEAD std::optional< PointerRNA > ptr
Definition bpy_rna.hh:133