Add Window::set_theme (#2553)

* Add `Window::set_theme`

* typo

* fix linux build

* fix wayland

* review changes

* update docs

* update changelog

* pin `image` dep

* suppport falling back to system default

* fix linux

* default to dark on macOS and x11

* fix `setAppearance` definition

* add macOS notes

* update docs

* Update CHANGELOG.md

Co-authored-by: Markus Siglreithmaier <m.siglreith@gmail.com>

* update doc

* Revert "pin `image` dep"

This reverts commit 7517f7c5065b4089ca146ce8799dab445ec32068.

* Update theme example with Window::set_theme

* Fix Window::theme getter on macOS

Co-authored-by: Markus Siglreithmaier <m.siglreith@gmail.com>
Co-authored-by: Mads Marquart <mads@marquart.dk>
This commit is contained in:
Amr Bashir 2022-11-29 11:05:51 +02:00 committed by GitHub
parent 9ae7498a8a
commit 28e34c2e1b
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
15 changed files with 127 additions and 65 deletions

View file

@ -87,7 +87,7 @@ extern_methods!(
}
#[sel(setAppearance:)]
pub fn setAppearance(&self, appearance: &NSAppearance);
pub fn setAppearance(&self, appearance: Option<&NSAppearance>);
#[sel(run)]
pub unsafe fn run(&self);

View file

@ -399,7 +399,7 @@ impl WinitWindow {
match attrs.preferred_theme {
Some(theme) => {
set_ns_theme(theme);
set_ns_theme(Some(theme));
let mut state = this.shared_state.lock().unwrap();
state.current_theme = Some(theme);
}
@ -1125,6 +1125,12 @@ impl WinitWindow {
state.current_theme
}
#[inline]
pub fn set_theme(&self, theme: Option<Theme>) {
set_ns_theme(theme);
self.lock_shared_state("set_theme").current_theme = theme.or_else(|| Some(get_ns_theme()));
}
#[inline]
pub fn set_content_protected(&self, protected: bool) {
self.setSharingType(if protected {
@ -1254,15 +1260,17 @@ pub(super) fn get_ns_theme() -> Theme {
}
}
fn set_ns_theme(theme: Theme) {
fn set_ns_theme(theme: Option<Theme>) {
let app = NSApp();
let has_theme: bool = unsafe { msg_send![&app, respondsToSelector: sel!(effectiveAppearance)] };
if has_theme {
let name = match theme {
Theme::Dark => NSString::from_str("NSAppearanceNameDarkAqua"),
Theme::Light => NSString::from_str("NSAppearanceNameAqua"),
};
let appearance = NSAppearance::appearanceNamed(&name);
app.setAppearance(&appearance);
let appearance = theme.map(|t| {
let name = match t {
Theme::Dark => NSString::from_str("NSAppearanceNameDarkAqua"),
Theme::Light => NSString::from_str("NSAppearanceNameAqua"),
};
NSAppearance::appearanceNamed(&name)
});
app.setAppearance(appearance.as_ref().map(|a| a.as_ref()));
}
}