color/
color.rs

1#![allow(deprecated)] // the cocoa crate is deprecated
2use cocoa::base::{id, nil, selector, NO};
3
4use cocoa::appkit::{
5    NSApp, NSApplication, NSApplicationActivateIgnoringOtherApps,
6    NSApplicationActivationPolicyRegular, NSBackingStoreType, NSColor, NSColorSpace, NSMenu,
7    NSMenuItem, NSRunningApplication, NSWindow, NSWindowStyleMask,
8};
9use cocoa::foundation::{NSAutoreleasePool, NSPoint, NSProcessInfo, NSRect, NSSize, NSString};
10
11fn main() {
12    unsafe {
13        // Create the app.
14        let app = create_app();
15
16        // Create some colors
17        let clear = NSColor::clearColor(nil);
18        let black = NSColor::colorWithRed_green_blue_alpha_(nil, 0.0, 0.0, 0.0, 1.0);
19        let srgb_red = NSColor::colorWithSRGBRed_green_blue_alpha_(nil, 1.0, 0.0, 0.0, 1.0);
20        let device_green = NSColor::colorWithDeviceRed_green_blue_alpha_(nil, 0.0, 1.0, 0.0, 1.0);
21        let display_p3_blue =
22            NSColor::colorWithDisplayP3Red_green_blue_alpha_(nil, 0.0, 0.0, 1.0, 1.0);
23        let calibrated_cyan =
24            NSColor::colorWithCalibratedRed_green_blue_alpha_(nil, 0.0, 1.0, 1.0, 1.0);
25
26        // Create windows with different color types.
27        let _win_clear = create_window(NSString::alloc(nil).init_str("clear"), clear);
28        let _win_black = create_window(NSString::alloc(nil).init_str("black"), black);
29        let _win_srgb_red = create_window(NSString::alloc(nil).init_str("srgb_red"), srgb_red);
30        let _win_device_green =
31            create_window(NSString::alloc(nil).init_str("device_green"), device_green);
32        let _win_display_p3_blue = create_window(
33            NSString::alloc(nil).init_str("display_p3_blue"),
34            display_p3_blue,
35        );
36        let _win_calibrated_cyan = create_window(
37            NSString::alloc(nil).init_str("calibrated_cyan"),
38            calibrated_cyan,
39        );
40
41        // Extract component values from a color.
42        // NOTE: some components will raise an exception if the color is not
43        // in the correct NSColorSpace. Refer to Apple's documentation for details.
44        // https://developer.apple.com/documentation/appkit/nscolor?language=objc
45        let my_color = NSColor::colorWithRed_green_blue_alpha_(nil, 0.25, 0.75, 0.5, 0.25);
46        println!("alphaComponent: {:?}", my_color.alphaComponent());
47        println!("redComponent: {:?}", my_color.redComponent());
48        println!("greenComponent: {:?}", my_color.greenComponent());
49        println!("blueComponent: {:?}", my_color.blueComponent());
50        println!("hueComponent: {:?}", my_color.hueComponent());
51        println!("saturationComponent: {:?}", my_color.saturationComponent());
52        println!("brightnessComponent: {:?}", my_color.brightnessComponent());
53
54        // Changing color spaces.
55        let my_color_cmyk_cs =
56            my_color.colorUsingColorSpace_(NSColorSpace::deviceCMYKColorSpace(nil));
57        println!("blackComponent: {:?}", my_color_cmyk_cs.blackComponent());
58        println!("cyanComponent: {:?}", my_color_cmyk_cs.cyanComponent());
59        println!(
60            "magentaComponent: {:?}",
61            my_color_cmyk_cs.magentaComponent()
62        );
63        println!("yellowComponent: {:?}", my_color_cmyk_cs.yellowComponent());
64
65        // Getting NSColorSpace name.
66        let cs = NSColorSpace::genericGamma22GrayColorSpace(nil);
67        let cs_name = cs.localizedName();
68        let cs_name_bytes = cs_name.UTF8String() as *const u8;
69        let cs_name_string =
70            std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap();
71        println!("NSColorSpace: {:?}", cs_name_string);
72
73        // Creating an NSColorSpace from CGColorSpaceRef.
74        let cg_cs = cs.CGColorSpace();
75        let cs = NSColorSpace::alloc(nil).initWithCGColorSpace_(cg_cs);
76        let cs_name = cs.localizedName();
77        let cs_name_bytes = cs_name.UTF8String() as *const u8;
78        let cs_name_string =
79            std::str::from_utf8(std::slice::from_raw_parts(cs_name_bytes, cs_name.len())).unwrap();
80        println!("initWithCGColorSpace_: {:?}", cs_name_string);
81
82        app.run();
83    }
84}
85
86unsafe fn create_window(title: id, color: id) -> id {
87    let window = NSWindow::alloc(nil)
88        .initWithContentRect_styleMask_backing_defer_(
89            NSRect::new(NSPoint::new(0., 0.), NSSize::new(200., 200.)),
90            NSWindowStyleMask::NSTitledWindowMask
91                | NSWindowStyleMask::NSClosableWindowMask
92                | NSWindowStyleMask::NSResizableWindowMask
93                | NSWindowStyleMask::NSMiniaturizableWindowMask
94                | NSWindowStyleMask::NSUnifiedTitleAndToolbarWindowMask,
95            NSBackingStoreType::NSBackingStoreBuffered,
96            NO,
97        )
98        .autorelease();
99
100    window.cascadeTopLeftFromPoint_(NSPoint::new(20., 20.));
101    window.setTitle_(title);
102    window.setBackgroundColor_(color);
103    window.makeKeyAndOrderFront_(nil);
104    window
105}
106
107unsafe fn create_app() -> id {
108    let _pool = NSAutoreleasePool::new(nil);
109
110    let app = NSApp();
111    app.setActivationPolicy_(NSApplicationActivationPolicyRegular);
112
113    // create Menu Bar
114    let menubar = NSMenu::new(nil).autorelease();
115    let app_menu_item = NSMenuItem::new(nil).autorelease();
116    menubar.addItem_(app_menu_item);
117    app.setMainMenu_(menubar);
118
119    // create Application menu
120    let app_menu = NSMenu::new(nil).autorelease();
121    let quit_prefix = NSString::alloc(nil).init_str("Quit ");
122    let quit_title =
123        quit_prefix.stringByAppendingString_(NSProcessInfo::processInfo(nil).processName());
124    let quit_action = selector("terminate:");
125    let quit_key = NSString::alloc(nil).init_str("q");
126    let quit_item = NSMenuItem::alloc(nil)
127        .initWithTitle_action_keyEquivalent_(quit_title, quit_action, quit_key)
128        .autorelease();
129    app_menu.addItem_(quit_item);
130    app_menu_item.setSubmenu_(app_menu);
131
132    let current_app = NSRunningApplication::currentApplication(nil);
133    current_app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps);
134
135    app
136}