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 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.
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
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
delegate pattern - objects registered to receive callbacks. With some creative assumptions, we can get somewhat close
to expected conventions.
@ -208,7 +208,7 @@ impl View {
height: LayoutAnchorDimension::height(view),
center_x: LayoutAnchorX::center(view),
center_y: LayoutAnchorY::center(view),
layer: Layer::wrap(unsafe {
msg_send![view, layer]
}),
@ -236,7 +236,7 @@ impl<T> View<T> where T: ViewDelegate + 'static {
pub fn with(delegate: T) -> View<T> {
let class = register_view_class_with_delegate(&delegate);
let mut delegate = Box::new(delegate);
let view = unsafe {
let view: id = msg_send![class, new];
let ptr = Box::into_raw(delegate);
@ -246,7 +246,7 @@ impl<T> View<T> where T: ViewDelegate + 'static {
};
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
}
@ -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_ivar::<id>(BACKGROUND_COLOR);
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`).
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
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.

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
already fine for some apps. The core repository has a wealth of examples to help you get started.
> **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
> **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
> 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.
>_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,
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
usage - just know it's happening, and in large part it's not going away. Issues pertaining to the mere
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
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
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
@ -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
## 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.
**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.
_(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.
**Isn't Objective-C dead?**
**Isn't Objective-C dead?**
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.
@ -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.
**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.
**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.
**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.
**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!).
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.
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() {
println!("cargo:rustc-link-lib=framework=Foundation");
#[cfg(feature = "appkit")]
println!("cargo:rustc-link-lib=framework=AppKit");
#[cfg(feature = "uikit")]
println!("cargo:rustc-link-lib=framework=UIKit");
@ -15,13 +15,13 @@ fn main() {
#[cfg(feature = "webview")]
println!("cargo:rustc-link-lib=framework=WebKit");
#[cfg(feature = "cloudkit")]
println!("cargo:rustc-link-lib=framework=CloudKit");
#[cfg(feature = "user-notifications")]
println!("cargo:rustc-link-lib=framework=UserNotifications");
#[cfg(feature = "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
//! into handlers, enabling basic animation support within `AnimationContext`.
//!
@ -132,7 +132,7 @@ impl WindowDelegate for AppWindow {
]
}).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.
self.key_monitor = Some(Event::local_monitor(EventMask::KeyDown, move |evt| {
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.leading.constraint_equal_to(&self.blue.trailing).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.leading.constraint_equal_to(&self.red.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 {
Action::Back => { webview.go_back(); },
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_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
// cheating, though: it's not outlandish to need to just manage things yourself when it
// comes to Objective-C/AppKit sometimes.

View file

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

View file

@ -40,7 +40,7 @@ impl Calculator {
pub fn run(&self, message: Msg) {
let mut expression = self.0.write().unwrap();
match message {
Msg::Push(i) => {
// 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();
App::<CalculatorApp, String>::dispatch_main(display);
},
Msg::Decimal => {
let display = (*expression).join("").split(" ").last().unwrap_or("0").to_string();
if !display.contains(".") {
@ -65,11 +65,11 @@ impl Calculator {
}
}
},
Msg::Subtract => {
(*expression).push(" - ".to_string());
},
Msg::Multiply => {
(*expression).push(" * ".to_string());
},
@ -90,7 +90,7 @@ impl Calculator {
}
println!("Expr: {}", expr);
match eval::eval(&expr) {
Ok(val) => { App::<CalculatorApp, String>::dispatch_main(val.to_string()); },
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.leading.constraint_equal_to(&view.leading),
self.zero.bottom.constraint_equal_to(&view.bottom),
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.bottom.constraint_equal_to(&view.bottom),

View file

@ -35,7 +35,7 @@ impl AppDelegate for CalculatorApp {
App::activate();
// 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.
//self.start_monitoring();

View file

@ -36,7 +36,7 @@ impl AppDelegate for DefaultsTest {
let teststring = defaults.get("teststring").unwrap();
assert_eq!(teststring.as_str().unwrap(), "Testing");
let bytes = defaults.get("testdata").unwrap();
let s = match std::str::from_utf8(bytes.as_data().unwrap()) {
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.trailing.constraint_equal_to(&view.trailing).offset(-16.),
self.green.height.constraint_equal_to_constant(120.),
self.blue.top.constraint_equal_to(&self.green.bottom).offset(16.),
self.blue.leading.constraint_equal_to(&view.leading).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 mut window = Window::new(bounds);
window.set_window_scene(scene);
let root_view_controller = ViewController::new(RootView::default());
window.set_root_view_controller(&root_view_controller);
window.show();
{
let mut w = self.window.write().unwrap();
*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
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`
**Platforms lacking AutoLayout:**
**Platforms lacking AutoLayout:**
`cargo run --example frame_layout --no-default-features --features appkit`
## Defaults

View file

@ -15,12 +15,12 @@ pub struct AddNewTodoWindow {
impl AddNewTodoWindow {
pub fn new() -> Self {
let content = ViewController::new(AddNewTodoContentView::default());
AddNewTodoWindow {
content: content
}
}
pub fn on_message(&self, message: Message) {
if let Some(delegate) = &self.content.view.delegate {
delegate.on_message(message);
@ -30,14 +30,14 @@ impl AddNewTodoWindow {
impl WindowDelegate for 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_minimum_content_size(300, 100);
window.set_title("Add a New Task");
window.set_content_view_controller(&self.content);
}
fn cancel(&self) {
dispatch_ui(Message::CloseSheet);
}

View file

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

View file

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

View file

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

View file

@ -10,7 +10,7 @@ pub struct AdvancedPreferencesContentView {
impl ViewDelegate for AdvancedPreferencesContentView {
const NAME: &'static str = "AdvancedPreferencesContentView";
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_alignment(TextAlign::Center);

View file

@ -1,5 +1,5 @@
//! 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
//! 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
//! event handlers inline.
use cacao::layout::{Layout, LayoutConstraint};
@ -17,7 +17,7 @@ pub struct GeneralPreferencesContentView {
impl ViewDelegate for GeneralPreferencesContentView {
const NAME: &'static str = "GeneralPreferencesContentView";
fn did_load(&mut self, view: View) {
self.example_option.configure(
"An example preference",

View file

@ -33,7 +33,7 @@ impl PreferencesWindow {
window: None
}
}
pub fn on_message(&self, message: Message) {
let window = self.window.as_ref().unwrap();
@ -56,11 +56,11 @@ impl PreferencesWindow {
impl WindowDelegate for 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_movable_by_background(true);
window.set_toolbar(&self.toolbar);
self.window = Some(window);
self.on_message(Message::SwitchPreferencesToGeneralPane);

View file

@ -23,7 +23,7 @@ impl Default for ToggleOptionView {
let title = Label::new();
view.add_subview(&title);
let subtitle = Label::new();
view.add_subview(&subtitle);
@ -31,7 +31,7 @@ impl Default for ToggleOptionView {
switch.top.constraint_equal_to(&view.top),
switch.leading.constraint_equal_to(&view.leading),
switch.width.constraint_equal_to_constant(24.),
title.top.constraint_equal_to(&view.top),
title.leading.constraint_equal_to(&switch.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");
item.set_image(icon);
item.set_action(|| {
dispatch_ui(Message::SwitchPreferencesToGeneralPane);
});
@ -26,14 +26,14 @@ impl Default for PreferencesToolbar {
}, {
let mut item = ToolbarItem::new("advanced");
item.set_title("Advanced");
let icon = Image::toolbar_icon(MacSystemIcon::PreferencesAdvanced, "Advanced");
item.set_image(icon);
item.set_action(|| {
dispatch_ui(Message::SwitchPreferencesToAdvancedPane);
});
item
}))
}
@ -41,7 +41,7 @@ impl Default for PreferencesToolbar {
impl ToolbarDelegate for PreferencesToolbar {
const NAME: &'static str = "PreferencesToolbar";
fn did_load(&mut self, toolbar: Toolbar) {
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.
fn toggle_bool(key: &str) {
let mut defaults = UserDefaults::standard();
if let Some(value) = defaults.get(key) {
if let Some(value) = value.as_bool() {
defaults.insert(key, Value::Bool(!value));
return;
}
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.
fn load_bool(key: &str) -> bool {
let defaults = UserDefaults::standard();
if let Some(value) = defaults.get(key) {
if let Some(value) = value.as_bool() {
return value;
}
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;
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
/// 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.

View file

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

View file

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

View file

@ -34,7 +34,7 @@ impl TodoViewRow {
impl ViewDelegate for TodoViewRow {
const NAME: &'static str = "TodoViewRow";
/// Called when the view is first created; handles setup of layout and associated styling that
/// doesn't change.
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.leading.constraint_equal_to(&view.leading).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.leading.constraint_equal_to(&view.leading).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())
}
}
pub fn on_message(&self, message: Message) {
if let Some(delegate) = &self.content.view.delegate {
delegate.on_message(message);
@ -36,8 +36,8 @@ impl TodosWindow {
impl WindowDelegate for 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_minimum_content_size(400, 400);
window.set_movable_by_background(true);

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -19,7 +19,7 @@ impl AnimationContext {
let _: () = msg_send![self.0, setDuration:duration];
}
}
/// Pass it a block, and the changes in that block will be animated, provided they're
/// properties that support animation.
///
@ -66,7 +66,7 @@ impl AnimationContext {
unsafe {
//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];
}
}

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 {
// @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
// useful.
// useful.
let activity = UserActivity::with_inner(activity);
match app::<T>(this).continue_user_activity(activity, || unsafe {
let handler = handler as *const Block<(id,), c_void>;
(*handler).call((nil,));
(*handler).call((nil,));
}) {
true => YES,
false => NO
@ -202,7 +202,7 @@ extern fn open_urls<T: AppDelegate>(this: &Object, _: Sel, _: id, file_urls: id)
let uri = NSString::retain(unsafe {
msg_send![url, absoluteString]
});
Url::parse(uri.to_str())
}).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
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, _, _));
// Managing Active Status
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, _, _));

View file

@ -12,10 +12,10 @@ pub enum TerminateResponse {
/// App should not be terminated.
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`.
///
/// 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.
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._
/// - _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 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`._
/// - _`AutoHideToolbar` may be used only when both `FullScreen` and `AutoHideMenuBar` are also set.
#[derive(Copy, Clone, Debug)]
@ -86,10 +86,10 @@ pub enum PresentationOption {
/// Menubar is entirely disabled.
HideMenuBar,
/// All Apple Menu items are disabled.
DisableAppleMenu,
/// The process switching user interface (Command + Tab to cycle through apps) is disabled.
DisableProcessSwitching,

View file

@ -6,7 +6,7 @@
//! ```rust,no_run
//! use cacao::app::{App, AppDelegate};
//! use cacao::window::Window;
//!
//!
//! #[derive(Default)]
//! struct BasicApp;
//!
@ -20,7 +20,7 @@
//! App::new("com.my.app", BasicApp::default()).run();
//! }
//! ```
//!
//!
//! ## Why do I need to do this?
//! 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
@ -29,7 +29,7 @@
//! - 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
//! should.
//!
//!
//! ### Platform specificity
//! Certain lifecycle events are specific to certain platforms. Where this is the case, the
//! 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.
/// If you're wondering where to go from here... you need an `AppDelegate` that implements
/// `did_finish_launching`. :)
@ -134,16 +134,16 @@ impl<T> App<T> where T: AppDelegate + 'static {
/// Objective-C side of things.
pub fn new(_bundle_id: &str, delegate: T) -> Self {
//set_bundle_id(bundle_id);
activate_cocoa_multithreading();
let pool = AutoReleasePool::new();
let objc = unsafe {
let app: id = msg_send![register_app_class(), sharedApplication];
Id::from_ptr(app)
};
let app_delegate = Box::new(delegate);
let objc_delegate = unsafe {
@ -163,7 +163,7 @@ impl<T> App<T> where T: AppDelegate + 'static {
_message: std::marker::PhantomData
}
}
}
}
// 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
@ -171,7 +171,7 @@ impl<T> App<T> where T: AppDelegate + 'static {
// 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
// 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
// on the implementation side, and makes it a bit easier to detect when a message has come in on
// 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.
pub fn dispatch_main(message: M) {
let queue = dispatch::Queue::main();
queue.exec_async(move || unsafe {
let app: id = msg_send![register_app_class(), sharedApplication];
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.
pub fn dispatch_background(message: M) {
let queue = dispatch::Queue::main();
queue.exec_async(move || unsafe {
let app: id = msg_send![register_app_class(), sharedApplication];
let app_delegate: id = msg_send![app, delegate];
@ -217,7 +217,7 @@ impl App {
let _: () = msg_send![app, registerForRemoteNotifications];
});
}
/// Unregisters for remote notifications from APNS.
pub fn unregister_for_remote_notifications() {
shared_application(|app| unsafe {

View file

@ -33,7 +33,7 @@ pub trait AppDelegate {
/// Fired when the application is about to resign active state.
fn will_resign_active(&self) {}
/// Fired when the user is going to continue an activity.
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) {}
/// Fires after the user accepted a CloudKit sharing invitation associated with your
/// application.
/// application.
#[cfg(feature = "cloudkit")]
fn user_accepted_cloudkit_share(&self, _share_metadata: CKShareMetaData) {}
/// Fired before the application terminates. You can use this to do any required cleanup.
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()`.
///
/// 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
/// you do this, you'll need to be sure to call `App::reply_to_termination_request()` to circle
/// back.
@ -107,12 +107,12 @@ pub trait AppDelegate {
/// `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`.
///
/// 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`.
///
/// 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.
///
/// 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
/// something in their settings).
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
/// documentation verbatim:
///
/// _"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.
/// The list can also include URLs for documents for which your app does not have an associated `NSDocument` class.
/// _"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.
/// 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
/// file."
///
@ -150,9 +150,9 @@ pub trait AppDelegate {
/// Fired when the file is requested to be opened programmatically. This is not a commonly used
/// 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."_
///
/// 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.
///
/// 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
/// when the occlusion region changes. You can use this method to increase responsiveness and save power by halting any
/// 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
/// 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._
fn occlusion_state_changed(&self) {}

View file

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

View file

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

View file

@ -17,12 +17,12 @@ use crate::events::EventModifierFlag;
static BLOCK_PTR: &'static str = "cacaoMenuItemBlockPtr";
/// 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
/// 0x1, and all point to whatever is there first (unsure if this is due to
/// 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
/// Rust or Cocoa or what).
///
/// 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.
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 item = Id::from_retained_ptr(match action {
Some(a) => msg_send![alloc, initWithTitle:&*title action:a keyEquivalent:&*key],
None => msg_send![alloc, initWithTitle:&*title
action:sel!(fireBlockAction:)
None => msg_send![alloc, initWithTitle:&*title
action:sel!(fireBlockAction:)
keyEquivalent:&*key]
});
@ -115,7 +115,7 @@ pub enum MenuItem {
/// A menu item for enabling copying (often text) from responders.
Copy,
/// A menu item for enabling cutting (often text) from responders.
Cut,
@ -126,10 +126,10 @@ pub enum MenuItem {
/// An "redo" menu item; particularly useful for supporting the cut/copy/paste/undo lifecycle
/// of events.
Redo,
/// A menu item for selecting all (often text) from responders.
SelectAll,
/// A menu item for pasting (often text) into responders.
Paste,
@ -158,7 +158,7 @@ impl MenuItem {
pub(crate) unsafe fn to_objc(self) -> Id<Object> {
match self {
Self::Custom(objc) => objc,
Self::About(app_name) => {
let title = format!("About {}", app_name);
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::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::EnterFullScreen => make_menu_item(
"Enter Full Screen",
Some("f"),
@ -225,7 +225,7 @@ impl MenuItem {
}
/// 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 {
if let MenuItem::Custom(objc) = self {
unsafe {
@ -271,7 +271,7 @@ impl MenuItem {
if let MenuItem::Custom(mut objc) = self {
let handler = Box::new(Action(Box::new(action)));
let ptr = Box::into_raw(handler);
unsafe {
(&mut *objc).set_ivar(BLOCK_PTR, ptr as usize);
let _: () = msg_send![&*objc, setTarget:&*objc];
@ -291,7 +291,7 @@ extern fn dealloc_cacao_menuitem(this: &Object, _: Sel) {
unsafe {
let ptr: usize = *this.get_ivar(BLOCK_PTR);
let obj = ptr as *mut Action;
if !obj.is_null() {
let _handler = Box::from_raw(obj);
}

View file

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

View file

@ -15,7 +15,7 @@ pub enum PrintResponse {
Failure,
/// 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.
ReplyLater
}

View file

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

View file

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

View file

@ -25,7 +25,7 @@ pub use enums::{ToolbarDisplayMode, ToolbarSizeMode, ItemIdentifier};
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.
pub struct Toolbar<T = ()> {
/// 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 cls = register_toolbar_class::<T>(&delegate);
let mut delegate = Box::new(delegate);
let (objc, objc_delegate) = unsafe {
let alloc: id = msg_send![class!(NSToolbar), alloc];
let identifier = NSString::new(&identifier);

View file

@ -27,7 +27,7 @@ pub trait ToolbarDelegate {
/// The default items in this toolbar.
fn default_item_identifiers(&self) -> Vec<ItemIdentifier>;
/// The default items in this toolbar. This defaults to a blank `Vec`, and is an optional
/// method - mostly useful for Preferences windows.
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 {
let window = load::<T>(this, WINDOW_DELEGATE_PTR);
let s = window.will_resize(size.width as f64, size.height as f64);
CGSize {
CGSize {
width: s.0 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 desired_opts = window.presentation_options_for_full_screen();
if desired_opts.is_none() {
if desired_opts.is_none() {
options
} else {
let mut opts: NSUInteger = 0;
@ -219,7 +219,7 @@ extern fn did_expose<T: WindowDelegate>(this: &Object, _: Sel, _: id) {
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
/// 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.

View file

@ -14,11 +14,11 @@ pub struct WindowConfig {
/// The initial dimensions for the window.
pub initial_dimensions: Rect,
/// From the Apple docs:
/// From the Apple docs:
///
/// _"When true, the window server defers creating the window device
/// until the window is moved onscreen. All display messages sent to
/// the window or its views are postponed until the window is created,
/// _"When true, the window server defers creating the window device
/// until the window is moved onscreen. All display messages sent to
/// the window or its views are postponed until the window is created,
/// just before its moved onscreen."_
///
/// 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;
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.
pub struct WindowController<T> {
/// 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
//! 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
//! not bother providing access to them. If you require functionality like that, you're free to use
//! 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
//! the `objc` field on a `Window` to instrument it with the Objective-C runtime on your own.
use block::ConcreteBlock;
@ -72,13 +72,13 @@ impl Window {
let _: () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:NO];
let alloc: id = msg_send![class!(NSWindow), alloc];
// 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.
let buffered: NSUInteger = 2;
let dimensions: CGRect = config.initial_dimensions.into();
let window: id = msg_send![alloc, initWithContentRect:dimensions
styleMask:config.style
let window: id = msg_send![alloc, initWithContentRect:dimensions
styleMask:config.style
backing:buffered
defer:match config.defer {
true => YES,
@ -93,7 +93,7 @@ impl Window {
// Objective-C runtime gets out of sync by releasing the window out from underneath of
// us.
let _: () = msg_send![window, setReleasedWhenClosed:NO];
let _: () = msg_send![window, setRestorable:NO];
// 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 {
let class = register_window_class_with_delegate::<T>(&delegate);
let mut delegate = Box::new(delegate);
let objc = unsafe {
// 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...
let _: () = msg_send![class!(NSWindow), setAllowsAutomaticWindowTabbing:NO];
let alloc: id = msg_send![class, alloc];
// 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.
let buffered: NSUInteger = 2;
let dimensions: CGRect = config.initial_dimensions.into();
let window: id = msg_send![alloc, initWithContentRect:dimensions
styleMask:config.style
let window: id = msg_send![alloc, initWithContentRect:dimensions
styleMask:config.style
backing:buffered
defer:match config.defer {
true => YES,
@ -226,7 +226,7 @@ impl<T> Window<T> {
pub fn set_autosave_name(&self, name: &str) {
unsafe {
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];
}
}
/// Sets the minimum size this window can shrink to.
pub fn set_minimum_size<F: Into<f64>>(&self, width: F, height: F) {
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>) {
unsafe {
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
/// this window.
pub fn toggle_toolbar_shown(&self) {
@ -377,9 +377,9 @@ impl<T> Window<T> {
///
/// From Apple's documentation:
///
/// _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
/// space. For nonvisible windows, it indicates whether ordering the window onscreen would cause it to
/// _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
/// space. For nonvisible windows, it indicates whether ordering the window onscreen would cause it to
/// be on the active space._
pub fn is_on_active_space(&self) -> bool {
to_bool(unsafe {
@ -453,7 +453,7 @@ impl<T> Window<T> {
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
/// 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 methods, but mix in a few extra things to handle offering configuration tools
/// in lieu of subclasses.
pub trait WindowDelegate {
pub trait WindowDelegate {
/// Used to cache subclass creations on the Objective-C side.
/// You can just set this to be the name of your view type. This
/// 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.
fn will_close(&self) {}
/// Fired when the window is about to move.
/// Fired when the window is about to move.
fn will_move(&self) {}
/// 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
/// do its thing. If you implement it, you probably want that.
fn will_resize(&self, width: f64, height: f64) -> (f64, f64) { (width, height) }
/// Fired after the window has resized.
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
/// to use. By default, this just returns the system-provided content size, but you can
/// 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)
}
@ -119,7 +119,7 @@ pub trait WindowDelegate {
/// Fires when this window failed to exit full screen.
fn did_fail_to_exit_full_screen(&self) {}
/// Fired when the occlusion state for this window has changed. Similar in nature to the
/// app-level event, just for a Window.
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;
// Class::get("NSBundle").unwrap();
// let types = format!("{}{}{}", Encoding::String, <*mut Object>::ENCODING, Sel::ENCODING);
let added = class_addMethod(
cls as *mut Class,
sel!(__bundleIdentifier),

View file

@ -44,7 +44,7 @@ pub enum BezelStyle {
/// A textured square style.
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).
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
/// 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.
///
/// ```rust,no_run
@ -75,7 +75,7 @@ pub struct Button {
pub image: Option<Image>,
handler: Option<TargetActionHandler>,
/// A pointer to the Objective-C runtime top layout constraint.
#[cfg(feature = "autolayout")]
pub top: LayoutAnchorY,
@ -130,47 +130,47 @@ impl Button {
];
let _: () = msg_send![button, setWantsLayer:YES];
#[cfg(feature = "autolayout")]
let _: () = msg_send![button, setTranslatesAutoresizingMaskIntoConstraints:NO];
button
};
Button {
handler: None,
image: None,
#[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view),
objc: ObjcProperty::retain(view),
}
}
@ -188,7 +188,7 @@ impl Button {
#[cfg(feature = "appkit")]
pub fn set_bezel_style(&self, bezel_style: BezelStyle) {
let style: NSUInteger = bezel_style.into();
self.objc.with_mut(|obj| unsafe {
let _: () = msg_send![obj, setBezelStyle:style];
});
@ -206,7 +206,7 @@ impl Button {
/// Call this to set the background color for the backing layer.
pub fn set_background_color<C: AsRef<Color>>(&self, color: C) {
let color: id = color.as_ref().into();
#[cfg(feature = "appkit")]
self.objc.with_mut(|obj| unsafe {
let cell: id = msg_send![obj, cell];
@ -227,7 +227,7 @@ impl Button {
Key::Char(s) => NSString::new(s),
Key::Delete => NSString::new("\u{08}")
};
unsafe {
let _: () = msg_send![obj, setKeyEquivalent:&*keychar];
}
@ -236,16 +236,16 @@ impl 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) {
#[cfg(feature = "appkit")]
self.objc.with_mut(move |obj| unsafe {
let text: id = msg_send![obj, attributedTitle];
let len: isize = msg_send![text, length];
let mut attr_str = AttributedString::wrap(text);
attr_str.set_text_color(color.as_ref(), 0..len);
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.
fn register_class() -> *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 {
let superclass = class!(NSButton);
let decl = ClassDecl::new("RSTButton", superclass).unwrap();
let decl = ClassDecl::new("RSTButton", superclass).unwrap();
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
//! 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
//! 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!(alphaComponent), alpha_component as extern fn(&Object, _) -> CGFloat);
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!(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_DARK_COLOR_NORMAL_CONTRAST);
decl.add_ivar::<id>(AQUA_DARK_COLOR_HIGH_CONTRAST);
VIEW_CLASS = decl.register();
});

View file

@ -1,5 +1,5 @@
//! 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
//! 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
//! themselves have differing levels of support for color work. Where possible,
//! we expose some platform-specific methods for creating and working with these.
//!
@ -27,7 +27,7 @@ use crate::foundation::id;
use crate::utils::os;
#[cfg(feature = "appkit")]
mod appkit_dynamic_color;
mod appkit_dynamic_color;
#[cfg(feature = "appkit")]
use appkit_dynamic_color::{
@ -49,7 +49,7 @@ pub enum Theme {
Dark
}
/// Represents the contrast level for a rendering context.
/// Represents the contrast level for a rendering context.
#[derive(Copy, Clone, Debug)]
pub enum Contrast {
/// The default contrast level for the system.
@ -71,7 +71,7 @@ pub struct Style {
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
/// 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
@ -84,7 +84,7 @@ pub enum Color {
/// 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.
///
/// 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.
Custom(Arc<RwLock<Id<Object>>>),
@ -136,7 +136,7 @@ pub enum Color {
/// The system-provided base gray color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray,
/// The system-provided secondary-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray2,
@ -148,11 +148,11 @@ pub enum Color {
/// The system-provided fourth-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray4,
/// The system-provided fifth-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray5,
/// The system-provided sixth-level gray color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemGray6,
@ -184,11 +184,11 @@ pub enum Color {
/// The default system second-level fill color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemFillSecondary,
/// The default system third-level fill color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemFillTertiary,
/// The default system fourth-level fill color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemFillQuaternary,
@ -204,7 +204,7 @@ pub enum Color {
/// The default system second-level background color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemBackgroundSecondary,
/// The default system third-level background color.
/// This value automatically switches to the correct variant depending on light or dark mode.
SystemBackgroundTertiary,
@ -256,7 +256,7 @@ impl Color {
{ 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
/// set to `255` by default. Shorthand for `rgba`.
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]) }
})))
}
/// Creates and returns a color in the RGB space, with the alpha level
/// set to `255` by default. Shorthand for `hsba`.
pub fn hsb(hue: u8, saturation: u8, brightness: u8) -> Self {
@ -292,7 +292,7 @@ impl Color {
Color::Custom(Arc::new(RwLock::new(unsafe {
#[cfg(feature = "appkit")]
{ Id::from_ptr(msg_send![class!(NSColor), colorWithCalibratedWhite:level alpha:alpha]) }
#[cfg(feature = "uikit")]
{ Id::from_ptr(msg_send![class!(UIColor), colorWithWhite:level alpha:alpha]) }
})))
@ -303,7 +303,7 @@ impl Color {
pub fn white(level: CGFloat) -> Self {
Color::white_alpha(level, 1.0)
}
/// 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
@ -377,15 +377,15 @@ impl Color {
color
});
Id::from_ptr(color)
})))
}
/// 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`
/// 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
/// in every context it's used in.
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::SystemIndigo => system_color_with_fallback!(color, systemIndigoColor, magentaColor),
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::SystemRed => system_color_with_fallback!(color, systemRedColor, redColor),
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::SystemBackgroundTertiary => system_color_with_fallback!(color, tertiarySystemBackgroundColor, clearColor),
Color::Separator => system_color_with_fallback!(color, separatorColor, lightGrayColor),
#[cfg(feature = "uikit")]
Color::OpaqueSeparator => system_color_with_fallback!(color, opaqueSeparatorColor, darkGrayColor),
Color::Link => system_color_with_fallback!(color, linkColor, blueColor),
Color::DarkText => system_color_with_fallback!(color, darkTextColor, blackColor),
Color::LightText => system_color_with_fallback!(color, lightTextColor, whiteColor),
#[cfg(feature = "appkit")]
Color::MacOSWindowBackgroundColor => system_color_with_fallback!(color, windowBackgroundColor, clearColor),
#[cfg(feature = "appkit")]
Color::MacOSUnderPageBackgroundColor => system_color_with_fallback!(color, underPageBackgroundColor, clearColor),
}

View file

@ -13,7 +13,7 @@ pub enum ControlSize {
/// A smaller control size.
Small,
/// The default, regular, size.
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) {
let control_size: NSUInteger = match size {
ControlSize::Mini => 2,

View file

@ -61,7 +61,7 @@ impl Default for UserDefaults {
impl UserDefaults {
/// 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
/// extension) you *probably* want to use `suite()` instead!_
///
@ -69,7 +69,7 @@ impl UserDefaults {
/// use cacao::defaults::UserDefaults;
///
/// let defaults = UserDefaults::standard();
///
///
/// let _ = defaults.get("test");
/// ```
pub fn standard() -> Self {
@ -108,7 +108,7 @@ impl UserDefaults {
/// use cacao::defaults::{UserDefaults, Value};
///
/// let mut defaults = UserDefaults::standard();
///
///
/// defaults.register({
/// let mut map = HashMap::new();
/// map.insert("test", Value::Bool(true));
@ -117,7 +117,7 @@ impl UserDefaults {
/// ```
pub fn register<K: AsRef<str>>(&mut self, values: HashMap<K, Value>) {
let dictionary = NSMutableDictionary::from(values);
unsafe {
let _: () = msg_send![&*self.0, registerDefaults:&*dictionary];
}
@ -140,7 +140,7 @@ impl UserDefaults {
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.
///
/// ```rust
@ -206,7 +206,7 @@ impl UserDefaults {
// For context: https://nshipster.com/type-encodings/
if NSNumber::is(result) {
let number = NSNumber::wrap(result);
return match number.objc_type() {
"c" => Some(Value::Bool(number.as_bool())),
"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
/// 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.
///
/// ```rust

View file

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

View file

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

View file

@ -15,7 +15,7 @@ use crate::filesystem::enums::{SearchPathDirectory, SearchPathDomainMask};
/// 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.
///
/// @TODO: Couldn't this just be a ShareId?
@ -55,7 +55,7 @@ impl FileManager {
let directory = unsafe {
let manager = self.0.read().unwrap();
let dir: id = msg_send![&**manager, URLForDirectory:dir
let dir: id = msg_send![&**manager, URLForDirectory:dir
inDomain:mask
appropriateForURL:nil
create:NO
@ -63,7 +63,7 @@ impl FileManager {
NSString::retain(msg_send![dir, absoluteString])
};
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`.
pub can_choose_directories: bool,
/// 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
/// is true. When this value is false, selecting an alias returns the alias instead of the
/// 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
/// is true. When this value is false, selecting an alias returns the alias instead of the
/// file or directory it represents.
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`.
pub allows_multiple_selection: bool
}

View file

@ -11,7 +11,7 @@ pub trait OpenSaveController {
/// Notifies you that the user changed directories.
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.
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.
fn from(objects: Vec<&Object>) -> Self {
NSArray(unsafe {
Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr()
Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr()
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.
fn from(objects: Vec<id>) -> Self {
NSArray(unsafe {
Id::from_ptr(msg_send![class!(NSArray),
Id::from_ptr(msg_send![class!(NSArray),
arrayWithObjects:objects.as_ptr()
count:objects.len()
])

View file

@ -39,7 +39,7 @@ impl ClassMap {
let mut map = HashMap::new();
// 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.
map.insert("_supers", HashMap::new());
@ -118,15 +118,15 @@ impl ClassMap {
}
/// 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
/// this class in the Objective-C runtime.
///
/// 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.
///
/// 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,
/// 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,
/// the entire framework will not really work.
///
/// There's definitely room to optimize here, but it works for now.
@ -155,7 +155,7 @@ where
return class;
},
None => {
None => {
panic!(
"Subclass of type {}_{} could not be allocated.",
subclass_name,

View file

@ -49,7 +49,7 @@ impl NSData {
NSData(Id::from_ptr(obj))
}
}
/// 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
@ -96,7 +96,7 @@ impl NSData {
x as usize
}
}
/// Returns a reference to the underlying bytes for the wrapped `NSData`.
///
/// 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)
pub fn bytes(&self) -> &[u8] {
let ptr: *const c_void = unsafe { msg_send![&*self.0, bytes] };
// The bytes pointer may be null for length zero
let (ptr, len) = if ptr.is_null() {
(0x1 as *const u8, 0)
} else {
(ptr as *const u8, self.len())
};
unsafe {
slice::from_raw_parts(ptr, len)
}
}
/// 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).
///
@ -126,11 +126,11 @@ impl NSData {
// often, but still... open to ideas.
pub fn into_vec(self) -> Vec<u8> {
let mut data = Vec::new();
let bytes = self.bytes();
data.resize(bytes.len(), 0);
data.copy_from_slice(bytes);
data
}
}

View file

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

View file

@ -22,7 +22,7 @@ impl NSNumber {
Id::from_ptr(data)
})
}
/// 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.
pub fn wrap(data: id) -> Self {

View file

@ -13,7 +13,7 @@ const UTF8_ENCODING: usize = 4;
/// 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.
#[derive(Debug)]
pub struct NSString<'a> {
@ -37,7 +37,7 @@ impl<'a> NSString<'a> {
phantom: PhantomData
}
}
/// Creates a new `NSString` without copying the bytes for the passed-in string.
pub fn no_copy(s: &'a str) -> Self {
NSString {
@ -89,14 +89,14 @@ impl<'a> NSString<'a> {
fn bytes_len(&self) -> usize {
unsafe {
msg_send![&*self.objc, lengthOfBytesUsingEncoding:UTF8_ENCODING]
}
}
}
/// A utility method for taking an `NSString` and bridging it to a Rust `&str`.
pub fn to_str(&self) -> &str {
let bytes = self.bytes();
let len = self.bytes_len();
unsafe {
let bytes = slice::from_raw_parts(bytes, len);
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.
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.
SecurityScoped,
/// 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
/// 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
/// read-only access to a file-system resource.
SecurityScopedReadOnly
}
@ -50,7 +50,7 @@ pub enum NSURLBookmarkResolutionOption {
/// Specifies that no volume should be mounted during resolution of the bookmark data.
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.
SecurityScoped
}

View file

@ -13,11 +13,11 @@ mod bookmark_options;
pub use bookmark_options::{NSURLBookmarkCreationOption, NSURLBookmarkResolutionOption};
mod resource_keys;
pub use resource_keys::{NSURLResourceKey, NSURLFileResource, NSUbiquitousItemDownloadingStatus};
pub use resource_keys::{NSURLResourceKey, NSURLFileResource, NSUbiquitousItemDownloadingStatus};
/// 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
/// being able to actually build useful things.
///
@ -52,11 +52,11 @@ impl<'a> NSURL<'a> {
phantom: PhantomData
}
}
/// Creates and returns a URL object by calling through to `[NSURL URLWithString]`.
pub fn with_str(url: &str) -> Self {
let url = NSString::new(url);
Self {
objc: unsafe {
ShareId::from_ptr(msg_send![class!(NSURL), URLWithString:&*url])
@ -65,7 +65,7 @@ impl<'a> NSURL<'a> {
phantom: PhantomData
}
}
/// 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
@ -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.
///
/// More information can be found at:
/// More information can be found at:
/// [https://developer.apple.com/documentation/foundation/nsurl/1417051-startaccessingsecurityscopedreso?language=objc]
pub fn start_accessing_security_scoped_resource(&self) {
unsafe {

View file

@ -8,7 +8,7 @@ use core_graphics::geometry::{CGRect, CGPoint, CGSize};
pub struct Rect {
/// Distance from the top, in points.
pub top: f64,
/// Distance from the left, in points.
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();
//decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
VIEW_CLASS = decl.register();
});

View file

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

View file

@ -67,7 +67,7 @@ impl MacSystemIcon {
MacSystemIcon::Add => SFSymbol::Plus.to_str(),
MacSystemIcon::Remove => SFSymbol::Minus.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 {
// if equal, just return source
if
source.origin.x == target.origin.x &&
source.origin.x == target.origin.x &&
source.origin.y == target.origin.y &&
source.size.width == target.size.width &&
source.size.height == target.size.height
@ -64,10 +64,10 @@ impl ResizeBehavior {
}
if
source.origin.x == 0. &&
source.origin.x == 0. &&
source.origin.y == 0. &&
source.size.width == 0. &&
source.size.height == 0.
source.size.height == 0.
{
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
/// provide a fallback image or user experience if you need to support an older OS.
pub fn symbol(symbol: SFSymbol, accessibility_description: &str) -> Self {
@ -246,7 +246,7 @@ impl Image {
);
let result = handler(resized_frame, &context);
let _: () = msg_send![class!(NSGraphicsContext), restoreGraphicsState];
match result {
@ -257,8 +257,8 @@ impl Image {
let block = block.copy();
Image(unsafe {
let img: id = msg_send![class!(NSImage), imageWithSize:target_frame.size
flipped:YES
let img: id = msg_send![class!(NSImage), imageWithSize:target_frame.size
flipped:YES
drawingHandler:block
];

View file

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

View file

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

View file

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

View file

@ -23,12 +23,12 @@ use crate::utils::load;
pub static ACTION_CALLBACK_PTR: &str = "rstTargetActionPtr";
/// 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
/// 0x1, and all point to whatever is there first (unsure if this is due to
/// 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
/// Rust or Cocoa or what).
///
/// 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.
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
/// the Objective-C side.
/// the Objective-C side.
///
/// This effectively wraps the target:action selector usage on NSControl and
/// 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,
/// 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.
///
/// 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
/// generic block over. It's still Rust, so you can't do crazy callbacks, but
/// 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
/// 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.
///
/// 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_method(sel!(perform:), perform::<F> as extern fn (&mut Object, _, id));
VIEW_CLASS = decl.register();
});

View file

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

View file

@ -91,18 +91,18 @@ pub enum LayoutAttribute {
/// The center along the y-axis of the objects alignment rectangle.
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.
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.
FirstBaseline,
/// A placeholder value that is used to indicate that the constraints
/// second item and second attribute are not used in any calculations.
/// A placeholder value that is used to indicate that the constraints
/// 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,
/// 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.
AlignAllLastBaseline,
/// 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
/// 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
/// 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
/// 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
/// ordering is reversed.
DirectionLeadingToTrailing,

View file

@ -58,7 +58,7 @@ impl LayoutAnchorDimension {
msg_send![*obj, constraintEqualToConstant:value]
});
}
panic!("Attempted to create a constant constraint with an uninitialized anchor.");
}
@ -70,10 +70,10 @@ impl LayoutAnchorDimension {
msg_send![*obj, constraintGreaterThanOrEqualToConstant:value]
});
}
panic!("Attempted to create a constraint (>=) with an uninitialized anchor.");
}
/// Return a constraint greater than or equal to a constant value.
pub fn constraint_less_than_or_equal_to_constant(&self, constant: f64) -> LayoutConstraint {
if let Self::Width(obj) | Self::Height(obj) = self {
@ -82,7 +82,7 @@ impl LayoutAnchorDimension {
msg_send![*obj, constraintLessThanOrEqualToConstant:value]
});
}
panic!("Attempted to create a constraint (<=) with an uninitialized anchor.");
}
@ -100,7 +100,7 @@ impl LayoutAnchorDimension {
(Self::Height(from), Self::Height(to)) => {
LayoutConstraint::new(handler(from, to))
},
(Self::Uninitialized, Self::Uninitialized) => {
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::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.
///
/// 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.
(Self::Leading(_), Self::Left(_)) | (Self::Left(_), Self::Leading(_)) => {
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.
Use either left/right or leading/trailing.
"#);
},
(Self::Leading(_), Self::Right(_)) | (Self::Right(_), Self::Leading(_)) => {
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.
Use either left/right or leading/trailing.
"#);
},
(Self::Trailing(_), Self::Left(_)) | (Self::Left(_), Self::Trailing(_)) => {
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.
Use either left/right or leading/trailing.
@ -141,7 +141,7 @@ impl LayoutAnchorX {
(Self::Trailing(_), Self::Right(_)) | (Self::Right(_), Self::Trailing(_)) => {
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.
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
//! `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.

View file

@ -55,12 +55,12 @@ pub trait Layout: ObjcAccess {
/// use an appropriate initializer for a given view type).
fn set_frame<R: Into<CGRect>>(&self, rect: R) {
let frame: CGRect = rect.into();
self.with_backing_obj_mut(move |backing_node| unsafe {
let _: () = msg_send![backing_node, setFrame:frame];
});
}
/// Sets whether the view for this trait should translate autoresizing masks into layout
/// constraints.
///
@ -78,7 +78,7 @@ pub trait Layout: ObjcAccess {
/// 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) {
self.with_backing_obj_mut(|obj| unsafe {
let _: () = msg_send![obj, setHidden:match hide {
@ -89,8 +89,8 @@ pub trait Layout: ObjcAccess {
}
/// 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()`.
fn is_hidden(&self) -> bool {
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.
#[cfg(feature = "appkit")]
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
/// currently to avoid compile issues.
#[cfg(feature = "appkit")]
fn unregister_dragged_types(&self) {
fn unregister_dragged_types(&self) {
self.with_backing_obj_mut(|obj| unsafe {
let _: () = msg_send![obj, unregisterDraggedTypes];
});

View file

@ -5,7 +5,7 @@ use objc_id::ShareId;
use crate::foundation::id;
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.
#[derive(Clone, Debug)]
pub enum LayoutAnchorY {
@ -59,7 +59,7 @@ impl LayoutAnchorY {
{
match (self, anchor_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::Center(to)) |

View file

@ -20,9 +20,9 @@
//! already fine for some apps.
//!
//! _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,
//! 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
//! 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
//! 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._
//!
//! # Hello World
@ -30,7 +30,7 @@
//! ```rust,no_run
//! use cacao::appkit::app::{App, AppDelegate};
//! use cacao::appkit::window::Window;
//!
//!
//! #[derive(Default)]
//! struct BasicApp {
//! window: Window
@ -98,7 +98,7 @@ pub use url;
pub use lazy_static;
//#[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_attr(docsrs, doc(cfg(feature = "appkit")))]

View file

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

View file

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

View file

@ -17,7 +17,7 @@ pub enum RowAnimation {
/// Animates in or out by sliding upwards.
SlideUp,
/// Animates in or out by sliding down.
SlideDown,
@ -61,7 +61,7 @@ impl Into<RowEdge> for NSInteger {
1 => RowEdge::Trailing,
// @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...
_ => { unreachable!(); }
}

View file

@ -5,7 +5,7 @@
//! 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.
//!
//!
//! ```rust,no_run
//! use cacao::color::rgb;
//! use cacao::layout::{Layout, LayoutConstraint};
@ -18,7 +18,7 @@
//! red: View,
//! window: Window
//! }
//!
//!
//! impl WindowDelegate for AppWindow {
//! fn did_load(&mut self, window: Window) {
//! window.set_minimum_content_size(300., 300.);
@ -26,7 +26,7 @@
//!
//! self.red.set_background_color(rgb(224, 82, 99));
//! self.content.add_subview(&self.red);
//!
//!
//! self.window.set_content_view(&self.content);
//!
//! LayoutConstraint::activate(&[
@ -97,7 +97,7 @@ use std::rc::Rc;
use std::cell::RefCell;
/// 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 {
// 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.
@ -203,15 +203,15 @@ impl Default for ListView {
}
impl ListView {
/// @TODO: The hell is this for?
/// @TODO: The hell is this for?
pub fn new() -> Self {
let class = register_listview_class();
let view = common_init(class);
#[cfg(feature = "appkit")]
let scrollview = {
let sview = ScrollView::new();
sview.objc.with_mut(|obj| unsafe {
let _: () = msg_send![obj, setDocumentView:view];
});
@ -225,7 +225,7 @@ impl ListView {
let anchor_view: id = scrollview.objc.get(|obj| unsafe {
msg_send![obj, self]
});
//#[cfg(all(feature = "uikit", feature = "autolayout"))]
//let anchor_view: id = view;
@ -233,37 +233,37 @@ impl ListView {
cell_factory: CellFactory::new(),
menu: PropertyNullable::default(),
delegate: None,
#[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(anchor_view),
#[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(anchor_view),
#[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(anchor_view),
#[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(anchor_view),
#[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(anchor_view),
#[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(anchor_view),
#[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(anchor_view),
#[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(anchor_view),
#[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(anchor_view),
#[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(anchor_view),
// Note that AppKit needs this to be the ScrollView!
// @TODO: Figure out if there's a use case for exposing the inner tableview animator
// property...
@ -284,7 +284,7 @@ impl<T> ListView<T> where T: ListViewDelegate + 'static {
let view = common_init(class);
let mut delegate = Box::new(delegate);
let cell = CellFactory::new();
unsafe {
let delegate_ptr: *const T = &*delegate;
(&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")]
let scrollview = {
let sview = ScrollView::new();
sview.objc.with_mut(|obj| unsafe {
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 {
msg_send![obj, self]
});
//#[cfg(feature = "uikit")]
//let anchor_view = view;
@ -321,38 +321,38 @@ impl<T> ListView<T> where T: ListViewDelegate + 'static {
#[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(anchor_view),
#[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(anchor_view),
#[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(anchor_view),
#[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(anchor_view),
#[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(anchor_view),
#[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(anchor_view),
#[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(anchor_view),
#[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(anchor_view),
#[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(anchor_view),
#[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(anchor_view),
scrollview
};
(&mut delegate).did_load(view.clone_as_handle());
(&mut delegate).did_load(view.clone_as_handle());
view.delegate = Some(delegate);
view
}
@ -373,31 +373,31 @@ impl<T> ListView<T> {
#[cfg(feature = "autolayout")]
top: self.top.clone(),
#[cfg(feature = "autolayout")]
leading: self.leading.clone(),
#[cfg(feature = "autolayout")]
left: self.left.clone(),
#[cfg(feature = "autolayout")]
trailing: self.trailing.clone(),
#[cfg(feature = "autolayout")]
right: self.right.clone(),
#[cfg(feature = "autolayout")]
bottom: self.bottom.clone(),
#[cfg(feature = "autolayout")]
width: self.width.clone(),
#[cfg(feature = "autolayout")]
height: self.height.clone(),
#[cfg(feature = "autolayout")]
center_x: self.center_x.clone(),
#[cfg(feature = "autolayout")]
center_y: self.center_y.clone(),
@ -423,7 +423,7 @@ impl<T> ListView<T> {
let cell: id = self.objc.get(|obj| unsafe {
msg_send![obj, makeViewWithIdentifier:&*key owner:nil]
});
if cell != nil {
ListViewRow::from_cached(cell)
} 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) {
self.objc.with_mut(|obj| unsafe {
let _: () = msg_send![obj, setSelectionHighlightStyle:style];
@ -544,7 +544,7 @@ impl<T> ListView<T> {
self.objc.get(|obj| unsafe {
let _: () = msg_send![obj, beginUpdates];
});
let handle = self.clone_as_handle();
update(handle);
@ -565,7 +565,7 @@ impl<T> ListView<T> {
#[cfg(feature = "appkit")]
unsafe {
let index_set: id = msg_send![class!(NSMutableIndexSet), new];
for index in indexes {
let x: NSUInteger = *index as NSUInteger;
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
// has also retained it.
let x = ShareId::from_ptr(index_set);
// This is done for a very explicit reason; see the comments on the method itself for
// an explanation.
self.hack_avoid_dequeue_loop(|obj| {
@ -590,7 +590,7 @@ impl<T> ListView<T> {
#[cfg(feature = "appkit")]
unsafe {
let index_set: id = msg_send![class!(NSMutableIndexSet), new];
for index in indexes {
let x: NSUInteger = *index as NSUInteger;
let _: () = msg_send![index_set, addIndex:x];
@ -617,7 +617,7 @@ impl<T> ListView<T> {
#[cfg(feature = "appkit")]
unsafe {
let index_set: id = msg_send![class!(NSMutableIndexSet), new];
for index in indexes {
let x: NSUInteger = *index as NSUInteger;
let _: () = msg_send![index_set, addIndex:x];
@ -705,7 +705,7 @@ impl<T> ListView<T> {
pub fn get_selected_row_index(&self) -> NSInteger {
self.objc.get(|obj| unsafe { msg_send![obj, selectedRow] })
}
/// 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
/// 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.
extern fn prepare_for_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
match view.prepare_for_drag_operation(DragInfo {
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.
extern fn perform_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) -> BOOL {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
match view.perform_drag_operation(DragInfo {
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.
extern fn conclude_drag_operation<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
view.conclude_drag_operation(DragInfo {
info: unsafe { Id::from_ptr(info) }
});
});
}
/// Called when a drag/drop operation has entered this view.
extern fn dragging_exited<T: ViewDelegate>(this: &mut Object, _: Sel, info: id) {
let view = load::<T>(this, LISTVIEW_ROW_DELEGATE_PTR);
view.dragging_exited(DragInfo {
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
/// 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
/// we know
/// we know
extern fn dealloc<T: ViewDelegate>(this: &Object, _: Sel) {
// Load the Box pointer here, and just let it drop normally.
unsafe {
@ -114,7 +114,7 @@ pub(crate) fn register_listview_row_class() -> *const Class {
let mut decl = ClassDecl::new("RSTTableViewRow", superclass).unwrap();
decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
VIEW_CLASS = decl.register();
});
@ -135,7 +135,7 @@ pub(crate) fn register_listview_row_class_with_delegate<T: ViewDelegate>() -> *c
// move.
decl.add_ivar::<usize>(LISTVIEW_ROW_DELEGATE_PTR);
decl.add_ivar::<id>(BACKGROUND_COLOR);
decl.add_method(sel!(isFlipped), enforce_normalcy as extern fn(&Object, _) -> BOOL);
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!(concludeDragOperation:), conclude_drag_operation::<T> as extern fn (&mut Object, _, _));
decl.add_method(sel!(draggingExited:), dragging_exited::<T> as extern fn (&mut Object, _, _));
// Cleanup
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.
//!
//! Views implement Autolayout, which enable you to specify how things should appear on the screen.
//!
//!
//! ```rust,no_run
//! use cacao::color::rgb;
//! use cacao::layout::{Layout, LayoutConstraint};
@ -18,7 +18,7 @@
//! red: View,
//! window: Window
//! }
//!
//!
//! impl WindowDelegate for AppWindow {
//! fn did_load(&mut self, window: Window) {
//! window.set_minimum_content_size(300., 300.);
@ -26,7 +26,7 @@
//!
//! self.red.set_background_color(rgb(224, 82, 99));
//! self.content.add_subview(&self.red);
//!
//!
//! self.window.set_content_view(&self.content);
//!
//! LayoutConstraint::activate(&[
@ -75,7 +75,7 @@ pub(crate) static BACKGROUND_COLOR: &str = "cacaoBackgroundColor";
pub(crate) static LISTVIEW_ROW_DELEGATE_PTR: &str = "cacaoListViewRowDelegatePtr";
/// 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 {
let view: id = msg_send![registration_fn(), new];
@ -85,7 +85,7 @@ fn allocate_view(registration_fn: fn() -> *const Class) -> id {
#[cfg(feature = "appkit")]
let _: () = msg_send![view, setWantsLayer:YES];
view
view
}
}
@ -106,7 +106,7 @@ pub struct ListViewRow<T = ()> {
/// A safe layout guide property.
#[cfg(feature = "autolayout")]
pub safe_layout_guide: SafeAreaLayoutGuide,
/// A pointer to the Objective-C runtime top layout constraint.
#[cfg(feature = "autolayout")]
pub top: LayoutAnchorY,
@ -155,7 +155,7 @@ impl Default for ListViewRow {
}
impl ListViewRow {
/// Returns a default `View`, suitable for
/// Returns a default `View`, suitable for
pub fn new() -> Self {
let view = allocate_view(register_listview_row_class);
@ -166,34 +166,34 @@ impl ListViewRow {
#[cfg(feature = "autolayout")]
safe_layout_guide: SafeAreaLayoutGuide::new(view),
#[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")]
center_y: LayoutAnchorY::center(view),
}
@ -227,34 +227,34 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
#[cfg(feature = "autolayout")]
safe_layout_guide: SafeAreaLayoutGuide::new(view),
#[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")]
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
/// 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>);
unsafe {
let ptr: *const T = &*delegate;
@ -283,39 +283,39 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
#[cfg(feature = "autolayout")]
safe_layout_guide: SafeAreaLayoutGuide::new(view),
#[cfg(feature = "autolayout")]
top: LayoutAnchorY::top(view),
#[cfg(feature = "autolayout")]
left: LayoutAnchorX::left(view),
#[cfg(feature = "autolayout")]
leading: LayoutAnchorX::leading(view),
#[cfg(feature = "autolayout")]
right: LayoutAnchorX::right(view),
#[cfg(feature = "autolayout")]
trailing: LayoutAnchorX::trailing(view),
#[cfg(feature = "autolayout")]
bottom: LayoutAnchorY::bottom(view),
#[cfg(feature = "autolayout")]
width: LayoutAnchorDimension::width(view),
#[cfg(feature = "autolayout")]
height: LayoutAnchorDimension::height(view),
#[cfg(feature = "autolayout")]
center_x: LayoutAnchorX::center(view),
#[cfg(feature = "autolayout")]
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
}
@ -332,7 +332,7 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
delegate: None,
objc: self.objc.clone(),
animator: self.animator.clone(),
#[cfg(feature = "autolayout")]
safe_layout_guide: self.safe_layout_guide.clone(),
@ -341,28 +341,28 @@ impl<T> ListViewRow<T> where T: ViewDelegate + 'static {
#[cfg(feature = "autolayout")]
leading: self.leading.clone(),
#[cfg(feature = "autolayout")]
left: self.left.clone(),
#[cfg(feature = "autolayout")]
trailing: self.trailing.clone(),
#[cfg(feature = "autolayout")]
right: self.right.clone(),
#[cfg(feature = "autolayout")]
bottom: self.bottom.clone(),
#[cfg(feature = "autolayout")]
width: self.width.clone(),
#[cfg(feature = "autolayout")]
height: self.height.clone(),
#[cfg(feature = "autolayout")]
center_x: self.center_x.clone(),
#[cfg(feature = "autolayout")]
center_y: self.center_y.clone(),
}
@ -387,31 +387,31 @@ impl<T> ListViewRow<T> {
#[cfg(feature = "autolayout")]
top: self.top.clone(),
#[cfg(feature = "autolayout")]
leading: self.leading.clone(),
#[cfg(feature = "autolayout")]
left: self.left.clone(),
#[cfg(feature = "autolayout")]
trailing: self.trailing.clone(),
#[cfg(feature = "autolayout")]
right: self.right.clone(),
#[cfg(feature = "autolayout")]
bottom: self.bottom.clone(),
#[cfg(feature = "autolayout")]
width: self.width.clone(),
#[cfg(feature = "autolayout")]
height: self.height.clone(),
#[cfg(feature = "autolayout")]
center_x: self.center_x.clone(),
#[cfg(feature = "autolayout")]
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.
pub fn set_background_color<C: AsRef<Color>>(&self, color: C) {
let color: id = color.as_ref().into();
self.objc.with_mut(|obj| unsafe {
(&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
/// work in here and return the menu as fast as possible.
fn context_menu(&self) -> Vec<MenuItem> { vec![] }
/// 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.
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.
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.
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.
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).
fn dragging_exited(&self, info: DragInfo) {}
}

View file

@ -1,6 +1,6 @@
//! 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
/// 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).
@ -35,14 +35,14 @@ impl URLRequest {
#[cfg(test)]
mod tests {
use objc::{class, msg_send, sel, sel_impl};
use crate::foundation::{id, NSString};
use crate::networking::URLRequest;
#[test]
fn test_urlrequest() {
let endpoint = "https://rymc.io/";
let url = unsafe {
let url = NSString::new(endpoint);
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