cocoanut 0.2.2

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
# Native Cocoa Integration Improvements

## Overview

This document describes the comprehensive improvements made to enhance Cocoanut's native Cocoa integration capabilities. These improvements provide better access to native AppKit features while maintaining the framework's simple, declarative API.

## Table of Contents

1. [Auto Layout Support]#auto-layout-support
2. [Native View Properties]#native-view-properties
3. [Responder Chain Management]#responder-chain-management
4. [Delegate Patterns]#delegate-patterns
5. [Additional Native Controls]#additional-native-controls
6. [Advanced Features]#advanced-features

---

## Auto Layout Support

### Overview

The new `layout` module provides type-safe wrappers around NSLayoutConstraint for building constraint-based layouts instead of frame-based layouts.

### Features

- **Layout Attributes**: All NSLayoutAttribute types (Leading, Trailing, Width, Height, CenterX, CenterY, etc.)
- **Layout Relations**: Equal, LessThanOrEqual, GreaterThanOrEqual
- **Layout Priorities**: Required, High, Medium, Low
- **Constraint Descriptors**: Chainable API for building constraints

### Usage Example

```rust
use cocoanut::prelude::*;

// Create a view with Auto Layout constraints
let view = View::button("Click Me")
    .uses_auto_layout(true)
    .constraint(
        ConstraintDescriptor::new(LayoutAttribute::Width)
            .constant(200.0)
    )
    .constraint(
        ConstraintDescriptor::new(LayoutAttribute::CenterX)
            .equal_to(LayoutAttribute::CenterX)
    );

// Or use helper functions
let view = View::button("Click Me")
    .constraints(constraints::center_in_superview())
    .constraint(constraints::width(200.0));
```

### Available Constraint Helpers

- `constraints::fill_superview()`: Pin to all edges
- `constraints::center_in_superview()`: Center horizontally and vertically
- `constraints::width(w)`: Set fixed width
- `constraints::height(h)`: Set fixed height
- `constraints::aspect_ratio(ratio)`: Set aspect ratio

---

## Native View Properties

### Overview

The new `native` module provides direct access to native NSView properties and behaviors.

### View Properties

#### Basic Properties

```rust
use cocoanut::native::view_properties;

// Alpha (opacity)
view_properties::set_alpha(view, 0.8);
let alpha = view_properties::alpha(view);

// Hidden state
view_properties::set_hidden(view, true);
let hidden = view_properties::is_hidden(view);

// Frame and bounds
view_properties::set_frame(view, 0.0, 0.0, 100.0, 100.0);
let (x, y, width, height) = view_properties::frame(view);
```

#### Advanced Styling

```rust
// Corner radius
view_properties::set_corner_radius(view, 10.0);

// Background color (RGBA)
view_properties::set_background_color(view, 1.0, 0.0, 0.0, 1.0);

// Border
view_properties::set_border(view, 2.0, 0.0, 0.0, 1.0, 1.0); // width, r, g, b, a

// Shadow
view_properties::set_shadow(view, 5.0, 0.5, 2.0, 2.0); // radius, opacity, offset_x, offset_y
```

#### Declarative API

All these properties can also be set declaratively on views:

```rust
View::button("Click Me")
    .shadow(5.0, 0.5, 2.0, 2.0)
    .corner_radius(12.0)
    .opacity(0.9)
    .wants_layer(true)
    .clips_to_bounds(true)
```

---

## Responder Chain Management

### Overview

The `native::responder` module provides access to NSResponder chain functionality.

### Features

```rust
use cocoanut::native::responder;

// Make a view the first responder
responder::make_first_responder(window, view);

// Get current first responder
let first = responder::first_responder(window);

// Check if view accepts first responder
let accepts = responder::accepts_first_responder(view);

// Resign first responder status
responder::resign_first_responder(view);
```

### Declarative API

```rust
View::text_field("Type here")
    .accepts_first_responder(true)
    .can_become_key_view(true)
```

---

## Delegate Patterns

### Overview

The new `delegate` module provides delegate pattern support for native controls that require data sources or delegates.

### Table Data Source

```rust
use cocoanut::prelude::*;
use std::sync::Arc;

// Create a data source
let data_source = Arc::new(VectorTableDataSource {
    columns: vec!["Name".to_string(), "Age".to_string()],
    rows: vec![
        vec!["Alice".to_string(), "30".to_string()],
        vec!["Bob".to_string(), "25".to_string()],
    ],
});

// Register the data source
register_table_data_source(1, data_source);

// Use in a table view
let table = View::table_view(
    vec!["Name", "Age"],
    vec![
        vec!["Alice".to_string(), "30".to_string()],
        vec!["Bob".to_string(), "25".to_string()],
    ]
);
```

### Text Field Delegate

```rust
use cocoanut::prelude::*;

// Custom delegate implementation
struct MyTextFieldDelegate;

impl TextFieldDelegate for MyTextFieldDelegate {
    fn text_did_change(&self, text: String) {
        println!("Text changed: {}", text);
    }
    
    fn text_did_end_editing(&self, text: String) {
        println!("Editing ended: {}", text);
    }
    
    fn should_change_text(&self, range: (usize, usize), replacement: String) -> bool {
        // Custom validation logic
        true
    }
}

// Register delegate
let delegate = Arc::new(MyTextFieldDelegate);
register_text_field_delegate(1, delegate);
```

---

## Additional Native Controls

### New Control Types

#### Segmented Control (NSSegmentedControl)

```rust
View::segmented_control(vec!["Option 1", "Option 2", "Option 3"])
    .on_click(callback_id)
```

#### Combo Box (NSComboBox)

```rust
View::combo_box(vec!["Apple", "Banana", "Cherry"])
    .on_change(callback_id)
```

#### Search Field (NSSearchField)

```rust
View::search_field("Search...")
    .on_change(callback_id)
```

#### Stepper (NSStepper)

```rust
View::stepper(0.0, 100.0, 50.0) // min, max, value
    .on_change(callback_id)
```

#### Level Indicator (NSLevelIndicator)

```rust
View::level_indicator(0.0, 100.0, 75.0) // min, max, value
```

#### Path Control (NSPathControl)

```rust
View::path_control("/Users/username/Documents")
```

---

## Advanced Features

### Window Management

```rust
use cocoanut::native::window;

// Set window level
window::set_level(window, window::FLOATING_LEVEL);

// Make window key and order front
window::make_key_and_order_front(window);

// Set window transparency
window::set_alpha(window, 0.95);

// Set window background color
window::set_background_color(window, 1.0, 1.0, 1.0, 1.0);
```

### Animation Support

```rust
use cocoanut::native::animation;

// Animate changes
animation::animate(0.3, || {
    view_properties::set_alpha(view, 0.5);
    view_properties::set_frame(view, 100.0, 100.0, 200.0, 200.0);
});

// Or manually
animation::begin_animation(0.3);
view_properties::set_alpha(view, 0.5);
animation::end_animation();
```

### Pasteboard (Clipboard) Operations

```rust
use cocoanut::native::pasteboard;

// Copy text to clipboard
pasteboard::copy_text("Hello, World!")?;

// Get text from clipboard
let text = pasteboard::get_text()?;
println!("Clipboard: {}", text);
```

---

## Architecture Changes

### New Modules

1. **`layout.rs`**: Auto Layout constraint system
2. **`native.rs`**: Native view property access and utilities
3. **`delegate.rs`**: Delegate pattern support

### Enhanced Modules

1. **`view.rs`**: 
   - Added `uses_auto_layout`, `constraints`, shadow, layer, and responder properties to `ViewStyle`
   - Added 6 new native control types to `ViewKind`
   - Added builder methods for new properties and controls

2. **`renderer.rs`**: 
   - Added `apply_native_styles()` helper for applying all native properties
   - Added render functions for 6 new control types
   - Updated layout calculations for new controls

3. **`lib.rs`**: 
   - Added exports for new modules in prelude

---

## Benefits

### 1. Better Native Integration

- Direct access to native AppKit features
- Auto Layout instead of frame-based layout
- Native delegate patterns

### 2. More Control Types

- 6 new native control types
- Total of 32 view types (was 26)

### 3. Enhanced Styling

- Layer-backed views
- Shadows, corner radius, borders
- Opacity and visibility control

### 4. Professional Features

- Animation support
- Clipboard operations
- Window management
- Responder chain control

### 5. Maintained Simplicity

- All features accessible via declarative API
- Chainable builder pattern
- Type-safe interfaces

---

## Example: Complete Native App

```rust
use cocoanut::prelude::*;

fn main() -> Result<()> {
    event::register(1, || println!("Button clicked"));
    event::register(2, || println!("Search changed"));

    app("Native Cocoa App")
        .size(800.0, 600.0)
        .dark()
        .build()
        .root(
            View::vstack()
                .child(
                    View::text("Native Cocoa Features")
                        .bold()
                        .font_size(24.0)
                        .shadow(3.0, 0.3, 0.0, 2.0)
                )
                .child(
                    View::search_field("Search...")
                        .on_change(2)
                        .corner_radius(8.0)
                )
                .child(
                    View::segmented_control(vec!["All", "Active", "Completed"])
                )
                .child(
                    View::button("Click Me")
                        .on_click(1)
                        .shadow(5.0, 0.5, 2.0, 2.0)
                        .corner_radius(12.0)
                )
        )
        .run()
}
```

---

## Migration Guide

### For Existing Code

Existing code will continue to work without changes. The new features are additive.

### Adopting New Features

1. **Replace frame-based layout with Auto Layout** (optional):
   ```rust
   // Before
   View::button("Click").width(200.0).height(32.0)
   
   // After (with Auto Layout)
   View::button("Click")
       .constraints(vec![
           constraints::width(200.0),
           constraints::height(32.0),
       ])
   ```

2. **Add visual enhancements**:
   ```rust
   View::button("Click")
       .shadow(5.0, 0.5, 2.0, 2.0)
       .corner_radius(12.0)
   ```

3. **Use new native controls**:
   ```rust
   // Instead of dropdown
   View::segmented_control(vec!["Option 1", "Option 2"])
   
   // Instead of text_field for search
   View::search_field("Search...")
   ```

---

## Performance Considerations

1. **Auto Layout**: Constraint-based layout may be slightly slower than frame-based but provides better flexibility
2. **Layer-backed views**: Using shadows, corner radius, etc. enables layer backing which uses more GPU memory
3. **Delegates**: Delegate callbacks have minimal overhead

---

## Future Enhancements

Potential future improvements:

1. NSCollectionView support
2. NSOutlineView (hierarchical table) support
3. Drag and drop support
4. NSToolbar integration
5. Touch Bar support
6. CloudKit integration

---

## Conclusion

These improvements significantly enhance Cocoanut's native Cocoa integration while maintaining its simple, declarative API. Developers now have access to:

- Professional visual effects (shadows, animations)
- Modern layout system (Auto Layout)
- Full control over native behaviors
- Additional native controls
- Advanced system integration (clipboard, responder chain)

All while keeping the codebase compact and maintainable.