use anyhow::Result;
pub fn configure_metal_layer_for_performance(window: &winit::window::Window) -> Result<()> {
#[cfg(target_os = "macos")]
{
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2_app_kit::NSView;
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
log::info!("🎯 Configuring CAMetalLayer for 60 FPS performance");
let window_handle = window.window_handle()?;
let ns_view_ptr = match window_handle.as_raw() {
RawWindowHandle::AppKit(handle) => handle.ns_view.as_ptr(),
_ => anyhow::bail!("Not a macOS AppKit window"),
};
unsafe {
let ns_view = ns_view_ptr as *mut NSView;
let view = &*ns_view;
let layer: Retained<AnyObject> = objc2::msg_send![view, layer];
let metal_layer_ptr = Retained::as_ptr(&layer);
let class_obj: *const objc2::runtime::AnyClass =
objc2::msg_send![metal_layer_ptr, class];
let class_name = objc2::runtime::AnyClass::name(&*class_obj);
let class_name_str = class_name.to_str().unwrap_or("Unknown");
log::info!("Layer class: {}", class_name_str);
if class_name_str == "CAMetalLayer" {
let _: () = objc2::msg_send![metal_layer_ptr, setOpaque: false];
let _: () = objc2::msg_send![metal_layer_ptr, setOpacity: 1.0_f32];
let _: () = objc2::msg_send![metal_layer_ptr, setDisplaySyncEnabled: false];
let display_sync_enabled: bool =
objc2::msg_send![metal_layer_ptr, displaySyncEnabled];
log::info!(
"✅ CAMetalLayer configured: displaySyncEnabled = {}",
display_sync_enabled
);
if display_sync_enabled {
log::warn!(
" ⚠️ displaySyncEnabled is still true! Setting may not have taken effect."
);
} else {
log::info!(" Expected: present() will no longer block for VSync");
log::info!(" Target: 60+ FPS instead of ~20 FPS");
}
} else {
log::warn!(
"❌ Layer is not CAMetalLayer (found: {}), skipping configuration",
class_name_str
);
log::warn!(" This is normal if called before wgpu creates the Metal surface");
log::warn!(" Will retry after renderer initialization");
anyhow::bail!("Layer is not yet a CAMetalLayer");
}
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = window; }
Ok(())
}
pub fn set_layer_opacity(window: &winit::window::Window, opacity: f32) -> Result<()> {
#[cfg(target_os = "macos")]
{
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2_app_kit::NSView;
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
let clamped = opacity.clamp(0.0, 1.0);
let window_handle = window.window_handle()?;
let ns_view_ptr = match window_handle.as_raw() {
RawWindowHandle::AppKit(handle) => handle.ns_view.as_ptr(),
_ => anyhow::bail!("Not a macOS AppKit window"),
};
if ns_view_ptr.is_null() {
anyhow::bail!("NSView pointer is null");
}
unsafe {
let ns_view = ns_view_ptr as *mut NSView;
let layer: Retained<AnyObject> = objc2::msg_send![ns_view, layer];
let metal_layer_ptr = Retained::as_ptr(&layer);
let _: () = objc2::msg_send![metal_layer_ptr, setOpaque: false];
let _: () = objc2::msg_send![metal_layer_ptr, setOpacity: clamped];
let current_opacity: f32 = objc2::msg_send![metal_layer_ptr, opacity];
log::debug!(
"CAMetalLayer content opacity set to {:.3} (reported {:.3})",
clamped,
current_opacity
);
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = (window, opacity);
}
Ok(())
}
pub fn set_window_background_for_translucency(
window: &winit::window::Window,
translucent: bool,
) -> Result<()> {
#[cfg(target_os = "macos")]
{
use objc2::rc::Retained;
use objc2_app_kit::{NSColor, NSView, NSWindow};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
let window_handle = window.window_handle()?;
let ns_view_ptr = match window_handle.as_raw() {
RawWindowHandle::AppKit(handle) => handle.ns_view.as_ptr(),
_ => anyhow::bail!("Not a macOS AppKit window"),
};
if ns_view_ptr.is_null() {
anyhow::bail!("NSView pointer is null");
}
unsafe {
let ns_view = ns_view_ptr as *mut NSView;
let ns_window: Option<Retained<NSWindow>> = objc2::msg_send![ns_view, window];
let Some(ns_window) = ns_window else {
anyhow::bail!("NSView is not installed in an NSWindow");
};
let color = if translucent {
NSColor::clearColor()
} else {
NSColor::windowBackgroundColor()
};
ns_window.setBackgroundColor(Some(&color));
if translucent {
ensure_titlebar_backing_bar(&ns_window)?;
} else {
remove_titlebar_backing_bar(&ns_window);
}
log::debug!(
"NSWindow background set to {} (translucent: {}); titlebar bar {}",
if translucent {
"clear"
} else {
"windowBackgroundColor"
},
translucent,
if translucent { "installed" } else { "removed" }
);
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = (window, translucent);
}
Ok(())
}
#[cfg(target_os = "macos")]
const TITLEBAR_BACKING_BAR_ID: &str = "par-term-titlebar-backing-bar";
#[cfg(target_os = "macos")]
fn find_titlebar_backing_bar(
frame_view: &objc2_app_kit::NSView,
) -> Option<objc2::rc::Retained<objc2_app_kit::NSView>> {
use objc2::rc::Retained;
use objc2::runtime::AnyObject;
use objc2_app_kit::NSView;
use objc2_foundation::NSString;
unsafe {
let subs: Retained<AnyObject> = objc2::msg_send![frame_view, subviews];
let count: usize = objc2::msg_send![&*subs, count];
for i in 0..count {
let sub: *mut AnyObject = objc2::msg_send![&*subs, objectAtIndex: i];
let ident: *mut AnyObject = objc2::msg_send![sub, identifier];
if ident.is_null() {
continue;
}
if (&*(ident as *const NSString)).to_string() == TITLEBAR_BACKING_BAR_ID {
return Retained::retain(sub as *mut NSView);
}
}
}
None
}
#[cfg(target_os = "macos")]
fn titlebar_strip(
layout_rect: &objc2_foundation::NSRect,
frame_bounds: &objc2_foundation::NSRect,
) -> Option<objc2_foundation::NSRect> {
use objc2_foundation::{NSPoint, NSSize};
let height = frame_bounds.size.height - layout_rect.size.height;
if height <= 1.0 {
return None;
}
Some(objc2_foundation::NSRect {
origin: NSPoint {
x: 0.0,
y: layout_rect.size.height,
},
size: NSSize {
width: frame_bounds.size.width,
height,
},
})
}
#[cfg(target_os = "macos")]
fn ensure_titlebar_backing_bar(ns_window: &objc2_app_kit::NSWindow) -> Result<()> {
use objc2::MainThreadMarker;
use objc2_app_kit::{
NSAutoresizingMaskOptions, NSBox, NSBoxType, NSTitlePosition, NSWindowOrderingMode,
};
use objc2_foundation::NSString;
let Some(frame_view) = ns_window
.contentView()
.and_then(|cv| unsafe { cv.superview() })
else {
anyhow::bail!("window has no frame view (not a titled window?)");
};
if let Some(bar) = find_titlebar_backing_bar(&frame_view) {
match titlebar_strip(&ns_window.contentLayoutRect(), &frame_view.bounds()) {
Some(strip) => {
bar.setFrame(strip);
bar.setHidden(false);
if let Some(b) = bar.downcast_ref::<NSBox>() {
b.setFillColor(&objc2_app_kit::NSColor::windowBackgroundColor());
}
}
None => bar.setHidden(true),
}
return Ok(());
}
let bar_frame = titlebar_strip(&ns_window.contentLayoutRect(), &frame_view.bounds())
.ok_or_else(|| anyhow::anyhow!("window has no titlebar strip to back"))?;
let mtm = MainThreadMarker::new()
.ok_or_else(|| anyhow::anyhow!("AppKit calls require the main thread"))?;
let bar = NSBox::initWithFrame(mtm.alloc(), bar_frame);
unsafe {
let ident = NSString::from_str(TITLEBAR_BACKING_BAR_ID);
let _: () = objc2::msg_send![&*bar, setIdentifier: &*ident];
}
bar.setBoxType(NSBoxType::Custom);
bar.setBorderWidth(0.0);
bar.setTitlePosition(NSTitlePosition::NoTitle);
bar.setFillColor(&objc2_app_kit::NSColor::windowBackgroundColor());
bar.setAutoresizingMask(
NSAutoresizingMaskOptions::ViewWidthSizable | NSAutoresizingMaskOptions::ViewMinYMargin,
);
frame_view.addSubview_positioned_relativeTo(
&bar,
NSWindowOrderingMode::Above,
ns_window.contentView().as_deref(),
);
let (z_index, subview_count) = unsafe {
let subs: objc2::rc::Retained<objc2::runtime::AnyObject> =
objc2::msg_send![&frame_view, subviews];
let count: usize = objc2::msg_send![&*subs, count];
let idx: usize = objc2::msg_send![&*subs, indexOfObject: &*bar];
(idx, count)
};
log::debug!(
"Installed opaque titlebar backing bar ({TITLEBAR_BACKING_BAR_ID}) \
at z-index {z_index} of {subview_count} frame-view subviews"
);
Ok(())
}
#[cfg(target_os = "macos")]
fn remove_titlebar_backing_bar(ns_window: &objc2_app_kit::NSWindow) {
if let Some(frame_view) = ns_window
.contentView()
.and_then(|cv| unsafe { cv.superview() })
&& let Some(bar) = find_titlebar_backing_bar(&frame_view)
{
bar.removeFromSuperview();
log::debug!("Removed titlebar backing bar");
}
}
#[allow(unused_variables)]
pub fn sync_titlebar_backing_bar_visibility(window: &winit::window::Window) -> Result<()> {
#[cfg(target_os = "macos")]
{
use objc2::rc::Retained;
use objc2_app_kit::{NSView, NSWindow, NSWindowStyleMask};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
let window_handle = window.window_handle()?;
let ns_view_ptr = match window_handle.as_raw() {
RawWindowHandle::AppKit(handle) => handle.ns_view.as_ptr(),
_ => anyhow::bail!("Not a macOS AppKit window"),
};
if ns_view_ptr.is_null() {
anyhow::bail!("NSView pointer is null");
}
unsafe {
let ns_view = ns_view_ptr as *mut NSView;
let ns_window: Option<Retained<NSWindow>> = objc2::msg_send![ns_view, window];
let Some(ns_window) = ns_window else {
anyhow::bail!("NSView is not installed in an NSWindow");
};
let fullscreen = ns_window
.styleMask()
.contains(NSWindowStyleMask::FullScreen);
if let Some(frame_view) = ns_window.contentView().and_then(|cv| cv.superview()) {
if fullscreen {
if let Some(bar) = find_titlebar_backing_bar(&frame_view) {
bar.setHidden(true);
}
} else if find_titlebar_backing_bar(&frame_view).is_some() {
ensure_titlebar_backing_bar(&ns_window)?;
}
}
}
}
#[cfg(not(target_os = "macos"))]
{
let _ = window;
}
Ok(())
}