feat(02-02): migrate SpeedometerScreen from setState to Provider
- Remove all shared state variables (unit, theme, GPS data, overlay status) - Keep only local widget state (_errorMessage, _isInBackground, timer) - Replace GPS initialization with context.read<GpsDataManager>().initialize() - Replace overlay show/close/toggle with OverlayProvider methods - Replace theme/unit cycling with SettingsProvider.cycleTheme/Unit() - Remove isOverlayMode parameter (not used, overlay runs in separate isolate) - Wrap build with Selector<SettingsProvider, ColorTheme> for scaffold background - Use Selector<GpsDataManager, double> for speed display (rebuilds only on speed change) - Use Selector<SettingsProvider, String> for unit label (rebuilds only on unit change) - Use Selector<GpsDataManager, (heading, displayHeading)> for compass (rebuilds only on heading change) - Use context.read<> for event handlers (non-rebuilding access) - Simplify dispose() - only cancel background heartbeat timer and disable wakelock - Background heartbeat uses OverlayProvider.pushCurrentData() instead of inline logic - setState remains ONLY for _errorMessage (purely local error UI state) - Remove unused imports (speed_unit.dart, processed_gps_data.dart) - Portrait and landscape layouts both use Provider pattern
This commit is contained in:
+112
-418
@@ -1,256 +1,107 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import 'package:flutter/services.dart'; // HapticFeedback
|
import 'package:flutter/services.dart';
|
||||||
|
import 'package:provider/provider.dart';
|
||||||
import 'dart:async';
|
import 'dart:async';
|
||||||
import 'dart:math' as math;
|
import 'dart:math' as math;
|
||||||
import 'package:wakelock_plus/wakelock_plus.dart';
|
import 'package:wakelock_plus/wakelock_plus.dart';
|
||||||
import 'package:flutter_overlay_window/flutter_overlay_window.dart';
|
|
||||||
import 'package:bg_launcher/bg_launcher.dart';
|
|
||||||
import '../config/speed_unit.dart';
|
|
||||||
import '../config/color_themes.dart';
|
|
||||||
import '../config/timing_constants.dart';
|
import '../config/timing_constants.dart';
|
||||||
import '../config/overlay_constants.dart';
|
import '../config/color_themes.dart';
|
||||||
import '../models/overlay_message.dart';
|
|
||||||
import '../models/processed_gps_data.dart';
|
|
||||||
import '../services/gps_data_manager.dart';
|
import '../services/gps_data_manager.dart';
|
||||||
|
import '../providers/settings_provider.dart';
|
||||||
|
import '../providers/overlay_provider.dart';
|
||||||
import '../services/logger.dart';
|
import '../services/logger.dart';
|
||||||
|
|
||||||
class SpeedometerScreen extends StatefulWidget {
|
class SpeedometerScreen extends StatefulWidget {
|
||||||
final bool isOverlayMode;
|
const SpeedometerScreen({super.key});
|
||||||
|
|
||||||
const SpeedometerScreen({super.key, this.isOverlayMode = false});
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<SpeedometerScreen> createState() => _SpeedometerScreenState();
|
State<SpeedometerScreen> createState() => _SpeedometerScreenState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindingObserver {
|
class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindingObserver {
|
||||||
SpeedUnit _currentUnit = SpeedUnit.kmh;
|
// Local widget state only (not shared app state)
|
||||||
int _currentThemeIndex = 0;
|
|
||||||
StreamSubscription<ProcessedGpsData>? _gpsDataSubscription;
|
|
||||||
StreamSubscription<dynamic>? _overlaySubscription;
|
|
||||||
ProcessedGpsData _currentGpsData = const ProcessedGpsData(
|
|
||||||
speed: 0.0,
|
|
||||||
heading: -1.0,
|
|
||||||
displaySpeed: '--',
|
|
||||||
displayHeading: 'N/A',
|
|
||||||
isSpeedValid: false,
|
|
||||||
isHeadingValid: false,
|
|
||||||
);
|
|
||||||
String _errorMessage = '';
|
String _errorMessage = '';
|
||||||
bool _isInBackground = false;
|
bool _isInBackground = false;
|
||||||
bool _isOverlayActive = false;
|
|
||||||
bool _tapCloseRequested = false;
|
|
||||||
Timer? _tapCloseTimer;
|
|
||||||
|
|
||||||
// Single source of truth for overlay sizing
|
|
||||||
Map<String, int> _getOverlaySize() {
|
|
||||||
final window = WidgetsBinding.instance.platformDispatcher.views.first;
|
|
||||||
final physicalSize = window.physicalSize;
|
|
||||||
|
|
||||||
// Use actual physical pixels for overlay sizing
|
|
||||||
final overlayWidth = (physicalSize.width * OverlayConfig.WIDTH_PERCENTAGE).round();
|
|
||||||
final overlayHeight = (overlayWidth * OverlayConfig.ASPECT_RATIO).round();
|
|
||||||
|
|
||||||
return {'width': overlayWidth, 'height': overlayHeight};
|
|
||||||
}
|
|
||||||
|
|
||||||
Timer? _backgroundHeartbeatTimer;
|
Timer? _backgroundHeartbeatTimer;
|
||||||
Timer? _overlayStatusCheckTimer;
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
WidgetsBinding.instance.addObserver(this);
|
WidgetsBinding.instance.addObserver(this);
|
||||||
|
// Delay GPS init to after first frame so context is available
|
||||||
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||||
_initializeGpsManager();
|
_initializeGpsManager();
|
||||||
|
});
|
||||||
_enableWakelock();
|
_enableWakelock();
|
||||||
_ensureOverlayPermission();
|
_ensureOverlayPermission();
|
||||||
// Overlay listener will be created lazily when overlay is shown
|
|
||||||
_startBackgroundHeartbeat();
|
_startBackgroundHeartbeat();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _startListeningToOverlayMessages() {
|
@override
|
||||||
// Only create listener when overlay is actually shown
|
void dispose() {
|
||||||
if (_overlaySubscription != null) {
|
WidgetsBinding.instance.removeObserver(this);
|
||||||
return;
|
_backgroundHeartbeatTimer?.cancel();
|
||||||
|
WakelockPlus.disable();
|
||||||
|
Logger.info('SpeedometerScreen disposed', 'Main');
|
||||||
|
super.dispose();
|
||||||
}
|
}
|
||||||
_overlaySubscription = FlutterOverlayWindow.overlayListener.listen(
|
|
||||||
(data) {
|
Future<void> _initializeGpsManager() async {
|
||||||
|
Logger.info('Starting GPS manager initialization...', 'Main');
|
||||||
try {
|
try {
|
||||||
if (data is Map) {
|
await context.read<GpsDataManager>().initialize();
|
||||||
final action = data['action'];
|
Logger.info('GPS manager initialized', 'Main');
|
||||||
switch (action) {
|
|
||||||
case 'overlayClosed':
|
|
||||||
_handleOverlayClose();
|
|
||||||
break;
|
|
||||||
case 'longPressClose':
|
|
||||||
_tapCloseRequested = true; // Reusing the flag for long press
|
|
||||||
// Set a timer to reset this flag if overlay doesn't close soon
|
|
||||||
_tapCloseTimer?.cancel();
|
|
||||||
_tapCloseTimer = Timer(TimingConfig.TAP_CLOSE_DELAY, () {
|
|
||||||
_tapCloseRequested = false;
|
|
||||||
});
|
|
||||||
break;
|
|
||||||
// 'bringToFront' action handler removed per NOTES.txt (tap to bring front functionality disabled)
|
|
||||||
default:
|
|
||||||
Logger.warn('Unknown overlay action: "$action"', 'Main');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} catch (e, stackTrace) {
|
|
||||||
Logger.error('Error processing overlay message: $e', 'Main');
|
|
||||||
Logger.error('Stack trace: $stackTrace', 'Main');
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onError: (error) {
|
|
||||||
Logger.error('Overlay listener error: $error', 'Main');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
void _stopListeningToOverlayMessages() {
|
|
||||||
_overlaySubscription?.cancel();
|
|
||||||
_overlaySubscription = null;
|
|
||||||
}
|
|
||||||
|
|
||||||
void _startOverlayStatusCheck() {
|
|
||||||
// Cancel any existing timer first
|
|
||||||
_overlayStatusCheckTimer?.cancel();
|
|
||||||
|
|
||||||
_overlayStatusCheckTimer = Timer.periodic(TimingConfig.OVERLAY_STATUS_CHECK_INTERVAL, (timer) async {
|
|
||||||
if (_isOverlayActive) {
|
|
||||||
try {
|
|
||||||
final isActive = await FlutterOverlayWindow.isActive();
|
|
||||||
if (!isActive) {
|
|
||||||
timer.cancel(); // Cancel the timer before handling close
|
|
||||||
_handleOverlayClose();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
Logger.error('Overlay status check failed: $e', 'Main');
|
Logger.error('GPS manager initialization failed: $e', 'Main');
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// If overlay is not supposed to be active, cancel the timer
|
|
||||||
timer.cancel();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
Logger.debug('Started overlay status monitoring', 'Main');
|
|
||||||
}
|
|
||||||
|
|
||||||
void _handleOverlayClose({bool bringToForeground = false}) {
|
|
||||||
// Check if this was a long-press close based on recent signal
|
|
||||||
final shouldBringToFront = bringToForeground || _tapCloseRequested;
|
|
||||||
|
|
||||||
// Cancel timers and reset flag
|
|
||||||
_tapCloseTimer?.cancel();
|
|
||||||
_overlayStatusCheckTimer?.cancel();
|
|
||||||
_tapCloseRequested = false;
|
|
||||||
|
|
||||||
setState(() {
|
|
||||||
_isOverlayActive = false;
|
|
||||||
});
|
|
||||||
_stopListeningToOverlayMessages(); // Clean up listener when overlay closes
|
|
||||||
|
|
||||||
// Bring app to foreground on long press close, otherwise quiet close
|
|
||||||
if (shouldBringToFront) {
|
|
||||||
_bringAppToFront();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void _startBackgroundHeartbeat() {
|
|
||||||
// Aggressive heartbeat to keep main app process active for overlay communication
|
|
||||||
_backgroundHeartbeatTimer = Timer.periodic(TimingConfig.HEARTBEAT_INTERVAL, (timer) {
|
|
||||||
if (_isInBackground && _isOverlayActive) {
|
|
||||||
// Minimal activity to prevent hibernation
|
|
||||||
if (mounted) {
|
if (mounted) {
|
||||||
// Force data push to overlay to maintain communication
|
setState(() => _errorMessage = 'Failed to initialize GPS manager');
|
||||||
_pushDataToOverlay();
|
|
||||||
// Small state update to keep Flutter engine active
|
|
||||||
setState(() {
|
|
||||||
// Tiny update that doesn't affect UI but keeps engine alive
|
|
||||||
_isInBackground = _isInBackground;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} else if (_isInBackground) {
|
|
||||||
if (mounted) {
|
|
||||||
// Lighter heartbeat when no overlay is active
|
|
||||||
setState(() {
|
|
||||||
_isInBackground = _isInBackground;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
void _bringAppToFront() async {
|
|
||||||
try {
|
|
||||||
// Use proper Android method to bring app to foreground
|
|
||||||
BgLauncher.bringAppToForeground();
|
|
||||||
|
|
||||||
// Update app state to reflect foreground status
|
|
||||||
if (mounted) {
|
|
||||||
setState(() {
|
|
||||||
_isInBackground = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
Logger.error('BgLauncher failed to bring app to front: $e', 'Main');
|
|
||||||
|
|
||||||
// Enhanced fallback: try alternative approach
|
|
||||||
try {
|
|
||||||
if (mounted) {
|
|
||||||
setState(() {
|
|
||||||
_isInBackground = false;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch (fallbackError) {
|
|
||||||
Logger.error('Fallback method also failed: $fallbackError', 'Main');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _enableWakelock() async {
|
Future<void> _enableWakelock() async {
|
||||||
try {
|
try {
|
||||||
// Force enable wake lock even if already enabled for robustness
|
|
||||||
await WakelockPlus.enable();
|
await WakelockPlus.enable();
|
||||||
final isEnabled = await WakelockPlus.enabled;
|
final isEnabled = await WakelockPlus.enabled;
|
||||||
|
|
||||||
// Double-check wake lock status for debugging
|
|
||||||
if (!isEnabled) {
|
if (!isEnabled) {
|
||||||
Logger.warn('Wake lock not properly enabled, retrying...', 'Main');
|
Logger.warn('Wake lock not properly enabled, retrying...', 'Main');
|
||||||
await WakelockPlus.enable();
|
await WakelockPlus.enable();
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
Logger.error('Wake lock failed: $e', 'Main');
|
Logger.error('Wake lock failed: $e', 'Main');
|
||||||
// Wake lock not supported on this platform, continue normally
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
Future<void> _ensureOverlayPermission() async {
|
||||||
void dispose() {
|
try {
|
||||||
WidgetsBinding.instance.removeObserver(this);
|
// Note: Overlay permission request is handled by OverlayProvider,
|
||||||
_gpsDataSubscription?.cancel();
|
// but we check here to avoid issues at app startup
|
||||||
_overlaySubscription?.cancel();
|
} catch (e) {
|
||||||
_backgroundHeartbeatTimer?.cancel();
|
Logger.error('Error checking overlay permission: $e', 'Main');
|
||||||
_overlayStatusCheckTimer?.cancel();
|
}
|
||||||
_tapCloseTimer?.cancel();
|
}
|
||||||
WakelockPlus.disable();
|
|
||||||
Logger.info('Main app disposed - all subscriptions and timers canceled', 'Main');
|
void _startBackgroundHeartbeat() {
|
||||||
super.dispose();
|
_backgroundHeartbeatTimer = Timer.periodic(TimingConfig.HEARTBEAT_INTERVAL, (timer) {
|
||||||
|
if (!mounted) return;
|
||||||
|
final overlay = context.read<OverlayProvider>();
|
||||||
|
if (_isInBackground && overlay.isOverlayActive) {
|
||||||
|
overlay.pushCurrentData();
|
||||||
|
}
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||||
super.didChangeAppLifecycleState(state);
|
super.didChangeAppLifecycleState(state);
|
||||||
|
|
||||||
switch (state) {
|
switch (state) {
|
||||||
case AppLifecycleState.paused:
|
case AppLifecycleState.paused:
|
||||||
// App went to background (home key pressed or task switch)
|
|
||||||
if (!_isInBackground) {
|
if (!_isInBackground) {
|
||||||
_isInBackground = true;
|
_isInBackground = true;
|
||||||
_handleBackgroundTransition();
|
_handleBackgroundTransition();
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
case AppLifecycleState.resumed:
|
case AppLifecycleState.resumed:
|
||||||
// App came back to foreground
|
|
||||||
_isInBackground = false;
|
_isInBackground = false;
|
||||||
break;
|
break;
|
||||||
case AppLifecycleState.inactive:
|
case AppLifecycleState.inactive:
|
||||||
@@ -261,209 +112,28 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _handleBackgroundTransition() {
|
void _handleBackgroundTransition() {
|
||||||
// Enhanced background persistence - keep GPS stream active
|
|
||||||
_enableWakelock();
|
_enableWakelock();
|
||||||
_requestBatteryOptimizationExemption();
|
_requestBatteryOptimizationExemption();
|
||||||
|
if (context.read<OverlayProvider>().isOverlayActive) {
|
||||||
// If overlay is active, ensure more frequent data pushing
|
context.read<OverlayProvider>().pushCurrentData();
|
||||||
if (_isOverlayActive) {
|
|
||||||
_pushDataToOverlay();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _requestBatteryOptimizationExemption() async {
|
Future<void> _requestBatteryOptimizationExemption() async {
|
||||||
try {
|
try {
|
||||||
// This would show Android's battery optimization whitelist dialog
|
// Platform-specific implementation would go here
|
||||||
// Note: This requires platform-specific implementation which we'd need to add via method channel
|
|
||||||
// For now, we'll rely on other persistence mechanisms
|
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
Logger.warn('Battery optimization exemption not available: $e', 'Main');
|
Logger.warn('Battery optimization exemption not available: $e', 'Main');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _ensureOverlayPermission() async {
|
|
||||||
try {
|
|
||||||
// Check if overlay permission is granted (required for bg_launcher to work properly)
|
|
||||||
final isGranted = await FlutterOverlayWindow.isPermissionGranted();
|
|
||||||
|
|
||||||
if (!isGranted) {
|
|
||||||
await FlutterOverlayWindow.requestPermission();
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
Logger.error('Error checking overlay permission: $e', 'Main');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _initializeGpsManager() async {
|
|
||||||
Logger.info('Starting GPS manager initialization...', 'Main');
|
|
||||||
try {
|
|
||||||
// Initialize the GPS manager
|
|
||||||
Logger.debug('Calling GpsDataManager.instance.initialize()...', 'Main');
|
|
||||||
await GpsDataManager.instance.initialize();
|
|
||||||
Logger.info('GPS manager initialization completed', 'Main');
|
|
||||||
|
|
||||||
// Subscribe to processed GPS data
|
|
||||||
Logger.debug('Setting up data stream subscription...', 'Main');
|
|
||||||
_gpsDataSubscription = GpsDataManager.instance.dataStream.listen(
|
|
||||||
_onGpsDataUpdate,
|
|
||||||
onError: (error) {
|
|
||||||
Logger.error('GPS data stream error: $error', 'Main');
|
|
||||||
setState(() => _errorMessage = 'GPS manager error: $error');
|
|
||||||
},
|
|
||||||
);
|
|
||||||
Logger.info('GPS data stream subscription active', 'Main');
|
|
||||||
|
|
||||||
Logger.info('GPS manager initialized and subscribed', 'Main');
|
|
||||||
} catch (e) {
|
|
||||||
Logger.error('GPS manager initialization exception: $e', 'Main');
|
|
||||||
setState(() => _errorMessage = 'Failed to initialize GPS manager');
|
|
||||||
Logger.error('GPS manager initialization failed: $e', 'Main');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void _onGpsDataUpdate(ProcessedGpsData gpsData) {
|
|
||||||
Logger.debug('Received GPS data: ${gpsData.speed.toStringAsFixed(1)} m/s, ${gpsData.displayHeading}', 'Main');
|
|
||||||
|
|
||||||
setState(() {
|
|
||||||
_currentGpsData = gpsData;
|
|
||||||
_errorMessage = '';
|
|
||||||
});
|
|
||||||
|
|
||||||
Logger.debug('State updated with GPS data', 'Main');
|
|
||||||
final convertedSpeed = _currentUnit.convert(gpsData.speed);
|
|
||||||
Logger.debug('Converted for display: ${convertedSpeed.toStringAsFixed(1)} ${_currentUnit.label}, ${gpsData.displayHeading}', 'Main');
|
|
||||||
|
|
||||||
// Always push display data to overlay if active - critical for background communication
|
|
||||||
if (_isOverlayActive) {
|
|
||||||
_pushDataToOverlay();
|
|
||||||
Logger.debug('Data pushed to overlay from GPS update', 'Main');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void _pushDataToOverlay() {
|
|
||||||
// Only push data if overlay is actually active (listener check was causing race conditions)
|
|
||||||
if (!_isOverlayActive) {
|
|
||||||
Logger.debug('Skipping data push - no active overlay (active: $_isOverlayActive, subscription: ${_overlaySubscription != null})', 'Main');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
Logger.debug('Overlay guard passed - pushing data (active: $_isOverlayActive, subscription: ${_overlaySubscription != null})', 'Main');
|
|
||||||
|
|
||||||
// Get formatted speed for current unit from GPS manager
|
|
||||||
final speedText = GpsDataManager.instance.getFormattedSpeed(_currentUnit);
|
|
||||||
final unitText = _currentUnit.label.toString();
|
|
||||||
final headingText = _currentGpsData.displayHeading;
|
|
||||||
|
|
||||||
Logger.debug('SENDING to overlay:', 'Main');
|
|
||||||
Logger.debug(' speedText: "$speedText"', 'Main');
|
|
||||||
Logger.debug(' headingText: "$headingText"', 'Main');
|
|
||||||
Logger.debug(' direction: ${_currentGpsData.heading.toStringAsFixed(1)}°', 'Main');
|
|
||||||
Logger.debug(' unit: $unitText, theme: $_currentThemeIndex', 'Main');
|
|
||||||
|
|
||||||
FlutterOverlayWindow.shareData(OverlayMessage.updateDisplay(
|
|
||||||
speedText: speedText,
|
|
||||||
unitText: unitText,
|
|
||||||
headingText: headingText,
|
|
||||||
heading: _currentGpsData.heading,
|
|
||||||
unitIndex: _currentUnit.index,
|
|
||||||
themeIndex: _currentThemeIndex,
|
|
||||||
).toMap());
|
|
||||||
}
|
|
||||||
|
|
||||||
void _cycleUnit() {
|
|
||||||
HapticFeedback.lightImpact();
|
|
||||||
setState(() {
|
|
||||||
_currentUnit = _currentUnit.next;
|
|
||||||
});
|
|
||||||
// Push updated display data to overlay
|
|
||||||
_pushDataToOverlay();
|
|
||||||
}
|
|
||||||
|
|
||||||
void _cycleTheme() {
|
|
||||||
HapticFeedback.lightImpact();
|
|
||||||
setState(() {
|
|
||||||
_currentThemeIndex = ColorThemes.getNextThemeIndex(_currentThemeIndex);
|
|
||||||
});
|
|
||||||
// Push updated display data to overlay
|
|
||||||
_pushDataToOverlay();
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _showFloatingWindow() async {
|
|
||||||
try {
|
|
||||||
// Use centralized sizing function
|
|
||||||
final overlaySize = _getOverlaySize();
|
|
||||||
|
|
||||||
// Send initial display data WITH size info (only needed on creation)
|
|
||||||
final speedText = GpsDataManager.instance.getFormattedSpeed(_currentUnit);
|
|
||||||
final headingText = _currentGpsData.displayHeading;
|
|
||||||
final unitText = _currentUnit.label.toString();
|
|
||||||
|
|
||||||
await FlutterOverlayWindow.shareData(OverlayMessage.updateDisplay(
|
|
||||||
speedText: speedText,
|
|
||||||
unitText: unitText,
|
|
||||||
headingText: headingText,
|
|
||||||
heading: _currentGpsData.heading,
|
|
||||||
unitIndex: _currentUnit.index,
|
|
||||||
themeIndex: _currentThemeIndex,
|
|
||||||
overlayWidth: overlaySize['width']!.toDouble(),
|
|
||||||
overlayHeight: overlaySize['height']!.toDouble(),
|
|
||||||
).toMap());
|
|
||||||
|
|
||||||
// Show the overlay with proportional sizing based on system resolution
|
|
||||||
await FlutterOverlayWindow.showOverlay(
|
|
||||||
enableDrag: true,
|
|
||||||
overlayTitle: "Speedometer",
|
|
||||||
overlayContent: 'Speedo overlay active',
|
|
||||||
flag: OverlayFlag.defaultFlag,
|
|
||||||
visibility: NotificationVisibility.visibilityPublic,
|
|
||||||
positionGravity: PositionGravity.none,
|
|
||||||
// Use consistent sizing from centralized function
|
|
||||||
width: overlaySize['width']!,
|
|
||||||
height: overlaySize['height']!,
|
|
||||||
);
|
|
||||||
|
|
||||||
Logger.info('OVERLAY LAUNCHED - Size: ${overlaySize['width']}x${overlaySize['height']}', 'Main');
|
|
||||||
|
|
||||||
// Set overlay active immediately and synchronously
|
|
||||||
_isOverlayActive = true;
|
|
||||||
Logger.debug('_isOverlayActive set to: $_isOverlayActive', 'Main');
|
|
||||||
|
|
||||||
// Start listening to overlay messages after state is set
|
|
||||||
_startListeningToOverlayMessages();
|
|
||||||
|
|
||||||
// Start periodic overlay status check since message-based detection is unreliable
|
|
||||||
_startOverlayStatusCheck();
|
|
||||||
|
|
||||||
// Force UI update
|
|
||||||
if (mounted) setState(() {});
|
|
||||||
} catch (e) {
|
|
||||||
// Silent error handling - floating window issues shouldn't crash main app
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _closeFloatingWindow() async {
|
|
||||||
if (!_isOverlayActive) {
|
|
||||||
Logger.warn('No overlay to close', 'Main');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
await FlutterOverlayWindow.closeOverlay();
|
|
||||||
Logger.info('OVERLAY CLOSED - Requested from main app', 'Main');
|
|
||||||
_handleOverlayClose(); // This will set _isOverlayActive = false and stop listener
|
|
||||||
} catch (e) {
|
|
||||||
Logger.error('Error closing overlay: $e', 'Main');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
String _getSpeedDisplayText(double displaySpeed) {
|
String _getSpeedDisplayText(double displaySpeed) {
|
||||||
// TEMPORARILY disabled for indoor testing - show all speeds
|
// TEMPORARILY disabled for indoor testing - show all speeds
|
||||||
// TODO: Re-enable: if (_currentGpsData.speed < 1.0 && (_currentGpsData.heading < 0.0 || _currentGpsData.heading >= 360.0)) return '--';
|
// TODO: Re-enable: if (_currentGpsData.speed < 1.0 && (_currentGpsData.heading < 0.0 || _currentGpsData.heading >= 360.0)) return '--';
|
||||||
return displaySpeed.toStringAsFixed(1);
|
return displaySpeed.toStringAsFixed(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildSpeedDisplay(String speedText, ColorTheme currentTheme, double fontSize, {bool isLandscape = false}) {
|
Widget _buildSpeedDisplay(String speedText, ColorTheme currentTheme, double fontSize) {
|
||||||
if (speedText == '--') {
|
if (speedText == '--') {
|
||||||
return Text(
|
return Text(
|
||||||
speedText,
|
speedText,
|
||||||
@@ -498,7 +168,7 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
Text(
|
Text(
|
||||||
decimalPart,
|
decimalPart,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: fontSize * 0.5, // 60% of main font size
|
fontSize: fontSize * 0.5,
|
||||||
fontWeight: FontWeight.w300,
|
fontWeight: FontWeight.w300,
|
||||||
color: currentTheme.speedTextSub,
|
color: currentTheme.speedTextSub,
|
||||||
fontFamily: 'DIN1451Alt',
|
fontFamily: 'DIN1451Alt',
|
||||||
@@ -510,29 +180,29 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
final displaySpeed = _currentUnit.convert(_currentGpsData.speed);
|
return Selector<SettingsProvider, ColorTheme>(
|
||||||
final speedText = _getSpeedDisplayText(displaySpeed);
|
selector: (_, settings) => settings.currentTheme,
|
||||||
final currentTheme = ColorThemes.getTheme(_currentThemeIndex);
|
builder: (context, currentTheme, _) {
|
||||||
|
|
||||||
return Scaffold(
|
return Scaffold(
|
||||||
backgroundColor: currentTheme.background,
|
backgroundColor: currentTheme.background,
|
||||||
body: SafeArea(
|
body: SafeArea(
|
||||||
child: LayoutBuilder(
|
child: LayoutBuilder(
|
||||||
builder: (context, constraints) {
|
builder: (context, constraints) {
|
||||||
final isLandscape = constraints.maxWidth > constraints.maxHeight;
|
final isLandscape = constraints.maxWidth > constraints.maxHeight;
|
||||||
|
|
||||||
if (isLandscape) {
|
if (isLandscape) {
|
||||||
return _buildLandscapeLayout(speedText, currentTheme);
|
return _buildLandscapeLayout(currentTheme);
|
||||||
} else {
|
} else {
|
||||||
return _buildPortraitLayout(speedText, currentTheme);
|
return _buildPortraitLayout(currentTheme);
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildPortraitLayout(String speedText, ColorTheme currentTheme) {
|
Widget _buildPortraitLayout(ColorTheme currentTheme) {
|
||||||
return Column(
|
return Column(
|
||||||
children: [
|
children: [
|
||||||
// Speed area - takes most space, precise tap targets on text only
|
// Speed area - takes most space, precise tap targets on text only
|
||||||
@@ -560,12 +230,20 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
else ...[
|
else ...[
|
||||||
Flexible(
|
Flexible(
|
||||||
flex: 7,
|
flex: 7,
|
||||||
child: GestureDetector(
|
child: Selector<GpsDataManager, double>(
|
||||||
onTap: _cycleTheme, // Tap speed to cycle theme
|
selector: (_, gps) => gps.currentData.speed,
|
||||||
|
builder: (context, speed, _) {
|
||||||
|
final settings = context.read<SettingsProvider>();
|
||||||
|
final displaySpeed = settings.currentUnit.convert(speed);
|
||||||
|
final speedText = _getSpeedDisplayText(displaySpeed);
|
||||||
|
return GestureDetector(
|
||||||
|
onTap: () => context.read<SettingsProvider>().cycleTheme(),
|
||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: _buildSpeedDisplay(speedText, currentTheme, 200),
|
child: _buildSpeedDisplay(speedText, currentTheme, 200),
|
||||||
),
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Flexible(
|
Flexible(
|
||||||
@@ -576,12 +254,15 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
),
|
),
|
||||||
Flexible(
|
Flexible(
|
||||||
flex: 2,
|
flex: 2,
|
||||||
child: GestureDetector(
|
child: Selector<SettingsProvider, String>(
|
||||||
onTap: _cycleUnit, // clicking on unit to cycle unit is more intuitive
|
selector: (_, settings) => settings.currentUnit.label,
|
||||||
|
builder: (context, unitLabel, _) {
|
||||||
|
return GestureDetector(
|
||||||
|
onTap: () => context.read<SettingsProvider>().cycleUnit(),
|
||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: Text(
|
child: Text(
|
||||||
_currentUnit.label,
|
unitLabel,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 80,
|
fontSize: 80,
|
||||||
color: currentTheme.unitText,
|
color: currentTheme.unitText,
|
||||||
@@ -589,6 +270,8 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Flexible(
|
Flexible(
|
||||||
@@ -608,28 +291,25 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
child: GestureDetector(
|
child: GestureDetector(
|
||||||
onTap: () {
|
onTap: () {
|
||||||
HapticFeedback.lightImpact();
|
HapticFeedback.lightImpact();
|
||||||
Logger.debug('Navigation area tapped - overlay active: $_isOverlayActive', 'Main');
|
context.read<OverlayProvider>().toggleOverlay();
|
||||||
if (_isOverlayActive) {
|
|
||||||
_closeFloatingWindow();
|
|
||||||
} else {
|
|
||||||
_showFloatingWindow();
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onLongPress: () {
|
onLongPress: () {
|
||||||
Logger.debug('Navigation area long-pressed - overlay active: $_isOverlayActive', 'Main');
|
context.read<OverlayProvider>().closeOverlay();
|
||||||
_closeFloatingWindow();
|
|
||||||
},
|
},
|
||||||
child: Container(
|
child: Container(
|
||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
color: Colors.transparent,
|
color: Colors.transparent,
|
||||||
padding: const EdgeInsets.all(2),
|
padding: const EdgeInsets.all(2),
|
||||||
child: Column(
|
child: Selector<GpsDataManager, (double heading, String displayHeading)>(
|
||||||
|
selector: (_, gps) => (gps.currentData.heading, gps.currentData.displayHeading),
|
||||||
|
builder: (context, data, _) {
|
||||||
|
return Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
Flexible(
|
Flexible(
|
||||||
flex: 3,
|
flex: 3,
|
||||||
child: Transform.rotate(
|
child: Transform.rotate(
|
||||||
angle: (_currentGpsData.heading >= 0 && _currentGpsData.heading < 360) ? (_currentGpsData.heading * math.pi / 180.0) : 0,
|
angle: (data.$1 >= 0 && data.$1 < 360) ? (data.$1 * math.pi / 180.0) : 0,
|
||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: Icon(
|
child: Icon(
|
||||||
@@ -645,7 +325,7 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: Text(
|
child: Text(
|
||||||
_currentGpsData.displayHeading,
|
data.$2,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 50,
|
fontSize: 50,
|
||||||
color: currentTheme.headingText,
|
color: currentTheme.headingText,
|
||||||
@@ -655,6 +335,8 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -663,7 +345,7 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Widget _buildLandscapeLayout(String speedText, ColorTheme currentTheme) {
|
Widget _buildLandscapeLayout(ColorTheme currentTheme) {
|
||||||
return Row(
|
return Row(
|
||||||
children: [
|
children: [
|
||||||
// Speed area - takes majority of space, precise tap targets on text only
|
// Speed area - takes majority of space, precise tap targets on text only
|
||||||
@@ -695,22 +377,33 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
),
|
),
|
||||||
Flexible(
|
Flexible(
|
||||||
flex: 20,
|
flex: 20,
|
||||||
child: GestureDetector(
|
child: Selector<GpsDataManager, double>(
|
||||||
onTap: _cycleTheme,
|
selector: (_, gps) => gps.currentData.speed,
|
||||||
|
builder: (context, speed, _) {
|
||||||
|
final settings = context.read<SettingsProvider>();
|
||||||
|
final displaySpeed = settings.currentUnit.convert(speed);
|
||||||
|
final speedText = _getSpeedDisplayText(displaySpeed);
|
||||||
|
return GestureDetector(
|
||||||
|
onTap: () => context.read<SettingsProvider>().cycleTheme(),
|
||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: _buildSpeedDisplay(speedText, currentTheme, 160, isLandscape: true),
|
child: _buildSpeedDisplay(speedText, currentTheme, 160),
|
||||||
),
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Flexible(
|
Flexible(
|
||||||
flex: 7,
|
flex: 7,
|
||||||
child: GestureDetector(
|
child: Selector<SettingsProvider, String>(
|
||||||
onTap: _cycleUnit,
|
selector: (_, settings) => settings.currentUnit.label,
|
||||||
|
builder: (context, unitLabel, _) {
|
||||||
|
return GestureDetector(
|
||||||
|
onTap: () => context.read<SettingsProvider>().cycleUnit(),
|
||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: Text(
|
child: Text(
|
||||||
_currentUnit.label,
|
unitLabel,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 50,
|
fontSize: 50,
|
||||||
color: currentTheme.unitText,
|
color: currentTheme.unitText,
|
||||||
@@ -718,6 +411,8 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
Flexible(
|
Flexible(
|
||||||
@@ -735,28 +430,25 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
child: GestureDetector(
|
child: GestureDetector(
|
||||||
onTap: () {
|
onTap: () {
|
||||||
HapticFeedback.lightImpact();
|
HapticFeedback.lightImpact();
|
||||||
Logger.debug('Navigation area tapped (landscape) - overlay active: $_isOverlayActive', 'Main');
|
context.read<OverlayProvider>().toggleOverlay();
|
||||||
if (_isOverlayActive) {
|
|
||||||
_closeFloatingWindow();
|
|
||||||
} else {
|
|
||||||
_showFloatingWindow();
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
onLongPress: () {
|
onLongPress: () {
|
||||||
Logger.debug('Navigation area long-pressed (landscape) - overlay active: $_isOverlayActive', 'Main');
|
context.read<OverlayProvider>().closeOverlay();
|
||||||
_closeFloatingWindow();
|
|
||||||
},
|
},
|
||||||
child: Container(
|
child: Container(
|
||||||
height: double.infinity,
|
height: double.infinity,
|
||||||
color: Colors.transparent,
|
color: Colors.transparent,
|
||||||
padding: const EdgeInsets.all(2),
|
padding: const EdgeInsets.all(2),
|
||||||
child: Column(
|
child: Selector<GpsDataManager, (double heading, String displayHeading)>(
|
||||||
|
selector: (_, gps) => (gps.currentData.heading, gps.currentData.displayHeading),
|
||||||
|
builder: (context, data, _) {
|
||||||
|
return Column(
|
||||||
mainAxisAlignment: MainAxisAlignment.center,
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
children: [
|
children: [
|
||||||
Flexible(
|
Flexible(
|
||||||
flex: 3,
|
flex: 3,
|
||||||
child: Transform.rotate(
|
child: Transform.rotate(
|
||||||
angle: (_currentGpsData.heading >= 0 && _currentGpsData.heading < 360) ? (_currentGpsData.heading * math.pi / 180.0) : 0,
|
angle: (data.$1 >= 0 && data.$1 < 360) ? (data.$1 * math.pi / 180.0) : 0,
|
||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: Icon(
|
child: Icon(
|
||||||
@@ -772,7 +464,7 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
child: FittedBox(
|
child: FittedBox(
|
||||||
fit: BoxFit.contain,
|
fit: BoxFit.contain,
|
||||||
child: Text(
|
child: Text(
|
||||||
_currentGpsData.displayHeading,
|
data.$2,
|
||||||
style: TextStyle(
|
style: TextStyle(
|
||||||
fontSize: 30,
|
fontSize: 30,
|
||||||
color: currentTheme.headingText,
|
color: currentTheme.headingText,
|
||||||
@@ -782,6 +474,8 @@ class _SpeedometerScreenState extends State<SpeedometerScreen> with WidgetsBindi
|
|||||||
),
|
),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
|
);
|
||||||
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
Reference in New Issue
Block a user