Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 23 additions & 4 deletions crates/processing_glfw/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,18 +75,31 @@ impl Default for AppliedWindow {

impl GlfwContext {
pub fn new(width: u32, height: u32, transparent: bool) -> Result<Self> {
let mut ctx = Self::init()?;
ctx.open_window(width, height, transparent);
Ok(ctx)
}

/// Start GLFW with no window yet, so monitors can be read before the sketch has a size.
pub fn init() -> Result<Self> {
if processing_render::ci::enabled() {
// Without the menubar GLFW never becomes a foreground (Dock, focus-taking) app on macOS.
glfw::init_hint(glfw::InitHint::CocoaMenubar(false));
}
let mut glfw = glfw::init(glfw::fail_on_errors).unwrap();
let main = Self::spawn_window(&mut glfw, width, height, transparent, "Processing");
let glfw = glfw::init(glfw::fail_on_errors).unwrap();
Ok(Self {
glfw,
windows: vec![main],
windows: Vec::new(),
})
}

/// Create the main window; a context has exactly one.
pub fn open_window(&mut self, width: u32, height: u32, transparent: bool) {
debug_assert!(self.windows.is_empty(), "the main window already exists");
let main = Self::spawn_window(&mut self.glfw, width, height, transparent, "Processing");
self.windows.insert(0, main);
}

/// Create a GLFW window on the shared instance and return its per-window state.
fn spawn_window(
glfw: &mut Glfw,
Expand Down Expand Up @@ -151,7 +164,8 @@ impl GlfwContext {
}
}

fn sync_monitors(&mut self) {
/// Mirror the connected monitors into the engine; needs the engine initialized.
pub fn sync_monitors(&mut self) {
let primary_name = self
.glfw
.with_primary_monitor(|_, monitor| monitor.and_then(|m| m.get_name()));
Expand Down Expand Up @@ -249,6 +263,11 @@ impl GlfwContext {

/// Create the render surface for the main window (index 0).
pub fn create_surface(&mut self, width: u32, height: u32, transparent: bool) -> Result<Entity> {
if self.windows.is_empty() {
return Err(processing_core::error::ProcessingError::InvalidArgument(
"the main window has not been opened".to_string(),
));
}
self.create_surface_for(0, width, height, transparent)
}

Expand Down
44 changes: 35 additions & 9 deletions crates/processing_pyo3/src/graphics.rs
Original file line number Diff line number Diff line change
Expand Up @@ -972,6 +972,35 @@ impl Graphics {
}
}

thread_local! {
/// GLFW and the engine started before the first window, so displays can be read in `setup()`.
static EARLY_CONTEXT: std::cell::RefCell<Option<GlfwContext>> = const { std::cell::RefCell::new(None) };
}

/// Start GLFW and the engine with no window, and mirror the monitors.
fn start_context(asset_path: &str, log_level: Option<&str>) -> PyResult<GlfwContext> {
let mut glfw_ctx = GlfwContext::init().map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;

let mut config = Config::new();
config.set(ConfigKey::AssetRootPath, asset_path.to_string());
if let Some(level) = log_level {
config.set(ConfigKey::LogLevel, level.to_string());
}
init(config).map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
glfw_ctx.sync_monitors();
Ok(glfw_ctx)
}

/// Start the context ahead of `size()`; the first windowed `Graphics` adopts it.
pub(crate) fn start_early(asset_path: &str, log_level: Option<&str>) -> PyResult<()> {
if EARLY_CONTEXT.with(|early| early.borrow().is_some()) {
return Ok(());
}
let ctx = start_context(asset_path, log_level)?;
EARLY_CONTEXT.with(|early| *early.borrow_mut() = Some(ctx));
Ok(())
}

#[pymethods]
impl Graphics {
/// Opaque id for this object.
Expand All @@ -987,15 +1016,12 @@ impl Graphics {
log_level: Option<&str>,
transparent: bool,
) -> PyResult<Self> {
let mut glfw_ctx = GlfwContext::new(width, height, transparent)
.map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;

let mut config = Config::new();
config.set(ConfigKey::AssetRootPath, asset_path.to_string());
if let Some(level) = log_level {
config.set(ConfigKey::LogLevel, level.to_string());
}
init(config).map_err(|e| PyRuntimeError::new_err(format!("{e}")))?;
let started = EARLY_CONTEXT.with(|early| early.borrow_mut().take());
let mut glfw_ctx = match started {
Some(ctx) => ctx,
None => start_context(asset_path, log_level)?,
};
glfw_ctx.open_window(width, height, transparent);

let surface = glfw_ctx
.create_surface(width, height, transparent)
Expand Down
9 changes: 9 additions & 0 deletions crates/processing_pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1255,6 +1255,15 @@ pub mod processing_py {
update_loop_state(|s| s.exit_requested = false);
let exit_requested = || LOOP_STATE.with(|s| s.get().exit_requested);

// the engine starts before setup() so it can size the sketch to the display
if get_graphics(module)?.is_none() {
let asset_path = get_asset_root()?;
graphics::start_early(&asset_path, Some("warn"))?;
let sys = PyModule::import(py, "sys")?;
let frame = sys.getattr("_getframe")?.call1((0,))?;
surface::sync_display_globals(&frame.getattr("f_globals")?)?;
}

if let Some(ref setup) = setup_fn {
setup.call0()?;
}
Expand Down
5 changes: 5 additions & 0 deletions crates/processing_pyo3/src/surface.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,11 @@ pub fn sync_globals(
set_tracked(globals, "window_x", wx)?;
set_tracked(globals, "window_y", wy)?;

sync_display_globals(globals)
}

/// `display_width`/`display_height`, valid as soon as the engine has started.
pub fn sync_display_globals(globals: &Bound<'_, PyAny>) -> PyResult<()> {
let (dw, dh) = match monitor::primary()? {
Some(m) => (m.width()?, m.height()?),
None => (0, 0),
Expand Down
Loading