77//! receiver.
88//!
99//! To allow Python users to create a similar experience, we provide module-level
10- //! functions that forward to a singleton Graphics object bepub(crate) pub(crate) hind the scenes.
10+ //! functions that forward to a singleton Graphics object pub(crate) behind the scenes.
1111mod glfw;
1212mod graphics;
1313
1414use graphics:: { Graphics , get_graphics, get_graphics_mut} ;
1515use pyo3:: { exceptions:: PyRuntimeError , prelude:: * } ;
1616
17+ use std:: env;
18+
1719#[ pymodule]
1820fn processing ( m : & Bound < ' _ , PyModule > ) -> PyResult < ( ) > {
1921 m. add_class :: < Graphics > ( ) ?;
@@ -26,13 +28,36 @@ fn processing(m: &Bound<'_, PyModule>) -> PyResult<()> {
2628 m. add_function ( wrap_pyfunction ! ( no_stroke, m) ?) ?;
2729 m. add_function ( wrap_pyfunction ! ( stroke_weight, m) ?) ?;
2830 m. add_function ( wrap_pyfunction ! ( rect, m) ?) ?;
31+ m. add_function ( wrap_pyfunction ! ( image, m) ?) ?;
2932 Ok ( ( ) )
3033}
3134
35+ fn get_asset_root ( ) -> PyResult < String > {
36+ if let Ok ( val) = env:: var ( "PROCESSING_ASSET_ROOT" ) {
37+ return Ok ( val) ;
38+ }
39+
40+ Python :: attach ( |py| {
41+ let sys = PyModule :: import ( py, "sys" ) ?;
42+ let argv: Vec < String > = sys. getattr ( "argv" ) ?. extract ( ) ?;
43+ let filename: & str = argv[ 0 ] . as_str ( ) ;
44+ let os = PyModule :: import ( py, "os" ) ?;
45+ let path = os. getattr ( "path" ) ?;
46+ let dirname = path. getattr ( "dirname" ) ?. call1 ( ( filename, ) ) ?;
47+ let abspath = path. getattr ( "abspath" ) ?. call1 ( ( dirname, ) ) ?;
48+ let asset_root = path
49+ . getattr ( "join" ) ?
50+ . call1 ( ( abspath, "assets" ) ) ?
51+ . to_string ( ) ;
52+ Ok ( asset_root)
53+ } )
54+ }
55+
3256#[ pyfunction]
3357#[ pyo3( pass_module) ]
3458fn size ( module : & Bound < ' _ , PyModule > , width : u32 , height : u32 ) -> PyResult < ( ) > {
35- let graphics = Graphics :: new ( width, height) ?;
59+ let asset_path: String = get_asset_root ( ) ?;
60+ let graphics = Graphics :: new ( width, height, asset_path. as_str ( ) ) ?;
3661 module. setattr ( "_graphics" , graphics) ?;
3762 Ok ( ( ) )
3863}
@@ -122,3 +147,9 @@ fn rect(
122147) -> PyResult < ( ) > {
123148 get_graphics ( module) ?. rect ( x, y, w, h, tl, tr, br, bl)
124149}
150+
151+ #[ pyfunction]
152+ #[ pyo3( pass_module, signature = ( image_file) ) ]
153+ fn image ( module : & Bound < ' _ , PyModule > , image_file : & str ) -> PyResult < ( ) > {
154+ get_graphics ( module) ?. image ( image_file)
155+ }
0 commit comments