Skip to content
Merged
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
2 changes: 1 addition & 1 deletion crates/app/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ libc.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
muda.workspace = true
objc2 = "0.6"
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWindow", "NSApplication"] }
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSApplication", "NSColor", "NSColorSpace", "NSHapticFeedback", "NSWindow", "objc2-core-foundation"] }
objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSObject", "NSAppleEventManager", "NSAppleEventDescriptor", "NSNotification", "NSString", "NSURL"] }

[target.'cfg(windows)'.build-dependencies]
Expand Down
6 changes: 3 additions & 3 deletions crates/app/src/ui/canvas/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ fn with_alpha(color: Color32, alpha: u8) -> Color32 {
Color32::from_rgba_unmultiplied(color.r(), color.g(), color.b(), alpha)
}

fn blend(foreground: Color32, background: Color32, amount: f32) -> Color32 {
pub(crate) fn blend(foreground: Color32, background: Color32, amount: f32) -> Color32 {
let mix = |a: u8, b: u8| (a as f32 * (1.0 - amount) + b as f32 * amount).round() as u8;
Color32::from_rgb(
mix(foreground.r(), background.r()),
Expand All @@ -80,7 +80,7 @@ fn blend(foreground: Color32, background: Color32, amount: f32) -> Color32 {
)
}

fn contrast_adjusted(mut color: Color32, background: Color32, minimum: f32) -> Color32 {
pub(crate) fn contrast_adjusted(mut color: Color32, background: Color32, minimum: f32) -> Color32 {
let target = if relative_luminance(background) > 0.45 {
Color32::BLACK
} else {
Expand All @@ -95,7 +95,7 @@ fn contrast_adjusted(mut color: Color32, background: Color32, minimum: f32) -> C
color
}

fn contrast_ratio(a: Color32, b: Color32) -> f32 {
pub(crate) fn contrast_ratio(a: Color32, b: Color32) -> f32 {
let (lighter, darker) = if relative_luminance(a) >= relative_luminance(b) {
(relative_luminance(a), relative_luminance(b))
} else {
Expand Down
10 changes: 8 additions & 2 deletions crates/app/src/ui/canvas/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ mod board_marquee;
mod board_notes;
mod board_sheet;
mod breadcrumb;
mod chrome;
pub(super) mod chrome;
mod craft_regions;
mod craft_results;
mod cursors;
Expand Down Expand Up @@ -70,6 +70,7 @@ mod regions;
mod render_detail;
mod slices;
mod snap;
mod snap_feedback;
mod spotlight;
mod symmetry;
mod tiling;
Expand Down Expand Up @@ -167,7 +168,11 @@ pub fn render_central(app: &mut PlotiumApp, ui: &mut Ui) {
let rect = geometry.board_rect;
let painter = painter.with_clip_rect(rect);
store_navigation_rect(ui.ctx(), rect);
let chrome = ChromeStyle::from_visuals(ui.visuals(), app.settings.appearance.canvas_accent);
let accent = app.settings.appearance.canvas_accent.unwrap_or_else(|| {
let accent = super::system_accent::canvas_default(ui.ctx(), ui.visuals());
[accent.r(), accent.g(), accent.b()]
});
let chrome = ChromeStyle::from_visuals(ui.visuals(), Some(accent));
consume_board_reveal(app, ui.ctx());
drive_board_fit(app, ui, &geometry);

Expand Down Expand Up @@ -258,6 +263,7 @@ pub fn render_central(app: &mut PlotiumApp, ui: &mut Ui) {
}
}
}
snap_feedback::update(ui.ctx(), &app.session.ui.snap_guides);
// A tile drop may remove the now-empty source canvas and switch focus to the
// target in the same UI pass. Refresh both values before any post-interaction
// painting; the old index can otherwise refer to a different canvas or be out
Expand Down
76 changes: 76 additions & 0 deletions crates/app/src/ui/canvas/snap_feedback.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
//! Trackpad feedback when a drag snaps to an alignment guide.
//!
//! The guide lines are the feedback on every platform; macOS adds a haptic tap
//! through `NSHapticFeedbackManager`, which does nothing without a Force Touch
//! trackpad.

use egui::{Context, Id};
use plotium_core::layout::SnapGuide;

const SHOWN: &str = "plotium_snap_feedback_guides";

/// Compares the guides left after this frame's interaction handling with those
/// of the previous frame. Interaction code may set and clear guides within one
/// frame, so only the settled result is compared.
pub(super) fn update(ctx: &Context, guides: &[SnapGuide]) {
let previous = ctx.data_mut(|data| {
let previous = data.get_temp::<Vec<SnapGuide>>(Id::new(SHOWN));
if previous.as_deref() != Some(guides) {
data.insert_temp(Id::new(SHOWN), guides.to_vec());
}
previous.unwrap_or_default()
});
if newly_engaged(&previous, guides) {
platform::alignment();
}
}

/// A guide that was not showing has appeared. Holding a snap keeps the same
/// guide, so one engagement gives one tap.
fn newly_engaged(previous: &[SnapGuide], current: &[SnapGuide]) -> bool {
current.iter().any(|guide| !previous.contains(guide))
}

#[cfg(target_os = "macos")]
mod platform {
use objc2_app_kit::{
NSHapticFeedbackManager, NSHapticFeedbackPattern, NSHapticFeedbackPerformanceTime,
NSHapticFeedbackPerformer,
};

pub(super) fn alignment() {
NSHapticFeedbackManager::defaultPerformer().performFeedbackPattern_performanceTime(
NSHapticFeedbackPattern::Alignment,
NSHapticFeedbackPerformanceTime::DrawCompleted,
);
}
}

#[cfg(not(target_os = "macos"))]
mod platform {
pub(super) fn alignment() {}
}

#[cfg(test)]
mod tests {
use super::*;

fn guide(vertical: bool, pos: f32) -> SnapGuide {
SnapGuide { vertical, pos }
}

#[test]
fn engaging_a_guide_fires_once_while_it_is_held() {
let x = guide(true, 72.0);
assert!(newly_engaged(&[], &[x]));
assert!(!newly_engaged(&[x], &[x]));
assert!(!newly_engaged(&[x], &[]));
}

#[test]
fn a_second_axis_or_a_different_line_fires_again() {
let x = guide(true, 72.0);
assert!(newly_engaged(&[x], &[x, guide(false, 36.0)]));
assert!(newly_engaged(&[x], &[guide(true, 144.0)]));
}
}
1 change: 1 addition & 0 deletions crates/app/src/ui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ mod settings_dialog;
mod shortcuts;
mod sidebars;
mod switcher;
mod system_accent;
#[cfg(not(target_os = "macos"))]
mod title_bar;
pub(crate) mod tools;
Expand Down
2 changes: 1 addition & 1 deletion crates/app/src/ui/properties/sections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ fn render_section(
.iter_mut()
.find(|row| row.presentation.id == app_preferences::ACCENT_COLOR)
{
let theme = ui.visuals().selection.bg_fill;
let theme = crate::ui::system_accent::canvas_default(ui.ctx(), ui.visuals());
let color =
PropertyValue::Color(plotium_figure::Color::rgb(theme.r(), theme.g(), theme.b()));
row.set.value = AggregateValue::Uniform(color.clone());
Expand Down
9 changes: 8 additions & 1 deletion crates/app/src/ui/settings_dialog/chrome.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ use egui_phosphor::regular as icon;
use plotium_core::settings::ThemeMode;
use plotium_core::state::{SettingsCategory, SettingsDialog};

use crate::ui::system_accent;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct ChromeGeometry {
control: u8,
Expand Down Expand Up @@ -88,9 +90,11 @@ pub(crate) fn apply_chrome_theme(ctx: &egui::Context, mode: ThemeMode) {
ThemeMode::Dark => egui::ThemePreference::Dark,
};
ctx.set_theme(pref);
let accent = system_accent::read();
for theme in [egui::Theme::Light, egui::Theme::Dark] {
ctx.style_mut_of(theme, |style| {
apply_chrome_geometry(style, ChromeGeometry::current());
system_accent::apply(&mut style.visuals, accent);
// Disabled widgets keep the normal button fill and fade only via
// `disabled_alpha`. Stock egui swaps in the near-panel
// `noninteractive` fill, which makes light-theme buttons *brighten*
Expand All @@ -103,12 +107,15 @@ pub(crate) fn apply_chrome_theme(ctx: &egui::Context, mode: ThemeMode) {
ctx.data_mut(|data| {
data.insert_temp(egui::Id::new("plotium_applied_chrome_theme"), mode);
});
system_accent::record(ctx, accent);
}

pub(crate) fn sync_chrome_theme(ctx: &egui::Context, mode: ThemeMode) {
let applied =
ctx.data(|data| data.get_temp::<ThemeMode>(egui::Id::new("plotium_applied_chrome_theme")));
if applied != Some(mode) {
let accent_changed =
system_accent::regained_focus(ctx) && system_accent::read() != system_accent::applied(ctx);
if applied != Some(mode) || accent_changed {
apply_chrome_theme(ctx, mode);
}
}
Expand Down
149 changes: 149 additions & 0 deletions crates/app/src/ui/system_accent.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
//! The operating system's accent colour, applied to selection chrome.
//!
//! macOS and Windows expose a user-chosen accent; Linux has no portable source,
//! so it keeps egui's stock blue. The accent is re-read whenever the window
//! regains focus, which is how a change made in System Settings arrives.

use egui::{Color32, Context, Id, Visuals};

use super::canvas::chrome::{blend, contrast_adjusted, contrast_ratio};

const APPLIED: &str = "plotium_applied_system_accent";
const FOCUSED: &str = "plotium_system_accent_window_focused";

/// Selected text and selected-row labels are body text.
const SELECTED_TEXT_CONTRAST: f32 = 4.5;
/// Keeps a selected row distinguishable from the panel; egui's stock fills
/// sit around 1.5.
const FILL_CONTRAST: f32 = 1.3;
/// Matches the contrast of egui's stock link colour, which also tints Ribbon
/// glyphs, so a system accent never reads weaker than the default.
const LINK_CONTRAST: f32 = 3.0;

/// Reads the platform accent. `None` keeps egui's defaults.
pub(crate) fn read() -> Option<Color32> {
platform::read()
}

/// The accent the chrome was last styled with.
pub(crate) fn applied(ctx: &Context) -> Option<Color32> {
ctx.data(|data| data.get_temp::<Option<Color32>>(Id::new(APPLIED)))
.flatten()
}

/// What canvas chrome follows when no `canvas_accent` is set: the system
/// accent, else the theme's selection fill.
pub(crate) fn canvas_default(ctx: &Context, visuals: &Visuals) -> Color32 {
applied(ctx).unwrap_or(visuals.selection.bg_fill)
}

pub(super) fn record(ctx: &Context, accent: Option<Color32>) {
ctx.data_mut(|data| data.insert_temp(Id::new(APPLIED), accent));
}

/// True on the first frame after the window regains focus.
pub(super) fn regained_focus(ctx: &Context) -> bool {
let focused = ctx.input(|input| input.focused);
let previous = ctx.data_mut(|data| {
let previous = data.get_temp::<bool>(Id::new(FOCUSED));
data.insert_temp(Id::new(FOCUSED), focused);
previous
});
focused && previous == Some(false)
}

/// Styles selection and link colours from `accent`, or restores egui's
/// defaults when there is none.
pub(super) fn apply(visuals: &mut Visuals, accent: Option<Color32>) {
let stock = if visuals.dark_mode {
Visuals::dark()
} else {
Visuals::light()
};
let Some(accent) = accent else {
visuals.selection = stock.selection;
visuals.hyperlink_color = stock.hyperlink_color;
return;
};
let background = visuals.panel_fill;
let tint = if visuals.dark_mode {
blend(accent, background, 0.45)
} else {
blend(accent, background, 0.6)
};
// A near-white or near-black custom accent would otherwise vanish into the
// panel and hide which row is selected.
let fill = contrast_adjusted(tint, background, FILL_CONTRAST);
let label_seed = if visuals.dark_mode {
blend(accent, Color32::WHITE, 0.7)
} else {
accent
};
visuals.selection.bg_fill = fill;
visuals.selection.stroke.color = readable_on(label_seed, fill, SELECTED_TEXT_CONTRAST);
visuals.hyperlink_color = contrast_adjusted(accent, background, LINK_CONTRAST);
}

/// `contrast_adjusted` stops after a fixed number of steps; fall back to black
/// or white so selected text is always readable on a mid-tone accent fill.
fn readable_on(seed: Color32, background: Color32, minimum: f32) -> Color32 {
let adjusted = contrast_adjusted(seed, background, minimum);
if contrast_ratio(adjusted, background) >= minimum {
return adjusted;
}
if contrast_ratio(Color32::BLACK, background) >= contrast_ratio(Color32::WHITE, background) {
Color32::BLACK
} else {
Color32::WHITE
}
}

#[cfg(target_os = "macos")]
mod platform {
use egui::Color32;
use objc2_app_kit::{NSColor, NSColorSpace};

pub(super) fn read() -> Option<Color32> {
// `controlAccentColor` is a dynamic colour whose space is unspecified;
// components are only defined after converting to a concrete space.
let color =
NSColor::controlAccentColor().colorUsingColorSpace(&NSColorSpace::sRGBColorSpace())?;
let channel = |value: f64| (value.clamp(0.0, 1.0) * 255.0).round() as u8;
Some(Color32::from_rgb(
channel(color.redComponent()),
channel(color.greenComponent()),
channel(color.blueComponent()),
))
}
}

#[cfg(windows)]
mod platform {
use egui::Color32;
use windows_sys::Win32::Graphics::Dwm::DwmGetColorizationColor;

pub(super) fn read() -> Option<Color32> {
let mut color = 0_u32;
let mut opaque = 0;
// SAFETY: both out-pointers refer to live locals for the call.
let result = unsafe { DwmGetColorizationColor(&mut color, &mut opaque) };
if result < 0 {
log::warn!("Reading the Windows accent colour failed: HRESULT {result:#x}");
return None;
}
// 0xAARRGGBB; the alpha is DWM's glass opacity, not part of the accent.
let [_, r, g, b] = color.to_be_bytes();
Some(Color32::from_rgb(r, g, b))
}
}

#[cfg(not(any(target_os = "macos", windows)))]
mod platform {
pub(super) fn read() -> Option<egui::Color32> {
None
}
}

#[cfg(test)]
#[path = "system_accent_tests.rs"]
mod tests;
Loading
Loading