5.3 KiB
5.3 KiB
System Patterns
Window Capture Architecture
Window Detection Pattern
-
SCShareableContent Access
- Async/await pattern for content access
- Proper error propagation
- Permission handling
-
Window Identification
- Multiple validation criteria:
let bundleID = window.owningApplication?.bundleIdentifier ?? "" let isChessApp = bundleID == "com.chess.iphone" let hasValidSize = window.frame.width > 100 && window.frame.height > 100 return isChessApp && window.isOnScreen && hasValidSize - Fail-fast approach with guard statements
- Clear error states
- Multiple validation criteria:
Capture System Pattern
-
Stream Configuration
- Window-specific capture setup
- Frame dimension matching
- Proper delegate handling
-
Frame Processing
- Main thread safety for UI updates
- Efficient image conversion pipeline
- Resource cleanup
Error Handling Pattern
-
Task Management
- Proper cancellation points
- Clean state management
- Resource cleanup
-
Error States
- Clear error types
- User-friendly messages
- State recovery
UI Architecture
MVVM Implementation
-
ViewModel
- @MainActor for thread safety
- Published properties for state
- Clear separation of concerns
-
View Layer
- SwiftUI declarative UI
- State-driven updates
- Error presentation
Async Operations
-
Task Management
- Structured concurrency
- Proper cancellation
- State synchronization
-
State Updates
- Main thread safety
- Clear state transitions
- Error recovery
Core Architecture
Resource Management Patterns
- Shared CIContext Pattern
- Static shared instance:
private static let shared = CIContext() private var context: CIContext { Self.shared } - Benefits:
- Prevents Metal command queue exhaustion
- Reduces resource overhead
- Enables long-running captures
- Implementation:
- Used in BoardDetector and ViewModel
- Proper cleanup on task completion
- Thread-safe access
- Static shared instance:
Screen Capture System
- Uses ScreenCaptureKit for efficient screen capture
- Implements SCStreamOutput protocol for frame processing
- Handles capture session lifecycle and cleanup
- Manages permissions and error handling
- Optimized resource usage
Board Detection System
Two implemented approaches:
-
Pattern Recognition Approach (Primary)
- Rectangle detection with Vision framework
- Aspect ratio-based filtering (0.3-0.5 for taller rectangles)
- Size-based filtering (0.4 minimum for larger areas)
- Single observation for precision
- Board extraction from upper portion
- Width-based square calculation
-
Coordinate Detection (Fallback)
- Text recognition for board coordinates
- Rectangle detection with Vision framework
- Grid-based validation
- Coordinate-based refinement
-
Common Infrastructure
- Asynchronous frame processing
- Dedicated processing queue
- Efficient memory management
- Performance monitoring
Coordinate Systems
- Vision framework: Bottom-left origin (0,0)
- NSImage/CGImage: Bottom-left origin (0,0)
- SwiftUI: Top-left origin (0,0)
- Transformations needed between systems:
- Vision → Screen: Flip Y coordinate
- Screen → Image: Direct mapping
- Image → View: SwiftUI handles automatically
Notification System
- Uses NotificationCenter for event propagation
- Key notifications:
- boardDetected: Sends detected board rectangle and confidence score
- captureStateChanged: Updates capture status
- capturedFrame: Delivers processed frames
- boardCoordinatesDetected: Reports coordinate detection
- detectionStats: Reports performance metrics
Design Patterns
MVVM Architecture
- ScreenCapture: Model layer handling capture logic
- ScreenCaptureViewModel: View model managing UI state
- ContentView: SwiftUI view for user interface
Observer Pattern
- NotificationCenter for loose coupling
- Enables modular component communication
- Supports async event handling
Error Handling
- Custom ScreenCaptureError enum
- Comprehensive error cases
- Proper error propagation
Technical Decisions
Vision Framework
- Primary tool for board detection
- Provides rectangle and text detection
- Handles various board orientations
- Requires coordinate system transformation
Pattern Recognition
- Focus on larger detection areas
- Use width as reference measurement
- Extract square board from top portion
- Maintain aspect ratio constraints
Performance Considerations
- Dedicated dispatch queue for frame processing
- Efficient memory management
- Proper resource cleanup
- Single observation optimization
Future Patterns
Planned Implementations
-
Board Position Analysis
- ML model integration
- Piece detection system
- Position validation
-
Move Analysis
- Stockfish integration
- Real-time evaluation
- Visual overlay system
-
State Management
- Game state tracking
- Move history
- Analysis persistence
Testing Patterns
Unit Testing
- ScreenCapture functionality
- Board detection accuracy
- Coordinate recognition
Integration Testing
- End-to-end capture workflow
- Vision framework integration
- Notification system
UI Testing
- SwiftUI interface validation
- User interaction flows
- Error state handling