Skip to content

Commit a33ed5b

Browse files
authored
Python draw setup functions (#42)
1 parent 64ff895 commit a33ed5b

File tree

2 files changed

+31
-21
lines changed

2 files changed

+31
-21
lines changed
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from processing import *
22

3-
# TODO: this should be in a setup function
4-
size(800, 600)
3+
def setup():
4+
size(800, 600)
55

66
def draw():
77
background(220)
@@ -12,4 +12,4 @@ def draw():
1212
rect(100, 100, 200, 150)
1313

1414
# TODO: this should happen implicitly on module load somehow
15-
run(draw)
15+
run()

crates/processing_pyo3/src/lib.rs

Lines changed: 28 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ mod glfw;
1212
mod graphics;
1313

1414
use graphics::{Graphics, get_graphics, get_graphics_mut};
15-
use pyo3::{exceptions::PyRuntimeError, prelude::*, types::PyAny};
15+
use pyo3::{exceptions::PyRuntimeError, prelude::*};
1616

1717
#[pymodule]
1818
fn processing(m: &Bound<'_, PyModule>) -> PyResult<()> {
@@ -38,27 +38,37 @@ fn size(module: &Bound<'_, PyModule>, width: u32, height: u32) -> PyResult<()> {
3838
}
3939

4040
#[pyfunction]
41-
#[pyo3(pass_module, signature = (draw_fn=None))]
42-
fn run(module: &Bound<'_, PyModule>, draw_fn: Option<Py<PyAny>>) -> PyResult<()> {
43-
loop {
44-
{
45-
let mut graphics = get_graphics_mut(module)?;
46-
if !graphics.surface.poll_events() {
47-
break;
41+
#[pyo3(pass_module)]
42+
fn run(module: &Bound<'_, PyModule>) -> PyResult<()> {
43+
Python::attach(|py| {
44+
let builtins = PyModule::import(py, "builtins")?;
45+
let locals = builtins.getattr("locals")?.call0()?;
46+
47+
let setup_fn = locals.get_item("setup")?;
48+
let draw_fn = locals.get_item("draw")?;
49+
50+
// call setup
51+
setup_fn.call0()?;
52+
53+
// start draw loop
54+
loop {
55+
{
56+
let mut graphics = get_graphics_mut(module)?;
57+
if !graphics.surface.poll_events() {
58+
break;
59+
}
60+
graphics.begin_draw()?;
4861
}
49-
graphics.begin_draw()?;
50-
}
5162

52-
if let Some(ref draw) = draw_fn {
53-
Python::attach(|py| {
54-
draw.call0(py)
55-
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))
56-
})?;
63+
draw_fn
64+
.call0()
65+
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
66+
67+
get_graphics(module)?.end_draw()?;
5768
}
5869

59-
get_graphics(module)?.end_draw()?;
60-
}
61-
Ok(())
70+
Ok(())
71+
})
6272
}
6373

6474
#[pyfunction]

0 commit comments

Comments
 (0)