# 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
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
View::button("Click").width(200.0).height(32.0)
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
View::segmented_control(vec!["Option 1", "Option 2"])
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.