Rust bindings to Core Foundation and other low level libraries on Mac OS X and iOS

Overview

core-foundation-rs

Build Status

Compatibility

Targets macOS 10.7 by default.

To enable features added in macOS 10.8, set Cargo feature mac_os_10_8_features. To have both 10.8 features and 10.7 compatibility, also set mac_os_10_7_support. Setting both requires weak linkage, which is a nightly-only feature as of Rust 1.19.

For more experimental but more complete, generated bindings take a look at https://github.com/michaelwu/RustKit.

Comments
  • Reference type as associated value instead of generic

    Reference type as associated value instead of generic

    Each CFFoo has exactly one CFFooRef and which one is defined by CFFoo, not by its user. Thus the type of reference can be an associated type instead of a generic.

    As you can see this greatly simplifies things such as calling instance_of and from_CFType_pairs as well as using CFPropertyListSubClass. It basically removes one generic parameter from any method dealing with TCFTypes in some way.

    This is a breaking change, so it would probably mean a 0.5.0 release if accepted. I don't know what your stance on breaking changes or version bumps is, so I don't know if you want this or not. But it would simplify the API, both here, but first and foremost in higher level crates using this.


    This change is Reviewable

    opened by faern 40
  • Rewrite all the bindings in a better way

    Rewrite all the bindings in a better way

    All the FFI functions have fancy types now and use references instead of raw pointers for arguments.

    Now, a CFRef<T> value represents a refcounted value to be released on Drop, CFShared<T> represents a shared value that can be retained to produce a new CFRef<T> (this will be a useful distinction for mutable types, where a bare T shouldn't be retainable to keep unique ownership).

    To simplify things and avoid either having wrappers of wrappers of all methods behind traits, I put the safe and thin methods directly on the opaque FFI types.

    Let's begin the infinite bikeshedding!


    This change is Reviewable

    opened by nox 35
  • Add consuming cheap cast

    Add consuming cheap cast

    There are a lot of places where we increment and decrement the retain count when we would not have to. For example, a very common use-case with PropertyLists is to just directly cast them to their correct sub type and then throw the PropertyList away (because there is nothing you can do with the PropertyList instance directly.)

    The reason we do this, I guess, is mostly because all Drop implementations force a retain count decrement. So we have to keep incrementing it to keep it correct. But if we add a flag to types that can be used to disable the decrement, then we can also get rid of the increment when we virtually just want to cast a pointer between two types.

    This PR implements this by adding a boolean flag to all CF structs that is used by the Drop impl to determine if it should CFRelease the instance or not. Then this flag is modified in appropriate places where we cast to other types and consume ourselves.

    I added some benchmarks locally. I did not want to commit them since benchmarking only works on nighty, and I did not feel like adding a feature flag for it etc. Anyhow, the following benchmarks:

    #[bench]
    fn bench_before(b: &mut Bencher) {
       let string = CFString::from_static_string("Bar");
        b.iter(|| unsafe {
            string.clone()
                .to_CFPropertyList()
                .downcast::<_, CFString>()
                .unwrap()
                .disable_release();
        })
    }
    
    #[bench]
    fn bench_after(b: &mut Bencher) {
        let string = CFString::from_static_string("Bar");
        b.iter(|| unsafe {
            string.clone()
                .into_CFPropertyList()
                .downcast_into::<_, CFString>()
                .unwrap()
                .disable_release();
        })
    }
    

    Given the following results:

    test propertylist::test::bench_after         ... bench:          16 ns/iter (+/- 3)
    test propertylist::test::bench_before        ... bench:          73 ns/iter (+/- 14)
    

    The final call to disable_release() in the benchmarks are to prevent the type coming out of the unwrap() from calling CFRelease on drop, and thus avoid measuring that. I want to try to measure only {to,into}_CFPropertyList, downcast and downcast_into. The clone is needed because the into version requires it and it would then not be fair to not have it on both.

    I would say that speeding it up by a factor of ~4 can be well worth it? (Well, that 4 is of course no good measurement of anything, microbenchmarks etc. etc.. The benchmark mostly shows that a lot can be gained from avoiding some retain counting.)


    This change is Reviewable

    opened by faern 18
  • Add CFMutableDictionary type.

    Add CFMutableDictionary type.

    Added CFMutableDictionary that presents the mutable dictionary functions of CF. Tries to present a similar interface as CFDictionary.

    Fixes issue #93.


    This change is Reviewable

    opened by djg 17
  • Fix timing sensitive test

    Fix timing sensitive test

    This problem was found when I tried to debug #132

    But since that PR grew so large, and this fix was very unrelated to the work in that PR I split it out to a separate one.


    This change is Reviewable

    opened by faern 15
  • BUG: Add test showing how downcasting to CFArray is unsound

    BUG: Add test showing how downcasting to CFArray is unsound

    This PR is not intended to me merged directly. It adds a test that causes undefined behavior without using unsafe {}. So it's more to show the problem and discuss a solution.

    The problem here is that if you have a CFArray<X> you can cast it up to a CFType and then down to a CFArray<Y> for any Y: TCFType. It never checks that the elements in the array are of type Y or not. At this point CFArray::iter will happily give out &Y references, while in fact the pointers backing those objects are pointing to XRef instances. So doing anything with the &Y will likely cause invalid memory access.

    How do we solve this?

    Ping @jrmuizel


    This change is Reviewable

    opened by faern 13
  • Use libc c_char instead of i8 for libc strlen() call

    Use libc c_char instead of i8 for libc strlen() call

    This patch allows build errors like https://buildd.debian.org/status/fetch.php?pkg=rust-core-foundation&arch=arm64&ver=0.6.1-1&stamp=1533301991&raw=0 to go through on architectures that use u8 as c_char.


    This change is Reviewable

    opened by silwol 12
  • Add CFSetApplyFunction and CFSetGetCount

    Add CFSetApplyFunction and CFSetGetCount

    I'm needing these CFSet functions for some USB HID interactions with IOKit, so here's the external references.

    They are defined in CoreFoundation:


    This change is Reviewable

    opened by jcjones 12
  • CFString refactor / cleanup

    CFString refactor / cleanup

    This pull request:

    • removes two unnecessary casts (from CFIndex to usize and back again)
    • extracts the to rust string conversion: instead of doing it on-the-fly in the Display implementation (and thus only supporting the indirect ToString way to get a rust string from a CFString, which always allocates) this implements From<&CFString> for Cow<str> allowing everyone the possibility of avoiding an allocation if the CFString is already formatted in UTF-8.

    Review on Reviewable

    opened by TimNN 12
  • Add basic contfibution guidelines to README

    Add basic contfibution guidelines to README

    In #453, @pmj proposed bare-bones contribution guidelines, which were received favorably by @jrmuizel. This pull request insert's @pmj's proposed text into the top-level README.

    opened by rectang 11
  • Fixes so the compiler can infer msg_send! return types

    Fixes so the compiler can infer msg_send! return types

    Currently, due to a quirk in Rust's type inference interacting with the structure of the msg_send! macro, a () return type will be inferred when the compiler cannot otherwise determine the return type. This behavior is expected to change, and in the future could resolve to a ! return type, which results in undefined behavior.

    Linting has previously been added for this in rust-lang/rust#39216, but it did not catch these cases due to SSheldon/rust-objc#62. An upcoming version of objc will be fixed to stop hiding these errors, at which point they will become compile errors.

    This change fixes these errors and allows cocoa to compile with the fixed version of objc.

    opened by SSheldon 11
  • Question about how to list all running window app names [Code Review/Question]

    Question about how to list all running window app names [Code Review/Question]

    I'm working with Rust and Core Foundations and I'd like to know if the code looks right or if it has some flaws or if I can make it simpler

    use core_foundation::base::{FromVoid, TCFType, TCFTypeRef, ToVoid};
    use core_foundation::dictionary::{CFDictionary, CFDictionaryRef};
    use core_foundation::string::CFString;
    use core_graphics::window::{copy_window_info, kCGNullWindowID, kCGWindowListOptionAll};
    fn main() {
        let windows_info = copy_window_info(kCGWindowListOptionAll, kCGNullWindowID).unwrap();
        for window_info in windows_info.get_all_values() {
            let key = CFString::from_static_string("kCGWindowName");
    
            let winfo_hash: CFDictionary =
                unsafe { TCFType::wrap_under_get_rule(window_info as CFDictionaryRef) };
    
            let window_name = winfo_hash.get(ToVoid::to_void(&key));
    
            let window_name: String =
                unsafe { CFString::from_void(window_name.as_void_ptr()).to_string() };
    
            println!("{:?}", window_name);
        }
    }
    

    Is that right? or do we have a "simpler" way of doing that? My goal is to take a screenshot of the window app if t matches some criteria

    Thanks in advance.

    opened by wsantos 1
  • GitHub Workflows security hardening

    GitHub Workflows security hardening

    This PR adds explicit permissions section to workflows. This is a security best practice because by default workflows run with extended set of permissions (except from on: pull_request from external forks). By specifying any permission explicitly all others are set to none. By using the principle of least privilege the damage a compromised workflow can do (because of an injection or compromised third party tool or action) is restricted. It is recommended to have most strict permissions on the top level and grant write permissions on job level case by case.

    opened by sashashura 2
  • Rust wrapper for NSAlert class

    Rust wrapper for NSAlert class

    https://developer.apple.com/documentation/appkit/nsalert?language=objc

    This is for modal dialogs. Would be convenient to have rust wrappers for setMessageText, showsSuppressionButton, etc. and for reading the result.

    opened by acarl005 0
  • core-graphics requires core-foundation 0.9.3 for mach_port

    core-graphics requires core-foundation 0.9.3 for mach_port

    Just hit this build error when I added wry to my app:

    error[E0432]: unresolved import `core_foundation::mach_port`
     --> /Users/adamfreeman/.cargo/registry/src/github.com-1ecc6299db9ec823/core-graphics-0.22.3/src/event.rs:4:5
      |
    4 |     mach_port::{CFMachPort, CFMachPortRef},
      |     ^^^^^^^^^ could not find `mach_port` in `core_foundation`
    
    error[E0433]: failed to resolve: could not find `mach_port` in `core_foundation`
      --> /Users/adamfreeman/.cargo/registry/src/github.com-1ecc6299db9ec823/core-graphics-0.22.3/src/sys.rs:32:44
       |
    32 |     pub type CGEventTapRef = core_foundation::mach_port::CFMachPortRef;
       |                                               ^^^^^^^^^ could not find `mach_port` in `core_foundation`
    

    trivial MR to fix this one, just update the dependency to 0.9.2 or 0.9.3, but there's probably more like this, and it may be worth adding something like https://crates.io/crates/cargo-minimal-versions to the CI to catch these in the future.

    opened by simonbuchan 1
  • Update cocoa Cargo.toml

    Update cocoa Cargo.toml

    Hello, since this commit cocoa-foundation went to 0.1.1, but its version hasn't been updated in cocoa Cargo.toml yet.

    @jrmuizel could you please check and release a new version if ok? Thanks.

    opened by n-eq 0
  • Trim dependencies

    Trim dependencies

    Of particular note:

    • libc is not needed in most cases, one can simply use std::os::raw
    • leaky-cow seems like it existed to work around compiler limitations, these are no more

    @jrmuizel I've included version bumps in here as well, would be nice if you could also do a new release after this

    opened by madsmtm 3
Owner
Servo
The Servo web browser engine
Servo
Provides Rust bindings for Gnome libraries

gtk-rs-core The gtk-rs organization aims to provide safe Rust binding over GObject-based libraries. You can find more about it on https://gtk-rs.org.

null 174 Dec 26, 2022
Provides Rust bindings for GTK libraries

gtk3-rs The gtk-rs organization aims to provide safe Rust binding over GObject-based libraries. You can find more about it on https://gtk-rs.org. This

null 431 Dec 30, 2022
An Anime Game Launcher variant written on Rust, GTK4 and libadwaita, using Anime Game Core library

An Anime Game Launcher GTK The launcher variant written on Rust, GTK4 and libadwaita, using Anime Game Core library You could also try the main branch

An Anime Team 77 Jan 9, 2023
Honkers Launcher variant written on Rust, GTK4 and libadwaita, using Anime Game Core library

You could also try the main branch Development Folder Description ui Blueprint UI files ui/.dist UI files compiled by the blueprint src Rust source co

An Anime Team 9 Nov 2, 2022
Test bed for gtk-rs-core experiments

Rust GObject Experiments class macro #[gobject::class(final)] mod obj { #[derive(Default)] pub struct MyObj { #[property(get, set)]

Jason Francis 2 May 28, 2022
Provides core language-agnostic functionality for LiveView Native across platforms

LiveView Native Core This repository contains an implementation of the LiveView Native core library, which is intended to handle all the details which

LiveView Native 35 Dec 27, 2022
autogen website (with Deno Core)

Kurit Static website generator ?? Warning WIP: It is still under development, so some of the features may not be developed. Project Structures graph T

null 11 Oct 16, 2023
Use C++ libraries from Rust

ritual ritual allows to use C++ libraries from Rust. It analyzes the C++ API of a library and generates a fully-featured crate that provides convenien

Rust-Qt 1.1k Jan 5, 2023
Rust bindings and wrappers for GLib, GDK 3, GTK+ 3 and Cairo.

THIS REPOSITORY IS DEPRECATED SEE: https://github.com/rust-gnome rgtk Rust bindings and wrappers for GLib, GDK 3, GTK+ 3 and Cairo. Building rgtk expe

Jeremy Letang 124 Jul 10, 2022
Rust bindings for the FLTK GUI library.

fltk-rs Rust bindings for the FLTK Graphical User Interface library. The FLTK crate is a crossplatform lightweight gui library which can be statically

Mohammed Alyousef 1.1k Jan 9, 2023
Rust bindings for Dear ImGui

imgui-rs: Rust bindings for Dear ImGui (Recently under new maintenance, things subject to change) Window::new(im_str!("Hello world")) .size([300.0

null 2k Jan 7, 2023
Rust bindings to the minimalist, native, cross-platform UI toolkit `libui`

Improved User Interface A cross-platform UI toolkit for Rust based on libui iui: ui-sys: iui is a simple (about 4 kLOC of Rust), small (about 800kb, i

Rust Native UI Group 865 Dec 27, 2022
QML (Qt Quick) bindings for Rust language

QML-rust - bindings for Qt Quick Bindings are based on DOtherSide C bindings for QML Library is mostly feature-compliant with other bindings based on

Oak 204 Dec 8, 2022
Rust bindings for Sciter

Rust bindings for Sciter Check this page for other language bindings (Delphi / D / Go / .NET / Python / Rust). Introduction Sciter is an embeddable mu

Terra Informatica Software, Inc 757 Dec 30, 2022
Drew's fast Rust AppKit bindings

Drew's fast Rust AppKit bindings Provides select Rust bindings for Apple AppKit framework. This may be compared to, appkit crate cacao objrs_framework

Drew Crawford 2 Oct 28, 2022
Rust bindings for Dear ImGui

imgui-rs: Rust bindings for Dear ImGui (Recently under new maintenance, things subject to change) ui.window("Hello world") .size([300.0, 100.0], C

null 2k Jan 7, 2023
Rust bindings for the FLTK GUI library.

fltk-rs Rust bindings for the FLTK Graphical User Interface library. The fltk crate is a cross-platform lightweight gui library which can be staticall

fltk-rs 1.1k Jan 9, 2023
Unsafe bindings and a safe wrapper for gtk4-layer-shell, automatically generated from a .gir file

gtk4-layer-shell: gtk4-layer-shell-sys: gtk4-layer-shell This is the safe wrapper for gtk4-layer-shell, automatically generated from its .gir file. Fo

null 3 Apr 30, 2023
The bindings to the Nuklear 2D immediate GUI library.

nuklear-rust The bindings to the Nuklear 2D immediate GUI library. Currently beta. Drawing backends: gfx-pre-ll for GFX 3D drawing engine (examples: O

Serhii Plyhun 332 Dec 27, 2022