use crate::cover::{Backing, CORNERS, Rect, Watch};
use crate::mac::{AppWindows, WINDOW_CHECK, desktop_level, join_desktop, usable_area};
use clairlune_platform::macos::find_screen;
use objc2::rc::Retained;
use objc2::runtime::{NSObjectProtocol, ProtocolObject};
use objc2::{MainThreadMarker, MainThreadOnly, define_class, msg_send};
use objc2_app_kit::{
NSAppearanceCustomization, NSBackingStoreType, NSColor, NSScreen, NSStatusItem, NSView,
NSWindow, NSWindowStyleMask,
};
use objc2_core_foundation::CFRetained;
use objc2_core_graphics::{CGColor, CGEventSource, CGEventSourceStateID, CGEventType};
use objc2_foundation::{NSActivityOptions, NSPoint, NSProcessInfo, NSRect, NSSize, NSString};
use objc2_quartz_core::{CALayer, CATransaction};
use std::time::{Duration, Instant};
define_class!(
#[unsafe(super(NSWindow))]
#[thread_kind = MainThreadOnly]
#[name = "ClairluneMenuBarWindow"]
struct BarWindow;
impl BarWindow {
#[unsafe(method(constrainFrameRect:toScreen:))]
fn constrain(&self, frame: NSRect, _screen: Option<&NSScreen>) -> NSRect {
frame
}
}
);
struct Strip {
frame: NSRect,
layer: Retained<CALayer>,
window: Retained<BarWindow>,
}
struct Bar {
monitor: String,
dark: bool,
place: Option<(Rect, NSRect)>,
watch: Watch,
shown: (Backing, bool),
strip: Option<Strip>,
}
const FAST: Duration = Duration::from_millis(8);
const FAST_FOR: Duration = Duration::from_millis(700);
const FIND: Duration = Duration::from_millis(40);
const INPUT_CHECK: Duration = Duration::from_millis(100);
fn input_count() -> u32 {
const GESTURE: CGEventType = CGEventType(29);
[
CGEventType::LeftMouseDown,
CGEventType::LeftMouseUp,
CGEventType::LeftMouseDragged,
CGEventType::FlagsChanged,
GESTURE,
]
.into_iter()
.map(|t| CGEventSource::counter_for_event_type(CGEventSourceStateID::CombinedSessionState, t))
.fold(0, u32::wrapping_add)
}
#[derive(Default)]
pub struct MenuBars {
bars: Vec<Bar>,
seen_dark: Option<bool>,
checked: Option<Instant>,
measured: Option<Instant>,
found: Option<Instant>,
asked_input: Option<Instant>,
input: u32,
fast_until: Option<Instant>,
awake: Option<Retained<ProtocolObject<dyn NSObjectProtocol>>>,
}
fn clear_menu_bar() -> bool {
NSProcessInfo::processInfo()
.operatingSystemVersion()
.majorVersion
>= 16
}
pub fn is_dark(item: &NSStatusItem) -> Option<bool> {
let button = item.button(MainThreadMarker::new()?)?;
Some(
button
.effectiveAppearance()
.name()
.to_string()
.contains("Dark"),
)
}
impl MenuBars {
pub fn set(&mut self, screens: Vec<(String, bool)>) {
if !clear_menu_bar() {
return;
}
let same = screens.len() == self.bars.len()
&& screens
.iter()
.zip(&self.bars)
.all(|((id, _), b)| *id == b.monitor);
if same {
for ((_, dark), bar) in screens.into_iter().zip(&mut self.bars) {
bar.dark = dark;
}
} else {
self.bars = screens
.into_iter()
.map(|(monitor, dark)| Bar {
monitor,
dark,
place: None,
watch: Watch::default(),
shown: (Backing::Clear, dark),
strip: None,
})
.collect();
}
self.checked = None;
self.measured = None;
self.stay_awake();
}
pub fn due(&self, now: Instant) -> bool {
!self.bars.is_empty() && self.checked.is_none_or(|t| now >= t + self.pace(now))
}
fn pace(&self, now: Instant) -> Duration {
match self.fast_until {
Some(t) if now < t => FAST,
_ => WINDOW_CHECK,
}
}
pub fn see(&mut self, dark: Option<bool>) {
self.seen_dark = dark;
}
pub fn tick(&mut self, now: Instant, windows: &mut AppWindows) -> Option<Instant> {
if self.bars.is_empty() {
return None;
}
if self.asked_input.is_none_or(|t| now >= t + INPUT_CHECK) {
self.asked_input = Some(now);
let input = input_count();
if std::mem::replace(&mut self.input, input) != input {
self.fast_until = Some(now + FAST_FOR);
}
}
if self.due(now)
&& let Some(mtm) = MainThreadMarker::new()
{
self.checked = Some(now);
if self.measured.is_none_or(|t| now >= t + WINDOW_CHECK) {
self.measured = Some(now);
for bar in &mut self.bars {
bar.measure(mtm);
}
}
let windows = if self.found.is_none_or(|t| now >= t + FIND) {
self.found = Some(now);
windows.look_now()
} else {
windows.look_again()
};
let mut moved = false;
for bar in &mut self.bars {
moved |= bar.update(mtm, now, windows, self.seen_dark);
}
if moved {
self.fast_until = Some(now + FAST_FOR);
}
self.stay_awake();
}
let look = self.checked.map(|t| t + self.pace(now));
let ask = self.asked_input.map(|t| t + INPUT_CHECK);
[look, ask].into_iter().flatten().min()
}
fn stay_awake(&mut self) {
let solid = self.bars.iter().any(|b| b.shown.0 != Backing::Clear);
if solid == self.awake.is_some() {
return;
}
let process = NSProcessInfo::processInfo();
match self.awake.take() {
Some(activity) => unsafe { process.endActivity(&activity) },
None => {
self.awake = Some(process.beginActivityWithOptions_reason(
NSActivityOptions::UserInitiatedAllowingIdleSystemSleep,
&NSString::from_str("The menu bar follows the windows"),
));
}
}
}
}
impl Bar {
fn measure(&mut self, mtm: MainThreadMarker) {
self.place = find_screen(mtm, &self.monitor)
.and_then(|s| Some((usable_area(mtm, &s)?, strip_frame(&s)?)));
let frame = self.place.map(|(_, f)| f);
if self.strip.as_ref().is_some_and(|s| Some(s.frame) != frame) {
self.strip = None;
self.watch = Watch::default();
self.shown.0 = Backing::Clear;
}
}
fn update(
&mut self,
mtm: MainThreadMarker,
now: Instant,
windows: &[Rect],
seen: Option<bool>,
) -> bool {
let Some((area, frame)) = self.place else {
return false;
};
let (backing, moved) = self.watch.look(now, area, windows);
let solid = backing != Backing::Clear;
let dark = if solid {
seen.unwrap_or(self.dark)
} else {
self.shown.1
};
if (backing, dark) != self.shown {
if solid != (self.shown.0 != Backing::Clear) || dark != self.shown.1 {
tracing::info!(target: "clairlune", screen = %self.monitor, solid, dark, "menu bar");
}
self.shown = (backing, dark);
self.strip
.get_or_insert_with(|| Strip::new(mtm, frame, dark))
.show(backing, dark);
}
moved
}
}
fn strip_frame(screen: &NSScreen) -> Option<NSRect> {
let (f, v) = (screen.frame(), screen.visibleFrame());
let bottom = v.origin.y + v.size.height;
let height = f.origin.y + f.size.height - bottom;
(height >= 1.0).then(|| {
NSRect::new(
NSPoint::new(f.origin.x, bottom - CORNERS),
NSSize::new(f.size.width, height + CORNERS),
)
})
}
fn colour(dark: bool) -> CFRetained<CGColor> {
let (r, g, b) = if dark {
(0.157, 0.157, 0.165)
} else {
(1.0, 1.0, 1.0)
};
CGColor::new_srgb(r, g, b, 1.0)
}
impl Strip {
fn new(mtm: MainThreadMarker, frame: NSRect, dark: bool) -> Strip {
let this = BarWindow::alloc(mtm).set_ivars(());
let window: Retained<BarWindow> = unsafe {
msg_send![
super(this),
initWithContentRect: frame,
styleMask: NSWindowStyleMask::Borderless,
backing: NSBackingStoreType::Buffered,
defer: false,
]
};
join_desktop(&window, desktop_level() + 1);
window.setOpaque(false);
window.setBackgroundColor(Some(&NSColor::clearColor()));
let view =
NSView::initWithFrame(NSView::alloc(mtm), NSRect::new(NSPoint::ZERO, frame.size));
let root = CALayer::new();
view.setLayer(Some(&root));
view.setWantsLayer(true);
let layer = CALayer::new();
layer.setBackgroundColor(Some(&colour(dark)));
layer.setOpacity(0.0);
root.addSublayer(&layer);
window.setContentView(Some(&view));
window.setFrame_display(frame, false);
window.orderFrontRegardless();
Strip {
frame,
layer,
window,
}
}
fn show(&self, backing: Backing, dark: bool) {
let size = self.frame.size;
let below = match backing {
Backing::BarAndCorners => 0.0,
Backing::Bar | Backing::Clear => CORNERS,
};
CATransaction::begin();
CATransaction::setDisableActions(true);
self.layer.setFrame(NSRect::new(
NSPoint::new(0.0, below),
NSSize::new(size.width, size.height - below),
));
self.layer.setBackgroundColor(Some(&colour(dark)));
self.layer
.setOpacity(if backing == Backing::Clear { 0.0 } else { 1.0 });
CATransaction::commit();
CATransaction::flush();
}
}
impl Drop for Strip {
fn drop(&mut self) {
self.window.orderOut(None);
self.window.close();
}
}