cocoanut 0.2.3

A minimal, declarative macOS GUI framework for Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
//! Native Cocoa integration utilities
//!
//! This module provides enhanced access to native NSView properties,
//! responder chain management, and other Cocoa-specific features.

use objc::runtime::Object;

/// Responder chain management
pub mod responder {
    use super::Object;
    #[cfg(not(test))]
    use objc::{msg_send, sel, sel_impl};

    /// Make a view the first responder
    ///
    /// # Safety
    /// The `window` and `view` pointers must be valid NSWindow and NSView objects.
    #[cfg(not(test))]
    pub unsafe fn make_first_responder(window: *mut Object, view: *mut Object) -> bool {
        let success: bool = msg_send![window, makeFirstResponder: view];
        success
    }

    /// Get the current first responder
    ///
    /// # Safety
    /// The `window` pointer must be a valid NSWindow object.
    #[cfg(not(test))]
    pub unsafe fn first_responder(window: *mut Object) -> *mut Object {
        msg_send![window, firstResponder]
    }

    /// Check if view accepts first responder
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn accepts_first_responder(view: *mut Object) -> bool {
        msg_send![view, acceptsFirstResponder]
    }

    /// Resign first responder status
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn resign_first_responder(view: *mut Object) -> bool {
        msg_send![view, resignFirstResponder]
    }

    #[cfg(test)]
    pub unsafe fn make_first_responder(_window: *mut Object, _view: *mut Object) -> bool {
        true
    }

    #[cfg(test)]
    pub unsafe fn first_responder(_window: *mut Object) -> *mut Object {
        std::ptr::null_mut()
    }

    #[cfg(test)]
    pub unsafe fn accepts_first_responder(_view: *mut Object) -> bool {
        true
    }

    #[cfg(test)]
    pub unsafe fn resign_first_responder(_view: *mut Object) -> bool {
        true
    }
}

/// Native view property access and manipulation
pub mod view_properties {
    use super::Object;
    #[cfg(not(test))]
    use objc::{msg_send, sel, sel_impl};

    /// Set view alpha (opacity)
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn set_alpha(view: *mut Object, alpha: f64) {
        let _: () = msg_send![view, setAlphaValue: alpha];
    }

    /// Get view alpha (opacity)
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn alpha(view: *mut Object) -> f64 {
        msg_send![view, alphaValue]
    }

    /// Set view hidden state
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn set_hidden(view: *mut Object, hidden: bool) {
        let _: () = msg_send![view, setHidden: hidden];
    }

    /// Get view hidden state
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn is_hidden(view: *mut Object) -> bool {
        msg_send![view, isHidden]
    }

    /// Set view frame
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn set_frame(view: *mut Object, x: f64, y: f64, width: f64, height: f64) {
        let frame = cocoa::foundation::NSRect {
            origin: cocoa::foundation::NSPoint { x, y },
            size: cocoa::foundation::NSSize { width, height },
        };
        let _: () = msg_send![view, setFrame: frame];
    }

    /// Get view frame
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn frame(view: *mut Object) -> (f64, f64, f64, f64) {
        let frame: cocoa::foundation::NSRect = msg_send![view, frame];
        (
            frame.origin.x,
            frame.origin.y,
            frame.size.width,
            frame.size.height,
        )
    }

    /// Get view bounds
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn bounds(view: *mut Object) -> (f64, f64, f64, f64) {
        let bounds: cocoa::foundation::NSRect = msg_send![view, bounds];
        (
            bounds.origin.x,
            bounds.origin.y,
            bounds.size.width,
            bounds.size.height,
        )
    }

    /// Set corner radius (via layer)
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn set_corner_radius(view: *mut Object, radius: f64) {
        let _: () = msg_send![view, setWantsLayer: true];
        let layer: *mut Object = msg_send![view, layer];
        if !layer.is_null() {
            let _: () = msg_send![layer, setCornerRadius: radius];
        }
    }

    /// Set background color
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn set_background_color(view: *mut Object, r: f64, g: f64, b: f64, a: f64) {
        let _: () = msg_send![view, setWantsLayer: true];
        let layer: *mut Object = msg_send![view, layer];
        if !layer.is_null() {
            let color_space = objc::class!(NSColorSpace);
            let srgb: *mut Object = msg_send![color_space, sRGBColorSpace];
            let color_class = objc::class!(NSColor);
            let color: *mut Object = msg_send![
                color_class,
                colorWithColorSpace: srgb
                components: [r, g, b, a].as_ptr()
                count: 4_u64
            ];
            let cg_color: *mut Object = msg_send![color, CGColor];
            let _: () = msg_send![layer, setBackgroundColor: cg_color];
        }
    }

    /// Set border
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn set_border(view: *mut Object, width: f64, r: f64, g: f64, b: f64, a: f64) {
        let _: () = msg_send![view, setWantsLayer: true];
        let layer: *mut Object = msg_send![view, layer];
        if !layer.is_null() {
            let _: () = msg_send![layer, setBorderWidth: width];
            let color_space = objc::class!(NSColorSpace);
            let srgb: *mut Object = msg_send![color_space, sRGBColorSpace];
            let color_class = objc::class!(NSColor);
            let color: *mut Object = msg_send![
                color_class,
                colorWithColorSpace: srgb
                components: [r, g, b, a].as_ptr()
                count: 4_u64
            ];
            let cg_color: *mut Object = msg_send![color, CGColor];
            let _: () = msg_send![layer, setBorderColor: cg_color];
        }
    }

    /// Set shadow
    ///
    /// # Safety
    /// The `view` pointer must be a valid NSView object.
    #[cfg(not(test))]
    pub unsafe fn set_shadow(
        view: *mut Object,
        radius: f64,
        opacity: f32,
        offset_x: f64,
        offset_y: f64,
    ) {
        let _: () = msg_send![view, setWantsLayer: true];
        let layer: *mut Object = msg_send![view, layer];
        if !layer.is_null() {
            let _: () = msg_send![layer, setShadowRadius: radius];
            let _: () = msg_send![layer, setShadowOpacity: opacity];
            let size = cocoa::foundation::NSSize {
                width: offset_x,
                height: offset_y,
            };
            let _: () = msg_send![layer, setShadowOffset: size];
        }
    }

    // Test mock implementations
    #[cfg(test)]
    pub unsafe fn set_alpha(_view: *mut Object, _alpha: f64) {}
    #[cfg(test)]
    pub unsafe fn alpha(_view: *mut Object) -> f64 {
        1.0
    }
    #[cfg(test)]
    pub unsafe fn set_hidden(_view: *mut Object, _hidden: bool) {}
    #[cfg(test)]
    pub unsafe fn is_hidden(_view: *mut Object) -> bool {
        false
    }
    #[cfg(test)]
    pub unsafe fn set_frame(_view: *mut Object, _x: f64, _y: f64, _width: f64, _height: f64) {}
    #[cfg(test)]
    pub unsafe fn frame(_view: *mut Object) -> (f64, f64, f64, f64) {
        (0.0, 0.0, 0.0, 0.0)
    }
    #[cfg(test)]
    pub unsafe fn bounds(_view: *mut Object) -> (f64, f64, f64, f64) {
        (0.0, 0.0, 0.0, 0.0)
    }
    #[cfg(test)]
    pub unsafe fn set_corner_radius(_view: *mut Object, _radius: f64) {}
    #[cfg(test)]
    pub unsafe fn set_background_color(_view: *mut Object, _r: f64, _g: f64, _b: f64, _a: f64) {}
    #[cfg(test)]
    pub unsafe fn set_border(_view: *mut Object, _width: f64, _r: f64, _g: f64, _b: f64, _a: f64) {}
    #[cfg(test)]
    pub unsafe fn set_shadow(_view: *mut Object, _radius: f64, _opacity: f32, _x: f64, _y: f64) {}
}

/// Window management utilities
pub mod window {
    use super::Object;
    #[cfg(not(test))]
    use objc::{msg_send, sel, sel_impl};

    /// Set window level
    ///
    /// # Safety
    /// The `window` pointer must be a valid NSWindow object.
    #[cfg(not(test))]
    pub unsafe fn set_level(window: *mut Object, level: i64) {
        let _: () = msg_send![window, setLevel: level];
    }

    /// Window levels
    pub const NORMAL_LEVEL: i64 = 0;
    pub const FLOATING_LEVEL: i64 = 3;
    pub const MODAL_PANEL_LEVEL: i64 = 8;
    pub const MAIN_MENU_LEVEL: i64 = 24;

    /// Make window key and order front
    ///
    /// # Safety
    /// The `window` pointer must be a valid NSWindow object.
    #[cfg(not(test))]
    pub unsafe fn make_key_and_order_front(window: *mut Object) {
        let _: () = msg_send![window, makeKeyAndOrderFront: std::ptr::null_mut::<Object>()];
    }

    /// Set window alpha value
    ///
    /// # Safety
    /// The `window` pointer must be a valid NSWindow object.
    #[cfg(not(test))]
    pub unsafe fn set_alpha(window: *mut Object, alpha: f64) {
        let _: () = msg_send![window, setAlphaValue: alpha];
    }

    /// Set window background color
    ///
    /// # Safety
    /// The `window` pointer must be a valid NSWindow object.
    #[cfg(not(test))]
    pub unsafe fn set_background_color(window: *mut Object, r: f64, g: f64, b: f64, a: f64) {
        let color_space = objc::class!(NSColorSpace);
        let srgb: *mut Object = msg_send![color_space, sRGBColorSpace];
        let color_class = objc::class!(NSColor);
        let color: *mut Object = msg_send![
            color_class,
            colorWithColorSpace: srgb
            components: [r, g, b, a].as_ptr()
            count: 4_u64
        ];
        let _: () = msg_send![window, setBackgroundColor: color];
    }

    #[cfg(test)]
    pub unsafe fn set_level(_window: *mut Object, _level: i64) {}
    #[cfg(test)]
    pub unsafe fn make_key_and_order_front(_window: *mut Object) {}
    #[cfg(test)]
    pub unsafe fn set_alpha(_window: *mut Object, _alpha: f64) {}
    #[cfg(test)]
    pub unsafe fn set_background_color(_window: *mut Object, _r: f64, _g: f64, _b: f64, _a: f64) {}
}

/// Animation support
pub mod animation {
    #[cfg(not(test))]
    use super::Object;
    #[cfg(not(test))]
    use objc::{msg_send, sel, sel_impl};

    /// Begin animation context
    #[cfg(not(test))]
    pub fn begin_animation(duration: f64) {
        unsafe {
            let context_class = objc::class!(NSAnimationContext);
            let _: () = msg_send![context_class, beginGrouping];
            let context: *mut Object = msg_send![context_class, currentContext];
            let _: () = msg_send![context, setDuration: duration];
        }
    }

    /// End animation context
    #[cfg(not(test))]
    pub fn end_animation() {
        unsafe {
            let context_class = objc::class!(NSAnimationContext);
            let _: () = msg_send![context_class, endGrouping];
        }
    }

    /// Run animation block
    #[cfg(not(test))]
    pub fn animate<F>(duration: f64, animations: F)
    where
        F: FnOnce(),
    {
        begin_animation(duration);
        animations();
        end_animation();
    }

    #[cfg(test)]
    pub fn begin_animation(_duration: f64) {}
    #[cfg(test)]
    pub fn end_animation() {}
    #[cfg(test)]
    pub fn animate<F>(_duration: f64, animations: F)
    where
        F: FnOnce(),
    {
        animations();
    }
}

/// Pasteboard (clipboard) operations
pub mod pasteboard {
    use crate::error::Result;
    #[cfg(not(test))]
    use super::Object;
    #[cfg(not(test))]
    use objc::{msg_send, sel, sel_impl};

    /// Copy text to clipboard
    #[cfg(not(test))]
    pub fn copy_text(text: &str) -> Result<()> {
        unsafe {
            let pb_class = objc::class!(NSPasteboard);
            let pb: *mut Object = msg_send![pb_class, generalPasteboard];
            let _: () = msg_send![pb, clearContents];

            let cstr = std::ffi::CString::new(text)?;
            let ns_str: *mut Object = msg_send![
                objc::class!(NSString),
                stringWithUTF8String: cstr.as_ptr()
            ];

            let array_class = objc::class!(NSArray);
            let array: *mut Object = msg_send![array_class, arrayWithObject: ns_str];
            let _: bool = msg_send![pb, writeObjects: array];
        }
        Ok(())
    }

    /// Get text from clipboard
    #[cfg(not(test))]
    pub fn get_text() -> Result<String> {
        unsafe {
            let pb_class = objc::class!(NSPasteboard);
            let pb: *mut Object = msg_send![pb_class, generalPasteboard];
            let ns_str: *mut Object =
                msg_send![pb, stringForType: objc::class!(NSPasteboardTypeString)];

            if ns_str.is_null() {
                return Ok(String::new());
            }

            let cstr: *const i8 = msg_send![ns_str, UTF8String];
            let rust_str = std::ffi::CStr::from_ptr(cstr)
                .to_string_lossy()
                .into_owned();
            Ok(rust_str)
        }
    }

    #[cfg(test)]
    pub fn copy_text(_text: &str) -> Result<()> {
        Ok(())
    }

    #[cfg(test)]
    pub fn get_text() -> Result<String> {
        Ok(String::new())
    }
}

#[cfg(test)]
mod mock_tests {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    use super::Object;
    use super::{animation, pasteboard, responder, view_properties, window};

    #[test]
    fn pasteboard_mock_copy_and_get() {
        assert!(pasteboard::copy_text("clip").is_ok());
        assert_eq!(pasteboard::get_text().unwrap(), "");
    }

    #[test]
    fn animation_mock_invokes_closure() {
        let n = Arc::new(AtomicUsize::new(0));
        let c = n.clone();
        animation::animate(0.0, move || {
            c.fetch_add(1, Ordering::SeqCst);
        });
        assert_eq!(n.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn view_responder_window_stubs_accept_null() {
        let p: *mut Object = std::ptr::null_mut();
        unsafe {
            view_properties::set_alpha(p, 0.5);
            assert_eq!(view_properties::alpha(p), 1.0);
            window::set_level(p, window::NORMAL_LEVEL);
            assert!(responder::make_first_responder(p, p));
            assert!(responder::accepts_first_responder(p));
            assert!(responder::resign_first_responder(p));
        }
    }
}