# EdgeToEdge Plugin - Threading Fixes for Android 11+

## Overview

The EdgeToEdge plugin has been updated to fix threading issues that commonly occur on Android 11+ devices. The main problem was the "Only the original thread that created a view hierarchy can touch its views" error, which happens when UI operations are performed from background threads.

## What Was Fixed

### 1. Threading Violations in OnApplyWindowInsetsListener

**Problem**: The `OnApplyWindowInsetsListener` callbacks can be triggered from background threads, but they were trying to modify UI elements and call Cordova callbacks directly.

**Solution**: All `OnApplyWindowInsetsListener` callbacks now:
- Are set up on the UI thread using `runOnUiThread()`
- Execute their callbacks on the UI thread using `runOnUiThread()`
- Use thread-safe result objects to avoid concurrency issues

### 2. Main Plugin Execution Thread Safety

**Problem**: Plugin methods could be called from any thread, potentially causing threading violations.

**Solution**: The main `execute()` method now:
- Checks if it's running on the UI thread
- Automatically switches to UI thread if needed
- Wraps all operations in proper thread-safe execution

### 3. WebView Layout Adjustment Thread Safety

**Problem**: The `adjustWebViewLayout()` method could be called from background threads.

**Solution**: The method now:
- Double-checks if it's on the UI thread
- Automatically switches to UI thread if needed
- Ensures all view modifications happen on the correct thread

## Code Changes Made

### Java Side (EdgeToEdge.java)

```java
// 1. Main execute method with thread safety
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    // Ensure all plugin methods run on the UI thread
    if (!cordova.getActivity().getMainLooper().getThread().equals(Thread.currentThread())) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    executeAction(action, args, callbackContext);
                } catch (Exception e) {
                    callbackContext.error("Error executing action on UI thread: " + e.getMessage());
                }
            }
        });
        return true;
    }
    
    return executeAction(action, args, callbackContext);
}

// 2. Thread-safe OnApplyWindowInsetsListener setup
cordova.getActivity().runOnUiThread(new Runnable() {
    @Override
    public void run() {
        decorView.setOnApplyWindowInsetsListener((v, windowInsets) -> {
            // ... handle insets ...
            
            // Ensure callback is executed on the main thread
            cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callbackContext.success(threadSafeResult);
                }
            });
            
            return windowInsets;
        });
    }
});

// 3. Thread-safe WebView layout adjustment
private void adjustWebViewLayout(final int statusBarHeight, final int navigationBarHeight) {
    // Double-check we're on the UI thread
    if (!cordova.getActivity().getMainLooper().getThread().equals(Thread.currentThread())) {
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                adjustWebViewLayout(statusBarHeight, navigationBarHeight);
            }
        });
        return;
    }
    
    // ... perform UI operations ...
}
```

### JavaScript Side (EdgeToEdge.js)

```javascript
// 1. Plugin availability check
isAvailable: function() {
    return typeof exec === 'function' && exec !== null;
},

// 2. Error handling in all methods
detectEdgeToEdge: function(successCallback, errorCallback) {
    if (!this.isAvailable()) {
        if (errorCallback) {
            errorCallback('Plugin not available');
        }
        return;
    }
    
    try {
        exec(successCallback, errorCallback, 'EdgeToEdge', 'detectEdgeToEdge', []);
    } catch (error) {
        if (errorCallback) {
            errorCallback('Error calling detectEdgeToEdge: ' + error.message);
        }
    }
}
```

## Usage Examples

### Basic Usage

```javascript
// Wait for Cordova to be ready
document.addEventListener('deviceready', function() {
    // Check if plugin is available
    if (typeof EdgeToEdge !== 'undefined' && EdgeToEdge.isAvailable()) {
        // Setup edge-to-edge display
        EdgeToEdge.setupEdgeToEdge(
            function(result) {
                console.log('Setup successful:', result);
            },
            function(error) {
                console.error('Setup failed:', error);
            }
        );
    }
}, false);
```

### Padding Reduction Control

The plugin now includes configurable padding reduction to prevent excessive spacing:

```javascript
// Customize padding reduction before setup
EdgeToEdge.setPaddingReduction({
    top: 20,      // Reduce top padding by 20px
    bottom: 20    // Reduce bottom padding by 20px
});

// Get current padding reduction settings
var currentReduction = EdgeToEdge.getPaddingReduction();
console.log('Current reduction:', currentReduction);

// Setup with custom padding
EdgeToEdge.setupEdgeToEdge(successCallback, errorCallback);
```

**Padding Reduction Options:**
- **Default**: 15px reduction (top and bottom)
- **Minimal**: 5px reduction for subtle spacing
- **None**: 0px reduction for full system bar heights
- **Custom**: Different values for top and bottom

### Advanced Usage with Fallback

```javascript
function setupEdgeToEdgeWithFallback() {
    EdgeToEdge.setupEdgeToEdge(
        function(result) {
            console.log('Setup successful:', result);
            applyEdgeToEdgeStyling(result);
        },
        function(error) {
            console.log('Setup failed, trying fallback:', error);
            
            // Try individual methods
            EdgeToEdge.detectEdgeToEdge(
                function(detectionResult) {
                    if (detectionResult.isEdgeToEdge) {
                        EdgeToEdge.adjustViewForEdgeToEdge(
                            function(adjustResult) {
                                console.log('Fallback adjustment successful');
                            },
                            function(adjustError) {
                                console.error('Fallback adjustment failed:', adjustError);
                            }
                        );
                    }
                },
                function(detectionError) {
                    console.error('Detection failed:', detectionError);
                }
            );
        }
    );
}
```

### CSS Usage

The plugin automatically sets CSS variables that you can use:

```css
.edge-to-edge-container {
    padding-top: var(--status-bar-height, 0px);
    padding-bottom: var(--navigation-bar-height, 0px);
    min-height: 100vh;
    box-sizing: border-box;
}

.safe-area-top {
    padding-top: var(--status-bar-height, 0px);
}

.safe-area-bottom {
    padding-bottom: var(--navigation-bar-height, 0px);
}
```

## Testing the Fixes

### 1. Build and Test

```bash
# Build the plugin
cordova plugin add ./path/to/edgetoedge-plugin

# Test on Android 11+ device
cordova run android
```

### 2. Verify Threading

Check the logs for any threading-related errors. You should see:
- No "Only the original thread that created a view hierarchy can touch its views" errors
- All operations completing successfully
- Proper edge-to-edge display on supported devices

### 3. Test Different Scenarios

- App startup and initialization
- Screen rotation
- System UI changes (status bar, navigation bar)
- Background/foreground transitions

### 4. Test Padding Reduction

Use the included test file to experiment with different padding values:

```bash
# Open the padding test file in your app
# examples/padding-test.html
```

The test file allows you to:
- Adjust top and bottom padding reduction with sliders
- Test different reduction values (0px to 50px)
- See real-time changes to the layout
- Reset to default values
- Apply custom padding configurations

### 5. Test System Bar Colors

The same test file also includes color controls:

```bash
# Open the comprehensive test file
# examples/padding-test.html
```

The color testing features include:
- Color pickers for status bar and navigation bar
- Icon style selection (light/dark)
- Preset color schemes (default, transparent, theme)
- Real-time color application
- Color format validation

## Common Issues and Solutions

### Issue: Plugin not found
**Solution**: Ensure the plugin is properly added to your Cordova project and wait for `deviceready` event.

### Issue: Methods returning errors
**Solution**: Check if the plugin is available using `EdgeToEdge.isAvailable()` before calling methods.

### Issue: View not adjusting properly
**Solution**: Ensure you're calling the methods after the WebView is fully loaded and the DOM is ready.

### Issue: CSS variables not set
**Solution**: The CSS variables are set automatically when `setupEdgeToEdge()` or `getSystemBarHeights()` completes successfully.

## Performance Considerations

- The threading fixes add minimal overhead
- All operations are batched and executed efficiently on the UI thread
- The plugin automatically handles thread switching when needed
- CSS adjustments are applied once and cached

## Compatibility

- **Android 5.0+ (API 21+)**: Basic edge-to-edge support
- **Android 9+ (API 28+)**: Enhanced edge-to-edge support
- **Android 11+ (API 30+)**: Full edge-to-edge support with threading fixes
- **iOS**: Not supported (iOS-specific implementation needed)

## Support

If you encounter any issues:
1. Check the console logs for detailed error messages
2. Verify the plugin is properly initialized
3. Ensure you're testing on a supported Android version
4. Check that all Cordova dependencies are up to date

## Changelog

### Version 2.0.0
- Fixed threading issues for Android 11+
- Added thread safety checks throughout the plugin
- Improved error handling and fallback mechanisms
- Enhanced JavaScript API with availability checks
- Added comprehensive examples and documentation
