Remove trailing whitespace

This commit is contained in:
Mads Marquart 2022-07-10 17:15:29 +02:00
parent a790eb95b7
commit 02f5d6aa87
136 changed files with 859 additions and 859 deletions

View file

@ -1,9 +1,9 @@
# Cacao Architecture # Cacao Architecture
Cacao is a library to interface with AppKit (macOS) or UIKit (iOS/iPadOS/tvOS). It uses the Objective-C runtime to Cacao is a library to interface with AppKit (macOS) or UIKit (iOS/iPadOS/tvOS). It uses the Objective-C runtime to
handle calling into these frameworks. handle calling into these frameworks.
Said frameworks typically use an Object Oriented style of programming (subclasses, etc), which can be tricky to Said frameworks typically use an Object Oriented style of programming (subclasses, etc), which can be tricky to
handle with the way that Rust works with regards to ownership. Thankfully, AppKit & UIKit often also use a handle with the way that Rust works with regards to ownership. Thankfully, AppKit & UIKit often also use a
delegate pattern - objects registered to receive callbacks. With some creative assumptions, we can get somewhat close delegate pattern - objects registered to receive callbacks. With some creative assumptions, we can get somewhat close
to expected conventions. to expected conventions.
@ -208,7 +208,7 @@ impl View {
height: LayoutAnchorDimension::height(view), height: LayoutAnchorDimension::height(view),
center_x: LayoutAnchorX::center(view), center_x: LayoutAnchorX::center(view),
center_y: LayoutAnchorY::center(view), center_y: LayoutAnchorY::center(view),
layer: Layer::wrap(unsafe { layer: Layer::wrap(unsafe {
msg_send![view, layer] msg_send![view, layer]
}), }),
@ -236,7 +236,7 @@ impl<T> View<T> where T: ViewDelegate + 'static {
pub fn with(delegate: T) -> View<T> { pub fn with(delegate: T) -> View<T> {
let class = register_view_class_with_delegate(&delegate); let class = register_view_class_with_delegate(&delegate);
let mut delegate = Box::new(delegate); let mut delegate = Box::new(delegate);
let view = unsafe { let view = unsafe {
let view: id = msg_send![class, new]; let view: id = msg_send![class, new];
let ptr = Box::into_raw(delegate); let ptr = Box::into_raw(delegate);
@ -246,7 +246,7 @@ impl<T> View<T> where T: ViewDelegate + 'static {
}; };
let mut view = View::init(view); let mut view = View::init(view);
(&mut delegate).did_load(view.clone_as_handle()); (&mut delegate).did_load(view.clone_as_handle());
view.delegate = Some(delegate); view.delegate = Some(delegate);
view view
} }
@ -363,7 +363,7 @@ pub(crate) fn register_view_class() -> *const Class {
decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL); decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
decl.add_ivar::<id>(BACKGROUND_COLOR); decl.add_ivar::<id>(BACKGROUND_COLOR);
VIEW_CLASS = decl.register(); VIEW_CLASS = decl.register();
}); });
@ -371,7 +371,7 @@ pub(crate) fn register_view_class() -> *const Class {
} }
``` ```
This function (called inside `View::new()`) creates one reusable `View` subclass, and returns the type on subsequent calls. We're able to add methods to it (`add_method`) which match This function (called inside `View::new()`) creates one reusable `View` subclass, and returns the type on subsequent calls. We're able to add methods to it (`add_method`) which match
Objective-C method signatures, as well as provision space for variable storage (`add_ivar`). Objective-C method signatures, as well as provision space for variable storage (`add_ivar`).
For our _delegate_ types, we need a different class creation method - one that creates a subclass per-unique-type: For our _delegate_ types, we need a different class creation method - one that creates a subclass per-unique-type:

View file

@ -99,5 +99,5 @@ Check out [their README](https://github.com/rust-lang-nursery/rustfmt) for detai
### Notes ### Notes
This project prefers verbose naming, to a certain degree - UI code is read more often than written, so it's This project prefers verbose naming, to a certain degree - UI code is read more often than written, so it's
worthwhile to ensure that it scans well. It also maps well to existing Cocoa/cacao idioms and is generally preferred. worthwhile to ensure that it scans well. It also maps well to existing Cocoa/cacao idioms and is generally preferred.

View file

@ -10,17 +10,17 @@ inform development. That said, this library is currently early stages and may ha
your own risk. However, provided you follow the rules (regarding memory/ownership) it's your own risk. However, provided you follow the rules (regarding memory/ownership) it's
already fine for some apps. The core repository has a wealth of examples to help you get started. already fine for some apps. The core repository has a wealth of examples to help you get started.
> **Important** > **Important**
> >
> If you are migrating from 0.2 to 0.3, you should elect either `appkit` or `uikit` as a feature in your `Cargo.toml`. This change was made to > If you are migrating from 0.2 to 0.3, you should elect either `appkit` or `uikit` as a feature in your `Cargo.toml`. This change was made to
> support platforms that aren't just macOS/iOS/tvOS (e.g, gnustep, airyx). One of these features is required to work; `appkit` is defaulted for > support platforms that aren't just macOS/iOS/tvOS (e.g, gnustep, airyx). One of these features is required to work; `appkit` is defaulted for
> ease of development. > ease of development.
>_Note that this crate relies on the Objective-C runtime. Interfacing with the runtime **requires** >_Note that this crate relies on the Objective-C runtime. Interfacing with the runtime **requires**
unsafe blocks; this crate handles those unsafe interactions for you and provides a safe wrapper, unsafe blocks; this crate handles those unsafe interactions for you and provides a safe wrapper,
but by using this crate you understand that usage of `unsafe` is a given and will be somewhat but by using this crate you understand that usage of `unsafe` is a given and will be somewhat
rampant for wrapped controls. This does **not** mean you can't assess, review, or question unsafe rampant for wrapped controls. This does **not** mean you can't assess, review, or question unsafe
usage - just know it's happening, and in large part it's not going away. Issues pertaining to the mere usage - just know it's happening, and in large part it's not going away. Issues pertaining to the mere
existence of unsafe will be closed without comment._ existence of unsafe will be closed without comment._
If you're looking to build the docs for this on your local machine, you'll want the following due to the way feature flags work If you're looking to build the docs for this on your local machine, you'll want the following due to the way feature flags work
@ -108,17 +108,17 @@ The following are a list of [Cargo features][cargo-features] that can be enabled
[cargo-features]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section [cargo-features]: https://doc.rust-lang.org/stable/cargo/reference/manifest.html#the-features-section
## General Notes ## General Notes
**Why not extend the existing cocoa-rs crate?** **Why not extend the existing cocoa-rs crate?**
A good question. At the end of the day, that crate (I believe, and someone can correct me if I'm wrong) is somewhat tied to Servo, and I wanted to experiment with what the best approach for representing the Cocoa UI model in Rust was. This crate doesn't ignore their work entirely, either - `core_foundation` and `core_graphics` are used internally and re-exported for general use. A good question. At the end of the day, that crate (I believe, and someone can correct me if I'm wrong) is somewhat tied to Servo, and I wanted to experiment with what the best approach for representing the Cocoa UI model in Rust was. This crate doesn't ignore their work entirely, either - `core_foundation` and `core_graphics` are used internally and re-exported for general use.
**Why should I write in Rust, rather than X language?** **Why should I write in Rust, rather than X language?**
In _my_ case, I want to be able to write native applications for my devices (and the platform I like to build products for) without being locked in to writing in Apple-specific languages... and without writing in C/C++ or JavaScript (note: the _toolchain_, not the language - ES6/Typescript are fine). I want to do this because I'm tired of hitting a mountain of work when I want to port my applications to other ecosystems. I think that Rust offers a (growing, but significant) viable model for sharing code across platforms and ecosystems without sacrificing performance. In _my_ case, I want to be able to write native applications for my devices (and the platform I like to build products for) without being locked in to writing in Apple-specific languages... and without writing in C/C++ or JavaScript (note: the _toolchain_, not the language - ES6/Typescript are fine). I want to do this because I'm tired of hitting a mountain of work when I want to port my applications to other ecosystems. I think that Rust offers a (growing, but significant) viable model for sharing code across platforms and ecosystems without sacrificing performance.
_(This is the part where the internet lights up and rants about some combination of Electron, Qt, and so on - we're not bothering here as it's beaten to death elsewhere)_ _(This is the part where the internet lights up and rants about some combination of Electron, Qt, and so on - we're not bothering here as it's beaten to death elsewhere)_
This crate is useful for people who don't need to go all-in on the Apple ecosystem, but want to port their work there with some relative ease. It's not expected that everyone will suddenly want to rewrite their macOS/iOS/tvOS apps in Rust. This crate is useful for people who don't need to go all-in on the Apple ecosystem, but want to port their work there with some relative ease. It's not expected that everyone will suddenly want to rewrite their macOS/iOS/tvOS apps in Rust.
**Isn't Objective-C dead?** **Isn't Objective-C dead?**
Yes, and no. Yes, and no.
It's true that Apple definitely favors Swift, and for good reason (and I say this as an unabashed lover of Objective-C). With that said, I would be surprised if we didn't have another ~5+ years of support; Apple is quick to deprecate, but removing the Objective-C runtime would require a ton of time and effort. Maybe SwiftUI kills it, who knows. A wrapper around this stuff should conceivably make it easier to swap out the underlying UI backend whenever it comes time. It's true that Apple definitely favors Swift, and for good reason (and I say this as an unabashed lover of Objective-C). With that said, I would be surprised if we didn't have another ~5+ years of support; Apple is quick to deprecate, but removing the Objective-C runtime would require a ton of time and effort. Maybe SwiftUI kills it, who knows. A wrapper around this stuff should conceivably make it easier to swap out the underlying UI backend whenever it comes time.
@ -133,21 +133,21 @@ Some might also decry Objective-C as slow. To that, I'd note the following:
**tl;dr** it's probably fine, and you have Rust for your performance needs. **tl;dr** it's probably fine, and you have Rust for your performance needs.
**Why not just wrap UIKit, and then rely on Catalyst?** **Why not just wrap UIKit, and then rely on Catalyst?**
I have yet to see a single application where Catalyst felt good. The goal is good, though, and if it got to a point where that just seemed like the way forward (e.g, Apple just kills AppKit) then it's certainly an option. I have yet to see a single application where Catalyst felt good. The goal is good, though, and if it got to a point where that just seemed like the way forward (e.g, Apple just kills AppKit) then it's certainly an option.
**You can't possibly wrap all platform-specific behavior here...** **You can't possibly wrap all platform-specific behavior here...**
Correct! Each UI control contains a `objc` field, which you can use as an escape hatch - if the control doesn't support something, you're free to drop to the Objective-C runtime yourself and handle it. Correct! Each UI control contains a `objc` field, which you can use as an escape hatch - if the control doesn't support something, you're free to drop to the Objective-C runtime yourself and handle it.
**Why don't you use bindings to automatically generate this stuff?** **Why don't you use bindings to automatically generate this stuff?**
For initial exploration purposes I've done most of this by hand, as I wanted to find an approach that fit well in the Rust model before committing to binding generation. This is something I'll likely focus on next now that I've got things "working" well enough. For initial exploration purposes I've done most of this by hand, as I wanted to find an approach that fit well in the Rust model before committing to binding generation. This is something I'll likely focus on next now that I've got things "working" well enough.
**Is this related to Cacao, the Swift project?** **Is this related to Cacao, the Swift project?**
No. The project referred to in this question aimed to map portions of Cocoa and UIKit over to run on Linux, but hasn't seen activity in some time (it was really cool, too!). No. The project referred to in this question aimed to map portions of Cocoa and UIKit over to run on Linux, but hasn't seen activity in some time (it was really cool, too!).
Open source project naming in 2020 is like trying to buy a `.com` domain: everything good is taken. Luckily, multiple projects can share a name... so that's what's going to happen here. Open source project naming in 2020 is like trying to buy a `.com` domain: everything good is taken. Luckily, multiple projects can share a name... so that's what's going to happen here.
**Isn't this kind of cheating the Rust object model?** **Isn't this kind of cheating the Rust object model?**
Depends on how you look at it. I personally don't care too much - the GUI layer for these platforms is a hard requirement to support for certain classes of products, and giving them up also means giving up battle-tested tools for things like Accessibility and deeper OS integration. With that said, internally there are efforts to try and make things respect Rust's model of how things should work. Depends on how you look at it. I personally don't care too much - the GUI layer for these platforms is a hard requirement to support for certain classes of products, and giving them up also means giving up battle-tested tools for things like Accessibility and deeper OS integration. With that said, internally there are efforts to try and make things respect Rust's model of how things should work.
You can think of this as similar to gtk-rs. If you want to support or try a more _pure_ model, go check out Druid or something. :) You can think of this as similar to gtk-rs. If you want to support or try a more _pure_ model, go check out Druid or something. :)

View file

@ -2,10 +2,10 @@
fn main() { fn main() {
println!("cargo:rustc-link-lib=framework=Foundation"); println!("cargo:rustc-link-lib=framework=Foundation");
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
println!("cargo:rustc-link-lib=framework=AppKit"); println!("cargo:rustc-link-lib=framework=AppKit");
#[cfg(feature = "uikit")] #[cfg(feature = "uikit")]
println!("cargo:rustc-link-lib=framework=UIKit"); println!("cargo:rustc-link-lib=framework=UIKit");
@ -15,13 +15,13 @@ fn main() {
#[cfg(feature = "webview")] #[cfg(feature = "webview")]
println!("cargo:rustc-link-lib=framework=WebKit"); println!("cargo:rustc-link-lib=framework=WebKit");
#[cfg(feature = "cloudkit")] #[cfg(feature = "cloudkit")]
println!("cargo:rustc-link-lib=framework=CloudKit"); println!("cargo:rustc-link-lib=framework=CloudKit");
#[cfg(feature = "user-notifications")] #[cfg(feature = "user-notifications")]
println!("cargo:rustc-link-lib=framework=UserNotifications"); println!("cargo:rustc-link-lib=framework=UserNotifications");
#[cfg(feature = "quicklook")] #[cfg(feature = "quicklook")]
println!("cargo:rustc-link-lib=framework=QuickLook"); println!("cargo:rustc-link-lib=framework=QuickLook");
} }

View file

@ -1,4 +1,4 @@
//! This example builds on the AutoLayout example, but adds in animation //! This example builds on the AutoLayout example, but adds in animation
//! via `AnimationContext`. Views and layout anchors have special proxy objects that can be cloned //! via `AnimationContext`. Views and layout anchors have special proxy objects that can be cloned
//! into handlers, enabling basic animation support within `AnimationContext`. //! into handlers, enabling basic animation support within `AnimationContext`.
//! //!
@ -132,7 +132,7 @@ impl WindowDelegate for AppWindow {
] ]
}).collect::<Vec<Vec<LayoutConstraintAnimatorProxy>>>(); }).collect::<Vec<Vec<LayoutConstraintAnimatorProxy>>>();
// Monitor key change events for w/a/s/d, and then animate each view to their correct // Monitor key change events for w/a/s/d, and then animate each view to their correct
// frame and alpha value. // frame and alpha value.
self.key_monitor = Some(Event::local_monitor(EventMask::KeyDown, move |evt| { self.key_monitor = Some(Event::local_monitor(EventMask::KeyDown, move |evt| {
let characters = evt.characters(); let characters = evt.characters();

View file

@ -93,7 +93,7 @@ impl WindowDelegate for AppWindow {
self.red.top.constraint_equal_to(&self.content.top).offset(46.), self.red.top.constraint_equal_to(&self.content.top).offset(46.),
self.red.leading.constraint_equal_to(&self.blue.trailing).offset(16.), self.red.leading.constraint_equal_to(&self.blue.trailing).offset(16.),
self.red.bottom.constraint_equal_to(&self.content.bottom).offset(-16.), self.red.bottom.constraint_equal_to(&self.content.bottom).offset(-16.),
self.green.top.constraint_equal_to(&self.content.top).offset(46.), self.green.top.constraint_equal_to(&self.content.top).offset(46.),
self.green.leading.constraint_equal_to(&self.red.trailing).offset(16.), self.green.leading.constraint_equal_to(&self.red.trailing).offset(16.),
self.green.trailing.constraint_equal_to(&self.content.trailing).offset(-16.), self.green.trailing.constraint_equal_to(&self.content.trailing).offset(-16.),

View file

@ -86,7 +86,7 @@ impl Dispatcher for BasicApp {
match message { match message {
Action::Back => { webview.go_back(); }, Action::Back => { webview.go_back(); },
Action::Forwards => { webview.go_forward(); }, Action::Forwards => { webview.go_forward(); },
Action::Load(url) => { window.load_url(&url); } Action::Load(url) => { window.load_url(&url); }
} }
} }
} }

View file

@ -45,8 +45,8 @@ impl BrowserToolbar {
let url_bar = TextField::with(URLBar); let url_bar = TextField::with(URLBar);
let url_bar_item = ToolbarItem::new(URL_BAR); let url_bar_item = ToolbarItem::new(URL_BAR);
// We cheat for now to link these, as there's no API for Toolbar yet // We cheat for now to link these, as there's no API for Toolbar yet
// to support arbitrary view types. The framework is designed to support this kind of // to support arbitrary view types. The framework is designed to support this kind of
// cheating, though: it's not outlandish to need to just manage things yourself when it // cheating, though: it's not outlandish to need to just manage things yourself when it
// comes to Objective-C/AppKit sometimes. // comes to Objective-C/AppKit sometimes.

View file

@ -36,7 +36,7 @@ impl ButtonRow {
_ => "W" _ => "W"
}, y.clone()); }, y.clone());
view.add_subview(&button); view.add_subview(&button);
button button
}).collect(); }).collect();
@ -69,7 +69,7 @@ impl ButtonRow {
buttons[3].trailing.constraint_equal_to(&view.trailing), buttons[3].trailing.constraint_equal_to(&view.trailing),
buttons[3].bottom.constraint_equal_to(&view.bottom), buttons[3].bottom.constraint_equal_to(&view.bottom),
buttons[3].width.constraint_equal_to(&width), buttons[3].width.constraint_equal_to(&width),
view.height.constraint_equal_to_constant(BUTTON_HEIGHT) view.height.constraint_equal_to_constant(BUTTON_HEIGHT)
]); ]);

View file

@ -40,7 +40,7 @@ impl Calculator {
pub fn run(&self, message: Msg) { pub fn run(&self, message: Msg) {
let mut expression = self.0.write().unwrap(); let mut expression = self.0.write().unwrap();
match message { match message {
Msg::Push(i) => { Msg::Push(i) => {
// Realistically you might want to check decimal length here or something. // Realistically you might want to check decimal length here or something.
@ -49,7 +49,7 @@ impl Calculator {
let display = (*expression).join("").split(" ").last().unwrap_or("0").to_string(); let display = (*expression).join("").split(" ").last().unwrap_or("0").to_string();
App::<CalculatorApp, String>::dispatch_main(display); App::<CalculatorApp, String>::dispatch_main(display);
}, },
Msg::Decimal => { Msg::Decimal => {
let display = (*expression).join("").split(" ").last().unwrap_or("0").to_string(); let display = (*expression).join("").split(" ").last().unwrap_or("0").to_string();
if !display.contains(".") { if !display.contains(".") {
@ -65,11 +65,11 @@ impl Calculator {
} }
} }
}, },
Msg::Subtract => { Msg::Subtract => {
(*expression).push(" - ".to_string()); (*expression).push(" - ".to_string());
}, },
Msg::Multiply => { Msg::Multiply => {
(*expression).push(" * ".to_string()); (*expression).push(" * ".to_string());
}, },
@ -90,7 +90,7 @@ impl Calculator {
} }
println!("Expr: {}", expr); println!("Expr: {}", expr);
match eval::eval(&expr) { match eval::eval(&expr) {
Ok(val) => { App::<CalculatorApp, String>::dispatch_main(val.to_string()); }, Ok(val) => { App::<CalculatorApp, String>::dispatch_main(val.to_string()); },
Err(e) => { eprintln!("Error parsing expression: {:?}", e); } Err(e) => { eprintln!("Error parsing expression: {:?}", e); }
@ -98,6 +98,6 @@ impl Calculator {
} }
_ => {} _ => {}
} }
} }
} }

View file

@ -133,7 +133,7 @@ impl ViewDelegate for CalculatorView {
self.zero.top.constraint_equal_to(&self.row3.view.bottom).offset(1.), self.zero.top.constraint_equal_to(&self.row3.view.bottom).offset(1.),
self.zero.leading.constraint_equal_to(&view.leading), self.zero.leading.constraint_equal_to(&view.leading),
self.zero.bottom.constraint_equal_to(&view.bottom), self.zero.bottom.constraint_equal_to(&view.bottom),
self.dot.top.constraint_equal_to(&self.row3.view.bottom).offset(1.), self.dot.top.constraint_equal_to(&self.row3.view.bottom).offset(1.),
self.dot.leading.constraint_equal_to(&self.zero.trailing).offset(1.), self.dot.leading.constraint_equal_to(&self.zero.trailing).offset(1.),
self.dot.bottom.constraint_equal_to(&view.bottom), self.dot.bottom.constraint_equal_to(&view.bottom),

View file

@ -35,7 +35,7 @@ impl AppDelegate for CalculatorApp {
App::activate(); App::activate();
// Event Monitors need to be started after the App has been activated. // Event Monitors need to be started after the App has been activated.
// We use an RwLock here, but it's possible this entire method can be // We use an RwLock here, but it's possible this entire method can be
// &mut self and you wouldn't need these kinds of shenanigans. // &mut self and you wouldn't need these kinds of shenanigans.
//self.start_monitoring(); //self.start_monitoring();

View file

@ -36,7 +36,7 @@ impl AppDelegate for DefaultsTest {
let teststring = defaults.get("teststring").unwrap(); let teststring = defaults.get("teststring").unwrap();
assert_eq!(teststring.as_str().unwrap(), "Testing"); assert_eq!(teststring.as_str().unwrap(), "Testing");
let bytes = defaults.get("testdata").unwrap(); let bytes = defaults.get("testdata").unwrap();
let s = match std::str::from_utf8(bytes.as_data().unwrap()) { let s = match std::str::from_utf8(bytes.as_data().unwrap()) {
Ok(s) => s, Ok(s) => s,

View file

@ -49,7 +49,7 @@ impl ViewDelegate for RootView {
self.green.leading.constraint_equal_to(&view.leading).offset(16.), self.green.leading.constraint_equal_to(&view.leading).offset(16.),
self.green.trailing.constraint_equal_to(&view.trailing).offset(-16.), self.green.trailing.constraint_equal_to(&view.trailing).offset(-16.),
self.green.height.constraint_equal_to_constant(120.), self.green.height.constraint_equal_to_constant(120.),
self.blue.top.constraint_equal_to(&self.green.bottom).offset(16.), self.blue.top.constraint_equal_to(&self.green.bottom).offset(16.),
self.blue.leading.constraint_equal_to(&view.leading).offset(16.), self.blue.leading.constraint_equal_to(&view.leading).offset(16.),
self.blue.trailing.constraint_equal_to(&view.trailing).offset(-16.), self.blue.trailing.constraint_equal_to(&view.trailing).offset(-16.),
@ -74,11 +74,11 @@ impl WindowSceneDelegate for WindowScene {
let bounds = scene.get_bounds(); let bounds = scene.get_bounds();
let mut window = Window::new(bounds); let mut window = Window::new(bounds);
window.set_window_scene(scene); window.set_window_scene(scene);
let root_view_controller = ViewController::new(RootView::default()); let root_view_controller = ViewController::new(RootView::default());
window.set_root_view_controller(&root_view_controller); window.set_root_view_controller(&root_view_controller);
window.show(); window.show();
{ {
let mut w = self.window.write().unwrap(); let mut w = self.window.write().unwrap();
*w = Some(window); *w = Some(window);

View file

@ -9,10 +9,10 @@ An example that showcases layout out a view with AutoLayout. This requires the f
## Frame Layout ## Frame Layout
An example that showcases laying out with a more old school Frame-based approach. Platforms where AutoLayout are not supported will want to try this instead of the AutoLayout example. An example that showcases laying out with a more old school Frame-based approach. Platforms where AutoLayout are not supported will want to try this instead of the AutoLayout example.
**macOS:** **macOS:**
`cargo run --example frame_layout` `cargo run --example frame_layout`
**Platforms lacking AutoLayout:** **Platforms lacking AutoLayout:**
`cargo run --example frame_layout --no-default-features --features appkit` `cargo run --example frame_layout --no-default-features --features appkit`
## Defaults ## Defaults

View file

@ -15,12 +15,12 @@ pub struct AddNewTodoWindow {
impl AddNewTodoWindow { impl AddNewTodoWindow {
pub fn new() -> Self { pub fn new() -> Self {
let content = ViewController::new(AddNewTodoContentView::default()); let content = ViewController::new(AddNewTodoContentView::default());
AddNewTodoWindow { AddNewTodoWindow {
content: content content: content
} }
} }
pub fn on_message(&self, message: Message) { pub fn on_message(&self, message: Message) {
if let Some(delegate) = &self.content.view.delegate { if let Some(delegate) = &self.content.view.delegate {
delegate.on_message(message); delegate.on_message(message);
@ -30,14 +30,14 @@ impl AddNewTodoWindow {
impl WindowDelegate for AddNewTodoWindow { impl WindowDelegate for AddNewTodoWindow {
const NAME: &'static str = "AddNewTodoWindow"; const NAME: &'static str = "AddNewTodoWindow";
fn did_load(&mut self, window: Window) { fn did_load(&mut self, window: Window) {
window.set_autosave_name("AddNewTodoWindow"); window.set_autosave_name("AddNewTodoWindow");
window.set_minimum_content_size(300, 100); window.set_minimum_content_size(300, 100);
window.set_title("Add a New Task"); window.set_title("Add a New Task");
window.set_content_view_controller(&self.content); window.set_content_view_controller(&self.content);
} }
fn cancel(&self) { fn cancel(&self) {
dispatch_ui(Message::CloseSheet); dispatch_ui(Message::CloseSheet);
} }

View file

@ -41,17 +41,17 @@ impl AddNewTodoContentView {
impl ViewDelegate for AddNewTodoContentView { impl ViewDelegate for AddNewTodoContentView {
const NAME: &'static str = "AddNewTodoContentView"; const NAME: &'static str = "AddNewTodoContentView";
fn did_load(&mut self, view: View) { fn did_load(&mut self, view: View) {
let instructions = Label::new(); let instructions = Label::new();
instructions.set_text("Let's be real: we both know this task isn't getting done."); instructions.set_text("Let's be real: we both know this task isn't getting done.");
let input = TextField::new(); let input = TextField::new();
let mut button = Button::new("Add"); let mut button = Button::new("Add");
button.set_key_equivalent("\r"); button.set_key_equivalent("\r");
button.set_action(|| dispatch_ui(Message::ProcessNewTodo)); button.set_action(|| dispatch_ui(Message::ProcessNewTodo));
view.add_subview(&instructions); view.add_subview(&instructions);
view.add_subview(&input); view.add_subview(&input);
view.add_subview(&button); view.add_subview(&button);

View file

@ -22,7 +22,7 @@ impl AppDelegate for TodosApp {
App::set_menu(menu()); App::set_menu(menu());
App::activate(); App::activate();
self.window_manager.open_main(); self.window_manager.open_main();
} }
} }

View file

@ -14,11 +14,11 @@ pub fn menu() -> Vec<Menu> {
Menu::new("", vec![ Menu::new("", vec![
MenuItem::About("Todos".to_string()), MenuItem::About("Todos".to_string()),
MenuItem::Separator, MenuItem::Separator,
MenuItem::new("Preferences").key(",").action(|| { MenuItem::new("Preferences").key(",").action(|| {
dispatch_ui(Message::OpenPreferencesWindow); dispatch_ui(Message::OpenPreferencesWindow);
}), }),
MenuItem::Separator, MenuItem::Separator,
MenuItem::Services, MenuItem::Services,
MenuItem::Separator, MenuItem::Separator,
@ -35,7 +35,7 @@ pub fn menu() -> Vec<Menu> {
}), }),
MenuItem::Separator, MenuItem::Separator,
MenuItem::new("Add Todo").key("+").action(|| { MenuItem::new("Add Todo").key("+").action(|| {
dispatch_ui(Message::OpenNewTodoSheet); dispatch_ui(Message::OpenNewTodoSheet);
}), }),
@ -54,7 +54,7 @@ pub fn menu() -> Vec<Menu> {
MenuItem::Separator, MenuItem::Separator,
MenuItem::SelectAll MenuItem::SelectAll
]), ]),
Menu::new("View", vec![ Menu::new("View", vec![
MenuItem::EnterFullScreen MenuItem::EnterFullScreen
]), ]),

View file

@ -10,7 +10,7 @@ pub struct AdvancedPreferencesContentView {
impl ViewDelegate for AdvancedPreferencesContentView { impl ViewDelegate for AdvancedPreferencesContentView {
const NAME: &'static str = "AdvancedPreferencesContentView"; const NAME: &'static str = "AdvancedPreferencesContentView";
fn did_load(&mut self, view: View) { fn did_load(&mut self, view: View) {
self.label.set_text("And this is where advanced preferences would be... if we had any."); self.label.set_text("And this is where advanced preferences would be... if we had any.");
self.label.set_text_alignment(TextAlign::Center); self.label.set_text_alignment(TextAlign::Center);

View file

@ -1,5 +1,5 @@
//! The main guts of the Preferences window. We store all our preferences in //! The main guts of the Preferences window. We store all our preferences in
//! `UserDefaults`, so there's not too much extra needed here - we can do most //! `UserDefaults`, so there's not too much extra needed here - we can do most
//! event handlers inline. //! event handlers inline.
use cacao::layout::{Layout, LayoutConstraint}; use cacao::layout::{Layout, LayoutConstraint};
@ -17,7 +17,7 @@ pub struct GeneralPreferencesContentView {
impl ViewDelegate for GeneralPreferencesContentView { impl ViewDelegate for GeneralPreferencesContentView {
const NAME: &'static str = "GeneralPreferencesContentView"; const NAME: &'static str = "GeneralPreferencesContentView";
fn did_load(&mut self, view: View) { fn did_load(&mut self, view: View) {
self.example_option.configure( self.example_option.configure(
"An example preference", "An example preference",

View file

@ -33,7 +33,7 @@ impl PreferencesWindow {
window: None window: None
} }
} }
pub fn on_message(&self, message: Message) { pub fn on_message(&self, message: Message) {
let window = self.window.as_ref().unwrap(); let window = self.window.as_ref().unwrap();
@ -56,11 +56,11 @@ impl PreferencesWindow {
impl WindowDelegate for PreferencesWindow { impl WindowDelegate for PreferencesWindow {
const NAME: &'static str = "PreferencesWindow"; const NAME: &'static str = "PreferencesWindow";
fn did_load(&mut self, window: Window) { fn did_load(&mut self, window: Window) {
window.set_autosave_name("TodosPreferencesWindow"); window.set_autosave_name("TodosPreferencesWindow");
window.set_movable_by_background(true); window.set_movable_by_background(true);
window.set_toolbar(&self.toolbar); window.set_toolbar(&self.toolbar);
self.window = Some(window); self.window = Some(window);
self.on_message(Message::SwitchPreferencesToGeneralPane); self.on_message(Message::SwitchPreferencesToGeneralPane);

View file

@ -23,7 +23,7 @@ impl Default for ToggleOptionView {
let title = Label::new(); let title = Label::new();
view.add_subview(&title); view.add_subview(&title);
let subtitle = Label::new(); let subtitle = Label::new();
view.add_subview(&subtitle); view.add_subview(&subtitle);
@ -31,7 +31,7 @@ impl Default for ToggleOptionView {
switch.top.constraint_equal_to(&view.top), switch.top.constraint_equal_to(&view.top),
switch.leading.constraint_equal_to(&view.leading), switch.leading.constraint_equal_to(&view.leading),
switch.width.constraint_equal_to_constant(24.), switch.width.constraint_equal_to_constant(24.),
title.top.constraint_equal_to(&view.top), title.top.constraint_equal_to(&view.top),
title.leading.constraint_equal_to(&switch.trailing), title.leading.constraint_equal_to(&switch.trailing),
title.trailing.constraint_equal_to(&view.trailing), title.trailing.constraint_equal_to(&view.trailing),

View file

@ -17,7 +17,7 @@ impl Default for PreferencesToolbar {
let icon = Image::toolbar_icon(MacSystemIcon::PreferencesGeneral, "General"); let icon = Image::toolbar_icon(MacSystemIcon::PreferencesGeneral, "General");
item.set_image(icon); item.set_image(icon);
item.set_action(|| { item.set_action(|| {
dispatch_ui(Message::SwitchPreferencesToGeneralPane); dispatch_ui(Message::SwitchPreferencesToGeneralPane);
}); });
@ -26,14 +26,14 @@ impl Default for PreferencesToolbar {
}, { }, {
let mut item = ToolbarItem::new("advanced"); let mut item = ToolbarItem::new("advanced");
item.set_title("Advanced"); item.set_title("Advanced");
let icon = Image::toolbar_icon(MacSystemIcon::PreferencesAdvanced, "Advanced"); let icon = Image::toolbar_icon(MacSystemIcon::PreferencesAdvanced, "Advanced");
item.set_image(icon); item.set_image(icon);
item.set_action(|| { item.set_action(|| {
dispatch_ui(Message::SwitchPreferencesToAdvancedPane); dispatch_ui(Message::SwitchPreferencesToAdvancedPane);
}); });
item item
})) }))
} }
@ -41,7 +41,7 @@ impl Default for PreferencesToolbar {
impl ToolbarDelegate for PreferencesToolbar { impl ToolbarDelegate for PreferencesToolbar {
const NAME: &'static str = "PreferencesToolbar"; const NAME: &'static str = "PreferencesToolbar";
fn did_load(&mut self, toolbar: Toolbar) { fn did_load(&mut self, toolbar: Toolbar) {
toolbar.set_selected("general"); toolbar.set_selected("general");
} }

View file

@ -42,13 +42,13 @@ impl Defaults {
/// should work, and I'd rather it crash with a meaningful message rather than `unwrap()` issues. /// should work, and I'd rather it crash with a meaningful message rather than `unwrap()` issues.
fn toggle_bool(key: &str) { fn toggle_bool(key: &str) {
let mut defaults = UserDefaults::standard(); let mut defaults = UserDefaults::standard();
if let Some(value) = defaults.get(key) { if let Some(value) = defaults.get(key) {
if let Some(value) = value.as_bool() { if let Some(value) = value.as_bool() {
defaults.insert(key, Value::Bool(!value)); defaults.insert(key, Value::Bool(!value));
return; return;
} }
panic!("Attempting to toggle a boolean value for {}, but it's not a boolean.", key); panic!("Attempting to toggle a boolean value for {}, but it's not a boolean.", key);
} }
@ -62,12 +62,12 @@ fn toggle_bool(key: &str) {
/// should work, and I'd rather it crash with a meaningful message rather than `unwrap()` issues. /// should work, and I'd rather it crash with a meaningful message rather than `unwrap()` issues.
fn load_bool(key: &str) -> bool { fn load_bool(key: &str) -> bool {
let defaults = UserDefaults::standard(); let defaults = UserDefaults::standard();
if let Some(value) = defaults.get(key) { if let Some(value) = defaults.get(key) {
if let Some(value) = value.as_bool() { if let Some(value) = value.as_bool() {
return value; return value;
} }
panic!("Attempting to load a boolean value for {}, but it's not a boolean.", key); panic!("Attempting to load a boolean value for {}, but it's not a boolean.", key);
} }

View file

@ -11,7 +11,7 @@ pub use defaults::Defaults;
mod todos; mod todos;
pub use todos::{Todos, Todo, TodoStatus}; pub use todos::{Todos, Todo, TodoStatus};
/// Message passing is our primary way of instructing UI changes without needing to do /// Message passing is our primary way of instructing UI changes without needing to do
/// constant crazy referencing in Rust. Dispatch a method using either `dispatch_ui` for the main /// constant crazy referencing in Rust. Dispatch a method using either `dispatch_ui` for the main
/// thread, or `dispatch` for a background thread, and the main `TodosApp` will receive the /// thread, or `dispatch` for a background thread, and the main `TodosApp` will receive the
/// message. From there, it can filter down to components, or just handle it as necessary. /// message. From there, it can filter down to components, or just handle it as necessary.

View file

@ -43,7 +43,7 @@ impl Todos {
*stack = todos; *stack = todos;
} }
/// Edit a Todo at the row specified. /// Edit a Todo at the row specified.
pub fn with_mut<F>(&self, row: usize, handler: F) pub fn with_mut<F>(&self, row: usize, handler: F)
where where

View file

@ -15,7 +15,7 @@ use row::TodoViewRow;
/// An identifier for the cell(s) we dequeue. /// An identifier for the cell(s) we dequeue.
const TODO_ROW: &'static str = "TodoViewRowCell"; const TODO_ROW: &'static str = "TodoViewRowCell";
/// The list view for todos. /// The list view for todos.
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct TodosListView { pub struct TodosListView {
view: Option<ListView>, view: Option<ListView>,
@ -33,10 +33,10 @@ impl TodosListView {
view.set_row_actions_visible(false); view.set_row_actions_visible(false);
} }
}, },
Message::MarkTodoIncomplete(row) => { Message::MarkTodoIncomplete(row) => {
self.todos.with_mut(row, |todo| todo.status = TodoStatus::Incomplete); self.todos.with_mut(row, |todo| todo.status = TodoStatus::Incomplete);
if let Some(view) = &self.view { if let Some(view) = &self.view {
view.reload_rows(&[row]); view.reload_rows(&[row]);
view.set_row_actions_visible(false); view.set_row_actions_visible(false);
@ -77,7 +77,7 @@ impl ListViewDelegate for TodosListView {
/// configuration. /// configuration.
fn item_for(&self, row: usize) -> ListViewRow { fn item_for(&self, row: usize) -> ListViewRow {
let mut view = self.view.as_ref().unwrap().dequeue::<TodoViewRow>(TODO_ROW); let mut view = self.view.as_ref().unwrap().dequeue::<TodoViewRow>(TODO_ROW);
if let Some(view) = &mut view.delegate { if let Some(view) = &mut view.delegate {
self.todos.with(row, |todo| view.configure_with(todo)); self.todos.with(row, |todo| view.configure_with(todo));
} }

View file

@ -34,7 +34,7 @@ impl TodoViewRow {
impl ViewDelegate for TodoViewRow { impl ViewDelegate for TodoViewRow {
const NAME: &'static str = "TodoViewRow"; const NAME: &'static str = "TodoViewRow";
/// Called when the view is first created; handles setup of layout and associated styling that /// Called when the view is first created; handles setup of layout and associated styling that
/// doesn't change. /// doesn't change.
fn did_load(&mut self, view: View) { fn did_load(&mut self, view: View) {
@ -50,7 +50,7 @@ impl ViewDelegate for TodoViewRow {
self.title.top.constraint_equal_to(&view.top).offset(16.), self.title.top.constraint_equal_to(&view.top).offset(16.),
self.title.leading.constraint_equal_to(&view.leading).offset(16.), self.title.leading.constraint_equal_to(&view.leading).offset(16.),
self.title.trailing.constraint_equal_to(&view.trailing).offset(-16.), self.title.trailing.constraint_equal_to(&view.trailing).offset(-16.),
self.status.top.constraint_equal_to(&self.title.bottom).offset(8.), self.status.top.constraint_equal_to(&self.title.bottom).offset(8.),
self.status.leading.constraint_equal_to(&view.leading).offset(16.), self.status.leading.constraint_equal_to(&view.leading).offset(16.),
self.status.trailing.constraint_equal_to(&view.trailing).offset(-16.), self.status.trailing.constraint_equal_to(&view.trailing).offset(-16.),

View file

@ -26,7 +26,7 @@ impl TodosWindow {
toolbar: Toolbar::new("TodosToolbar", TodosToolbar::default()) toolbar: Toolbar::new("TodosToolbar", TodosToolbar::default())
} }
} }
pub fn on_message(&self, message: Message) { pub fn on_message(&self, message: Message) {
if let Some(delegate) = &self.content.view.delegate { if let Some(delegate) = &self.content.view.delegate {
delegate.on_message(message); delegate.on_message(message);
@ -36,8 +36,8 @@ impl TodosWindow {
impl WindowDelegate for TodosWindow { impl WindowDelegate for TodosWindow {
const NAME: &'static str = "TodosWindow"; const NAME: &'static str = "TodosWindow";
fn did_load(&mut self, window: Window) { fn did_load(&mut self, window: Window) {
window.set_autosave_name("TodosWindow"); window.set_autosave_name("TodosWindow");
window.set_minimum_content_size(400, 400); window.set_minimum_content_size(400, 400);
window.set_movable_by_background(true); window.set_movable_by_background(true);

View file

@ -17,7 +17,7 @@ impl Default for TodosToolbar {
let mut item = ToolbarItem::new("AddTodoButton"); let mut item = ToolbarItem::new("AddTodoButton");
item.set_title("Add Todo"); item.set_title("Add Todo");
item.set_button(Button::new("+ New")); item.set_button(Button::new("+ New"));
item.set_action(|| { item.set_action(|| {
dispatch_ui(Message::OpenNewTodoSheet); dispatch_ui(Message::OpenNewTodoSheet);
}); });

View file

@ -29,7 +29,7 @@ where
F: Fn() -> (WindowConfig, T) F: Fn() -> (WindowConfig, T)
{ {
let mut lock = window.write().unwrap(); let mut lock = window.write().unwrap();
if let Some(win) = &*lock { if let Some(win) = &*lock {
win.show(); win.show();
} else { } else {
@ -55,7 +55,7 @@ impl WindowManager {
F: Fn() + Send + Sync + 'static F: Fn() + Send + Sync + 'static
{ {
let main = self.main.write().unwrap(); let main = self.main.write().unwrap();
if let Some(main_window) = &*main { if let Some(main_window) = &*main {
main_window.begin_sheet(window, completion); main_window.begin_sheet(window, completion);
} }

View file

@ -38,8 +38,8 @@ impl WebViewDelegate for WebViewInstance {
<h1>Welcome 🍫</h1> <h1>Welcome 🍫</h1>
<a href="/hello.html">Link</a> <a href="/hello.html">Link</a>
</body> </body>
</html>"#; </html>"#;
let link_html = r#" let link_html = r#"
<!DOCTYPE html> <!DOCTYPE html>
<html lang="en"> <html lang="en">
@ -52,7 +52,7 @@ impl WebViewDelegate for WebViewInstance {
<h1>Hello!</h1> <h1>Hello!</h1>
<a href="/index.html">Back home</a> <a href="/index.html">Back home</a>
</body> </body>
</html>"#; </html>"#;
return match requested_asset_path.as_str() { return match requested_asset_path.as_str() {
"/hello.html" => Some(link_html.as_bytes().into()), "/hello.html" => Some(link_html.as_bytes().into()),

View file

@ -39,7 +39,7 @@ impl AppDelegate for BasicApp {
]); ]);
App::activate(); App::activate();
self.window.show(); self.window.show();
} }

View file

@ -9,13 +9,13 @@
//! //!
//! ```rust //! ```rust
//! use cacao::appkit::{App, AppDelegate, Alert}; //! use cacao::appkit::{App, AppDelegate, Alert};
//! //!
//! #[derive(Default)] //! #[derive(Default)]
//! struct ExampleApp; //! struct ExampleApp;
//! //!
//! impl AppDelegate { //! impl AppDelegate {
//! fn did_finish_launching(&self) { //! fn did_finish_launching(&self) {
//! //!
//! } //! }
//! } //! }
//! //!

View file

@ -19,7 +19,7 @@ impl AnimationContext {
let _: () = msg_send![self.0, setDuration:duration]; let _: () = msg_send![self.0, setDuration:duration];
} }
} }
/// Pass it a block, and the changes in that block will be animated, provided they're /// Pass it a block, and the changes in that block will be animated, provided they're
/// properties that support animation. /// properties that support animation.
/// ///
@ -66,7 +66,7 @@ impl AnimationContext {
unsafe { unsafe {
//let context: id = msg_send![class!(NSAnimationContext), currentContext]; //let context: id = msg_send![class!(NSAnimationContext), currentContext];
let _: () = msg_send![class!(NSAnimationContext), runAnimationGroup:block let _: () = msg_send![class!(NSAnimationContext), runAnimationGroup:block
completionHandler:completion_block]; completionHandler:completion_block];
} }
} }

View file

@ -146,12 +146,12 @@ extern fn will_continue_user_activity_with_type<T: AppDelegate>(this: &Object, _
extern fn continue_user_activity<T: AppDelegate>(this: &Object, _: Sel, _: id, activity: id, handler: id) -> BOOL { extern fn continue_user_activity<T: AppDelegate>(this: &Object, _: Sel, _: id, activity: id, handler: id) -> BOOL {
// @TODO: This needs to support restorable objects, but it involves a larger question about how // @TODO: This needs to support restorable objects, but it involves a larger question about how
// much `NSObject` retainping we want to do here. For now, pass the handler for whenever it's // much `NSObject` retainping we want to do here. For now, pass the handler for whenever it's
// useful. // useful.
let activity = UserActivity::with_inner(activity); let activity = UserActivity::with_inner(activity);
match app::<T>(this).continue_user_activity(activity, || unsafe { match app::<T>(this).continue_user_activity(activity, || unsafe {
let handler = handler as *const Block<(id,), c_void>; let handler = handler as *const Block<(id,), c_void>;
(*handler).call((nil,)); (*handler).call((nil,));
}) { }) {
true => YES, true => YES,
false => NO false => NO
@ -202,7 +202,7 @@ extern fn open_urls<T: AppDelegate>(this: &Object, _: Sel, _: id, file_urls: id)
let uri = NSString::retain(unsafe { let uri = NSString::retain(unsafe {
msg_send![url, absoluteString] msg_send![url, absoluteString]
}); });
Url::parse(uri.to_str()) Url::parse(uri.to_str())
}).into_iter().filter_map(|url| url.ok()).collect(); }).into_iter().filter_map(|url| url.ok()).collect();
@ -307,7 +307,7 @@ pub(crate) fn register_app_delegate_class<T: AppDelegate + AppDelegate>() -> *co
// Launching Applications // Launching Applications
decl.add_method(sel!(applicationWillFinishLaunching:), will_finish_launching::<T> as extern fn(&Object, _, _)); decl.add_method(sel!(applicationWillFinishLaunching:), will_finish_launching::<T> as extern fn(&Object, _, _));
decl.add_method(sel!(applicationDidFinishLaunching:), did_finish_launching::<T> as extern fn(&Object, _, _)); decl.add_method(sel!(applicationDidFinishLaunching:), did_finish_launching::<T> as extern fn(&Object, _, _));
// Managing Active Status // Managing Active Status
decl.add_method(sel!(applicationWillBecomeActive:), will_become_active::<T> as extern fn(&Object, _, _)); decl.add_method(sel!(applicationWillBecomeActive:), will_become_active::<T> as extern fn(&Object, _, _));
decl.add_method(sel!(applicationDidBecomeActive:), did_become_active::<T> as extern fn(&Object, _, _)); decl.add_method(sel!(applicationDidBecomeActive:), did_become_active::<T> as extern fn(&Object, _, _));

View file

@ -12,10 +12,10 @@ pub enum TerminateResponse {
/// App should not be terminated. /// App should not be terminated.
Cancel, Cancel,
/// It might be fine to proceed with termination later. Returning this value causes /// It might be fine to proceed with termination later. Returning this value causes
/// Cocoa to run the run loop until `should_terminate()` returns `true` or `false`. /// Cocoa to run the run loop until `should_terminate()` returns `true` or `false`.
/// ///
/// This return value is for primarily for cases where you need to provide alerts /// This return value is for primarily for cases where you need to provide alerts
/// in order to decide whether to quit. /// in order to decide whether to quit.
Later Later
} }
@ -67,7 +67,7 @@ impl From<AppDelegateResponse> for NSUInteger {
/// - _`AutoHideMenuBar` and `HideMenuBar` are mutually exclusive: You may specify one or the other, but not both._ /// - _`AutoHideMenuBar` and `HideMenuBar` are mutually exclusive: You may specify one or the other, but not both._
/// - _If you specify `HideMenuBar`, it must be accompanied by `HideDock`._ /// - _If you specify `HideMenuBar`, it must be accompanied by `HideDock`._
/// - _If you specify `AutoHideMenuBar`, it must be accompanied by either `HideDock` or `AutoHideDock`._ /// - _If you specify `AutoHideMenuBar`, it must be accompanied by either `HideDock` or `AutoHideDock`._
/// - _If you specify any of `DisableProcessSwitching`, `DisableForceQuit`, `DisableSessionTermination`, or `DisableMenuBarTransparency`, /// - _If you specify any of `DisableProcessSwitching`, `DisableForceQuit`, `DisableSessionTermination`, or `DisableMenuBarTransparency`,
/// it must be accompanied by either `HideDock` or `AutoHideDock`._ /// it must be accompanied by either `HideDock` or `AutoHideDock`._
/// - _`AutoHideToolbar` may be used only when both `FullScreen` and `AutoHideMenuBar` are also set. /// - _`AutoHideToolbar` may be used only when both `FullScreen` and `AutoHideMenuBar` are also set.
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
@ -86,10 +86,10 @@ pub enum PresentationOption {
/// Menubar is entirely disabled. /// Menubar is entirely disabled.
HideMenuBar, HideMenuBar,
/// All Apple Menu items are disabled. /// All Apple Menu items are disabled.
DisableAppleMenu, DisableAppleMenu,
/// The process switching user interface (Command + Tab to cycle through apps) is disabled. /// The process switching user interface (Command + Tab to cycle through apps) is disabled.
DisableProcessSwitching, DisableProcessSwitching,

View file

@ -6,7 +6,7 @@
//! ```rust,no_run //! ```rust,no_run
//! use cacao::app::{App, AppDelegate}; //! use cacao::app::{App, AppDelegate};
//! use cacao::window::Window; //! use cacao::window::Window;
//! //!
//! #[derive(Default)] //! #[derive(Default)]
//! struct BasicApp; //! struct BasicApp;
//! //!
@ -20,7 +20,7 @@
//! App::new("com.my.app", BasicApp::default()).run(); //! App::new("com.my.app", BasicApp::default()).run();
//! } //! }
//! ``` //! ```
//! //!
//! ## Why do I need to do this? //! ## Why do I need to do this?
//! A good question. Cocoa does many things for you (e.g, setting up and managing a runloop, //! A good question. Cocoa does many things for you (e.g, setting up and managing a runloop,
//! handling the view/window heirarchy, and so on). This requires certain things happen before your //! handling the view/window heirarchy, and so on). This requires certain things happen before your
@ -29,7 +29,7 @@
//! - It ensures that the `sharedApplication` is properly initialized with your delegate. //! - It ensures that the `sharedApplication` is properly initialized with your delegate.
//! - It ensures that Cocoa is put into multi-threaded mode, so standard POSIX threads work as they //! - It ensures that Cocoa is put into multi-threaded mode, so standard POSIX threads work as they
//! should. //! should.
//! //!
//! ### Platform specificity //! ### Platform specificity
//! Certain lifecycle events are specific to certain platforms. Where this is the case, the //! Certain lifecycle events are specific to certain platforms. Where this is the case, the
//! documentation makes every effort to note. //! documentation makes every effort to note.
@ -114,7 +114,7 @@ impl<T, M> fmt::Debug for App<T, M> {
} }
} }
impl<T> App<T> { impl<T> App<T> {
/// Kicks off the NSRunLoop for the NSApplication instance. This blocks when called. /// Kicks off the NSRunLoop for the NSApplication instance. This blocks when called.
/// If you're wondering where to go from here... you need an `AppDelegate` that implements /// If you're wondering where to go from here... you need an `AppDelegate` that implements
/// `did_finish_launching`. :) /// `did_finish_launching`. :)
@ -134,16 +134,16 @@ impl<T> App<T> where T: AppDelegate + 'static {
/// Objective-C side of things. /// Objective-C side of things.
pub fn new(_bundle_id: &str, delegate: T) -> Self { pub fn new(_bundle_id: &str, delegate: T) -> Self {
//set_bundle_id(bundle_id); //set_bundle_id(bundle_id);
activate_cocoa_multithreading(); activate_cocoa_multithreading();
let pool = AutoReleasePool::new(); let pool = AutoReleasePool::new();
let objc = unsafe { let objc = unsafe {
let app: id = msg_send![register_app_class(), sharedApplication]; let app: id = msg_send![register_app_class(), sharedApplication];
Id::from_ptr(app) Id::from_ptr(app)
}; };
let app_delegate = Box::new(delegate); let app_delegate = Box::new(delegate);
let objc_delegate = unsafe { let objc_delegate = unsafe {
@ -163,7 +163,7 @@ impl<T> App<T> where T: AppDelegate + 'static {
_message: std::marker::PhantomData _message: std::marker::PhantomData
} }
} }
} }
// This is a very basic "dispatch" mechanism. In macOS, it's critical that UI work happen on the // This is a very basic "dispatch" mechanism. In macOS, it's critical that UI work happen on the
// UI ("main") thread. We can hook into the standard mechanism for this by dispatching on // UI ("main") thread. We can hook into the standard mechanism for this by dispatching on
@ -171,7 +171,7 @@ impl<T> App<T> where T: AppDelegate + 'static {
// for the main queue. They automatically forward through to our registered `AppDelegate`. // for the main queue. They automatically forward through to our registered `AppDelegate`.
// //
// One thing I don't like about GCD is that detecting incorrect thread usage has historically been // One thing I don't like about GCD is that detecting incorrect thread usage has historically been
// a bit... annoying. Here, the `Dispatcher` trait explicitly requires implementing two methods - // a bit... annoying. Here, the `Dispatcher` trait explicitly requires implementing two methods -
// one for UI messages, and one for background messages. I think that this helps separate intent // one for UI messages, and one for background messages. I think that this helps separate intent
// on the implementation side, and makes it a bit easier to detect when a message has come in on // on the implementation side, and makes it a bit easier to detect when a message has come in on
// the wrong side. // the wrong side.
@ -185,7 +185,7 @@ impl<T, M> App<T, M> where M: Send + Sync + 'static, T: AppDelegate + Dispatcher
/// and passing back through there. /// and passing back through there.
pub fn dispatch_main(message: M) { pub fn dispatch_main(message: M) {
let queue = dispatch::Queue::main(); let queue = dispatch::Queue::main();
queue.exec_async(move || unsafe { queue.exec_async(move || unsafe {
let app: id = msg_send![register_app_class(), sharedApplication]; let app: id = msg_send![register_app_class(), sharedApplication];
let app_delegate: id = msg_send![app, delegate]; let app_delegate: id = msg_send![app, delegate];
@ -199,7 +199,7 @@ impl<T, M> App<T, M> where M: Send + Sync + 'static, T: AppDelegate + Dispatcher
/// and passing back through there. /// and passing back through there.
pub fn dispatch_background(message: M) { pub fn dispatch_background(message: M) {
let queue = dispatch::Queue::main(); let queue = dispatch::Queue::main();
queue.exec_async(move || unsafe { queue.exec_async(move || unsafe {
let app: id = msg_send![register_app_class(), sharedApplication]; let app: id = msg_send![register_app_class(), sharedApplication];
let app_delegate: id = msg_send![app, delegate]; let app_delegate: id = msg_send![app, delegate];
@ -217,7 +217,7 @@ impl App {
let _: () = msg_send![app, registerForRemoteNotifications]; let _: () = msg_send![app, registerForRemoteNotifications];
}); });
} }
/// Unregisters for remote notifications from APNS. /// Unregisters for remote notifications from APNS.
pub fn unregister_for_remote_notifications() { pub fn unregister_for_remote_notifications() {
shared_application(|app| unsafe { shared_application(|app| unsafe {

View file

@ -33,7 +33,7 @@ pub trait AppDelegate {
/// Fired when the application is about to resign active state. /// Fired when the application is about to resign active state.
fn will_resign_active(&self) {} fn will_resign_active(&self) {}
/// Fired when the user is going to continue an activity. /// Fired when the user is going to continue an activity.
fn will_continue_user_activity(&self, _activity_type: &str) -> bool { false } fn will_continue_user_activity(&self, _activity_type: &str) -> bool { false }
@ -59,10 +59,10 @@ pub trait AppDelegate {
fn failed_to_register_for_remote_notifications(&self, _error: Error) {} fn failed_to_register_for_remote_notifications(&self, _error: Error) {}
/// Fires after the user accepted a CloudKit sharing invitation associated with your /// Fires after the user accepted a CloudKit sharing invitation associated with your
/// application. /// application.
#[cfg(feature = "cloudkit")] #[cfg(feature = "cloudkit")]
fn user_accepted_cloudkit_share(&self, _share_metadata: CKShareMetaData) {} fn user_accepted_cloudkit_share(&self, _share_metadata: CKShareMetaData) {}
/// Fired before the application terminates. You can use this to do any required cleanup. /// Fired before the application terminates. You can use this to do any required cleanup.
fn will_terminate(&self) {} fn will_terminate(&self) {}
@ -92,7 +92,7 @@ pub trait AppDelegate {
/// This is fired after the `Quit` menu item has been selected, or after you've called `App::terminate()`. /// This is fired after the `Quit` menu item has been selected, or after you've called `App::terminate()`.
/// ///
/// In most cases you just want `TerminateResponse::Now` here, which enables business as usual. If you need, /// In most cases you just want `TerminateResponse::Now` here, which enables business as usual. If you need,
/// though, you can cancel the termination via `TerminateResponse::Cancel` to continue something essential. If /// though, you can cancel the termination via `TerminateResponse::Cancel` to continue something essential. If
/// you do this, you'll need to be sure to call `App::reply_to_termination_request()` to circle /// you do this, you'll need to be sure to call `App::reply_to_termination_request()` to circle
/// back. /// back.
@ -107,12 +107,12 @@ pub trait AppDelegate {
/// `has_visible_windows` indicates whether the Application object found any visible windows in your application. /// `has_visible_windows` indicates whether the Application object found any visible windows in your application.
/// You can use this value as an indication of whether the application would do anything if you return `true`. /// You can use this value as an indication of whether the application would do anything if you return `true`.
/// ///
/// Return `true` if you want the application to perform its normal tasks, or `false` if you want the /// Return `true` if you want the application to perform its normal tasks, or `false` if you want the
/// application to do nothing. The default implementation of this method returns `true`. /// application to do nothing. The default implementation of this method returns `true`.
/// ///
/// Some finer points of discussion, from Apple documentation: /// Some finer points of discussion, from Apple documentation:
/// ///
/// These events are sent whenever the Finder reactivates an already running application because someone /// These events are sent whenever the Finder reactivates an already running application because someone
/// double-clicked it again or used the dock to activate it. /// double-clicked it again or used the dock to activate it.
/// ///
/// For most document-based applications, an untitled document will be created. /// For most document-based applications, an untitled document will be created.
@ -133,13 +133,13 @@ pub trait AppDelegate {
/// Fired when the screen parameters for the application have changed (e.g, the user changed /// Fired when the screen parameters for the application have changed (e.g, the user changed
/// something in their settings). /// something in their settings).
fn did_change_screen_parameters(&self) {} fn did_change_screen_parameters(&self) {}
/// Fired when you have a list of `Url`'s to open. This is best explained by quoting the Apple /// Fired when you have a list of `Url`'s to open. This is best explained by quoting the Apple
/// documentation verbatim: /// documentation verbatim:
/// ///
/// _"AppKit calls this method when your app is asked to open one or more URL-based resources. /// _"AppKit calls this method when your app is asked to open one or more URL-based resources.
/// You must declare the URL types that your app supports in your `Info.plist` file using the `CFBundleURLTypes` key. /// You must declare the URL types that your app supports in your `Info.plist` file using the `CFBundleURLTypes` key.
/// The list can also include URLs for documents for which your app does not have an associated `NSDocument` class. /// The list can also include URLs for documents for which your app does not have an associated `NSDocument` class.
/// You configure document types by adding the `CFBundleDocumentTypes` key to your Info.plist /// You configure document types by adding the `CFBundleDocumentTypes` key to your Info.plist
/// file." /// file."
/// ///
@ -150,9 +150,9 @@ pub trait AppDelegate {
/// Fired when the file is requested to be opened programmatically. This is not a commonly used /// Fired when the file is requested to be opened programmatically. This is not a commonly used
/// or implemented method. /// or implemented method.
/// ///
/// According to Apple: /// According to Apple:
/// ///
/// _"The method should open the file without bringing up its applications user interface—that is, /// _"The method should open the file without bringing up its applications user interface—that is,
/// work with the file is under programmatic control of sender, rather than under keyboard control of the user."_ /// work with the file is under programmatic control of sender, rather than under keyboard control of the user."_
/// ///
/// It's unclear how supported this is in sandbox environments, so use at your own risk. /// It's unclear how supported this is in sandbox environments, so use at your own risk.
@ -195,9 +195,9 @@ pub trait AppDelegate {
/// Fired when the occlusion state for the app has changed. /// Fired when the occlusion state for the app has changed.
/// ///
/// From Apple's docs, as there's no other way to describe this better: _upon receiving this method, you can query the /// From Apple's docs, as there's no other way to describe this better: _upon receiving this method, you can query the
/// application for its occlusion state. Note that this only notifies about changes in the state of the occlusion, not /// application for its occlusion state. Note that this only notifies about changes in the state of the occlusion, not
/// when the occlusion region changes. You can use this method to increase responsiveness and save power by halting any /// when the occlusion region changes. You can use this method to increase responsiveness and save power by halting any
/// expensive calculations that the user can not see._ /// expensive calculations that the user can not see._
fn occlusion_state_changed(&self) {} fn occlusion_state_changed(&self) {}

View file

@ -20,19 +20,19 @@ pub enum CursorType {
/// A pointing hand, like clicking a link. /// A pointing hand, like clicking a link.
PointingHand, PointingHand,
/// Indicator that something can be resized to the left. /// Indicator that something can be resized to the left.
ResizeLeft, ResizeLeft,
/// Indicator that something can be resized to the right. /// Indicator that something can be resized to the right.
ResizeRight, ResizeRight,
/// Indicator that something can be resized on the horizontal axis. /// Indicator that something can be resized on the horizontal axis.
ResizeLeftRight, ResizeLeftRight,
/// Indicates that something can be resized up. /// Indicates that something can be resized up.
ResizeUp, ResizeUp,
/// Indicates that something can be resized down. /// Indicates that something can be resized down.
ResizeDown, ResizeDown,
@ -58,7 +58,7 @@ pub enum CursorType {
/// Used for drag-and-drop usually, will displayu the standard "+" icon next to the cursor. /// Used for drag-and-drop usually, will displayu the standard "+" icon next to the cursor.
DragCopy, DragCopy,
/// Indicates a context menu will open. /// Indicates a context menu will open.
ContextMenu ContextMenu
} }
@ -114,7 +114,7 @@ impl Cursor {
CursorType::DragCopy => msg_send![class!(NSCursor), dragCopyCursor], CursorType::DragCopy => msg_send![class!(NSCursor), dragCopyCursor],
CursorType::ContextMenu => msg_send![class!(NSCursor), contextualMenuCursor] CursorType::ContextMenu => msg_send![class!(NSCursor), contextualMenuCursor]
}; };
let _: () = msg_send![cursor, push]; let _: () = msg_send![cursor, push];
} }
} }

View file

@ -7,7 +7,7 @@ use crate::foundation::{NSUInteger};
pub enum FocusRingType { pub enum FocusRingType {
/// Whatever the default is. /// Whatever the default is.
Default, Default,
/// None. /// None.
None, None,

View file

@ -17,12 +17,12 @@ use crate::events::EventModifierFlag;
static BLOCK_PTR: &'static str = "cacaoMenuItemBlockPtr"; static BLOCK_PTR: &'static str = "cacaoMenuItemBlockPtr";
/// An Action is just an indirection layer to get around Rust and optimizing /// An Action is just an indirection layer to get around Rust and optimizing
/// zero-sum types; without this, pointers to callbacks will end up being /// zero-sum types; without this, pointers to callbacks will end up being
/// 0x1, and all point to whatever is there first (unsure if this is due to /// 0x1, and all point to whatever is there first (unsure if this is due to
/// Rust or Cocoa or what). /// Rust or Cocoa or what).
/// ///
/// Point is, Button aren't created that much in the grand scheme of things, /// Point is, Button aren't created that much in the grand scheme of things,
/// and the heap isn't our enemy in a GUI framework anyway. If someone knows /// and the heap isn't our enemy in a GUI framework anyway. If someone knows
/// a better way to do this that doesn't require double-boxing, I'm all ears. /// a better way to do this that doesn't require double-boxing, I'm all ears.
pub struct Action(Box<dyn Fn() + 'static>); pub struct Action(Box<dyn Fn() + 'static>);
@ -58,9 +58,9 @@ fn make_menu_item<S: AsRef<str>>(
let alloc: id = msg_send![register_menu_item_class(), alloc]; let alloc: id = msg_send![register_menu_item_class(), alloc];
let item = Id::from_retained_ptr(match action { let item = Id::from_retained_ptr(match action {
Some(a) => msg_send![alloc, initWithTitle:&*title action:a keyEquivalent:&*key], Some(a) => msg_send![alloc, initWithTitle:&*title action:a keyEquivalent:&*key],
None => msg_send![alloc, initWithTitle:&*title None => msg_send![alloc, initWithTitle:&*title
action:sel!(fireBlockAction:) action:sel!(fireBlockAction:)
keyEquivalent:&*key] keyEquivalent:&*key]
}); });
@ -115,7 +115,7 @@ pub enum MenuItem {
/// A menu item for enabling copying (often text) from responders. /// A menu item for enabling copying (often text) from responders.
Copy, Copy,
/// A menu item for enabling cutting (often text) from responders. /// A menu item for enabling cutting (often text) from responders.
Cut, Cut,
@ -126,10 +126,10 @@ pub enum MenuItem {
/// An "redo" menu item; particularly useful for supporting the cut/copy/paste/undo lifecycle /// An "redo" menu item; particularly useful for supporting the cut/copy/paste/undo lifecycle
/// of events. /// of events.
Redo, Redo,
/// A menu item for selecting all (often text) from responders. /// A menu item for selecting all (often text) from responders.
SelectAll, SelectAll,
/// A menu item for pasting (often text) into responders. /// A menu item for pasting (often text) into responders.
Paste, Paste,
@ -158,7 +158,7 @@ impl MenuItem {
pub(crate) unsafe fn to_objc(self) -> Id<Object> { pub(crate) unsafe fn to_objc(self) -> Id<Object> {
match self { match self {
Self::Custom(objc) => objc, Self::Custom(objc) => objc,
Self::About(app_name) => { Self::About(app_name) => {
let title = format!("About {}", app_name); let title = format!("About {}", app_name);
make_menu_item(&title, None, Some(sel!(orderFrontStandardAboutPanel:)), None) make_menu_item(&title, None, Some(sel!(orderFrontStandardAboutPanel:)), None)
@ -192,7 +192,7 @@ impl MenuItem {
Self::Redo => make_menu_item("Redo", Some("Z"), Some(sel!(redo:)), None), Self::Redo => make_menu_item("Redo", Some("Z"), Some(sel!(redo:)), None),
Self::SelectAll => make_menu_item("Select All", Some("a"), Some(sel!(selectAll:)), None), Self::SelectAll => make_menu_item("Select All", Some("a"), Some(sel!(selectAll:)), None),
Self::Paste => make_menu_item("Paste", Some("v"), Some(sel!(paste:)), None), Self::Paste => make_menu_item("Paste", Some("v"), Some(sel!(paste:)), None),
Self::EnterFullScreen => make_menu_item( Self::EnterFullScreen => make_menu_item(
"Enter Full Screen", "Enter Full Screen",
Some("f"), Some("f"),
@ -225,7 +225,7 @@ impl MenuItem {
} }
/// Configures the a custom item to have specified key equivalent. This does nothing if called /// Configures the a custom item to have specified key equivalent. This does nothing if called
/// on a `MenuItem` type that is not `Custom`, /// on a `MenuItem` type that is not `Custom`,
pub fn key(self, key: &str) -> Self { pub fn key(self, key: &str) -> Self {
if let MenuItem::Custom(objc) = self { if let MenuItem::Custom(objc) = self {
unsafe { unsafe {
@ -271,7 +271,7 @@ impl MenuItem {
if let MenuItem::Custom(mut objc) = self { if let MenuItem::Custom(mut objc) = self {
let handler = Box::new(Action(Box::new(action))); let handler = Box::new(Action(Box::new(action)));
let ptr = Box::into_raw(handler); let ptr = Box::into_raw(handler);
unsafe { unsafe {
(&mut *objc).set_ivar(BLOCK_PTR, ptr as usize); (&mut *objc).set_ivar(BLOCK_PTR, ptr as usize);
let _: () = msg_send![&*objc, setTarget:&*objc]; let _: () = msg_send![&*objc, setTarget:&*objc];
@ -291,7 +291,7 @@ extern fn dealloc_cacao_menuitem(this: &Object, _: Sel) {
unsafe { unsafe {
let ptr: usize = *this.get_ivar(BLOCK_PTR); let ptr: usize = *this.get_ivar(BLOCK_PTR);
let obj = ptr as *mut Action; let obj = ptr as *mut Action;
if !obj.is_null() { if !obj.is_null() {
let _handler = Box::from_raw(obj); let _handler = Box::from_raw(obj);
} }

View file

@ -99,7 +99,7 @@ impl Menu {
MenuItem::Separator, MenuItem::Separator,
MenuItem::SelectAll MenuItem::SelectAll
]), ]),
Menu::new("View", vec![ Menu::new("View", vec![
MenuItem::EnterFullScreen MenuItem::EnterFullScreen
]), ]),

View file

@ -15,7 +15,7 @@ pub enum PrintResponse {
Failure, Failure,
/// For when the result of printing cannot be returned immediately (e.g, if printing causes a sheet to appear). /// For when the result of printing cannot be returned immediately (e.g, if printing causes a sheet to appear).
/// If your method returns PrintResponse::ReplyLater it must always invoke `App::reply_to_open_or_print()` when the /// If your method returns PrintResponse::ReplyLater it must always invoke `App::reply_to_open_or_print()` when the
/// entire print operation has been completed, successfully or not. /// entire print operation has been completed, successfully or not.
ReplyLater ReplyLater
} }

View file

@ -58,7 +58,7 @@ extern fn item_for_identifier<T: ToolbarDelegate>(
) -> id { ) -> id {
let toolbar = load::<T>(this, TOOLBAR_PTR); let toolbar = load::<T>(this, TOOLBAR_PTR);
let identifier = NSString::from_retained(identifier); let identifier = NSString::from_retained(identifier);
let item = toolbar.item_for(identifier.to_str()); let item = toolbar.item_for(identifier.to_str());
unsafe { unsafe {
msg_send![&*item.objc, self] msg_send![&*item.objc, self]

View file

@ -72,7 +72,7 @@ impl ToolbarItem {
button.objc.with_mut(|obj| unsafe { button.objc.with_mut(|obj| unsafe {
let _: () = msg_send![&*self.objc, setView:obj]; let _: () = msg_send![&*self.objc, setView:obj];
}); });
self.button = Some(button); self.button = Some(button);
} }

View file

@ -25,7 +25,7 @@ pub use enums::{ToolbarDisplayMode, ToolbarSizeMode, ItemIdentifier};
pub(crate) static TOOLBAR_PTR: &str = "cacaoToolbarPtr"; pub(crate) static TOOLBAR_PTR: &str = "cacaoToolbarPtr";
/// A wrapper for `NSToolbar`. Holds (retains) pointers for the Objective-C runtime /// A wrapper for `NSToolbar`. Holds (retains) pointers for the Objective-C runtime
/// where our `NSToolbar` and associated delegate live. /// where our `NSToolbar` and associated delegate live.
pub struct Toolbar<T = ()> { pub struct Toolbar<T = ()> {
/// An internal identifier used by the toolbar. We cache it here in case users want it. /// An internal identifier used by the toolbar. We cache it here in case users want it.
@ -48,7 +48,7 @@ impl<T> Toolbar<T> where T: ToolbarDelegate + 'static {
let identifier = identifier.into(); let identifier = identifier.into();
let cls = register_toolbar_class::<T>(&delegate); let cls = register_toolbar_class::<T>(&delegate);
let mut delegate = Box::new(delegate); let mut delegate = Box::new(delegate);
let (objc, objc_delegate) = unsafe { let (objc, objc_delegate) = unsafe {
let alloc: id = msg_send![class!(NSToolbar), alloc]; let alloc: id = msg_send![class!(NSToolbar), alloc];
let identifier = NSString::new(&identifier); let identifier = NSString::new(&identifier);

View file

@ -27,7 +27,7 @@ pub trait ToolbarDelegate {
/// The default items in this toolbar. /// The default items in this toolbar.
fn default_item_identifiers(&self) -> Vec<ItemIdentifier>; fn default_item_identifiers(&self) -> Vec<ItemIdentifier>;
/// The default items in this toolbar. This defaults to a blank `Vec`, and is an optional /// The default items in this toolbar. This defaults to a blank `Vec`, and is an optional
/// method - mostly useful for Preferences windows. /// method - mostly useful for Preferences windows.
fn selectable_item_identifiers(&self) -> Vec<ItemIdentifier> { vec![] } fn selectable_item_identifiers(&self) -> Vec<ItemIdentifier> { vec![] }

View file

@ -59,8 +59,8 @@ extern fn did_change_screen_profile<T: WindowDelegate>(this: &Object, _: Sel, _:
extern fn will_resize<T: WindowDelegate>(this: &Object, _: Sel, _: id, size: CGSize) -> CGSize { extern fn will_resize<T: WindowDelegate>(this: &Object, _: Sel, _: id, size: CGSize) -> CGSize {
let window = load::<T>(this, WINDOW_DELEGATE_PTR); let window = load::<T>(this, WINDOW_DELEGATE_PTR);
let s = window.will_resize(size.width as f64, size.height as f64); let s = window.will_resize(size.width as f64, size.height as f64);
CGSize { CGSize {
width: s.0 as CGFloat, width: s.0 as CGFloat,
height: s.1 as CGFloat height: s.1 as CGFloat
} }
@ -134,8 +134,8 @@ extern fn options_for_full_screen<T: WindowDelegate>(this: &Object, _: Sel, _: i
let window = load::<T>(this, WINDOW_DELEGATE_PTR); let window = load::<T>(this, WINDOW_DELEGATE_PTR);
let desired_opts = window.presentation_options_for_full_screen(); let desired_opts = window.presentation_options_for_full_screen();
if desired_opts.is_none() { if desired_opts.is_none() {
options options
} else { } else {
let mut opts: NSUInteger = 0; let mut opts: NSUInteger = 0;
@ -219,7 +219,7 @@ extern fn did_expose<T: WindowDelegate>(this: &Object, _: Sel, _: id) {
window.did_expose(); window.did_expose();
} }
/// Called as part of the responder chain, when, say, the ESC key is hit. If your /// Called as part of the responder chain, when, say, the ESC key is hit. If your
/// delegate returns `true` in `should_cancel_on_esc`, then this will allow your /// delegate returns `true` in `should_cancel_on_esc`, then this will allow your
/// window to close when the Esc key is hit. This is mostly useful for Sheet-presented /// window to close when the Esc key is hit. This is mostly useful for Sheet-presented
/// windows, and so the default response from delegates is `false` and must be opted in to. /// windows, and so the default response from delegates is `false` and must be opted in to.

View file

@ -14,11 +14,11 @@ pub struct WindowConfig {
/// The initial dimensions for the window. /// The initial dimensions for the window.
pub initial_dimensions: Rect, pub initial_dimensions: Rect,
/// From the Apple docs: /// From the Apple docs:
/// ///
/// _"When true, the window server defers creating the window device /// _"When true, the window server defers creating the window device
/// until the window is moved onscreen. All display messages sent to /// until the window is moved onscreen. All display messages sent to
/// the window or its views are postponed until the window is created, /// the window or its views are postponed until the window is created,
/// just before its moved onscreen."_ /// just before its moved onscreen."_
/// ///
/// You generally just want this to be true, and it's the default for this struct. /// You generally just want this to be true, and it's the default for this struct.

View file

@ -40,7 +40,7 @@ use crate::appkit::window::{Window, WindowConfig, WindowDelegate, WINDOW_DELEGAT
mod class; mod class;
use class::register_window_controller_class; use class::register_window_controller_class;
/// A `WindowController` wraps your `WindowDelegate` into an underlying `Window`, and /// A `WindowController` wraps your `WindowDelegate` into an underlying `Window`, and
/// provides some extra lifecycle methods. /// provides some extra lifecycle methods.
pub struct WindowController<T> { pub struct WindowController<T> {
/// A handler to the underlying `NSWindowController`. /// A handler to the underlying `NSWindowController`.

View file

@ -4,8 +4,8 @@
//! resizing, closing, and so on). Note that interaction patterns are different between macOS and //! resizing, closing, and so on). Note that interaction patterns are different between macOS and
//! iOS windows, so your codebase may need to differ quite a bit here. //! iOS windows, so your codebase may need to differ quite a bit here.
//! //!
//! Of note: on macOS, in places where things are outright deprecated, this framework will opt to //! Of note: on macOS, in places where things are outright deprecated, this framework will opt to
//! not bother providing access to them. If you require functionality like that, you're free to use //! not bother providing access to them. If you require functionality like that, you're free to use
//! the `objc` field on a `Window` to instrument it with the Objective-C runtime on your own. //! the `objc` field on a `Window` to instrument it with the Objective-C runtime on your own.
use block::ConcreteBlock; use block::ConcreteBlock;
@ -72,13 +72,13 @@ impl Window {
let _: () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:NO]; let _: () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:NO];
let alloc: id = msg_send![class!(NSWindow), alloc]; let alloc: id = msg_send![class!(NSWindow), alloc];
// Other types of backing (Retained/NonRetained) are archaic, dating back to the // Other types of backing (Retained/NonRetained) are archaic, dating back to the
// NeXTSTEP era, and are outright deprecated... so we don't allow setting them. // NeXTSTEP era, and are outright deprecated... so we don't allow setting them.
let buffered: NSUInteger = 2; let buffered: NSUInteger = 2;
let dimensions: CGRect = config.initial_dimensions.into(); let dimensions: CGRect = config.initial_dimensions.into();
let window: id = msg_send![alloc, initWithContentRect:dimensions let window: id = msg_send![alloc, initWithContentRect:dimensions
styleMask:config.style styleMask:config.style
backing:buffered backing:buffered
defer:match config.defer { defer:match config.defer {
true => YES, true => YES,
@ -93,7 +93,7 @@ impl Window {
// Objective-C runtime gets out of sync by releasing the window out from underneath of // Objective-C runtime gets out of sync by releasing the window out from underneath of
// us. // us.
let _: () = msg_send![window, setReleasedWhenClosed:NO]; let _: () = msg_send![window, setReleasedWhenClosed:NO];
let _: () = msg_send![window, setRestorable:NO]; let _: () = msg_send![window, setRestorable:NO];
// This doesn't exist prior to Big Sur, but is important to support for Big Sur. // This doesn't exist prior to Big Sur, but is important to support for Big Sur.
@ -122,20 +122,20 @@ impl<T> Window<T> where T: WindowDelegate + 'static {
pub fn with(config: WindowConfig, delegate: T) -> Self { pub fn with(config: WindowConfig, delegate: T) -> Self {
let class = register_window_class_with_delegate::<T>(&delegate); let class = register_window_class_with_delegate::<T>(&delegate);
let mut delegate = Box::new(delegate); let mut delegate = Box::new(delegate);
let objc = unsafe { let objc = unsafe {
// This behavior might make sense to keep as default (YES), but I think the majority of // This behavior might make sense to keep as default (YES), but I think the majority of
// apps that would use this toolkit wouldn't be tab-oriented... // apps that would use this toolkit wouldn't be tab-oriented...
let _: () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:NO]; let _: () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:NO];
let alloc: id = msg_send![class, alloc]; let alloc: id = msg_send![class, alloc];
// Other types of backing (Retained/NonRetained) are archaic, dating back to the // Other types of backing (Retained/NonRetained) are archaic, dating back to the
// NeXTSTEP era, and are outright deprecated... so we don't allow setting them. // NeXTSTEP era, and are outright deprecated... so we don't allow setting them.
let buffered: NSUInteger = 2; let buffered: NSUInteger = 2;
let dimensions: CGRect = config.initial_dimensions.into(); let dimensions: CGRect = config.initial_dimensions.into();
let window: id = msg_send![alloc, initWithContentRect:dimensions let window: id = msg_send![alloc, initWithContentRect:dimensions
styleMask:config.style styleMask:config.style
backing:buffered backing:buffered
defer:match config.defer { defer:match config.defer {
true => YES, true => YES,
@ -226,7 +226,7 @@ impl<T> Window<T> {
pub fn set_autosave_name(&self, name: &str) { pub fn set_autosave_name(&self, name: &str) {
unsafe { unsafe {
let autosave = NSString::new(name); let autosave = NSString::new(name);
let _: () = msg_send![&*self.objc, setFrameAutosaveName:autosave]; let _: () = msg_send![&*self.objc, setFrameAutosaveName:autosave];
} }
} }
@ -253,7 +253,7 @@ impl<T> Window<T> {
let _: () = msg_send![&*self.objc, setContentMaxSize:size]; let _: () = msg_send![&*self.objc, setContentMaxSize:size];
} }
} }
/// Sets the minimum size this window can shrink to. /// Sets the minimum size this window can shrink to.
pub fn set_minimum_size<F: Into<f64>>(&self, width: F, height: F) { pub fn set_minimum_size<F: Into<f64>>(&self, width: F, height: F) {
unsafe { unsafe {
@ -262,13 +262,13 @@ impl<T> Window<T> {
} }
} }
/// Used for setting a toolbar on this window. /// Used for setting a toolbar on this window.
pub fn set_toolbar<TC: ToolbarDelegate>(&self, toolbar: &Toolbar<TC>) { pub fn set_toolbar<TC: ToolbarDelegate>(&self, toolbar: &Toolbar<TC>) {
unsafe { unsafe {
let _: () = msg_send![&*self.objc, setToolbar:&*toolbar.objc]; let _: () = msg_send![&*self.objc, setToolbar:&*toolbar.objc];
} }
} }
/// Toggles whether the toolbar is shown for this window. Has no effect if no toolbar exists on /// Toggles whether the toolbar is shown for this window. Has no effect if no toolbar exists on
/// this window. /// this window.
pub fn toggle_toolbar_shown(&self) { pub fn toggle_toolbar_shown(&self) {
@ -377,9 +377,9 @@ impl<T> Window<T> {
/// ///
/// From Apple's documentation: /// From Apple's documentation:
/// ///
/// _The value of this property is YES if the window is on the currently active space; otherwise, NO. /// _The value of this property is YES if the window is on the currently active space; otherwise, NO.
/// For visible windows, this property indicates whether the window is currently visible on the active /// For visible windows, this property indicates whether the window is currently visible on the active
/// space. For nonvisible windows, it indicates whether ordering the window onscreen would cause it to /// space. For nonvisible windows, it indicates whether ordering the window onscreen would cause it to
/// be on the active space._ /// be on the active space._
pub fn is_on_active_space(&self) -> bool { pub fn is_on_active_space(&self) -> bool {
to_bool(unsafe { to_bool(unsafe {
@ -453,7 +453,7 @@ impl<T> Window<T> {
let _: () = msg_send![&*self.objc, setTitlebarSeparatorStyle:style]; let _: () = msg_send![&*self.objc, setTitlebarSeparatorStyle:style];
} }
} }
/// Returns the backing scale (e.g, `1.0` for non retina, `2.0` for retina) used on this /// Returns the backing scale (e.g, `1.0` for non retina, `2.0` for retina) used on this
/// window. /// window.
/// ///

View file

@ -8,7 +8,7 @@ use crate::appkit::window::Window;
/// Lifecycle events for anything that `impl Window`'s. These map to the standard Cocoa /// Lifecycle events for anything that `impl Window`'s. These map to the standard Cocoa
/// lifecycle methods, but mix in a few extra things to handle offering configuration tools /// lifecycle methods, but mix in a few extra things to handle offering configuration tools
/// in lieu of subclasses. /// in lieu of subclasses.
pub trait WindowDelegate { pub trait WindowDelegate {
/// Used to cache subclass creations on the Objective-C side. /// Used to cache subclass creations on the Objective-C side.
/// You can just set this to be the name of your view type. This /// You can just set this to be the name of your view type. This
/// value *must* be unique per-type. /// value *must* be unique per-type.
@ -34,7 +34,7 @@ pub trait WindowDelegate {
/// perhaps you have a long running task, or something that should be removed. /// perhaps you have a long running task, or something that should be removed.
fn will_close(&self) {} fn will_close(&self) {}
/// Fired when the window is about to move. /// Fired when the window is about to move.
fn will_move(&self) {} fn will_move(&self) {}
/// Fired after the window has moved. /// Fired after the window has moved.
@ -47,7 +47,7 @@ pub trait WindowDelegate {
/// The default implementation of this method returns `None`, indicating the system should just /// The default implementation of this method returns `None`, indicating the system should just
/// do its thing. If you implement it, you probably want that. /// do its thing. If you implement it, you probably want that.
fn will_resize(&self, width: f64, height: f64) -> (f64, f64) { (width, height) } fn will_resize(&self, width: f64, height: f64) -> (f64, f64) { (width, height) }
/// Fired after the window has resized. /// Fired after the window has resized.
fn did_resize(&self) {} fn did_resize(&self) {}
@ -93,7 +93,7 @@ pub trait WindowDelegate {
/// Fires when the system is moving a window to full screen and wants to know what content size /// Fires when the system is moving a window to full screen and wants to know what content size
/// to use. By default, this just returns the system-provided content size, but you can /// to use. By default, this just returns the system-provided content size, but you can
/// override it if need be. /// override it if need be.
fn content_size_for_full_screen(&self, proposed_width: f64, proposed_height: f64) -> (f64, f64) { fn content_size_for_full_screen(&self, proposed_width: f64, proposed_height: f64) -> (f64, f64) {
(proposed_width, proposed_height) (proposed_width, proposed_height)
} }
@ -119,7 +119,7 @@ pub trait WindowDelegate {
/// Fires when this window failed to exit full screen. /// Fires when this window failed to exit full screen.
fn did_fail_to_exit_full_screen(&self) {} fn did_fail_to_exit_full_screen(&self) {}
/// Fired when the occlusion state for this window has changed. Similar in nature to the /// Fired when the occlusion state for this window has changed. Similar in nature to the
/// app-level event, just for a Window. /// app-level event, just for a Window.
fn did_change_occlusion_state(&self) {} fn did_change_occlusion_state(&self) {}

View file

@ -80,7 +80,7 @@ unsafe fn swizzle_bundle_id<F>(bundle_id: &str, func: F) where F: MethodImplemen
// let mut cls = class!(NSBundle) as *mut Class; // let mut cls = class!(NSBundle) as *mut Class;
// Class::get("NSBundle").unwrap(); // Class::get("NSBundle").unwrap();
// let types = format!("{}{}{}", Encoding::String, <*mut Object>::ENCODING, Sel::ENCODING); // let types = format!("{}{}{}", Encoding::String, <*mut Object>::ENCODING, Sel::ENCODING);
let added = class_addMethod( let added = class_addMethod(
cls as *mut Class, cls as *mut Class,
sel!(__bundleIdentifier), sel!(__bundleIdentifier),

View file

@ -44,7 +44,7 @@ pub enum BezelStyle {
/// A textured square style. /// A textured square style.
TexturedSquare, TexturedSquare,
/// Any style that's not known by this framework (e.g, if Apple /// Any style that's not known by this framework (e.g, if Apple
/// introduces something new). /// introduces something new).
Unknown(NSUInteger) Unknown(NSUInteger)
} }

View file

@ -52,7 +52,7 @@ pub use enums::*;
/// ///
/// You'd use this type to create a button that a user can interact with. Buttons can be configured /// You'd use this type to create a button that a user can interact with. Buttons can be configured
/// a number of ways, and support setting a callback to fire when they're clicked or tapped. /// a number of ways, and support setting a callback to fire when they're clicked or tapped.
/// ///
/// Some properties are platform-specific; see the documentation for further information. /// Some properties are platform-specific; see the documentation for further information.
/// ///
/// ```rust,no_run /// ```rust,no_run
@ -75,7 +75,7 @@ pub struct Button {
pub image: Option<Image>, pub image: Option<Image>,
handler: Option<TargetActionHandler>, handler: Option<TargetActionHandler>,
/// A pointer to the Objective-C runtime top layout constraint. /// A pointer to the Objective-C runtime top layout constraint.
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
pub top: LayoutAnchorY, pub top: LayoutAnchorY,
@ -130,47 +130,47 @@ impl Button {
]; ];
let _: () = msg_send![button, setWantsLayer:YES]; let _: () = msg_send![button, setWantsLayer:YES];
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
let _: () = msg_send![button, setTranslatesAutoresizingMaskIntoConstraints:NO]; let _: () = msg_send![button, setTranslatesAutoresizingMaskIntoConstraints:NO];
button button
}; };
Button { Button {
handler: None, handler: None,
image: None, image: None,
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view), top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view), left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view), leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view), right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view), trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view), bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view), width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view), height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view), center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view), center_y: LayoutAnchorY::center(view),
objc: ObjcProperty::retain(view), objc: ObjcProperty::retain(view),
} }
} }
@ -188,7 +188,7 @@ impl Button {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
pub fn set_bezel_style(&self, bezel_style: BezelStyle) { pub fn set_bezel_style(&self, bezel_style: BezelStyle) {
let style: NSUInteger = bezel_style.into(); let style: NSUInteger = bezel_style.into();
self.objc.with_mut(|obj| unsafe { self.objc.with_mut(|obj| unsafe {
let _: () = msg_send![obj, setBezelStyle:style]; let _: () = msg_send![obj, setBezelStyle:style];
}); });
@ -206,7 +206,7 @@ impl Button {
/// Call this to set the background color for the backing layer. /// Call this to set the background color for the backing layer.
pub fn set_background_color<C: AsRef<Color>>(&self, color: C) { pub fn set_background_color<C: AsRef<Color>>(&self, color: C) {
let color: id = color.as_ref().into(); let color: id = color.as_ref().into();
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
self.objc.with_mut(|obj| unsafe { self.objc.with_mut(|obj| unsafe {
let cell: id = msg_send![obj, cell]; let cell: id = msg_send![obj, cell];
@ -227,7 +227,7 @@ impl Button {
Key::Char(s) => NSString::new(s), Key::Char(s) => NSString::new(s),
Key::Delete => NSString::new("\u{08}") Key::Delete => NSString::new("\u{08}")
}; };
unsafe { unsafe {
let _: () = msg_send![obj, setKeyEquivalent:&*keychar]; let _: () = msg_send![obj, setKeyEquivalent:&*keychar];
} }
@ -236,16 +236,16 @@ impl Button {
/// Sets the text color for this button. /// Sets the text color for this button.
/// ///
/// On appkit, this is done by way of an `AttributedString` under the hood. /// On appkit, this is done by way of an `AttributedString` under the hood.
pub fn set_text_color<C: AsRef<Color>>(&self, color: C) { pub fn set_text_color<C: AsRef<Color>>(&self, color: C) {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
self.objc.with_mut(move |obj| unsafe { self.objc.with_mut(move |obj| unsafe {
let text: id = msg_send![obj, attributedTitle]; let text: id = msg_send![obj, attributedTitle];
let len: isize = msg_send![text, length]; let len: isize = msg_send![text, length];
let mut attr_str = AttributedString::wrap(text); let mut attr_str = AttributedString::wrap(text);
attr_str.set_text_color(color.as_ref(), 0..len); attr_str.set_text_color(color.as_ref(), 0..len);
let _: () = msg_send![obj, setAttributedTitle:&*attr_str]; let _: () = msg_send![obj, setAttributedTitle:&*attr_str];
}); });
} }
@ -332,7 +332,7 @@ impl Drop for Button {
} }
} }
/// Registers an `NSButton` subclass, and configures it to hold some ivars /// Registers an `NSButton` subclass, and configures it to hold some ivars
/// for various things we need to store. /// for various things we need to store.
fn register_class() -> *const Class { fn register_class() -> *const Class {
static mut VIEW_CLASS: *const Class = 0 as *const Class; static mut VIEW_CLASS: *const Class = 0 as *const Class;
@ -340,7 +340,7 @@ fn register_class() -> *const Class {
INIT.call_once(|| unsafe { INIT.call_once(|| unsafe {
let superclass = class!(NSButton); let superclass = class!(NSButton);
let decl = ClassDecl::new("RSTButton", superclass).unwrap(); let decl = ClassDecl::new("RSTButton", superclass).unwrap();
VIEW_CLASS = decl.register(); VIEW_CLASS = decl.register();
}); });

View file

@ -1,7 +1,7 @@
//! This module provides a custom NSColor subclass for macOS that mimics the dynamic //! This module provides a custom NSColor subclass for macOS that mimics the dynamic
//! UIColor provider found on iOS. Notably, this works with older versions of macOS as //! UIColor provider found on iOS. Notably, this works with older versions of macOS as
//! well; it runs the block on creation and caches the created color instances to avoid //! well; it runs the block on creation and caches the created color instances to avoid
//! repeated allocations - this might not be a big thing to worry about as NSColor //! repeated allocations - this might not be a big thing to worry about as NSColor
//! changed slightly behind the scenes in 10.15+, so this could be changed down the //! changed slightly behind the scenes in 10.15+, so this could be changed down the
//! road. //! road.
//! //!
@ -278,7 +278,7 @@ pub(crate) fn register_class() -> *const Class {
decl.add_method(sel!(getCyan:magenta:yellow:black:alpha:), get_cmyk as extern fn(&Object, _, CGFloat, CGFloat, CGFloat, CGFloat, CGFloat)); decl.add_method(sel!(getCyan:magenta:yellow:black:alpha:), get_cmyk as extern fn(&Object, _, CGFloat, CGFloat, CGFloat, CGFloat, CGFloat));
decl.add_method(sel!(alphaComponent), alpha_component as extern fn(&Object, _) -> CGFloat); decl.add_method(sel!(alphaComponent), alpha_component as extern fn(&Object, _) -> CGFloat);
decl.add_method(sel!(CGColor), cg_color as extern fn(&Object, _) -> id); decl.add_method(sel!(CGColor), cg_color as extern fn(&Object, _) -> id);
decl.add_method(sel!(setStroke), set_stroke as extern fn(&Object, _)); decl.add_method(sel!(setStroke), set_stroke as extern fn(&Object, _));
decl.add_method(sel!(setFill), set_fill as extern fn(&Object, _)); decl.add_method(sel!(setFill), set_fill as extern fn(&Object, _));
@ -295,7 +295,7 @@ pub(crate) fn register_class() -> *const Class {
decl.add_ivar::<id>(AQUA_LIGHT_COLOR_HIGH_CONTRAST); decl.add_ivar::<id>(AQUA_LIGHT_COLOR_HIGH_CONTRAST);
decl.add_ivar::<id>(AQUA_DARK_COLOR_NORMAL_CONTRAST); decl.add_ivar::<id>(AQUA_DARK_COLOR_NORMAL_CONTRAST);
decl.add_ivar::<id>(AQUA_DARK_COLOR_HIGH_CONTRAST); decl.add_ivar::<id>(AQUA_DARK_COLOR_HIGH_CONTRAST);
VIEW_CLASS = decl.register(); VIEW_CLASS = decl.register();
}); });

View file

@ -1,5 +1,5 @@
//! Implements a wrapper type for `NSColor` and `UIColor`. It attempts to map //! Implements a wrapper type for `NSColor` and `UIColor`. It attempts to map
//! to a common shared API, but it's important to note that the platforms //! to a common shared API, but it's important to note that the platforms
//! themselves have differing levels of support for color work. Where possible, //! themselves have differing levels of support for color work. Where possible,
//! we expose some platform-specific methods for creating and working with these. //! we expose some platform-specific methods for creating and working with these.
//! //!
@ -27,7 +27,7 @@ use crate::foundation::id;
use crate::utils::os; use crate::utils::os;
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
mod appkit_dynamic_color; mod appkit_dynamic_color;
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
use appkit_dynamic_color::{ use appkit_dynamic_color::{
@ -49,7 +49,7 @@ pub enum Theme {
Dark Dark
} }
/// Represents the contrast level for a rendering context. /// Represents the contrast level for a rendering context.
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub enum Contrast { pub enum Contrast {
/// The default contrast level for the system. /// The default contrast level for the system.
@ -71,7 +71,7 @@ pub struct Style {
pub contrast: Contrast pub contrast: Contrast
} }
/// Represents a Color. You can create custom colors using the various /// Represents a Color. You can create custom colors using the various
/// initializers, or opt to use a system-provided color. The system provided /// initializers, or opt to use a system-provided color. The system provided
/// colors will automatically switch to the "correct" colors/shades depending on whether /// colors will automatically switch to the "correct" colors/shades depending on whether
/// the user is in light or dark mode; to support this with custom colors, you can create a /// the user is in light or dark mode; to support this with custom colors, you can create a
@ -84,7 +84,7 @@ pub enum Color {
/// Represents an `NSColor` on macOS, and a `UIColor` everywhere else. You typically /// Represents an `NSColor` on macOS, and a `UIColor` everywhere else. You typically
/// don't create this variant yourself; use the initializers found on this enum. /// don't create this variant yourself; use the initializers found on this enum.
/// ///
/// If you need to do custom work not covered by this enum, you can drop to /// If you need to do custom work not covered by this enum, you can drop to
/// the Objective-C level yourself and wrap your color in this. /// the Objective-C level yourself and wrap your color in this.
Custom(Arc<RwLock<Id<Object>>>), Custom(Arc<RwLock<Id<Object>>>),
@ -136,7 +136,7 @@ pub enum Color {
/// The system-provided base gray color. /// The system-provided base gray color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray, SystemGray,
/// The system-provided secondary-level gray color. /// The system-provided secondary-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray2, SystemGray2,
@ -148,11 +148,11 @@ pub enum Color {
/// The system-provided fourth-level gray color. /// The system-provided fourth-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray4, SystemGray4,
/// The system-provided fifth-level gray color. /// The system-provided fifth-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray5, SystemGray5,
/// The system-provided sixth-level gray color. /// The system-provided sixth-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray6, SystemGray6,
@ -184,11 +184,11 @@ pub enum Color {
/// The default system second-level fill color. /// The default system second-level fill color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemFillSecondary, SystemFillSecondary,
/// The default system third-level fill color. /// The default system third-level fill color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemFillTertiary, SystemFillTertiary,
/// The default system fourth-level fill color. /// The default system fourth-level fill color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemFillQuaternary, SystemFillQuaternary,
@ -204,7 +204,7 @@ pub enum Color {
/// The default system second-level background color. /// The default system second-level background color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemBackgroundSecondary, SystemBackgroundSecondary,
/// The default system third-level background color. /// The default system third-level background color.
/// This value automatically switches to the correct variant depending on light or dark mode. /// This value automatically switches to the correct variant depending on light or dark mode.
SystemBackgroundTertiary, SystemBackgroundTertiary,
@ -256,7 +256,7 @@ impl Color {
{ Id::from_ptr(msg_send![class!(UIColor), colorWithRed:r green:g blue:b alpha:a]) } { Id::from_ptr(msg_send![class!(UIColor), colorWithRed:r green:g blue:b alpha:a]) }
}))) })))
} }
/// Creates and returns a color in the RGB space, with the alpha level /// Creates and returns a color in the RGB space, with the alpha level
/// set to `255` by default. Shorthand for `rgba`. /// set to `255` by default. Shorthand for `rgba`.
pub fn rgb(red: u8, green: u8, blue: u8) -> Self { pub fn rgb(red: u8, green: u8, blue: u8) -> Self {
@ -279,7 +279,7 @@ impl Color {
{ Id::from_ptr(msg_send![class!(UIColor), colorWithHue:h saturation:s brightness:b alpha:a]) } { Id::from_ptr(msg_send![class!(UIColor), colorWithHue:h saturation:s brightness:b alpha:a]) }
}))) })))
} }
/// Creates and returns a color in the RGB space, with the alpha level /// Creates and returns a color in the RGB space, with the alpha level
/// set to `255` by default. Shorthand for `hsba`. /// set to `255` by default. Shorthand for `hsba`.
pub fn hsb(hue: u8, saturation: u8, brightness: u8) -> Self { pub fn hsb(hue: u8, saturation: u8, brightness: u8) -> Self {
@ -292,7 +292,7 @@ impl Color {
Color::Custom(Arc::new(RwLock::new(unsafe { Color::Custom(Arc::new(RwLock::new(unsafe {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
{ Id::from_ptr(msg_send![class!(NSColor), colorWithCalibratedWhite:level alpha:alpha]) } { Id::from_ptr(msg_send![class!(NSColor), colorWithCalibratedWhite:level alpha:alpha]) }
#[cfg(feature = "uikit")] #[cfg(feature = "uikit")]
{ Id::from_ptr(msg_send![class!(UIColor), colorWithWhite:level alpha:alpha]) } { Id::from_ptr(msg_send![class!(UIColor), colorWithWhite:level alpha:alpha]) }
}))) })))
@ -303,7 +303,7 @@ impl Color {
pub fn white(level: CGFloat) -> Self { pub fn white(level: CGFloat) -> Self {
Color::white_alpha(level, 1.0) Color::white_alpha(level, 1.0)
} }
/// Given a hex code and alpha level, returns a `Color` in the RGB space. /// Given a hex code and alpha level, returns a `Color` in the RGB space.
/// ///
/// This method is not an ideal one to use, but is offered as a convenience method for those /// This method is not an ideal one to use, but is offered as a convenience method for those
@ -377,15 +377,15 @@ impl Color {
color color
}); });
Id::from_ptr(color) Id::from_ptr(color)
}))) })))
} }
/// Returns a CGColor, which can be used in Core Graphics calls as well as other areas. /// Returns a CGColor, which can be used in Core Graphics calls as well as other areas.
/// ///
/// Note that CGColor is _not_ a context-aware color, unlike our `NSColor` and `UIColor` /// Note that CGColor is _not_ a context-aware color, unlike our `NSColor` and `UIColor`
/// objects. If you're painting in a context that requires dark mode support, make sure /// objects. If you're painting in a context that requires dark mode support, make sure
/// you're not using a cached version of this unless you explicitly want the _same_ color /// you're not using a cached version of this unless you explicitly want the _same_ color
/// in every context it's used in. /// in every context it's used in.
pub fn cg_color(&self) -> CGColor { pub fn cg_color(&self) -> CGColor {
@ -471,7 +471,7 @@ unsafe fn to_objc(obj: &Color) -> id {
Color::SystemGreen => system_color_with_fallback!(color, systemGreenColor, greenColor), Color::SystemGreen => system_color_with_fallback!(color, systemGreenColor, greenColor),
Color::SystemIndigo => system_color_with_fallback!(color, systemIndigoColor, magentaColor), Color::SystemIndigo => system_color_with_fallback!(color, systemIndigoColor, magentaColor),
Color::SystemOrange => system_color_with_fallback!(color, systemOrangeColor, orangeColor), Color::SystemOrange => system_color_with_fallback!(color, systemOrangeColor, orangeColor),
Color::SystemPink => system_color_with_fallback!(color, systemPinkColor, pinkColor), Color::SystemPink => system_color_with_fallback!(color, systemPinkColor, pinkColor),
Color::SystemPurple => system_color_with_fallback!(color, systemPurpleColor, purpleColor), Color::SystemPurple => system_color_with_fallback!(color, systemPurpleColor, purpleColor),
Color::SystemRed => system_color_with_fallback!(color, systemRedColor, redColor), Color::SystemRed => system_color_with_fallback!(color, systemRedColor, redColor),
Color::SystemTeal => system_color_with_fallback!(color, systemTealColor, blueColor), Color::SystemTeal => system_color_with_fallback!(color, systemTealColor, blueColor),
@ -496,17 +496,17 @@ unsafe fn to_objc(obj: &Color) -> id {
Color::SystemBackgroundSecondary => system_color_with_fallback!(color, secondarySystemBackgroundColor, clearColor), Color::SystemBackgroundSecondary => system_color_with_fallback!(color, secondarySystemBackgroundColor, clearColor),
Color::SystemBackgroundTertiary => system_color_with_fallback!(color, tertiarySystemBackgroundColor, clearColor), Color::SystemBackgroundTertiary => system_color_with_fallback!(color, tertiarySystemBackgroundColor, clearColor),
Color::Separator => system_color_with_fallback!(color, separatorColor, lightGrayColor), Color::Separator => system_color_with_fallback!(color, separatorColor, lightGrayColor),
#[cfg(feature = "uikit")] #[cfg(feature = "uikit")]
Color::OpaqueSeparator => system_color_with_fallback!(color, opaqueSeparatorColor, darkGrayColor), Color::OpaqueSeparator => system_color_with_fallback!(color, opaqueSeparatorColor, darkGrayColor),
Color::Link => system_color_with_fallback!(color, linkColor, blueColor), Color::Link => system_color_with_fallback!(color, linkColor, blueColor),
Color::DarkText => system_color_with_fallback!(color, darkTextColor, blackColor), Color::DarkText => system_color_with_fallback!(color, darkTextColor, blackColor),
Color::LightText => system_color_with_fallback!(color, lightTextColor, whiteColor), Color::LightText => system_color_with_fallback!(color, lightTextColor, whiteColor),
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
Color::MacOSWindowBackgroundColor => system_color_with_fallback!(color, windowBackgroundColor, clearColor), Color::MacOSWindowBackgroundColor => system_color_with_fallback!(color, windowBackgroundColor, clearColor),
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
Color::MacOSUnderPageBackgroundColor => system_color_with_fallback!(color, underPageBackgroundColor, clearColor), Color::MacOSUnderPageBackgroundColor => system_color_with_fallback!(color, underPageBackgroundColor, clearColor),
} }

View file

@ -13,7 +13,7 @@ pub enum ControlSize {
/// A smaller control size. /// A smaller control size.
Small, Small,
/// The default, regular, size. /// The default, regular, size.
Regular, Regular,
@ -36,7 +36,7 @@ pub trait Control: ObjcAccess {
}); });
} }
/// Sets the underlying control size. /// Sets the underlying control size.
fn set_control_size(&self, size: ControlSize) { fn set_control_size(&self, size: ControlSize) {
let control_size: NSUInteger = match size { let control_size: NSUInteger = match size {
ControlSize::Mini => 2, ControlSize::Mini => 2,

View file

@ -61,7 +61,7 @@ impl Default for UserDefaults {
impl UserDefaults { impl UserDefaults {
/// Returns the `standardUserDefaults`, which is... exactly what it sounds like. /// Returns the `standardUserDefaults`, which is... exactly what it sounds like.
/// ///
/// _Note that if you're planning to share preferences across things (e.g, an app and an /// _Note that if you're planning to share preferences across things (e.g, an app and an
/// extension) you *probably* want to use `suite()` instead!_ /// extension) you *probably* want to use `suite()` instead!_
/// ///
@ -69,7 +69,7 @@ impl UserDefaults {
/// use cacao::defaults::UserDefaults; /// use cacao::defaults::UserDefaults;
/// ///
/// let defaults = UserDefaults::standard(); /// let defaults = UserDefaults::standard();
/// ///
/// let _ = defaults.get("test"); /// let _ = defaults.get("test");
/// ``` /// ```
pub fn standard() -> Self { pub fn standard() -> Self {
@ -108,7 +108,7 @@ impl UserDefaults {
/// use cacao::defaults::{UserDefaults, Value}; /// use cacao::defaults::{UserDefaults, Value};
/// ///
/// let mut defaults = UserDefaults::standard(); /// let mut defaults = UserDefaults::standard();
/// ///
/// defaults.register({ /// defaults.register({
/// let mut map = HashMap::new(); /// let mut map = HashMap::new();
/// map.insert("test", Value::Bool(true)); /// map.insert("test", Value::Bool(true));
@ -117,7 +117,7 @@ impl UserDefaults {
/// ``` /// ```
pub fn register<K: AsRef<str>>(&mut self, values: HashMap<K, Value>) { pub fn register<K: AsRef<str>>(&mut self, values: HashMap<K, Value>) {
let dictionary = NSMutableDictionary::from(values); let dictionary = NSMutableDictionary::from(values);
unsafe { unsafe {
let _: () = msg_send![&*self.0, registerDefaults:&*dictionary]; let _: () = msg_send![&*self.0, registerDefaults:&*dictionary];
} }
@ -140,7 +140,7 @@ impl UserDefaults {
let _: () = msg_send![&*self.0, setObject:value forKey:key]; let _: () = msg_send![&*self.0, setObject:value forKey:key];
} }
} }
/// Remove the default associated with the key. If the key doesn't exist, this is a noop. /// Remove the default associated with the key. If the key doesn't exist, this is a noop.
/// ///
/// ```rust /// ```rust
@ -206,7 +206,7 @@ impl UserDefaults {
// For context: https://nshipster.com/type-encodings/ // For context: https://nshipster.com/type-encodings/
if NSNumber::is(result) { if NSNumber::is(result) {
let number = NSNumber::wrap(result); let number = NSNumber::wrap(result);
return match number.objc_type() { return match number.objc_type() {
"c" => Some(Value::Bool(number.as_bool())), "c" => Some(Value::Bool(number.as_bool())),
"d" => Some(Value::Float(number.as_f64())), "d" => Some(Value::Float(number.as_f64())),
@ -227,8 +227,8 @@ impl UserDefaults {
/// Returns a boolean value if the object stored for the specified key is managed by an /// Returns a boolean value if the object stored for the specified key is managed by an
/// administrator. This is rarely used - mostly in managed environments, e.g a classroom. /// administrator. This is rarely used - mostly in managed environments, e.g a classroom.
/// ///
/// For managed keys, the application should disable any user interface that allows the /// For managed keys, the application should disable any user interface that allows the
/// user to modify the value of key. /// user to modify the value of key.
/// ///
/// ```rust /// ```rust

View file

@ -31,7 +31,7 @@ impl Value {
pub fn string<S: Into<String>>(value: S) -> Self { pub fn string<S: Into<String>>(value: S) -> Self {
Value::String(value.into()) Value::String(value.into())
} }
/// Returns `true` if the value is a boolean value. Returns `false` otherwise. /// Returns `true` if the value is a boolean value. Returns `false` otherwise.
pub fn is_boolean(&self) -> bool { pub fn is_boolean(&self) -> bool {
match self { match self {
@ -47,7 +47,7 @@ impl Value {
_ => None _ => None
} }
} }
/// Returns `true` if the value is a string. Returns `false` otherwise. /// Returns `true` if the value is a string. Returns `false` otherwise.
pub fn is_string(&self) -> bool { pub fn is_string(&self) -> bool {
match self { match self {
@ -63,7 +63,7 @@ impl Value {
_ => None _ => None
} }
} }
/// Returns `true` if the value is a float. Returns `false` otherwise. /// Returns `true` if the value is a float. Returns `false` otherwise.
pub fn is_integer(&self) -> bool { pub fn is_integer(&self) -> bool {
match self { match self {
@ -154,7 +154,7 @@ where
let mut dictionary = NSMutableDictionary::new(); let mut dictionary = NSMutableDictionary::new();
for (key, value) in map.into_iter() { for (key, value) in map.into_iter() {
let k = NSString::new(key.as_ref()); let k = NSString::new(key.as_ref());
dictionary.insert(k, value.into()); dictionary.insert(k, value.into());
} }

View file

@ -156,7 +156,7 @@ pub enum SearchPathDirectory {
/// (_/Library/PreferencePanes_) /// (_/Library/PreferencePanes_)
PreferencePanes, PreferencePanes,
/// The user scripts folder for the calling application /// The user scripts folder for the calling application
/// (_~/Library/Application Scripts/<code-signing-id>_). /// (_~/Library/Application Scripts/<code-signing-id>_).
ApplicationScripts, ApplicationScripts,

View file

@ -15,7 +15,7 @@ use crate::filesystem::enums::{SearchPathDirectory, SearchPathDomainMask};
/// A FileManager can be used for file operations (moving files, etc). /// A FileManager can be used for file operations (moving files, etc).
/// ///
/// If your app is not sandboxed, you can use your favorite Rust library - /// If your app is not sandboxed, you can use your favorite Rust library -
/// but if you _are_ operating in the sandbox, there's a good chance you'll want to use this. /// but if you _are_ operating in the sandbox, there's a good chance you'll want to use this.
/// ///
/// @TODO: Couldn't this just be a ShareId? /// @TODO: Couldn't this just be a ShareId?
@ -55,7 +55,7 @@ impl FileManager {
let directory = unsafe { let directory = unsafe {
let manager = self.0.read().unwrap(); let manager = self.0.read().unwrap();
let dir: id = msg_send![&**manager, URLForDirectory:dir let dir: id = msg_send![&**manager, URLForDirectory:dir
inDomain:mask inDomain:mask
appropriateForURL:nil appropriateForURL:nil
create:NO create:NO
@ -63,7 +63,7 @@ impl FileManager {
NSString::retain(msg_send![dir, absoluteString]) NSString::retain(msg_send![dir, absoluteString])
}; };
Url::parse(directory.to_str()).map_err(|e| e.into()) Url::parse(directory.to_str()).map_err(|e| e.into())
} }

View file

@ -30,13 +30,13 @@ pub struct FileSelectPanel {
/// Whether the user can choose directories. Defaults to `false`. /// Whether the user can choose directories. Defaults to `false`.
pub can_choose_directories: bool, pub can_choose_directories: bool,
/// When the value of this property is true, dropping an alias on the panel or asking /// When the value of this property is true, dropping an alias on the panel or asking
/// for filenames or URLs returns the resolved aliases. The default value of this property /// for filenames or URLs returns the resolved aliases. The default value of this property
/// is true. When this value is false, selecting an alias returns the alias instead of the /// is true. When this value is false, selecting an alias returns the alias instead of the
/// file or directory it represents. /// file or directory it represents.
pub resolves_aliases: bool, pub resolves_aliases: bool,
/// When the value of this property is true, the user may select multiple items from the /// When the value of this property is true, the user may select multiple items from the
/// browser. Defaults to `false`. /// browser. Defaults to `false`.
pub allows_multiple_selection: bool pub allows_multiple_selection: bool
} }

View file

@ -11,7 +11,7 @@ pub trait OpenSaveController {
/// Notifies you that the user changed directories. /// Notifies you that the user changed directories.
fn did_change_to_directory(&self, _url: &str) {} fn did_change_to_directory(&self, _url: &str) {}
/// Notifies you that the Save panel is about to expand or collapse because the user /// Notifies you that the Save panel is about to expand or collapse because the user
/// clicked the disclosure triangle that displays or hides the file browser. /// clicked the disclosure triangle that displays or hides the file browser.
fn will_expand(&self, _expanding: bool) {} fn will_expand(&self, _expanding: bool) {}

View file

@ -65,8 +65,8 @@ impl From<Vec<&Object>> for NSArray {
/// Given a set of `Object`s, creates an `NSArray` that holds them. /// Given a set of `Object`s, creates an `NSArray` that holds them.
fn from(objects: Vec<&Object>) -> Self { fn from(objects: Vec<&Object>) -> Self {
NSArray(unsafe { NSArray(unsafe {
Id::from_ptr(msg_send![class!(NSArray), Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr() arrayWithObjects:objects.as_ptr()
count:objects.len() count:objects.len()
]) ])
}) })
@ -77,7 +77,7 @@ impl From<Vec<id>> for NSArray {
/// Given a set of `*mut Object`s, creates an `NSArray` that holds them. /// Given a set of `*mut Object`s, creates an `NSArray` that holds them.
fn from(objects: Vec<id>) -> Self { fn from(objects: Vec<id>) -> Self {
NSArray(unsafe { NSArray(unsafe {
Id::from_ptr(msg_send![class!(NSArray), Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr() arrayWithObjects:objects.as_ptr()
count:objects.len() count:objects.len()
]) ])

View file

@ -39,7 +39,7 @@ impl ClassMap {
let mut map = HashMap::new(); let mut map = HashMap::new();
// Top-level classes, like `NSView`, we cache here. The reasoning is that if a subclass // Top-level classes, like `NSView`, we cache here. The reasoning is that if a subclass
// is being created, we can avoid querying the runtime for the superclass - i.e, many // is being created, we can avoid querying the runtime for the superclass - i.e, many
// subclasses will have `NSView` as their superclass. // subclasses will have `NSView` as their superclass.
map.insert("_supers", HashMap::new()); map.insert("_supers", HashMap::new());
@ -118,15 +118,15 @@ impl ClassMap {
} }
/// Attempts to load a subclass, given a `superclass_name` and subclass_name. If /// Attempts to load a subclass, given a `superclass_name` and subclass_name. If
/// the subclass cannot be loaded, it's dynamically created and injected into /// the subclass cannot be loaded, it's dynamically created and injected into
/// the runtime, and then returned. The returned value can be used for allocating new instances of /// the runtime, and then returned. The returned value can be used for allocating new instances of
/// this class in the Objective-C runtime. /// this class in the Objective-C runtime.
/// ///
/// The `config` block can be used to customize the Class declaration before it's registered with /// The `config` block can be used to customize the Class declaration before it's registered with
/// the runtime. This is useful for adding method handlers and ivar storage. /// the runtime. This is useful for adding method handlers and ivar storage.
/// ///
/// If the superclass cannot be loaded, this will panic. If the subclass cannot be /// If the superclass cannot be loaded, this will panic. If the subclass cannot be
/// created, this will panic. In general, this is expected to work, and if it doesn't, /// created, this will panic. In general, this is expected to work, and if it doesn't,
/// the entire framework will not really work. /// the entire framework will not really work.
/// ///
/// There's definitely room to optimize here, but it works for now. /// There's definitely room to optimize here, but it works for now.
@ -155,7 +155,7 @@ where
return class; return class;
}, },
None => { None => {
panic!( panic!(
"Subclass of type {}_{} could not be allocated.", "Subclass of type {}_{} could not be allocated.",
subclass_name, subclass_name,

View file

@ -49,7 +49,7 @@ impl NSData {
NSData(Id::from_ptr(obj)) NSData(Id::from_ptr(obj))
} }
} }
/// Given a slice of bytes, creates, retains, and returns a wrapped `NSData`. /// Given a slice of bytes, creates, retains, and returns a wrapped `NSData`.
/// ///
/// This method is borrowed straight out of [objc-foundation](objc-foundation) by the amazing /// This method is borrowed straight out of [objc-foundation](objc-foundation) by the amazing
@ -96,7 +96,7 @@ impl NSData {
x as usize x as usize
} }
} }
/// Returns a reference to the underlying bytes for the wrapped `NSData`. /// Returns a reference to the underlying bytes for the wrapped `NSData`.
/// ///
/// This, like `NSData::new()`, is cribbed from [objc-foundation](objc-foundation). /// This, like `NSData::new()`, is cribbed from [objc-foundation](objc-foundation).
@ -104,19 +104,19 @@ impl NSData {
/// [objc-foundation](https://crates.io/crates/objc-foundation) /// [objc-foundation](https://crates.io/crates/objc-foundation)
pub fn bytes(&self) -> &[u8] { pub fn bytes(&self) -> &[u8] {
let ptr: *const c_void = unsafe { msg_send![&*self.0, bytes] }; let ptr: *const c_void = unsafe { msg_send![&*self.0, bytes] };
// The bytes pointer may be null for length zero // The bytes pointer may be null for length zero
let (ptr, len) = if ptr.is_null() { let (ptr, len) = if ptr.is_null() {
(0x1 as *const u8, 0) (0x1 as *const u8, 0)
} else { } else {
(ptr as *const u8, self.len()) (ptr as *const u8, self.len())
}; };
unsafe { unsafe {
slice::from_raw_parts(ptr, len) slice::from_raw_parts(ptr, len)
} }
} }
/// Creates a new Vec, copies the NSData (safely, but quickly) bytes into that Vec, and /// Creates a new Vec, copies the NSData (safely, but quickly) bytes into that Vec, and
/// consumes the NSData enabling it to release (provided nothing in Cocoa is using it). /// consumes the NSData enabling it to release (provided nothing in Cocoa is using it).
/// ///
@ -126,11 +126,11 @@ impl NSData {
// often, but still... open to ideas. // often, but still... open to ideas.
pub fn into_vec(self) -> Vec<u8> { pub fn into_vec(self) -> Vec<u8> {
let mut data = Vec::new(); let mut data = Vec::new();
let bytes = self.bytes(); let bytes = self.bytes();
data.resize(bytes.len(), 0); data.resize(bytes.len(), 0);
data.copy_from_slice(bytes); data.copy_from_slice(bytes);
data data
} }
} }

View file

@ -53,7 +53,7 @@ pub fn to_bool(result: BOOL) -> bool {
match result { match result {
YES => true, YES => true,
NO => false, NO => false,
//#[cfg(target_arch = "aarch64")] //#[cfg(target_arch = "aarch64")]
#[cfg(not(target_arch = "aarch64"))] #[cfg(not(target_arch = "aarch64"))]
_ => { std::unreachable!(); } _ => { std::unreachable!(); }

View file

@ -22,7 +22,7 @@ impl NSNumber {
Id::from_ptr(data) Id::from_ptr(data)
}) })
} }
/// If we're vended an NSNumber from a method (e.g, `NSUserDefaults` querying) we might want to /// If we're vended an NSNumber from a method (e.g, `NSUserDefaults` querying) we might want to
/// wrap it while we figure out what to do with it. This does that. /// wrap it while we figure out what to do with it. This does that.
pub fn wrap(data: id) -> Self { pub fn wrap(data: id) -> Self {

View file

@ -13,7 +13,7 @@ const UTF8_ENCODING: usize = 4;
/// A wrapper for `NSString`. /// A wrapper for `NSString`.
/// ///
/// We can make a few safety guarantees in this module as the UTF8 code on the Foundation /// We can make a few safety guarantees in this module as the UTF8 code on the Foundation
/// side is fairly battle tested. /// side is fairly battle tested.
#[derive(Debug)] #[derive(Debug)]
pub struct NSString<'a> { pub struct NSString<'a> {
@ -37,7 +37,7 @@ impl<'a> NSString<'a> {
phantom: PhantomData phantom: PhantomData
} }
} }
/// Creates a new `NSString` without copying the bytes for the passed-in string. /// Creates a new `NSString` without copying the bytes for the passed-in string.
pub fn no_copy(s: &'a str) -> Self { pub fn no_copy(s: &'a str) -> Self {
NSString { NSString {
@ -89,14 +89,14 @@ impl<'a> NSString<'a> {
fn bytes_len(&self) -> usize { fn bytes_len(&self) -> usize {
unsafe { unsafe {
msg_send![&*self.objc, lengthOfBytesUsingEncoding:UTF8_ENCODING] msg_send![&*self.objc, lengthOfBytesUsingEncoding:UTF8_ENCODING]
} }
} }
/// A utility method for taking an `NSString` and bridging it to a Rust `&str`. /// A utility method for taking an `NSString` and bridging it to a Rust `&str`.
pub fn to_str(&self) -> &str { pub fn to_str(&self) -> &str {
let bytes = self.bytes(); let bytes = self.bytes();
let len = self.bytes_len(); let len = self.bytes_len();
unsafe { unsafe {
let bytes = slice::from_raw_parts(bytes, len); let bytes = slice::from_raw_parts(bytes, len);
str::from_utf8(bytes).unwrap() str::from_utf8(bytes).unwrap()

View file

@ -9,12 +9,12 @@ pub enum NSURLBookmarkCreationOption {
/// Specifies that the bookmark data should include properties required to create Finder alias files. /// Specifies that the bookmark data should include properties required to create Finder alias files.
SuitableForBookmarkFile, SuitableForBookmarkFile,
/// Specifies that you want to create a security-scoped bookmark that, when resolved, provides a /// Specifies that you want to create a security-scoped bookmark that, when resolved, provides a
/// security-scoped URL allowing read/write access to a file-system resource. /// security-scoped URL allowing read/write access to a file-system resource.
SecurityScoped, SecurityScoped,
/// When combined with the NSURLBookmarkCreationOptions::SecurityScoped option, specifies that you /// When combined with the NSURLBookmarkCreationOptions::SecurityScoped option, specifies that you
/// want to create a security-scoped bookmark that, when resolved, provides a security-scoped URL allowing /// want to create a security-scoped bookmark that, when resolved, provides a security-scoped URL allowing
/// read-only access to a file-system resource. /// read-only access to a file-system resource.
SecurityScopedReadOnly SecurityScopedReadOnly
} }
@ -50,7 +50,7 @@ pub enum NSURLBookmarkResolutionOption {
/// Specifies that no volume should be mounted during resolution of the bookmark data. /// Specifies that no volume should be mounted during resolution of the bookmark data.
WithoutMounting, WithoutMounting,
/// Specifies that the security scope, applied to the bookmark when it was created, should /// Specifies that the security scope, applied to the bookmark when it was created, should
/// be used during resolution of the bookmark data. /// be used during resolution of the bookmark data.
SecurityScoped SecurityScoped
} }

View file

@ -13,11 +13,11 @@ mod bookmark_options;
pub use bookmark_options::{NSURLBookmarkCreationOption, NSURLBookmarkResolutionOption}; pub use bookmark_options::{NSURLBookmarkCreationOption, NSURLBookmarkResolutionOption};
mod resource_keys; mod resource_keys;
pub use resource_keys::{NSURLResourceKey, NSURLFileResource, NSUbiquitousItemDownloadingStatus}; pub use resource_keys::{NSURLResourceKey, NSURLFileResource, NSUbiquitousItemDownloadingStatus};
/// Wraps `NSURL` for use throughout the framework. /// Wraps `NSURL` for use throughout the framework.
/// ///
/// This type may also be returned to users in some callbacks (e.g, file manager/selectors) as it's /// This type may also be returned to users in some callbacks (e.g, file manager/selectors) as it's
/// a core part of the macOS/iOS experience and bridging around it is arguably blocking people from /// a core part of the macOS/iOS experience and bridging around it is arguably blocking people from
/// being able to actually build useful things. /// being able to actually build useful things.
/// ///
@ -52,11 +52,11 @@ impl<'a> NSURL<'a> {
phantom: PhantomData phantom: PhantomData
} }
} }
/// Creates and returns a URL object by calling through to `[NSURL URLWithString]`. /// Creates and returns a URL object by calling through to `[NSURL URLWithString]`.
pub fn with_str(url: &str) -> Self { pub fn with_str(url: &str) -> Self {
let url = NSString::new(url); let url = NSString::new(url);
Self { Self {
objc: unsafe { objc: unsafe {
ShareId::from_ptr(msg_send![class!(NSURL), URLWithString:&*url]) ShareId::from_ptr(msg_send![class!(NSURL), URLWithString:&*url])
@ -65,7 +65,7 @@ impl<'a> NSURL<'a> {
phantom: PhantomData phantom: PhantomData
} }
} }
/// Returns the absolute string path that this URL points to. /// Returns the absolute string path that this URL points to.
/// ///
/// Note that if the underlying file moved, this won't be accurate - you likely want to /// Note that if the underlying file moved, this won't be accurate - you likely want to
@ -145,7 +145,7 @@ impl<'a> NSURL<'a> {
/// In an app that has adopted App Sandbox, makes the resource pointed to by a security-scoped URL available to the app. /// In an app that has adopted App Sandbox, makes the resource pointed to by a security-scoped URL available to the app.
/// ///
/// More information can be found at: /// More information can be found at:
/// [https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc] /// [https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc]
pub fn start_accessing_security_scoped_resource(&self) { pub fn start_accessing_security_scoped_resource(&self) {
unsafe { unsafe {

View file

@ -8,7 +8,7 @@ use core_graphics::geometry::{CGRect, CGPoint, CGSize};
pub struct Rect { pub struct Rect {
/// Distance from the top, in points. /// Distance from the top, in points.
pub top: f64, pub top: f64,
/// Distance from the left, in points. /// Distance from the left, in points.
pub left: f64, pub left: f64,

View file

@ -31,7 +31,7 @@ pub(crate) fn register_image_view_class() -> *const Class {
let decl = ClassDecl::new("RSTImageView", superclass).unwrap(); let decl = ClassDecl::new("RSTImageView", superclass).unwrap();
//decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL); //decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
VIEW_CLASS = decl.register(); VIEW_CLASS = decl.register();
}); });

View file

@ -2,7 +2,7 @@
use objc_id::ShareId; use objc_id::ShareId;
use objc::runtime::Object; use objc::runtime::Object;
/// Views get passed these, and can /// Views get passed these, and can
#[derive(Debug)] #[derive(Debug)]
pub struct ViewHandle<T> { pub struct ViewHandle<T> {
/// A pointer to the Objective-C runtime view controller. /// A pointer to the Objective-C runtime view controller.
@ -37,7 +37,7 @@ pub struct ViewHandle<T> {
impl<T> TextControl for ViewHandle<T> impl<T> TextControl for ViewHandle<T>
where where
T: T:
impl<T> Layout for ViewHandle<T> { impl<T> Layout for ViewHandle<T> {
fn get_backing_node(&self) -> ShareId<Object> { fn get_backing_node(&self) -> ShareId<Object> {

View file

@ -67,7 +67,7 @@ impl MacSystemIcon {
MacSystemIcon::Add => SFSymbol::Plus.to_str(), MacSystemIcon::Add => SFSymbol::Plus.to_str(),
MacSystemIcon::Remove => SFSymbol::Minus.to_str(), MacSystemIcon::Remove => SFSymbol::Minus.to_str(),
MacSystemIcon::Folder => SFSymbol::FolderFilled.to_str() MacSystemIcon::Folder => SFSymbol::FolderFilled.to_str()
} }
} }
} }

View file

@ -55,7 +55,7 @@ impl ResizeBehavior {
pub fn apply(&self, source: CGRect, target: CGRect) -> CGRect { pub fn apply(&self, source: CGRect, target: CGRect) -> CGRect {
// if equal, just return source // if equal, just return source
if if
source.origin.x == target.origin.x && source.origin.x == target.origin.x &&
source.origin.y == target.origin.y && source.origin.y == target.origin.y &&
source.size.width == target.size.width && source.size.width == target.size.width &&
source.size.height == target.size.height source.size.height == target.size.height
@ -64,10 +64,10 @@ impl ResizeBehavior {
} }
if if
source.origin.x == 0. && source.origin.x == 0. &&
source.origin.y == 0. && source.origin.y == 0. &&
source.size.width == 0. && source.size.width == 0. &&
source.size.height == 0. source.size.height == 0.
{ {
return source; return source;
} }
@ -195,7 +195,7 @@ impl Image {
}) })
} }
/// Creates and returns an Image with the specified `SFSymbol`. Note that `SFSymbol` is /// Creates and returns an Image with the specified `SFSymbol`. Note that `SFSymbol` is
/// supported on 11.0+; as such, this will panic if called on a lower system. Take care to /// supported on 11.0+; as such, this will panic if called on a lower system. Take care to
/// provide a fallback image or user experience if you need to support an older OS. /// provide a fallback image or user experience if you need to support an older OS.
pub fn symbol(symbol: SFSymbol, accessibility_description: &str) -> Self { pub fn symbol(symbol: SFSymbol, accessibility_description: &str) -> Self {
@ -246,7 +246,7 @@ impl Image {
); );
let result = handler(resized_frame, &context); let result = handler(resized_frame, &context);
let _: () = msg_send![class!(NSGraphicsContext), restoreGraphicsState]; let _: () = msg_send![class!(NSGraphicsContext), restoreGraphicsState];
match result { match result {
@ -257,8 +257,8 @@ impl Image {
let block = block.copy(); let block = block.copy();
Image(unsafe { Image(unsafe {
let img: id = msg_send![class!(NSImage), imageWithSize:target_frame.size let img: id = msg_send![class!(NSImage), imageWithSize:target_frame.size
flipped:YES flipped:YES
drawingHandler:block drawingHandler:block
]; ];

View file

@ -30,17 +30,17 @@ mod icons;
pub use icons::*; pub use icons::*;
/// A helper method for instantiating view classes and applying default settings to them. /// A helper method for instantiating view classes and applying default settings to them.
fn allocate_view(registration_fn: fn() -> *const Class) -> id { fn allocate_view(registration_fn: fn() -> *const Class) -> id {
unsafe { unsafe {
let view: id = msg_send![registration_fn(), new]; let view: id = msg_send![registration_fn(), new];
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
let _: () = msg_send![view, setTranslatesAutoresizingMaskIntoConstraints:NO]; let _: () = msg_send![view, setTranslatesAutoresizingMaskIntoConstraints:NO];
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
let _: () = msg_send![view, setWantsLayer:YES]; let _: () = msg_send![view, setWantsLayer:YES];
view view
} }
} }
@ -51,7 +51,7 @@ fn allocate_view(registration_fn: fn() -> *const Class) -> id {
pub struct ImageView { pub struct ImageView {
/// A pointer to the Objective-C runtime view controller. /// A pointer to the Objective-C runtime view controller.
pub objc: ObjcProperty, pub objc: ObjcProperty,
/// A pointer to the Objective-C runtime top layout constraint. /// A pointer to the Objective-C runtime top layout constraint.
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
pub top: LayoutAnchorY, pub top: LayoutAnchorY,
@ -100,41 +100,41 @@ impl Default for ImageView {
} }
impl ImageView { impl ImageView {
/// Returns a default `View`, suitable for /// Returns a default `View`, suitable for
pub fn new() -> Self { pub fn new() -> Self {
let view = allocate_view(register_image_view_class); let view = allocate_view(register_image_view_class);
ImageView { ImageView {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view), top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view), left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view), leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view), right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view), trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view), bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view), width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view), height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view), center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view), center_y: LayoutAnchorY::center(view),
objc: ObjcProperty::retain(view), objc: ObjcProperty::retain(view),
} }
} }

View file

@ -23,7 +23,7 @@ pub trait ViewDelegate {
/// Invoked when the dragged image enters destination bounds or frame; returns dragging operation to perform. /// Invoked when the dragged image enters destination bounds or frame; returns dragging operation to perform.
fn dragging_entered(&self, _info: DragInfo) -> DragOperation { DragOperation::None } fn dragging_entered(&self, _info: DragInfo) -> DragOperation { DragOperation::None }
/// Invoked when the image is released, allowing the receiver to agree to or refuse drag operation. /// Invoked when the image is released, allowing the receiver to agree to or refuse drag operation.
fn prepare_for_drag_operation(&self, _info: DragInfo) -> bool { false } fn prepare_for_drag_operation(&self, _info: DragInfo) -> bool { false }
@ -33,7 +33,7 @@ pub trait ViewDelegate {
/// Invoked when the dragging operation is complete, signaling the receiver to perform any necessary clean-up. /// Invoked when the dragging operation is complete, signaling the receiver to perform any necessary clean-up.
fn conclude_drag_operation(&self, _info: DragInfo) {} fn conclude_drag_operation(&self, _info: DragInfo) {}
/// Invoked when the dragged image exits the destinations bounds rectangle (in the case of a view) or its frame /// Invoked when the dragged image exits the destinations bounds rectangle (in the case of a view) or its frame
/// rectangle (in the case of a window object). /// rectangle (in the case of a window object).
fn dragging_exited(&self, _info: DragInfo) {} fn dragging_exited(&self, _info: DragInfo) {}
} }

View file

@ -36,7 +36,7 @@ extern "C" fn text_should_begin_editing<T: TextFieldDelegate>(
) -> BOOL { ) -> BOOL {
let view = load::<T>(this, TEXTFIELD_DELEGATE_PTR); let view = load::<T>(this, TEXTFIELD_DELEGATE_PTR);
let s = NSString::retain(unsafe { msg_send![this, stringValue] }); let s = NSString::retain(unsafe { msg_send![this, stringValue] });
match view.text_should_begin_editing(s.to_str()) { match view.text_should_begin_editing(s.to_str()) {
true => YES, true => YES,
false => NO false => NO

View file

@ -25,7 +25,7 @@
//! self.label.set_background_color(rgb(224, 82, 99)); //! self.label.set_background_color(rgb(224, 82, 99));
//! self.label.set_text("LOL"); //! self.label.set_text("LOL");
//! self.content.add_subview(&self.red); //! self.content.add_subview(&self.red);
//! //!
//! self.window.set_content_view(&self.content); //! self.window.set_content_view(&self.content);
//! //!
//! LayoutConstraint::activate(&[ //! LayoutConstraint::activate(&[
@ -96,7 +96,7 @@ pub struct TextField<T = ()> {
/// A pointer to the delegate for this view. /// A pointer to the delegate for this view.
pub delegate: Option<Box<T>>, pub delegate: Option<Box<T>>,
/// A pointer to the Objective-C runtime top layout constraint. /// A pointer to the Objective-C runtime top layout constraint.
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
pub top: LayoutAnchorY, pub top: LayoutAnchorY,
@ -153,36 +153,36 @@ impl TextField {
TextField { TextField {
delegate: None, delegate: None,
objc: ObjcProperty::retain(view), objc: ObjcProperty::retain(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view), top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view), left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view), leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view), right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view), trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view), bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view), width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view), height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view), center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view) center_y: LayoutAnchorY::center(view)
} }
} }
} }
@ -206,34 +206,34 @@ where
let mut label = TextField { let mut label = TextField {
delegate: None, delegate: None,
objc: ObjcProperty::retain(label), objc: ObjcProperty::retain(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(label), top: LayoutAnchorY::top(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(label), left: LayoutAnchorX::left(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(label), leading: LayoutAnchorX::leading(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(label), right: LayoutAnchorX::right(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(label), trailing: LayoutAnchorX::trailing(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(label), bottom: LayoutAnchorY::bottom(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(label), width: LayoutAnchorDimension::width(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(label), height: LayoutAnchorDimension::height(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(label), center_x: LayoutAnchorX::center(label),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(label), center_y: LayoutAnchorY::center(label),
}; };
@ -253,34 +253,34 @@ impl<T> TextField<T> {
TextField { TextField {
delegate: None, delegate: None,
objc: self.objc.clone(), objc: self.objc.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: self.top.clone(), top: self.top.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: self.leading.clone(), leading: self.leading.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: self.left.clone(), left: self.left.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: self.trailing.clone(), trailing: self.trailing.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: self.right.clone(), right: self.right.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: self.bottom.clone(), bottom: self.bottom.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: self.width.clone(), width: self.width.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: self.height.clone(), height: self.height.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: self.center_x.clone(), center_x: self.center_x.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: self.center_y.clone(), center_y: self.center_y.clone(),
} }

View file

@ -23,12 +23,12 @@ use crate::utils::load;
pub static ACTION_CALLBACK_PTR: &str = "rstTargetActionPtr"; pub static ACTION_CALLBACK_PTR: &str = "rstTargetActionPtr";
/// An Action is just an indirection layer to get around Rust and optimizing /// An Action is just an indirection layer to get around Rust and optimizing
/// zero-sum types; without this, pointers to callbacks will end up being /// zero-sum types; without this, pointers to callbacks will end up being
/// 0x1, and all point to whatever is there first (unsure if this is due to /// 0x1, and all point to whatever is there first (unsure if this is due to
/// Rust or Cocoa or what). /// Rust or Cocoa or what).
/// ///
/// Point is, Button aren't created that much in the grand scheme of things, /// Point is, Button aren't created that much in the grand scheme of things,
/// and the heap isn't our enemy in a GUI framework anyway. If someone knows /// and the heap isn't our enemy in a GUI framework anyway. If someone knows
/// a better way to do this that doesn't require double-boxing, I'm all ears. /// a better way to do this that doesn't require double-boxing, I'm all ears.
pub struct Action(Box<dyn Fn() + Send + Sync + 'static>); pub struct Action(Box<dyn Fn() + Send + Sync + 'static>);
@ -40,7 +40,7 @@ impl fmt::Debug for Action {
} }
/// A handler that contains the class for callback storage and invocation on /// A handler that contains the class for callback storage and invocation on
/// the Objective-C side. /// the Objective-C side.
/// ///
/// This effectively wraps the target:action selector usage on NSControl and /// This effectively wraps the target:action selector usage on NSControl and
/// associated widgets. /// associated widgets.
@ -84,12 +84,12 @@ extern fn perform<F: Fn() + 'static>(this: &mut Object, _: Sel, _sender: id) {
} }
/// Due to the way that Rust and Objective-C live... very different lifestyles, /// Due to the way that Rust and Objective-C live... very different lifestyles,
/// we need to find a way to make events work without _needing_ the whole /// we need to find a way to make events work without _needing_ the whole
/// target/action setup you'd use in a standard Cocoa/AppKit/UIKit app. /// target/action setup you'd use in a standard Cocoa/AppKit/UIKit app.
/// ///
/// Here, we inject a subclass that can store a pointer for a callback. We use /// Here, we inject a subclass that can store a pointer for a callback. We use
/// this as our target/action combo, which allows passing a /// this as our target/action combo, which allows passing a
/// generic block over. It's still Rust, so you can't do crazy callbacks, but /// generic block over. It's still Rust, so you can't do crazy callbacks, but
/// you can at least fire an event off and do something. /// you can at least fire an event off and do something.
/// ///
/// The `NSButton` owns this object on instantiation, and will release it /// The `NSButton` owns this object on instantiation, and will release it
@ -105,7 +105,7 @@ pub(crate) fn register_invoker_class<F: Fn() + 'static>() -> *const Class {
decl.add_ivar::<usize>(ACTION_CALLBACK_PTR); decl.add_ivar::<usize>(ACTION_CALLBACK_PTR);
decl.add_method(sel!(perform:), perform::<F> as extern fn (&mut Object, _, id)); decl.add_method(sel!(perform:), perform::<F> as extern fn (&mut Object, _, id));
VIEW_CLASS = decl.register(); VIEW_CLASS = decl.register();
}); });

View file

@ -18,7 +18,7 @@ use crate::foundation::id;
use crate::utils::properties::ObjcProperty; use crate::utils::properties::ObjcProperty;
/// Represents a `CALayer`. /// Represents a `CALayer`.
/// ///
/// Each widget has an underlying `layer` field that you can access, which offers additional /// Each widget has an underlying `layer` field that you can access, which offers additional
/// rendering tools. /// rendering tools.
/// ///

View file

@ -91,18 +91,18 @@ pub enum LayoutAttribute {
/// The center along the y-axis of the objects alignment rectangle. /// The center along the y-axis of the objects alignment rectangle.
CenterY, CenterY,
/// The objects baseline. For objects with more than one line of text, /// The objects baseline. For objects with more than one line of text,
/// this is the baseline for the bottommost line of text. /// this is the baseline for the bottommost line of text.
LastBaseline, LastBaseline,
/// The objects baseline. For objects with more than one line of text, /// The objects baseline. For objects with more than one line of text,
/// this is the baseline for the topmost line of text. /// this is the baseline for the topmost line of text.
FirstBaseline, FirstBaseline,
/// A placeholder value that is used to indicate that the constraints /// A placeholder value that is used to indicate that the constraints
/// second item and second attribute are not used in any calculations. /// second item and second attribute are not used in any calculations.
/// ///
/// This can be useful constraint that assigns a constant to an attribute. /// This can be useful constraint that assigns a constant to an attribute.
NotAnAttribute, NotAnAttribute,
/// Represents an unknown value. This should never be constructed, but acts as a guard against /// Represents an unknown value. This should never be constructed, but acts as a guard against
@ -166,10 +166,10 @@ pub enum LayoutFormat {
/// Align all specified interface elements using the last baseline of each one. /// Align all specified interface elements using the last baseline of each one.
AlignAllLastBaseline, AlignAllLastBaseline,
/// Arrange objects in order based on the normal text flow for the current user /// Arrange objects in order based on the normal text flow for the current user
/// interface language. In left-to-right languages (like English), this arrangement /// interface language. In left-to-right languages (like English), this arrangement
/// results in the first object being placed farthest to the left, the next one to /// results in the first object being placed farthest to the left, the next one to
/// its right, and so on. In right-to-left languages (like Arabic or Hebrew), the /// its right, and so on. In right-to-left languages (like Arabic or Hebrew), the
/// ordering is reversed. /// ordering is reversed.
DirectionLeadingToTrailing, DirectionLeadingToTrailing,

View file

@ -58,7 +58,7 @@ impl LayoutAnchorDimension {
msg_send![*obj, constraintEqualToConstant:value] msg_send![*obj, constraintEqualToConstant:value]
}); });
} }
panic!("Attempted to create a constant constraint with an uninitialized anchor."); panic!("Attempted to create a constant constraint with an uninitialized anchor.");
} }
@ -70,10 +70,10 @@ impl LayoutAnchorDimension {
msg_send![*obj, constraintGreaterThanOrEqualToConstant:value] msg_send![*obj, constraintGreaterThanOrEqualToConstant:value]
}); });
} }
panic!("Attempted to create a constraint (>=) with an uninitialized anchor."); panic!("Attempted to create a constraint (>=) with an uninitialized anchor.");
} }
/// Return a constraint greater than or equal to a constant value. /// Return a constraint greater than or equal to a constant value.
pub fn constraint_less_than_or_equal_to_constant(&self, constant: f64) -> LayoutConstraint { pub fn constraint_less_than_or_equal_to_constant(&self, constant: f64) -> LayoutConstraint {
if let Self::Width(obj) | Self::Height(obj) = self { if let Self::Width(obj) | Self::Height(obj) = self {
@ -82,7 +82,7 @@ impl LayoutAnchorDimension {
msg_send![*obj, constraintLessThanOrEqualToConstant:value] msg_send![*obj, constraintLessThanOrEqualToConstant:value]
}); });
} }
panic!("Attempted to create a constraint (<=) with an uninitialized anchor."); panic!("Attempted to create a constraint (<=) with an uninitialized anchor.");
} }
@ -100,7 +100,7 @@ impl LayoutAnchorDimension {
(Self::Height(from), Self::Height(to)) => { (Self::Height(from), Self::Height(to)) => {
LayoutConstraint::new(handler(from, to)) LayoutConstraint::new(handler(from, to))
}, },
(Self::Uninitialized, Self::Uninitialized) => { (Self::Uninitialized, Self::Uninitialized) => {
panic!("Attempted to create constraints with an uninitialized \"from\" and \"to\" dimension anchor."); panic!("Attempted to create constraints with an uninitialized \"from\" and \"to\" dimension anchor.");
}, },

View file

@ -5,7 +5,7 @@ use objc_id::ShareId;
use crate::foundation::id; use crate::foundation::id;
use crate::layout::constraint::LayoutConstraint; use crate::layout::constraint::LayoutConstraint;
/// A wrapper for `NSLayoutAnchorX`, used to handle values for how a given view should /// A wrapper for `NSLayoutAnchorX`, used to handle values for how a given view should
/// layout along the x-axis. /// layout along the x-axis.
/// ///
/// Of note: mismatches of incorrect left/leading and right/trailing anchors are detected at /// Of note: mismatches of incorrect left/leading and right/trailing anchors are detected at
@ -114,25 +114,25 @@ impl LayoutAnchorX {
// undefined/unexpected layout behavior when a system has differing ltr/rtl setups. // undefined/unexpected layout behavior when a system has differing ltr/rtl setups.
(Self::Leading(_), Self::Left(_)) | (Self::Left(_), Self::Leading(_)) => { (Self::Leading(_), Self::Left(_)) | (Self::Left(_), Self::Leading(_)) => {
panic!(r#" panic!(r#"
Attempted to attach a "leading" constraint to a "left" constraint. This will Attempted to attach a "leading" constraint to a "left" constraint. This will
result in undefined behavior for LTR and RTL system settings, and Cacao blocks this. result in undefined behavior for LTR and RTL system settings, and Cacao blocks this.
Use either left/right or leading/trailing. Use either left/right or leading/trailing.
"#); "#);
}, },
(Self::Leading(_), Self::Right(_)) | (Self::Right(_), Self::Leading(_)) => { (Self::Leading(_), Self::Right(_)) | (Self::Right(_), Self::Leading(_)) => {
panic!(r#" panic!(r#"
Attempted to attach a "leading" constraint to a "right" constraint. This will Attempted to attach a "leading" constraint to a "right" constraint. This will
result in undefined behavior for LTR and RTL system settings, and Cacao blocks this. result in undefined behavior for LTR and RTL system settings, and Cacao blocks this.
Use either left/right or leading/trailing. Use either left/right or leading/trailing.
"#); "#);
}, },
(Self::Trailing(_), Self::Left(_)) | (Self::Left(_), Self::Trailing(_)) => { (Self::Trailing(_), Self::Left(_)) | (Self::Left(_), Self::Trailing(_)) => {
panic!(r#" panic!(r#"
Attempted to attach a "trailing" constraint to a "left" constraint. This will Attempted to attach a "trailing" constraint to a "left" constraint. This will
result in undefined behavior for LTR and RTL system settings, and Cacao blocks this. result in undefined behavior for LTR and RTL system settings, and Cacao blocks this.
Use either left/right or leading/trailing. Use either left/right or leading/trailing.
@ -141,7 +141,7 @@ impl LayoutAnchorX {
(Self::Trailing(_), Self::Right(_)) | (Self::Right(_), Self::Trailing(_)) => { (Self::Trailing(_), Self::Right(_)) | (Self::Right(_), Self::Trailing(_)) => {
panic!(r#" panic!(r#"
Attempted to attach a "trailing" constraint to a "right" constraint. This will Attempted to attach a "trailing" constraint to a "right" constraint. This will
result in undefined behavior for LTR and RTL system settings, and Cacao blocks this. result in undefined behavior for LTR and RTL system settings, and Cacao blocks this.
Use either left/right or leading/trailing. Use either left/right or leading/trailing.

View file

@ -1,4 +1,4 @@
//! This module contains traits and helpers for layout. By default, standard frame-based layouts //! This module contains traits and helpers for layout. By default, standard frame-based layouts
//! are supported via the `Layout` trait, which all widgets implement. If you opt in to the //! are supported via the `Layout` trait, which all widgets implement. If you opt in to the
//! `AutoLayout` feature, each widget will default to using AutoLayout, which can be beneficial in //! `AutoLayout` feature, each widget will default to using AutoLayout, which can be beneficial in
//! more complicated views that need to deal with differing screen sizes. //! more complicated views that need to deal with differing screen sizes.

View file

@ -55,12 +55,12 @@ pub trait Layout: ObjcAccess {
/// use an appropriate initializer for a given view type). /// use an appropriate initializer for a given view type).
fn set_frame<R: Into<CGRect>>(&self, rect: R) { fn set_frame<R: Into<CGRect>>(&self, rect: R) {
let frame: CGRect = rect.into(); let frame: CGRect = rect.into();
self.with_backing_obj_mut(move |backing_node| unsafe { self.with_backing_obj_mut(move |backing_node| unsafe {
let _: () = msg_send![backing_node, setFrame:frame]; let _: () = msg_send![backing_node, setFrame:frame];
}); });
} }
/// Sets whether the view for this trait should translate autoresizing masks into layout /// Sets whether the view for this trait should translate autoresizing masks into layout
/// constraints. /// constraints.
/// ///
@ -78,7 +78,7 @@ pub trait Layout: ObjcAccess {
/// Sets whether the view for this is hidden or not. /// Sets whether the view for this is hidden or not.
/// ///
/// When hidden, widgets don't receive events and is not visible. /// When hidden, widgets don't receive events and is not visible.
fn set_hidden(&self, hide: bool) { fn set_hidden(&self, hide: bool) {
self.with_backing_obj_mut(|obj| unsafe { self.with_backing_obj_mut(|obj| unsafe {
let _: () = msg_send![obj, setHidden:match hide { let _: () = msg_send![obj, setHidden:match hide {
@ -89,8 +89,8 @@ pub trait Layout: ObjcAccess {
} }
/// Returns whether this is hidden or not. /// Returns whether this is hidden or not.
/// ///
/// Note that this can report `false` if an ancestor widget is hidden, thus hiding this - to check in /// Note that this can report `false` if an ancestor widget is hidden, thus hiding this - to check in
/// that case, you may want `is_hidden_or_ancestor_is_hidden()`. /// that case, you may want `is_hidden_or_ancestor_is_hidden()`.
fn is_hidden(&self) -> bool { fn is_hidden(&self) -> bool {
self.get_from_backing_obj(|obj| { self.get_from_backing_obj(|obj| {
@ -99,7 +99,7 @@ pub trait Layout: ObjcAccess {
}) })
}) })
} }
/// Returns whether this is hidden, *or* whether an ancestor view is hidden. /// Returns whether this is hidden, *or* whether an ancestor view is hidden.
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
fn is_hidden_or_ancestor_is_hidden(&self) -> bool { fn is_hidden_or_ancestor_is_hidden(&self) -> bool {
@ -131,7 +131,7 @@ pub trait Layout: ObjcAccess {
/// This should be supported under UIKit as well, but is featured gated under AppKit /// This should be supported under UIKit as well, but is featured gated under AppKit
/// currently to avoid compile issues. /// currently to avoid compile issues.
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
fn unregister_dragged_types(&self) { fn unregister_dragged_types(&self) {
self.with_backing_obj_mut(|obj| unsafe { self.with_backing_obj_mut(|obj| unsafe {
let _: () = msg_send![obj, unregisterDraggedTypes]; let _: () = msg_send![obj, unregisterDraggedTypes];
}); });

View file

@ -5,7 +5,7 @@ use objc_id::ShareId;
use crate::foundation::id; use crate::foundation::id;
use crate::layout::constraint::LayoutConstraint; use crate::layout::constraint::LayoutConstraint;
/// A wrapper for `NSLayoutAnchorY`, used to handle values for how a given view should /// A wrapper for `NSLayoutAnchorY`, used to handle values for how a given view should
/// layout along the y-axis. /// layout along the y-axis.
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum LayoutAnchorY { pub enum LayoutAnchorY {
@ -59,7 +59,7 @@ impl LayoutAnchorY {
{ {
match (self, anchor_to) { match (self, anchor_to) {
(Self::Top(from), Self::Top(to)) | (Self::Top(from), Self::Bottom(to)) | (Self::Top(from), Self::Top(to)) | (Self::Top(from), Self::Bottom(to)) |
(Self::Top(from), Self::Center(to)) | (Self::Top(from), Self::Center(to)) |
(Self::Bottom(from), Self::Bottom(to)) | (Self::Bottom(from), Self::Top(to)) | (Self::Bottom(from), Self::Bottom(to)) | (Self::Bottom(from), Self::Top(to)) |
(Self::Bottom(from), Self::Center(to)) | (Self::Bottom(from), Self::Center(to)) |

View file

@ -20,9 +20,9 @@
//! already fine for some apps. //! already fine for some apps.
//! //!
//! _Note that this crate relies on the Objective-C runtime. Interfacing with the runtime *requires* //! _Note that this crate relies on the Objective-C runtime. Interfacing with the runtime *requires*
//! unsafe blocks; this crate handles those unsafe interactions for you and provides a mostly safe wrapper, //! unsafe blocks; this crate handles those unsafe interactions for you and provides a mostly safe wrapper,
//! but by using this crate you understand that usage of `unsafe` is a given and will be somewhat //! but by using this crate you understand that usage of `unsafe` is a given and will be somewhat
//! rampant for wrapped controls. This does _not_ mean you can't assess, review, or question unsafe //! rampant for wrapped controls. This does _not_ mean you can't assess, review, or question unsafe
//! usage - just know it's happening, and in large part it's not going away._ //! usage - just know it's happening, and in large part it's not going away._
//! //!
//! # Hello World //! # Hello World
@ -30,7 +30,7 @@
//! ```rust,no_run //! ```rust,no_run
//! use cacao::appkit::app::{App, AppDelegate}; //! use cacao::appkit::app::{App, AppDelegate};
//! use cacao::appkit::window::Window; //! use cacao::appkit::window::Window;
//! //!
//! #[derive(Default)] //! #[derive(Default)]
//! struct BasicApp { //! struct BasicApp {
//! window: Window //! window: Window
@ -98,7 +98,7 @@ pub use url;
pub use lazy_static; pub use lazy_static;
//#[cfg(all(feature = "appkit", feature = "uikit", not(feature = "doc_cfg")))] //#[cfg(all(feature = "appkit", feature = "uikit", not(feature = "doc_cfg")))]
//compile_error!("The \"appkit\" and \"uikit\" features cannot be enabled together. Pick one. :)"); //compile_error!("The \"appkit\" and \"uikit\" features cannot be enabled together. Pick one. :)");
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
#[cfg_attr(docsrs, doc(cfg(feature = "appkit")))] #[cfg_attr(docsrs, doc(cfg(feature = "appkit")))]

View file

@ -59,7 +59,7 @@ impl RowAction {
let action = RowAction(unsafe { let action = RowAction(unsafe {
Id::from_ptr(action) Id::from_ptr(action)
}); });
handler(action, row as usize); handler(action, row as usize);
}); });
let block = block.copy(); let block = block.copy();
@ -77,7 +77,7 @@ impl RowAction {
/// Sets the title of this action. /// Sets the title of this action.
pub fn set_title(&mut self, title: &str) { pub fn set_title(&mut self, title: &str) {
let title = NSString::new(title); let title = NSString::new(title);
unsafe { unsafe {
let _: () = msg_send![&*self.0, setTitle:&*title]; let _: () = msg_send![&*self.0, setTitle:&*title];
} }

View file

@ -70,7 +70,7 @@ extern fn will_display_cell<T: ListViewDelegate>(
_table_view: id, _table_view: id,
_cell: id, _cell: id,
_column: id, _column: id,
item: NSInteger item: NSInteger
) { ) {
let view = load::<T>(this, LISTVIEW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_DELEGATE_PTR);
view.will_display_item(item as usize); view.will_display_item(item as usize);
@ -96,7 +96,7 @@ extern fn select_row<T: ListViewDelegate>(
this: &Object, this: &Object,
_: Sel, _: Sel,
_table_view: id, _table_view: id,
item: NSInteger item: NSInteger
) -> BOOL { ) -> BOOL {
let view = load::<T>(this, LISTVIEW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_DELEGATE_PTR);
view.item_selected(item as usize); view.item_selected(item as usize);
@ -130,7 +130,7 @@ extern fn row_actions_for_row<T: ListViewDelegate>(
) -> id { ) -> id {
let edge: RowEdge = edge.into(); let edge: RowEdge = edge.into();
let view = load::<T>(this, LISTVIEW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_DELEGATE_PTR);
let mut ids: NSArray = view.actions_for(row as usize, edge) let mut ids: NSArray = view.actions_for(row as usize, edge)
.iter_mut() .iter_mut()
.map(|action| &*action.0) .map(|action| &*action.0)
@ -156,7 +156,7 @@ extern fn dragging_entered<T: ListViewDelegate>(this: &mut Object, _: Sel, info:
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn prepare_for_drag_operation<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL { extern fn prepare_for_drag_operation<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL {
let view = load::<T>(this, LISTVIEW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_DELEGATE_PTR);
match view.prepare_for_drag_operation(DragInfo { match view.prepare_for_drag_operation(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}) { }) {
@ -168,7 +168,7 @@ extern fn prepare_for_drag_operation<T: ListViewDelegate>(this: &mut Object, _:
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn perform_drag_operation<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL { extern fn perform_drag_operation<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL {
let view = load::<T>(this, LISTVIEW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_DELEGATE_PTR);
match view.perform_drag_operation(DragInfo { match view.perform_drag_operation(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}) { }) {
@ -180,16 +180,16 @@ extern fn perform_drag_operation<T: ListViewDelegate>(this: &mut Object, _: Sel,
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn conclude_drag_operation<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) { extern fn conclude_drag_operation<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) {
let view = load::<T>(this, LISTVIEW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_DELEGATE_PTR);
view.conclude_drag_operation(DragInfo { view.conclude_drag_operation(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}); });
} }
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn dragging_exited<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) { extern fn dragging_exited<T: ListViewDelegate>(this: &mut Object, _: Sel, info: id) {
let view = load::<T>(this, LISTVIEW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_DELEGATE_PTR);
view.dragging_exited(DragInfo { view.dragging_exited(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}); });
@ -221,7 +221,7 @@ pub(crate) fn register_listview_class() -> *const Class {
pub(crate) fn register_listview_class_with_delegate<T: ListViewDelegate>(instance: &T) -> *const Class { pub(crate) fn register_listview_class_with_delegate<T: ListViewDelegate>(instance: &T) -> *const Class {
load_or_register_class("NSTableView", instance.subclass_name(), |decl| unsafe { load_or_register_class("NSTableView", instance.subclass_name(), |decl| unsafe {
decl.add_ivar::<usize>(LISTVIEW_DELEGATE_PTR); decl.add_ivar::<usize>(LISTVIEW_DELEGATE_PTR);
decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL); decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
// Tableview-specific // Tableview-specific

View file

@ -17,7 +17,7 @@ pub enum RowAnimation {
/// Animates in or out by sliding upwards. /// Animates in or out by sliding upwards.
SlideUp, SlideUp,
/// Animates in or out by sliding down. /// Animates in or out by sliding down.
SlideDown, SlideDown,
@ -61,7 +61,7 @@ impl Into<RowEdge> for NSInteger {
1 => RowEdge::Trailing, 1 => RowEdge::Trailing,
// @TODO: This *should* be unreachable, provided macOS doesn't start // @TODO: This *should* be unreachable, provided macOS doesn't start
// letting people swipe from vertical directions to reveal stuff. Have to // letting people swipe from vertical directions to reveal stuff. Have to
// feel like there's a better way to do this, though... // feel like there's a better way to do this, though...
_ => { unreachable!(); } _ => { unreachable!(); }
} }

View file

@ -5,7 +5,7 @@
//! people expect in 2020, and layer-backing all views by default. //! people expect in 2020, and layer-backing all views by default.
//! //!
//! Views implement Autolayout, which enable you to specify how things should appear on the screen. //! Views implement Autolayout, which enable you to specify how things should appear on the screen.
//! //!
//! ```rust,no_run //! ```rust,no_run
//! use cacao::color::rgb; //! use cacao::color::rgb;
//! use cacao::layout::{Layout, LayoutConstraint}; //! use cacao::layout::{Layout, LayoutConstraint};
@ -18,7 +18,7 @@
//! red: View, //! red: View,
//! window: Window //! window: Window
//! } //! }
//! //!
//! impl WindowDelegate for AppWindow { //! impl WindowDelegate for AppWindow {
//! fn did_load(&mut self, window: Window) { //! fn did_load(&mut self, window: Window) {
//! window.set_minimum_content_size(300., 300.); //! window.set_minimum_content_size(300., 300.);
@ -26,7 +26,7 @@
//! //!
//! self.red.set_background_color(rgb(224, 82, 99)); //! self.red.set_background_color(rgb(224, 82, 99));
//! self.content.add_subview(&self.red); //! self.content.add_subview(&self.red);
//! //!
//! self.window.set_content_view(&self.content); //! self.window.set_content_view(&self.content);
//! //!
//! LayoutConstraint::activate(&[ //! LayoutConstraint::activate(&[
@ -97,7 +97,7 @@ use std::rc::Rc;
use std::cell::RefCell; use std::cell::RefCell;
/// A helper method for instantiating view classes and applying default settings to them. /// A helper method for instantiating view classes and applying default settings to them.
fn common_init(class: *const Class) -> id { fn common_init(class: *const Class) -> id {
unsafe { unsafe {
// Note: we do *not* enable AutoLayout here as we're by default placing this in a scroll // Note: we do *not* enable AutoLayout here as we're by default placing this in a scroll
// view, and we want it to just do its thing. // view, and we want it to just do its thing.
@ -203,15 +203,15 @@ impl Default for ListView {
} }
impl ListView { impl ListView {
/// @TODO: The hell is this for? /// @TODO: The hell is this for?
pub fn new() -> Self { pub fn new() -> Self {
let class = register_listview_class(); let class = register_listview_class();
let view = common_init(class); let view = common_init(class);
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
let scrollview = { let scrollview = {
let sview = ScrollView::new(); let sview = ScrollView::new();
sview.objc.with_mut(|obj| unsafe { sview.objc.with_mut(|obj| unsafe {
let _: () = msg_send![obj, setDocumentView:view]; let _: () = msg_send![obj, setDocumentView:view];
}); });
@ -225,7 +225,7 @@ impl ListView {
let anchor_view: id = scrollview.objc.get(|obj| unsafe { let anchor_view: id = scrollview.objc.get(|obj| unsafe {
msg_send![obj, self] msg_send![obj, self]
}); });
//#[cfg(all(feature = "uikit", feature = "autolayout"))] //#[cfg(all(feature = "uikit", feature = "autolayout"))]
//let anchor_view: id = view; //let anchor_view: id = view;
@ -233,37 +233,37 @@ impl ListView {
cell_factory: CellFactory::new(), cell_factory: CellFactory::new(),
menu: PropertyNullable::default(), menu: PropertyNullable::default(),
delegate: None, delegate: None,
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(anchor_view), top: LayoutAnchorY::top(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(anchor_view), left: LayoutAnchorX::left(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(anchor_view), leading: LayoutAnchorX::leading(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(anchor_view), right: LayoutAnchorX::right(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(anchor_view), trailing: LayoutAnchorX::trailing(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(anchor_view), bottom: LayoutAnchorY::bottom(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(anchor_view), width: LayoutAnchorDimension::width(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(anchor_view), height: LayoutAnchorDimension::height(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(anchor_view), center_x: LayoutAnchorX::center(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(anchor_view), center_y: LayoutAnchorY::center(anchor_view),
// Note that AppKit needs this to be the ScrollView! // Note that AppKit needs this to be the ScrollView!
// @TODO: Figure out if there's a use case for exposing the inner tableview animator // @TODO: Figure out if there's a use case for exposing the inner tableview animator
// property... // property...
@ -284,7 +284,7 @@ impl<T> ListView<T> where T: ListViewDelegate + 'static {
let view = common_init(class); let view = common_init(class);
let mut delegate = Box::new(delegate); let mut delegate = Box::new(delegate);
let cell = CellFactory::new(); let cell = CellFactory::new();
unsafe { unsafe {
let delegate_ptr: *const T = &*delegate; let delegate_ptr: *const T = &*delegate;
(&mut *view).set_ivar(LISTVIEW_DELEGATE_PTR, delegate_ptr as usize); (&mut *view).set_ivar(LISTVIEW_DELEGATE_PTR, delegate_ptr as usize);
@ -295,7 +295,7 @@ impl<T> ListView<T> where T: ListViewDelegate + 'static {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
let scrollview = { let scrollview = {
let sview = ScrollView::new(); let sview = ScrollView::new();
sview.objc.with_mut(|obj| unsafe { sview.objc.with_mut(|obj| unsafe {
let _: () = msg_send![obj, setDocumentView:view]; let _: () = msg_send![obj, setDocumentView:view];
}); });
@ -308,7 +308,7 @@ impl<T> ListView<T> where T: ListViewDelegate + 'static {
let anchor_view: id = scrollview.objc.get(|obj| unsafe { let anchor_view: id = scrollview.objc.get(|obj| unsafe {
msg_send![obj, self] msg_send![obj, self]
}); });
//#[cfg(feature = "uikit")] //#[cfg(feature = "uikit")]
//let anchor_view = view; //let anchor_view = view;
@ -321,38 +321,38 @@ impl<T> ListView<T> where T: ListViewDelegate + 'static {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(anchor_view), top: LayoutAnchorY::top(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(anchor_view), left: LayoutAnchorX::left(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(anchor_view), leading: LayoutAnchorX::leading(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(anchor_view), right: LayoutAnchorX::right(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(anchor_view), trailing: LayoutAnchorX::trailing(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(anchor_view), bottom: LayoutAnchorY::bottom(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(anchor_view), width: LayoutAnchorDimension::width(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(anchor_view), height: LayoutAnchorDimension::height(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(anchor_view), center_x: LayoutAnchorX::center(anchor_view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(anchor_view), center_y: LayoutAnchorY::center(anchor_view),
scrollview scrollview
}; };
(&mut delegate).did_load(view.clone_as_handle()); (&mut delegate).did_load(view.clone_as_handle());
view.delegate = Some(delegate); view.delegate = Some(delegate);
view view
} }
@ -373,31 +373,31 @@ impl<T> ListView<T> {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: self.top.clone(), top: self.top.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: self.leading.clone(), leading: self.leading.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: self.left.clone(), left: self.left.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: self.trailing.clone(), trailing: self.trailing.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: self.right.clone(), right: self.right.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: self.bottom.clone(), bottom: self.bottom.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: self.width.clone(), width: self.width.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: self.height.clone(), height: self.height.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: self.center_x.clone(), center_x: self.center_x.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: self.center_y.clone(), center_y: self.center_y.clone(),
@ -423,7 +423,7 @@ impl<T> ListView<T> {
let cell: id = self.objc.get(|obj| unsafe { let cell: id = self.objc.get(|obj| unsafe {
msg_send![obj, makeViewWithIdentifier:&*key owner:nil] msg_send![obj, makeViewWithIdentifier:&*key owner:nil]
}); });
if cell != nil { if cell != nil {
ListViewRow::from_cached(cell) ListViewRow::from_cached(cell)
} else { } else {
@ -474,7 +474,7 @@ impl<T> ListView<T> {
}); });
} }
/// Set the selection highlight style. /// Set the selection highlight style.
pub fn set_selection_highlight_style(&self, style: crate::foundation::NSInteger) { pub fn set_selection_highlight_style(&self, style: crate::foundation::NSInteger) {
self.objc.with_mut(|obj| unsafe { self.objc.with_mut(|obj| unsafe {
let _: () = msg_send![obj, setSelectionHighlightStyle:style]; let _: () = msg_send![obj, setSelectionHighlightStyle:style];
@ -544,7 +544,7 @@ impl<T> ListView<T> {
self.objc.get(|obj| unsafe { self.objc.get(|obj| unsafe {
let _: () = msg_send![obj, beginUpdates]; let _: () = msg_send![obj, beginUpdates];
}); });
let handle = self.clone_as_handle(); let handle = self.clone_as_handle();
update(handle); update(handle);
@ -565,7 +565,7 @@ impl<T> ListView<T> {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
unsafe { unsafe {
let index_set: id = msg_send![class!(NSMutableIndexSet), new]; let index_set: id = msg_send![class!(NSMutableIndexSet), new];
for index in indexes { for index in indexes {
let x: NSUInteger = *index as NSUInteger; let x: NSUInteger = *index as NSUInteger;
let _: () = msg_send![index_set, addIndex:x]; let _: () = msg_send![index_set, addIndex:x];
@ -576,7 +576,7 @@ impl<T> ListView<T> {
// We need to temporarily retain this; it can drop after the underlying NSTableView // We need to temporarily retain this; it can drop after the underlying NSTableView
// has also retained it. // has also retained it.
let x = ShareId::from_ptr(index_set); let x = ShareId::from_ptr(index_set);
// This is done for a very explicit reason; see the comments on the method itself for // This is done for a very explicit reason; see the comments on the method itself for
// an explanation. // an explanation.
self.hack_avoid_dequeue_loop(|obj| { self.hack_avoid_dequeue_loop(|obj| {
@ -590,7 +590,7 @@ impl<T> ListView<T> {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
unsafe { unsafe {
let index_set: id = msg_send![class!(NSMutableIndexSet), new]; let index_set: id = msg_send![class!(NSMutableIndexSet), new];
for index in indexes { for index in indexes {
let x: NSUInteger = *index as NSUInteger; let x: NSUInteger = *index as NSUInteger;
let _: () = msg_send![index_set, addIndex:x]; let _: () = msg_send![index_set, addIndex:x];
@ -617,7 +617,7 @@ impl<T> ListView<T> {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
unsafe { unsafe {
let index_set: id = msg_send![class!(NSMutableIndexSet), new]; let index_set: id = msg_send![class!(NSMutableIndexSet), new];
for index in indexes { for index in indexes {
let x: NSUInteger = *index as NSUInteger; let x: NSUInteger = *index as NSUInteger;
let _: () = msg_send![index_set, addIndex:x]; let _: () = msg_send![index_set, addIndex:x];
@ -705,7 +705,7 @@ impl<T> ListView<T> {
pub fn get_selected_row_index(&self) -> NSInteger { pub fn get_selected_row_index(&self) -> NSInteger {
self.objc.get(|obj| unsafe { msg_send![obj, selectedRow] }) self.objc.get(|obj| unsafe { msg_send![obj, selectedRow] })
} }
/// Returns the currently clicked row. This is AppKit-specific, and is generally used in context /// Returns the currently clicked row. This is AppKit-specific, and is generally used in context
/// menu generation to determine what item the context menu should be for. If the clicked area /// menu generation to determine what item the context menu should be for. If the clicked area
/// is not an actual row, this will return `-1`. /// is not an actual row, this will return `-1`.

View file

@ -35,7 +35,7 @@ extern fn dragging_entered<T: ViewDelegate>(this: &mut Object, _: Sel, info: id)
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn prepare_for_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL { extern fn prepare_for_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
match view.prepare_for_drag_operation(DragInfo { match view.prepare_for_drag_operation(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}) { }) {
@ -47,7 +47,7 @@ extern fn prepare_for_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel,
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn perform_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL { extern fn perform_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
match view.perform_drag_operation(DragInfo { match view.perform_drag_operation(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}) { }) {
@ -59,16 +59,16 @@ extern fn perform_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, inf
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn conclude_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) { extern fn conclude_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
view.conclude_drag_operation(DragInfo { view.conclude_drag_operation(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}); });
} }
/// Called when a drag/drop operation has entered this view. /// Called when a drag/drop operation has entered this view.
extern fn dragging_exited<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) { extern fn dragging_exited<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR); let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
view.dragging_exited(DragInfo { view.dragging_exited(DragInfo {
info: unsafe { Id::from_ptr(info) } info: unsafe { Id::from_ptr(info) }
}); });
@ -90,7 +90,7 @@ extern fn update_layer(this: &Object, _: Sel) {
/// Normally, you might not want to do a custom dealloc override. However, reusable cells are /// Normally, you might not want to do a custom dealloc override. However, reusable cells are
/// tricky - since we "forget" them when we give them to the system, we need to make sure to do /// tricky - since we "forget" them when we give them to the system, we need to make sure to do
/// proper cleanup then the backing (cached) version is deallocated on the Objective-C side. Since /// proper cleanup then the backing (cached) version is deallocated on the Objective-C side. Since
/// we know /// we know
extern fn dealloc<T: ViewDelegate>(this: &Object, _: Sel) { extern fn dealloc<T: ViewDelegate>(this: &Object, _: Sel) {
// Load the Box pointer here, and just let it drop normally. // Load the Box pointer here, and just let it drop normally.
unsafe { unsafe {
@ -114,7 +114,7 @@ pub(crate) fn register_listview_row_class() -> *const Class {
let mut decl = ClassDecl::new("RSTTableViewRow", superclass).unwrap(); let mut decl = ClassDecl::new("RSTTableViewRow", superclass).unwrap();
decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL); decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
VIEW_CLASS = decl.register(); VIEW_CLASS = decl.register();
}); });
@ -135,7 +135,7 @@ pub(crate) fn register_listview_row_class_with_delegate<T: ViewDelegate>() -> *c
// move. // move.
decl.add_ivar::<usize>(LISTVIEW_ROW_DELEGATE_PTR); decl.add_ivar::<usize>(LISTVIEW_ROW_DELEGATE_PTR);
decl.add_ivar::<id>(BACKGROUND_COLOR); decl.add_ivar::<id>(BACKGROUND_COLOR);
decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL); decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
decl.add_method(sel!(updateLayer), update_layer as extern fn(&Object, _)); decl.add_method(sel!(updateLayer), update_layer as extern fn(&Object, _));
@ -145,7 +145,7 @@ pub(crate) fn register_listview_row_class_with_delegate<T: ViewDelegate>() -> *c
decl.add_method(sel!(performDragOperation:), perform_drag_operation::<T> as extern fn (&mut Object, _, _) -> BOOL); decl.add_method(sel!(performDragOperation:), perform_drag_operation::<T> as extern fn (&mut Object, _, _) -> BOOL);
decl.add_method(sel!(concludeDragOperation:), conclude_drag_operation::<T> as extern fn (&mut Object, _, _)); decl.add_method(sel!(concludeDragOperation:), conclude_drag_operation::<T> as extern fn (&mut Object, _, _));
decl.add_method(sel!(draggingExited:), dragging_exited::<T> as extern fn (&mut Object, _, _)); decl.add_method(sel!(draggingExited:), dragging_exited::<T> as extern fn (&mut Object, _, _));
// Cleanup // Cleanup
decl.add_method(sel!(dealloc), dealloc::<T> as extern fn (&Object, _)); decl.add_method(sel!(dealloc), dealloc::<T> as extern fn (&Object, _));

View file

@ -5,7 +5,7 @@
//! people expect in 2020, and layer-backing all views by default. //! people expect in 2020, and layer-backing all views by default.
//! //!
//! Views implement Autolayout, which enable you to specify how things should appear on the screen. //! Views implement Autolayout, which enable you to specify how things should appear on the screen.
//! //!
//! ```rust,no_run //! ```rust,no_run
//! use cacao::color::rgb; //! use cacao::color::rgb;
//! use cacao::layout::{Layout, LayoutConstraint}; //! use cacao::layout::{Layout, LayoutConstraint};
@ -18,7 +18,7 @@
//! red: View, //! red: View,
//! window: Window //! window: Window
//! } //! }
//! //!
//! impl WindowDelegate for AppWindow { //! impl WindowDelegate for AppWindow {
//! fn did_load(&mut self, window: Window) { //! fn did_load(&mut self, window: Window) {
//! window.set_minimum_content_size(300., 300.); //! window.set_minimum_content_size(300., 300.);
@ -26,7 +26,7 @@
//! //!
//! self.red.set_background_color(rgb(224, 82, 99)); //! self.red.set_background_color(rgb(224, 82, 99));
//! self.content.add_subview(&self.red); //! self.content.add_subview(&self.red);
//! //!
//! self.window.set_content_view(&self.content); //! self.window.set_content_view(&self.content);
//! //!
//! LayoutConstraint::activate(&[ //! LayoutConstraint::activate(&[
@ -75,7 +75,7 @@ pub(crate) static BACKGROUND_COLOR: &str = "cacaoBackgroundColor";
pub(crate) static LISTVIEW_ROW_DELEGATE_PTR: &str = "cacaoListViewRowDelegatePtr"; pub(crate) static LISTVIEW_ROW_DELEGATE_PTR: &str = "cacaoListViewRowDelegatePtr";
/// A helper method for instantiating view classes and applying default settings to them. /// A helper method for instantiating view classes and applying default settings to them.
fn allocate_view(registration_fn: fn() -> *const Class) -> id { fn allocate_view(registration_fn: fn() -> *const Class) -> id {
unsafe { unsafe {
let view: id = msg_send![registration_fn(), new]; let view: id = msg_send![registration_fn(), new];
@ -85,7 +85,7 @@ fn allocate_view(registration_fn: fn() -> *const Class) -> id {
#[cfg(feature = "appkit")] #[cfg(feature = "appkit")]
let _: () = msg_send![view, setWantsLayer:YES]; let _: () = msg_send![view, setWantsLayer:YES];
view view
} }
} }
@ -106,7 +106,7 @@ pub struct ListViewRow<T = ()> {
/// A safe layout guide property. /// A safe layout guide property.
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
pub safe_layout_guide: SafeAreaLayoutGuide, pub safe_layout_guide: SafeAreaLayoutGuide,
/// A pointer to the Objective-C runtime top layout constraint. /// A pointer to the Objective-C runtime top layout constraint.
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
pub top: LayoutAnchorY, pub top: LayoutAnchorY,
@ -155,7 +155,7 @@ impl Default for ListViewRow {
} }
impl ListViewRow { impl ListViewRow {
/// Returns a default `View`, suitable for /// Returns a default `View`, suitable for
pub fn new() -> Self { pub fn new() -> Self {
let view = allocate_view(register_listview_row_class); let view = allocate_view(register_listview_row_class);
@ -166,34 +166,34 @@ impl ListViewRow {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
safe_layout_guide: SafeAreaLayoutGuide::new(view), safe_layout_guide: SafeAreaLayoutGuide::new(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view), top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view), left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view), leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view), right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view), trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view), bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view), width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view), height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view), center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view), center_y: LayoutAnchorY::center(view),
} }
@ -227,34 +227,34 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
safe_layout_guide: SafeAreaLayoutGuide::new(view), safe_layout_guide: SafeAreaLayoutGuide::new(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view), top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view), left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view), leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view), right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view), trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view), bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view), width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view), height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view), center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view), center_y: LayoutAnchorY::center(view),
}; };
@ -269,7 +269,7 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
/// Initializes a new View with a given `ViewDelegate`. This enables you to respond to events /// Initializes a new View with a given `ViewDelegate`. This enables you to respond to events
/// and customize the view as a module, similar to class-based systems. /// and customize the view as a module, similar to class-based systems.
pub fn with_boxed(mut delegate: Box<T>) -> ListViewRow<T> { pub fn with_boxed(mut delegate: Box<T>) -> ListViewRow<T> {
let view = allocate_view(register_listview_row_class_with_delegate::<T>); let view = allocate_view(register_listview_row_class_with_delegate::<T>);
unsafe { unsafe {
let ptr: *const T = &*delegate; let ptr: *const T = &*delegate;
@ -283,39 +283,39 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
safe_layout_guide: SafeAreaLayoutGuide::new(view), safe_layout_guide: SafeAreaLayoutGuide::new(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view), top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view), left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view), leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view), right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view), trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view), bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view), width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view), height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view), center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view), center_y: LayoutAnchorY::center(view),
}; };
(&mut delegate).did_load(view.clone_as_handle()); (&mut delegate).did_load(view.clone_as_handle());
view.delegate = Some(delegate); view.delegate = Some(delegate);
view view
} }
@ -332,7 +332,7 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
delegate: None, delegate: None,
objc: self.objc.clone(), objc: self.objc.clone(),
animator: self.animator.clone(), animator: self.animator.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
safe_layout_guide: self.safe_layout_guide.clone(), safe_layout_guide: self.safe_layout_guide.clone(),
@ -341,28 +341,28 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: self.leading.clone(), leading: self.leading.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: self.left.clone(), left: self.left.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: self.trailing.clone(), trailing: self.trailing.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: self.right.clone(), right: self.right.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: self.bottom.clone(), bottom: self.bottom.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: self.width.clone(), width: self.width.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: self.height.clone(), height: self.height.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: self.center_x.clone(), center_x: self.center_x.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: self.center_y.clone(), center_y: self.center_y.clone(),
} }
@ -387,31 +387,31 @@ impl<T> ListViewRow<T> {
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
top: self.top.clone(), top: self.top.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
leading: self.leading.clone(), leading: self.leading.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
left: self.left.clone(), left: self.left.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
trailing: self.trailing.clone(), trailing: self.trailing.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
right: self.right.clone(), right: self.right.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
bottom: self.bottom.clone(), bottom: self.bottom.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
width: self.width.clone(), width: self.width.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
height: self.height.clone(), height: self.height.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_x: self.center_x.clone(), center_x: self.center_x.clone(),
#[cfg(feature = "autolayout")] #[cfg(feature = "autolayout")]
center_y: self.center_y.clone(), center_y: self.center_y.clone(),
} }
@ -429,7 +429,7 @@ impl<T> ListViewRow<T> {
/// Call this to set the background color for the backing layer. /// Call this to set the background color for the backing layer.
pub fn set_background_color<C: AsRef<Color>>(&self, color: C) { pub fn set_background_color<C: AsRef<Color>>(&self, color: C) {
let color: id = color.as_ref().into(); let color: id = color.as_ref().into();
self.objc.with_mut(|obj| unsafe { self.objc.with_mut(|obj| unsafe {
(&mut *obj).set_ivar(BACKGROUND_COLOR, color); (&mut *obj).set_ivar(BACKGROUND_COLOR, color);
}); });

View file

@ -44,7 +44,7 @@ pub trait ListViewDelegate {
/// depending on, say, what the user has context-clicked on. You should avoid any expensive /// depending on, say, what the user has context-clicked on. You should avoid any expensive
/// work in here and return the menu as fast as possible. /// work in here and return the menu as fast as possible.
fn context_menu(&self) -> Vec<MenuItem> { vec![] } fn context_menu(&self) -> Vec<MenuItem> { vec![] }
/// An optional delegate method; implement this if you'd like swipe-to-reveal to be /// An optional delegate method; implement this if you'd like swipe-to-reveal to be
/// supported for a given row by returning a vector of actions to show. /// supported for a given row by returning a vector of actions to show.
fn actions_for(&self, row: usize, edge: RowEdge) -> Vec<RowAction> { Vec::new() } fn actions_for(&self, row: usize, edge: RowEdge) -> Vec<RowAction> { Vec::new() }
@ -63,7 +63,7 @@ pub trait ListViewDelegate {
/// Invoked when the dragged image enters destination bounds or frame; returns dragging operation to perform. /// Invoked when the dragged image enters destination bounds or frame; returns dragging operation to perform.
fn dragging_entered(&self, info: DragInfo) -> DragOperation { DragOperation::None } fn dragging_entered(&self, info: DragInfo) -> DragOperation { DragOperation::None }
/// Invoked when the image is released, allowing the receiver to agree to or refuse drag operation. /// Invoked when the image is released, allowing the receiver to agree to or refuse drag operation.
fn prepare_for_drag_operation(&self, info: DragInfo) -> bool { false } fn prepare_for_drag_operation(&self, info: DragInfo) -> bool { false }
@ -73,7 +73,7 @@ pub trait ListViewDelegate {
/// Invoked when the dragging operation is complete, signaling the receiver to perform any necessary clean-up. /// Invoked when the dragging operation is complete, signaling the receiver to perform any necessary clean-up.
fn conclude_drag_operation(&self, info: DragInfo) {} fn conclude_drag_operation(&self, info: DragInfo) {}
/// Invoked when the dragged image exits the destinations bounds rectangle (in the case of a view) or its frame /// Invoked when the dragged image exits the destinations bounds rectangle (in the case of a view) or its frame
/// rectangle (in the case of a window object). /// rectangle (in the case of a window object).
fn dragging_exited(&self, info: DragInfo) {} fn dragging_exited(&self, info: DragInfo) {}
} }

View file

@ -1,6 +1,6 @@
//! A lightweight wrapper over some networking components, like `NSURLRequest` and co. //! A lightweight wrapper over some networking components, like `NSURLRequest` and co.
//! //!
/// At the moment, this is mostly used for inspection of objects returned from system /// At the moment, this is mostly used for inspection of objects returned from system
/// calls, as `NSURL` is pervasive in some filesystem references. Over time this may grow to /// calls, as `NSURL` is pervasive in some filesystem references. Over time this may grow to
/// include a proper networking stack, but the expectation for v0.1 is that most apps will want to /// include a proper networking stack, but the expectation for v0.1 is that most apps will want to
/// use their standard Rust networking libraries (however... odd... the async story may be). /// use their standard Rust networking libraries (however... odd... the async story may be).
@ -35,14 +35,14 @@ impl URLRequest {
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use objc::{class, msg_send, sel, sel_impl}; use objc::{class, msg_send, sel, sel_impl};
use crate::foundation::{id, NSString}; use crate::foundation::{id, NSString};
use crate::networking::URLRequest; use crate::networking::URLRequest;
#[test] #[test]
fn test_urlrequest() { fn test_urlrequest() {
let endpoint = "https://rymc.io/"; let endpoint = "https://rymc.io/";
let url = unsafe { let url = unsafe {
let url = NSString::new(endpoint); let url = NSString::new(endpoint);
let url: id = msg_send![class!(NSURL), URLWithString:&*url]; let url: id = msg_send![class!(NSURL), URLWithString:&*url];

Some files were not shown because too many files have changed in this diff Show more