### Clone Repository and Install Dependencies Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Instructions to clone the Media Picker Plus repository and install project dependencies using Flutter. ```bash git clone https://github.com/thanhtunguet/media_picker_plus.git cd media_picker_plus/example flutter pub get ``` -------------------------------- ### API Documentation and Usage Examples Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODOS.md Guidelines for creating comprehensive API documentation, including detailed explanations, usage examples, tutorials, setup instructions, and migration guides. ```APIDOC API Documentation Standards: - Structure: Organize documentation by feature, class, or module. - Clarity: Use clear and concise language. - Completeness: Cover all public methods, parameters, return values, and exceptions. - Examples: Provide practical code snippets demonstrating common use cases. - Tutorials: Include step-by-step guides for complex workflows. - README: Ensure the main README file provides essential setup and basic usage information. Example Documentation Entry (Conceptual): MediaPickerPlus.pickMedia(): - Description: Opens the media picker interface to allow users to select images or videos. - Parameters: - `mediaType`: (enum MediaDataType) Specifies whether to pick images, videos, or both. Defaults to `MediaDataType.image`. - `multiSelect`: (bool) If true, allows multiple media items to be selected. Defaults to `false`. - Returns: - `Future>`: A future that resolves to a list of `MediaFile` objects representing the selected media. - Throws: - `PlatformException`: If an error occurs during the picking process (e.g., permissions denied). - Example: ```dart List selectedMedia = await MediaPickerPlus.pickMedia( mediaType: MediaDataType.image, multiSelect: true, ); ``` ``` -------------------------------- ### Running the Example App Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/README.md Instructions on how to navigate to the example directory and run the Flutter example app. ```bash cd example flutter run ``` -------------------------------- ### Run Example App on Different Platforms Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Commands to run the example application on Android, iOS, macOS, and Web using Flutter. ```bash # For Android flutter run -d android # For iOS flutter run -d ios # For macOS flutter run -d macos # For Web flutter run -d chrome ``` -------------------------------- ### Android Permissions Setup Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Required camera, storage, and media permissions to be added to the AndroidManifest.xml file. ```xml ``` -------------------------------- ### iOS Permissions Setup Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Required camera, photo library, and microphone usage descriptions for the Info.plist file on iOS. ```xml NSCameraUsageDescription This app needs camera access to capture photos and videos NSPhotoLibraryUsageDescription This app needs photo library access to pick images and videos NSMicrophoneUsageDescription This app needs microphone access to record videos ``` -------------------------------- ### macOS Permissions Setup Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Required camera, photo library, and microphone usage descriptions for the Info.plist file on macOS, along with file access entitlements. ```xml NSCameraUsageDescription This app needs camera access to capture photos and videos NSPhotoLibraryUsageDescription This app needs photo library access to pick images and videos NSMicrophoneUsageDescription This app needs microphone access to record videos com.apple.security.device.camera com.apple.security.files.user-selected.read-write ``` -------------------------------- ### Install Media Picker Plus via CLI Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/README.md This snippet demonstrates how to install the media_picker_plus plugin using the Flutter CLI command. ```bash flutter pub add media_picker_plus ``` -------------------------------- ### Integration Demonstration Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/CLAUDE.md An example application demonstrating how to integrate and use the Media Picker Plus plugin in a Flutter project. ```dart // example/lib/main.dart - Integration demonstration ``` -------------------------------- ### Picking Multiple Media Files Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/web/index.html This example demonstrates how to pick multiple media files (images and videos) simultaneously. It iterates through the selected files and prints their paths. ```dart import 'package:media_picker_plus/media_picker_plus.dart'; Future pickMultipleMedia() async { List mediaFiles = await MediaPicker.pick(mediaType: MediaType.all, multiple: true); if (mediaFiles.isNotEmpty) { for (var mediaFile in mediaFiles) { print('Picked media: ${mediaFile.path}'); } } else { print('No media selected.'); } } ``` -------------------------------- ### Flutter Unit and Integration Tests Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Demonstrates how to run unit and integration tests for a Flutter project using the `flutter test` command. It also shows platform-specific testing commands for Android, iOS, and Web. ```bash flutter test flutter test integration_test/ # Android flutter test --platform android # iOS flutter test --platform ios # Web flutter test --platform chrome ``` -------------------------------- ### Media Picker Plus Integration Example Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/GEMINI.md A basic example demonstrating how to integrate and use the Media Picker Plus plugin in a Flutter application. It shows calling the `processImage` method. ```dart import 'package:flutter/material.dart'; import 'package:media_picker_plus/media_picker_plus.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { String? _processedImagePath; Future _cropImage() async { final String? selectedImagePath = await MediaPickerPlus.pickImage(); // Assuming a pickImage method exists if (selectedImagePath != null) { // Define crop options (example: ratio, position) final Map cropOptions = { 'ratioX': 1.0, 'ratioY': 1.0, 'x': 0.0, 'y': 0.0, 'width': 100.0, 'height': 100.0 }; try { final String? processedPath = await MediaPickerPlus.processImage(selectedImagePath, cropOptions); setState(() { _processedImagePath = processedPath; }); } catch (e) { print('Error processing image: $e'); } } } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: Text('Media Picker Plus Example')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ if (_processedImagePath != null) Image.asset(_processedImagePath!), // Use Image.file for actual file paths ElevatedButton(onPressed: _cropImage, child: Text('Pick and Crop Image')) ], ), ), ), ); } } // Mock implementation for demonstration purposes class MediaPickerPlus { static Future pickImage() async { // In a real app, this would open the image picker. return "path/to/your/selected/image.jpg"; } static Future processImage(String imagePath, Map cropOptions) async { // In a real app, this would call the platform implementation. print('Processing image: $imagePath with options: $cropOptions'); return "path/to/your/processed/image.jpg"; } } ``` -------------------------------- ### CI/CD Pipeline Setup (GitHub Actions) Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODOS.md Configuration for setting up a Continuous Integration and Continuous Deployment (CI/CD) pipeline using GitHub Actions. This includes automated testing, publishing workflows, and code coverage reporting. ```APIDOC CI/CD Pipeline with GitHub Actions: Workflow File: `.github/workflows/ci.yml` Triggers: - `push`: On pushes to the main branch. - `pull_request`: On pull requests to the main branch. Jobs: - `build_and_test`: - Runs on: `ubuntu-latest` (or platform-specific runners like `macos-latest`, `windows-latest`). - Steps: - Checkout code. - Set up Flutter SDK. - Install dependencies (`flutter pub get`). - Run linters (`flutter analyze`). - Run unit tests (`flutter test`). - Run integration tests (if applicable). - Generate code coverage report (e.g., using `lcov`). - Upload coverage report as an artifact. - `publish` (optional, triggered on tag push): - Depends on: `build_and_test`. - Steps: - Authenticate with pub.dev. - Publish the package (`flutter pub publish`). Platform-Specific Test Runners: - Configure jobs to run tests on different operating systems (macOS for iOS/macOS, Linux for Android, etc.). - Use matrix strategies in GitHub Actions for efficient parallel execution. ``` -------------------------------- ### Enable Debug Mode Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Runs the Flutter application with debug mode enabled, which can provide more detailed output and enable debugging tools. ```bash flutter run --debug ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Retrieves detailed logs from the Flutter application, including verbose output that can help in diagnosing issues. ```bash flutter logs --verbose ``` -------------------------------- ### iOS Build Configuration Notes Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Provides information on the automatic build configurations handled by the plugin, including framework setup, Swift version compatibility, and iOS version availability checks. ```APIDOC Build Configuration: - Automatically configures required frameworks. - Sets up proper Swift version compatibility. - Handles iOS version availability checks. ``` -------------------------------- ### Testing and Documentation Enhancement Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODO_SESSION_HISTORY.md Describes the planned enhancements for the testing suite, including unit, widget, and integration tests, as well as improvements to documentation with API references and guides. ```APIDOC Enhanced Testing Suite: - Unit tests for cropping functionality - Widget tests for interactive UI - Integration tests for platform implementations - Performance benchmarking tests Documentation Enhancement: - Complete API documentation - Platform-specific implementation guides - Usage examples and tutorials - Performance best practices ``` -------------------------------- ### Installation and Import Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/API_USAGE.md Instructions for adding the media_picker_plus plugin to your Flutter project's pubspec.yaml file and importing it into your Dart code. ```yaml dependencies: media_picker_plus: ^1.0.0 ``` ```dart import 'package:media_picker_plus/media_picker_plus.dart'; ``` -------------------------------- ### Picking Only Videos Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/web/index.html This example demonstrates how to pick only video files. It configures the picker to accept only videos and processes the selected video. ```dart import 'package:media_picker_plus/media_picker_plus.dart'; Future pickVideo() async { var videoFile = await MediaPicker.pick(mediaType: MediaType.video); if (videoFile != null) { print('Picked video: ${videoFile.path}'); } else { print('No video selected.'); } } ``` -------------------------------- ### Core Plugin Structure Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/PROJECT_PLAN.md Illustrates the directory structure of the MediaPickerPlus Flutter plugin, highlighting the main API, configuration files, platform-specific implementations, and the example application. ```tree MediaPickerPlus/ ├── lib/ │ ├── media_picker_plus.dart # Main plugin API │ ├── media_options.dart # Configuration classes │ ├── crop_options.dart # Crop configuration │ ├── crop_ui.dart # Interactive crop widget │ ├── crop_helper.dart # Crop workflow utilities │ └── media_picker_plus_platform_interface.dart ├── android/ # Android native implementation ├── ios/ # iOS native implementation ├── macos/ # macOS native implementation ├── web/ # Web implementation └── example/ # Example application ``` -------------------------------- ### Basic Media Picking Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/web/index.html This snippet shows the basic functionality of picking a single media file using Media Picker Plus. It handles the selection and displays the picked file's path. ```dart import 'package:media_picker_plus/media_picker_plus.dart'; Future pickMedia() async { var mediaFile = await MediaPicker.pick(mediaType: MediaType.image); if (mediaFile != null) { print('Picked media: ${mediaFile.path}'); } else { print('No media selected.'); } } ``` -------------------------------- ### Smart Video Recording with Permissions Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Records video with audio, handling camera and microphone permissions. It includes options for watermarking and setting maximum duration. The function first checks for camera permission, requests it if not granted, then displays a dialog to inform the user about microphone permission requirements before proceeding with the recording. ```dart Future recordVideoWithSmartPermissions() async { // Check camera permission first if (!await MediaPickerPlus.hasCameraPermission()) { final granted = await MediaPickerPlus.requestCameraPermission(); if (!granted) { _showError('Camera permission is required'); return; } } // Show microphone permission info dialog final shouldContinue = await _showMicrophonePermissionDialog(); if (!shouldContinue) return; try { final timestamp = _generateDetailedTimestamp(); final path = await MediaPickerPlus.recordVideo( options: MediaOptions( watermark: '🎬 Recorded: $timestamp', watermarkFontSize: 26, watermarkPosition: WatermarkPosition.topLeft, maxDuration: Duration(minutes: 5), ), ); if (path != null) { print('Video recorded with timestamp: $path'); } } catch (e) { print('Error: $e'); } } /// Show informative microphone permission dialog Future _showMicrophonePermissionDialog() async { final result = await showDialog( context: context, builder: (context) => AlertDialog( title: Text('Microphone Permission Info'), content: Text( 'For video recording with audio, the app will automatically request ' 'microphone permission when needed. On some platforms, audio recording ' 'may require additional permissions to be granted manually in device settings.', ), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(false), child: Text('Cancel'), ), ElevatedButton( onPressed: () => Navigator.of(context).pop(true), child: Text('Continue Recording'), ), ], ), ); return result ?? false; } ``` -------------------------------- ### Pick Image with Watermark Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Picks an image from the gallery and applies a watermark with specified quality and dimensions. Handles potential errors during the picking process. ```dart Future pickImage() async { try { final path = await MediaPickerPlus.pickImage( options: const MediaOptions( imageQuality: 85, maxWidth: 1920, maxHeight: 1080, watermark: '📸 Media Picker Plus', watermarkPosition: WatermarkPosition.bottomRight, ), ); if (path != null) { print('Image picked: $path'); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Check and Request Permissions Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Checks the current status of camera and gallery permissions and requests them if they have not been granted. This function ensures that the application has the necessary permissions before attempting media operations. ```dart Future checkAndRequestPermissions() async { // Check current permissions final cameraPermission = await MediaPickerPlus.hasCameraPermission(); final galleryPermission = await MediaPickerPlus.hasGalleryPermission(); // Request permissions if needed if (!cameraPermission) { await MediaPickerPlus.requestCameraPermission(); } if (!galleryPermission) { await MediaPickerPlus.requestGalleryPermission(); } } ``` -------------------------------- ### Troubleshooting: File Access Issues Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Guides users through resolving file access problems, emphasizing sandboxing compliance, temporary directory permissions, file cleanup, and security-scoped resource access. ```APIDOC Troubleshooting: File Access Issues: - Ensure proper sandboxing compliance. - Check temporary directory permissions. - Verify file cleanup doesn't occur prematurely. - Handle security-scoped resource access properly. ``` -------------------------------- ### Error Handling Example Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/README.md Illustrates how to use a try-catch block to handle potential errors during media picking operations. ```dart try { final String? imagePath = await MediaPickerPlus.pickImage(); if (imagePath != null) { // Process the image } else { // User cancelled the operation } } catch (e) { // Handle errors (permission denied, etc.) print('Error: $e'); } ``` -------------------------------- ### Multiple Image Selection with Options Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/API_USAGE.md Example of picking multiple images from the gallery with custom options for quality, dimensions, and watermarking. ```dart Future pickMultipleImages() async { try { final paths = await MediaPickerPlus.pickMultipleImages( options: const MediaOptions( imageQuality: 80, maxWidth: 1080, maxHeight: 1080, watermark: '📸 Gallery', watermarkPosition: WatermarkPosition.bottomCenter, ), ); if (paths != null && paths.isNotEmpty) { print('Picked ${paths.length} images'); for (final path in paths) { print('Image: $path'); } } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Pick Image with Timestamp Watermark Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Picks an image and applies a timestamped watermark. Includes helper functions to generate both standard and detailed timestamp formats. ```dart /// Generate timestamp: 2024-07-17 14:30:25 String _generateTimestamp() { final now = DateTime.now(); return '${now.year}-${now.month.toString().padLeft(2, '0')}-${now.day.toString().padLeft(2, '0')} ' '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}'; } /// Pick image with real-time timestamp Future pickImageWithTimestamp() async { try { final timestamp = _generateTimestamp(); final path = await MediaPickerPlus.pickImage( options: MediaOptions( imageQuality: 90, maxWidth: 1920, maxHeight: 1080, watermark: '📸 $timestamp', watermarkFontSize: 24, watermarkPosition: WatermarkPosition.bottomRight, ), ); if (path != null) { print('Timestamped image: $path'); } } catch (e) { print('Error: $e'); } } /// Generate detailed timestamp: Jul 17, 2024 • 14:30:25 String _generateDetailedTimestamp() { final now = DateTime.now(); final months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; return '${months[now.month - 1]} ${now.day}, ${now.year} • ' '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}:${now.second.toString().padLeft(2, '0')}'; } ``` -------------------------------- ### Web Configuration - PWA Manifest Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/README.md An example of a web app manifest JSON file for Progressive Web App (PWA) features. It defines the application's name, display mode, and permissions for camera and microphone. ```json { "name": "Media Picker Plus App", "short_name": "MediaPicker", "start_url": "/", "display": "standalone", "background_color": "#ffffff", "theme_color": "#000000", "permissions": [ "camera", "microphone" ] } ``` -------------------------------- ### Pick Multiple Images Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Allows users to select multiple images from their gallery. This function configures options such as image quality and adds a watermark to the selected images. It handles potential errors during the picking process. ```dart Future pickMultipleImages() async { try { final paths = await MediaPickerPlus.pickMultipleImages( options: const MediaOptions( imageQuality: 80, watermark: '📸 Multiple Images', watermarkPosition: WatermarkPosition.bottomLeft, ), ); if (paths != null && paths.isNotEmpty) { print('Picked ${paths.length} images'); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Record Video with Camera Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/API_USAGE.md Provides an example of recording a video using the device's camera with MediaPickerPlus.recordVideo(). Includes error handling for the video recording process. ```dart Future recordVideo() async { try { final path = await MediaPickerPlus.recordVideo(); if (path != null) { // Use the recorded video path print('Video recorded: $path'); } } catch (e) { print('Error recording video: $e'); } } ``` -------------------------------- ### CORS Configuration for Cross-Origin File Processing Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/web.md Provides an example of server-side CORS configuration headers necessary for enabling cross-origin file processing. This includes specifying allowed origins, methods, and headers. ```yaml # Example server configuration Access-Control-Allow-Origin: "*" Access-Control-Allow-Methods: "GET, POST, PUT, DELETE" Access-Control-Allow-Headers: "Content-Type, Authorization" ``` -------------------------------- ### Pick Document with Extension Filtering Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/README.md Enables the selection of specific document types, such as PDFs, Word documents, and text files. The function filters files based on a provided list of allowed extensions, ensuring only compatible files are chosen. Error handling is included for the file picking process. ```dart Future pickDocument() async { try { final path = await MediaPickerPlus.pickFile( allowedExtensions: ['.pdf', '.doc', '.docx', '.txt'], ); if (path != null) { print('Document picked: $path'); } } catch (e) { print('Error: $e'); } } ``` -------------------------------- ### Platform Implementation Details Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODO_SESSION_HISTORY.md Provides an overview of the technical improvements and key implementation details across different platforms, including coordinate systems, gesture tracking, and performance optimizations. ```APIDOC Platform Implementation Details: - Normalized coordinate system (0.0-1.0) for cross-platform compatibility - Ratio-based gesture tracking for precise movement - Multi-layer validation with comprehensive error handling - Dynamic minimum size calculation based on screen dimensions - Enhanced zoom functionality with visual indicators Key Implementation Details: - Minimum Crop Size: 30% of smaller screen edge (width for portrait, height for landscape) - Zoom Functionality: Dynamic maxScale (5x when at minimum size, 3x otherwise) - Coordinate System: Normalized 0.0-1.0 coordinates for cross-platform compatibility - Gesture Tracking: Ratio-based movement calculations for precise UI interaction - Performance: Throttled callbacks (16ms), cached paint objects, RepaintBoundary Known Issues Resolved: - ✅ ArgumentError(0.1) with minimum size constraints - ✅ Scale assertion crashes (scale != 0.0) - ✅ Infinite size rendering errors - ✅ Gesture tracking precision issues - ✅ Original image returned instead of processed crop ``` -------------------------------- ### Future Platform Support Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODO_SESSION_HISTORY.md Outlines the planned implementation for macOS and Web platforms, including native media picking, camera access, permission handling, and UI integration. ```APIDOC macOS Implementation: - Native media picking using NSOpenPanel - Camera access using AVCaptureDevice - Permission handling for camera and photo library - Image processing and cropping with Core Graphics - Interactive cropping UI integration Web Implementation: - HTML5 media APIs for camera access - File picker for gallery selection - Client-side image/video processing - Canvas-based cropping functionality - Interactive cropping UI with HTML5 Canvas ``` -------------------------------- ### File Paths Definition Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/README.md Defines the file paths that can be shared via FileProvider. This example specifies a path for storing images. ```xml ``` -------------------------------- ### Testing: Integration Testing Recommendations Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Provides recommendations for integration testing, covering cross-iOS version compatibility, device variations, different media formats, and permission flow scenarios. ```APIDOC Testing: Integration Testing Recommendations: - Cross-iOS version compatibility (iOS 12-17+) - Different device types and capabilities - Various image/video formats and sizes - Permission flow scenarios ``` -------------------------------- ### Picking Only Images Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/web/index.html This snippet focuses on picking only image files. It sets the media type to 'image' and handles the selection of a single image. ```dart import 'package:media_picker_plus/media_picker_plus.dart'; Future pickImage() async { var imageFile = await MediaPicker.pick(mediaType: MediaType.image); if (imageFile != null) { print('Picked image: ${imageFile.path}'); } else { print('No image selected.'); } } ``` -------------------------------- ### Testing: Unit Testing Recommendations Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Suggests key areas for unit testing, including permission state management, image processing logic, file path resolution, and error handling scenarios. ```APIDOC Testing: Unit Testing Recommendations: - Permission state management logic - Image processing operations - File path resolution and cleanup - Error handling scenarios ``` -------------------------------- ### Testing: Performance Testing Recommendations Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Outlines recommendations for performance testing, including memory usage profiling, processing time benchmarks, large file handling, and concurrent operation testing. ```APIDOC Testing: Performance Testing Recommendations: - Memory usage profiling during processing - Processing time benchmarks across devices - Large file handling verification - Concurrent operation handling ``` -------------------------------- ### Dart - Capture Photo Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/README.md Provides an example of capturing a photo using the device's camera with MediaPickerPlus. Options for quality, dimensions, and watermarking are available. ```dart final String? photoPath = await MediaPickerPlus.capturePhoto( context: context, // Optional: enables interactive cropping UI when freeform cropping options: const MediaOptions( imageQuality: 90, maxWidth: 2560, maxHeight: 1440, watermark: 'Captured with My App', watermarkPosition: WatermarkPosition.bottomCenter, ), ); ``` -------------------------------- ### Dart - Record Video Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/README.md Provides an example of recording a video using the device's camera with MediaPickerPlus. Options for dimensions, watermarking, and maximum duration are available. ```dart final String? recordedPath = await MediaPickerPlus.recordVideo( options: const MediaOptions( maxWidth: 1920, maxHeight: 1080, watermark: 'Live Recording', watermarkPosition: WatermarkPosition.middleCenter, maxDuration: Duration(minutes: 2), ), ); ``` -------------------------------- ### Platform-Specific Unit Tests (Mocking) Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODOS.md Guidelines for creating platform-specific unit tests for Android, iOS, macOS, and Web. This involves mocking external dependencies and platform APIs to ensure isolated testing of logic. ```APIDOC Platform-Specific Unit Tests: - Android: Use Mockito or similar frameworks to mock Android SDK components. - iOS: Utilize XCTest and Objective-C/Swift mocking techniques. - macOS: Employ XCTest and Objective-C/Swift mocking techniques. - Web: Use Jest or similar JavaScript testing frameworks with Jest mocks. Mocking Strategy: - Mock all external dependencies (e.g., file system access, camera APIs, network requests). - Mock platform-specific APIs to isolate business logic. - Test error handling and edge cases by providing mocked error responses. - Example (Conceptual - Dart/Flutter): when(mockCameraPlugin.takePicture()).thenThrow(PlatformException(code: 'CAMERA_ERROR')); ``` -------------------------------- ### Native iOS Frameworks Overview Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md This section provides an overview of the core iOS frameworks utilized in the media picker implementation, detailing their purpose and implementation status. ```APIDOC AVFoundation: Purpose: Camera capture, video processing, and media composition. Enables camera access, video recording, and metadata retrieval. Status: ✅ Fully implemented Photos/PhotosUI: Purpose: Gallery access and modern photo picker. Supports PHPickerViewController (iOS 14+) and provides fallbacks. Status: ✅ Fully implemented with fallbacks UIKit: Purpose: User interface and image picker. Utilizes UIImagePickerController for view presentation. Status: ✅ Complete implementation Core Graphics: Purpose: Image processing and manipulation. Used for image cropping, watermarking, and drawing operations. Status: ✅ Complete implementation Core Animation: Purpose: Video watermark overlay. Employs CATextLayer and CALayer composition for video watermarks. Status: ✅ Complete implementation UniformTypeIdentifiers: Purpose: File type handling (iOS 14+). Provides modern file type identification and filtering with legacy fallbacks. Status: ✅ Complete with legacy fallbacks ``` -------------------------------- ### Troubleshooting: Permission Denied Errors Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Provides guidance on resolving 'Permission Denied' errors, including checks for Info.plist entries, request timing, and using built-in permission check methods. ```APIDOC Troubleshooting: Permission Denied Errors: - Verify Info.plist entries are present and descriptive. - Check for proper permission request timing. - Ensure app is not calling APIs before permissions granted. - Use plugin's built-in permission check methods. ``` -------------------------------- ### Interactive Cropping UI Implementation Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODO_SESSION_HISTORY.md Details the implementation of the interactive cropping UI widget, including gesture tracking, minimum size constraints, and zoom functionality. This is a core component for manual crop selection. ```dart /// lib/crop_ui.dart - Main interactive cropping implementation /// lib/crop_options.dart - Crop configuration API /// lib/crop_helper.dart - Crop workflow utilities // Key Implementation Details: // - Minimum Crop Size: 30% of smaller screen edge (width for portrait, height for landscape) // - Zoom Functionality: Dynamic maxScale (5x when at minimum size, 3x otherwise) // - Coordinate System: Normalized 0.0-1.0 coordinates for cross-platform compatibility // - Gesture Tracking: Ratio-based movement calculations for precise UI interaction // - Performance: Throttled callbacks (16ms), cached paint objects, RepaintBoundary // Known Issues Resolved: // - ✅ ArgumentError(0.1) with minimum size constraints // - ✅ Scale assertion crashes (scale != 0.0) // - ✅ Infinite size rendering errors // - ✅ Gesture tracking precision issues // - ✅ Original image returned instead of processed crop ``` -------------------------------- ### Video Cropping Support Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODO_SESSION_HISTORY.md Details the plan to extend cropping functionality to video files, including native implementations for Android and iOS, and preview capabilities in the interactive UI. ```APIDOC Video Cropping Support: - Extend cropping functionality to video files - Native video cropping on Android (Mp4Composer) - Native video cropping on iOS (AVFoundation) - Video crop preview in interactive UI ``` -------------------------------- ### Platform-Specific Implementation Technologies Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/GEMINI.md Lists the primary technologies used for implementing the Media Picker Plus plugin on different platforms. ```APIDOC Platform Implementations: Android: - Language: Java - Libraries: Mp4Composer (for video watermarking), image cropping libraries. - Capabilities: Full media picking, camera access, image/video processing, watermarking. iOS: - Language: Swift - Libraries: AVFoundation (for video processing), Core Graphics (for image cropping). - Capabilities: Full media picking, camera access, image/video processing, watermarking. macOS: - Language: Swift - Libraries: NSOpenPanel (for media picking), AVCaptureDevice (for camera access). - Status: Minimal implementation (5%), requires completion for media picking, camera, processing, and watermarking. Web: - Language: JavaScript - Libraries: HTML5 media APIs (for camera access), Canvas API (for watermarking). - Capabilities: Client-side image/video processing, watermarking. - Status: Minimal implementation (5%), requires completion for media picking, camera access, and processing. ``` -------------------------------- ### Permission System Features Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Details the implementation of the permission system, covering camera, microphone, photo library access, and runtime requests. ```APIDOC Camera Access: Method: AVCaptureDevice authorization with proper status handling. Microphone Access: Method: Audio recording permissions for video capture. Photo Library: Method: PHPhotoLibrary authorization with limited/full access support. Runtime Requests: Method: Proper asynchronous permission request flows with completion handlers. ``` -------------------------------- ### Android Build Configuration Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/android.md Specifies the minimum Android SDK versions required for the project. This includes compileSdkVersion, minSdkVersion, and targetSdkVersion. ```gradle android { compileSdkVersion 34 defaultConfig { minSdkVersion 23 targetSdkVersion 34 } } ``` -------------------------------- ### Media Picker Plus - Platform Implementations Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/CLAUDE.md Outlines the platform-specific implementation details for Media Picker Plus, including technologies used for media processing and cropping. ```APIDOC Platform Implementations: Android: - Language: Java - Libraries: Mp4Composer for video watermarking, image cropping libraries. - Functionality: Full media picking, camera access, image/video processing, watermarking. iOS: - Language: Swift - Libraries: AVFoundation for video processing, Core Graphics for image cropping. - Functionality: Full media picking, camera access, image/video processing, watermarking. macOS: - Language: Swift (to be completed) - Functionality: Basic plugin registration (minimal implementation). Web: - Language: JavaScript (to be completed) - Technologies: HTML5 media APIs, Canvas API for watermarking. - Functionality: Basic plugin registration (minimal implementation). ``` -------------------------------- ### Performance Monitoring Tools Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Recommends using Xcode Instruments for performance monitoring, specifically for memory usage, CPU utilization, energy impact, and disk I/O. ```APIDOC Performance Monitoring: Monitor using Xcode Instruments: - Memory usage during image/video processing - CPU utilization during export operations - Energy impact of camera and processing operations - Disk I/O for file operations ``` -------------------------------- ### macOS Media Picking and Camera Access (Swift) Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODOS.md Implementation details for macOS media picking using NSOpenPanel and camera access using AVCaptureDevice. This includes handling permissions for camera and photo library, and following iOS patterns for a native Swift implementation. ```swift import Cocoa import AVFoundation // Placeholder for NSOpenPanel implementation func pickMediaFromGallery() { let panel = NSOpenPanel() panel.allowsMultipleSelection = false panel.canChooseDirectories = false panel.canChooseFiles = true panel.allowedFileTypes = ["jpg", "jpeg", "png", "gif", "mov", "mp4"] panel.begin { // Handle selected files } } // Placeholder for AVCaptureDevice implementation func accessCamera() { let session = AVCaptureSession() // Configure session with AVCaptureDevice input // Handle permissions for camera access } ``` -------------------------------- ### macOS Sandboxing Entitlements Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/macos.md Configuration for granting camera, microphone, and file system access for App Store distribution. This involves updating the `macos/Runner/Release.entitlements` file. ```xml com.apple.security.device.camera com.apple.security.device.microphone com.apple.security.files.user-selected.read-write com.apple.security.temporary-exception.files.absolute-path.read-write /private/tmp/ ``` -------------------------------- ### Interactive Cropping System Components Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/GEMINI.md Details the components involved in the interactive cropping system, including configuration, coordinate representation, the UI widget, and workflow management. ```dart class CropOptions { // Configuration for crop settings, aspect ratios, and presets // Example: aspectRatio: 16.0/9.0 } class CropRect { // Normalized coordinate system (0.0-1.0) for crop rectangles // Example: left: 0.1, top: 0.1, width: 0.8, height: 0.8 } class CropUI extends StatefulWidget { // Interactive widget with draggable handles and visual feedback // Handles aspect ratio control, zoom support, and minimum size protection. } class CropHelper { // Workflow management for seamless crop integration // Manages the lifecycle and state of the cropping process. } ``` -------------------------------- ### Architecture: Error Handling Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Explains the error handling approach, focusing on graceful degradation, user feedback, recovery mechanisms, and comprehensive logging. ```APIDOC Architecture: Error Handling: - Graceful Degradation: Fallbacks for failed operations - User Feedback: Proper error messages via Flutter result callbacks - Recovery: Automatic cleanup and state reset - Logging: Comprehensive error logging for debugging ``` -------------------------------- ### Web Media APIs and File Picking (JavaScript) Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODOS.md Implementation of web-based media picking using HTML5 APIs. This includes using getUserMedia for camera access and file input for gallery selection, along with handling web permissions and security. ```javascript async function accessCamera() { try { const stream = await navigator.mediaDevices.getUserMedia({ video: true }); // Use the stream for video display or recording } catch (err) { console.error('Error accessing camera:', err); } } const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', (event) => { const files = event.target.files; // Process selected files }); ``` -------------------------------- ### Cloud Storage Integration Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODOS.md Functionality for integrating with cloud storage services, enabling direct uploads, streaming for large files, and providing progress callbacks for upload operations. ```APIDOC Cloud Storage Integration: - Direct Upload: - Implement methods to upload selected media files directly to cloud services (e.g., AWS S3, Google Cloud Storage, Firebase Storage). - Support authentication mechanisms for different cloud providers. - Streaming Uploads: - For large files, implement streaming uploads to efficiently transfer data without loading the entire file into memory. - Progress Callbacks: - Provide real-time progress updates (e.g., percentage complete) for ongoing upload operations. Example (Conceptual - Uploading to a generic cloud service): Future uploadFileToCloud(File file, String cloudPath) async { // Initialize cloud service client // Create upload task // Listen to upload progress stream // Handle upload completion or errors } ``` -------------------------------- ### Permission Handling Performance Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Describes the performance aspects of permission handling, including response time, user experience, and caching mechanisms. ```APIDOC Permission Handling Performance: Response Time: Immediate for cached permissions, 1-2s for new requests User Experience: Native iOS permission dialogs Caching: Proper permission state caching and monitoring ``` -------------------------------- ### macOS Deployment Target Configuration Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/macos.md Sets the minimum deployment target for macOS applications. This configuration ensures compatibility with specific macOS versions and enables the use of features available from that version onwards. ```bash MACOSX_DEPLOYMENT_TARGET = 10.14 ``` -------------------------------- ### Workflow Helper Utilities Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/CLAUDE.md Contains utility functions and helper classes to manage the image cropping workflow, ensuring smooth operation and data handling. ```dart // lib/crop_helper.dart - Workflow helper utilities ``` -------------------------------- ### Performance Optimization: Preloading and Service Worker Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/web.md This snippet demonstrates how to preload FFmpeg.js assets for video features and set up a service worker for caching to improve performance. It uses HTML link tags for preloading and JavaScript for service worker registration. ```html ``` -------------------------------- ### Architecture: iOS Version Compatibility Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Describes the strategy for supporting different iOS versions, including the use of modern APIs with availability checks and fallbacks for older versions. ```APIDOC Architecture: iOS Version Compatibility: - Modern APIs: iOS 14+ features with availability checks - Legacy Support: Fallbacks for iOS 12-13 - Runtime Checks: Dynamic feature availability detection - Graceful Degradation: Feature reduction on older versions ``` -------------------------------- ### iOS Info.plist Permissions Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/docs/ios.md Specifies the required permissions for camera, microphone, and photo library access in the `Info.plist` file. These descriptions are shown to the user when the app requests access. ```xml NSCameraUsageDescription This app needs camera access to capture photos and videos NSMicrophoneUsageDescription This app needs microphone access to record audio with videos NSPhotoLibraryUsageDescription This app needs photo library access to select images and videos NSPhotoLibraryAddUsageDescription This app needs photo library access to save processed media ``` -------------------------------- ### Video Compression Options Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/TODOS.md Implementation of video compression features, allowing users to adjust video quality settings, convert video formats, and optimize file sizes. ```APIDOC Video Compression Features: - Quality Settings: Allow users to select desired video quality (e.g., low, medium, high) or specify a bitrate. - Format Conversion: Support conversion between common video formats (e.g., MP4, MOV, AVI). - File Size Optimization: Implement algorithms to reduce video file size while maintaining acceptable quality. Implementation Notes: - Platform-specific APIs or libraries will be required for video processing (e.g., FFmpeg, AVFoundation on iOS/macOS, MediaCodec on Android). - Consider using background processing for video compression to avoid blocking the UI thread. - Provide clear feedback to the user regarding the compression process and potential quality trade-offs. ``` -------------------------------- ### iOS Permissions Source: https://github.com/thanhtunguet/media_picker_plus/blob/main/example/API_USAGE.md Details the required keys to be added to the `Info.plist` file for iOS to request camera and photo library usage descriptions from the user. ```xml NSCameraUsageDescription This app needs camera access to capture photos and videos NSPhotoLibraryUsageDescription This app needs photo library access to pick images and videos ```