import 'dart:async'; import 'dart:collection'; import 'dart:convert'; import 'dart:io' show Platform; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:gal/gal.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:share_plus/share_plus.dart'; import 'package:wakelock_plus/wakelock_plus.dart'; import 'local_server.dart'; /// SkyContour native shell. /// /// The whole app is the React + WASM web build bundled under assets/web/ /// (see scripts/build_web.sh). This shell: /// * serves that build over http://localhost (a secure context, so the /// WebView's camera, motion sensors and geolocation work; see /// local_server.dart) and brings server and page back after the OS /// suspended the app or killed the WebView's process, /// * asks for the OS camera and location permissions and grants them to the /// WebView, /// * saves export files (Android: Downloads, iOS: Files › SkyContour) and /// opens the system share sheet (a WebView can do neither by itself), /// * keeps the screen awake during capture and gives haptic ticks, /// * routes the Android back button into the web app's navigation, /// * shows a native tab bar (iOS) / navigation bar (Android) on the main /// screens; the web app reports its screen via the `route` handler. void main() { WidgetsFlutterBinding.ensureInitialized(); // Capture only works upright (docs/SPEC.md). SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]); // Light icons on the dark UI; bars drawn over the app's own background. SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( statusBarColor: Colors.transparent, statusBarIconBrightness: Brightness.light, statusBarBrightness: Brightness.dark, systemNavigationBarColor: Color(0xFF04060B), systemNavigationBarIconBrightness: Brightness.light, )); runApp(const SfzenithApp()); } class SfzenithApp extends StatelessWidget { const SfzenithApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: 'SkyContour', debugShowCheckedModeBanner: false, theme: ThemeData.dark(useMaterial3: true).copyWith( scaffoldBackgroundColor: const Color(0xFF04060B), ), home: const WebShell(), ); } } /// A file handed over from the web app: {name, mime, base64}. class _WebFile { _WebFile(this.name, this.mime, this.bytes); final String name; final String mime; final Uint8List bytes; static List<_WebFile> parse(List args) { final list = args.isNotEmpty && args[0] is List ? args[0] as List : const []; return list.whereType().map((m) { final name = (m['name'] ?? 'file').toString(); final mime = (m['mime'] ?? 'application/octet-stream').toString(); return _WebFile(name, mime, base64Decode((m['base64'] ?? '').toString())); }).toList(); } } class WebShell extends StatefulWidget { const WebShell({super.key}); @override State createState() => _WebShellState(); } class _WebShellState extends State with WidgetsBindingObserver { static const _files = MethodChannel('sfzenith/files'); static const _location = MethodChannel('sfzenith/location'); final LocalServer _server = LocalServer(); InAppWebViewController? _controller; bool _ready = false; String? _error; /// A new key builds a fresh WebView (after its content process died). Key _webKey = UniqueKey(); bool _recovering = false; int _loadRetries = 0; /// Watchdog: the page reports its first screen through the `route` handler. /// No report within [_readyTimeout] → fresh WebView; after /// [_maxWatchdogRestarts] in a row the error screen with Try again shows. static const _readyTimeout = Duration(seconds: 6); static const _maxWatchdogRestarts = 3; bool _pageReady = false; Timer? _readyTimer; int _watchdogRestarts = 0; /// After a long time in the background start from a fresh page anyway: /// iOS often leaves a WebView behind that no longer draws. static const _staleAfter = Duration(minutes: 30); DateTime? _backgroundSince; /// Selected tab while the bar is shown; null = hidden (survey flow, welcome). int? _tab; /// Tab labels and writing direction in the web app's language. Map _tabLabels = const {}; bool _rtl = false; @override void initState() { super.initState(); WidgetsBinding.instance.addObserver(this); _boot(); } Future _boot() async { if (mounted) setState(() => _error = null); try { // Ask up front: getUserMedia/geolocation inside the WebView only work // once the app itself holds the OS permissions. await [Permission.camera, Permission.locationWhenInUse].request(); await _server.start(); if (mounted) setState(() => _ready = true); } catch (e) { if (mounted) setState(() => _error = 'SkyContour could not start.\n\n$e'); } } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _readyTimer?.cancel(); _server.stop(); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.paused || state == AppLifecycleState.hidden) { _backgroundSince ??= DateTime.now(); } else if (state == AppLifecycleState.resumed) { final since = _backgroundSince; _backgroundSince = null; if (!_ready) return; final stale = since != null && DateTime.now().difference(since) > _staleAfter; // Give the WebView a moment to come back to the screen before probing it. Future.delayed(const Duration(milliseconds: 600), () => _recover(forceNewWebView: stale)); } } /// Back from the background: iOS may have taken the server's socket and /// killed (or frozen) the page's process while the app was suspended. Future _recover({bool forceNewWebView = false}) async { if (_recovering || !mounted) return; _recovering = true; try { await _server.ensureRunning(); if (forceNewWebView || !await _pageAlive()) _newWebView(); if (mounted && _error != null) setState(() => _error = null); } catch (e) { if (mounted) setState(() => _error = 'SkyContour could not start.\n\n$e'); } finally { _recovering = false; } } /// Alive = the page runs script AND draws: it answers after an animation /// frame and has content. A WebView that lost its renderer never answers. Future _pageAlive() async { final c = _controller; if (c == null || !_pageReady) return false; try { final res = await c .callAsyncJavaScript( functionBody: "return await new Promise((resolve) => requestAnimationFrame(() => " "resolve((document.getElementById('root') || {}).childElementCount || 0)));", ) .timeout(const Duration(seconds: 3)); final n = res?.value; return res?.error == null && n is num && n > 0; } catch (_) { return false; } } void _newWebView() { if (!mounted) return; setState(() { _controller = null; _pageReady = false; _webKey = UniqueKey(); }); } /// Started with every WebView: no first screen in time → start a fresh one. void _armWatchdog() { _readyTimer?.cancel(); _readyTimer = Timer(_readyTimeout, () { if (!mounted || _pageReady || _error != null) return; if (_watchdogRestarts >= _maxWatchdogRestarts) { setState(() => _error = 'SkyContour could not load its screen.'); return; } _watchdogRestarts++; _recover(forceNewWebView: true); }); } /// A tap on the native tab bar must change the page; if the page is dead, restart it. Future _probeAfterTap() async { await Future.delayed(const Duration(milliseconds: 300)); if (mounted && _ready && !await _pageAlive()) _recover(forceNewWebView: true); } /// The page itself failed to load (server not answering): bind again, retry a few times. void _onMainFrameError() { if (_loadRetries >= 3) return; _loadRetries++; Future.delayed(Duration(milliseconds: 400 * _loadRetries), () => _recover(forceNewWebView: true)); } Future _saveOne(_WebFile f) async { final args = {'name': f.name, 'mime': f.mime, 'bytes': f.bytes}; try { return await _files.invokeMethod('saveToDownloads', args) ?? f.name; } on PlatformException { // Android 9 and older need the storage permission for Downloads. if (Platform.isAndroid && await Permission.storage.request().isGranted) { return await _files.invokeMethod('saveToDownloads', args) ?? f.name; } rethrow; } } Future _handleSaveFiles(List args) async { // Plain data back to the page; it shows the message in the user's language. final files = _WebFile.parse(args); final saved = []; for (final f in files) { final where = await _saveOne(f); saved.add(where.split(RegExp(r'[/›]')).last.trim()); // file name as stored } return {'saved': saved, 'platform': Platform.isIOS ? 'ios' : 'android'}; } Future _handleShareFiles(List args) async { final files = _WebFile.parse(args); if (files.isEmpty) return {'status': 'cancelled'}; // iPad needs an anchor for the share popover: bottom centre of the screen. final size = mounted ? MediaQuery.sizeOf(context) : const Size(390, 844); final result = await SharePlus.instance.share(ShareParams( files: [for (final f in files) XFile.fromData(f.bytes, name: f.name, mimeType: f.mime)], fileNameOverrides: [for (final f in files) f.name], sharePositionOrigin: Rect.fromLTWH(size.width / 2, size.height - 90, 1, 1), )); return {'status': result.status == ShareResultStatus.dismissed ? 'cancelled' : 'shared'}; } /// iOS: one location fix from Core Location ({lat, lon, accuracy, alt?} or /// {error}); the WebView's own geolocation would ask again on every launch. /// Android: {unsupported} – the page uses navigator.geolocation, whose /// prompt the shell answers once and for all (onGeolocationPermissionsShowPrompt). Future _handleGetLocation(List args) async { if (!Platform.isIOS) return {'unsupported': true}; try { return await _location.invokeMapMethod('getLocation'); } on PlatformException catch (e) { return {'error': e.code}; } } /// Screen stays on while the web app captures (WebView has no Wake Lock API). Future _handleKeepAwake(List args) async { final on = args.isNotEmpty && args[0] == true; await WakelockPlus.toggle(enable: on); return on; } Future _handleHaptic(List args) async { await HapticFeedback.mediumImpact(); return true; } /// Android back: let the web app go one screen back; leave the app on the start screen. Future _onBack() async { final handled = await _controller?.evaluateJavascript( source: 'window.__sfzBack ? window.__sfzBack() : false', ); if (handled != true) await SystemNavigator.pop(); } /// The web app reports its screen: {name, tab: 'sites'|'settings'|null}. Future _handleRoute(List args) async { // First report = the page is up and drawing (watchdog satisfied). _pageReady = true; _watchdogRestarts = 0; _readyTimer?.cancel(); final info = args.isNotEmpty && args[0] is Map ? args[0] as Map : const {}; final index = _tabs.indexWhere((t) => t.id == info['tab']); final labels = info['labels'] is Map ? (info['labels'] as Map).map((k, v) => MapEntry(k.toString(), v.toString())) : _tabLabels; if (mounted) { setState(() { _tab = index >= 0 ? index : null; _tabLabels = labels; _rtl = info['rtl'] == true; }); } _pushInsets(); return true; } /// The WebView sits inside a Flutter platform view and gets no safe-area /// insets of its own (CSS env() is 0 on both platforms), so hand the system /// bar sizes to the page as --safe-top / --safe-bottom. With the tab bar /// shown, the bar itself covers the bottom inset. String _insetsScript() { final pad = MediaQuery.paddingOf(context); final bottom = _tab == null ? pad.bottom : 0.0; return "document.documentElement.style.setProperty('--safe-top','${pad.top}px');" "document.documentElement.style.setProperty('--safe-bottom','${bottom}px');"; } void _pushInsets() { if (!mounted) return; WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted) _controller?.evaluateJavascript(source: _insetsScript()); }); } @override void didChangeDependencies() { super.didChangeDependencies(); _pushInsets(); // rotation, notch / system bar changes } void _selectTab(int index) { HapticFeedback.selectionClick(); final id = _tabs[index].id; _controller?.evaluateJavascript(source: "window.__sfzNav && window.__sfzNav('$id')"); _probeAfterTap(); } /// Kept for older web builds that saved the raw panorama PNG to the gallery. Future _handleSavePng(List args) async { final base64Str = args.isNotEmpty ? args[0] as String : ''; final name = args.length > 1 ? args[1] as String : 'panorama.png'; if (base64Str.isEmpty) return 'no data'; if (!await Gal.hasAccess()) await Gal.requestAccess(); await Gal.putImageBytes(base64Decode(base64Str), name: name.replaceAll('.png', '')); return 'gallery'; } @override Widget build(BuildContext context) { final Widget body; if (_error != null) { body = Center( child: Padding( padding: const EdgeInsets.all(24), child: Column( mainAxisSize: MainAxisSize.min, children: [ Text(_error!, textAlign: TextAlign.center), const SizedBox(height: 20), FilledButton( style: FilledButton.styleFrom(backgroundColor: _accent, foregroundColor: Colors.black), onPressed: () { _loadRetries = 0; _watchdogRestarts = 0; if (_ready) { _recover(forceNewWebView: true); } else { _boot(); } }, child: const Text('Try again'), ), ], ), ), ); } else if (!_ready) { // Same colour as the native splash, so the hand-over does not flash. body = const SizedBox.expand(); } else { body = InAppWebView( key: _webKey, initialUrlRequest: URLRequest(url: WebUri('${_server.origin}/index.html$_devQuery')), initialUserScripts: UnmodifiableListView([ UserScript(source: _insetsScript(), injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START), ]), onLoadStop: (controller, url) { _loadRetries = 0; _pushInsets(); }, onReceivedError: (controller, request, error) { if (request.isForMainFrame ?? true) _onMainFrameError(); }, // The OS killed the page's process (memory, background): start a fresh WebView. onWebContentProcessDidTerminate: (controller) => _recover(forceNewWebView: true), onRenderProcessGone: (controller, detail) => _recover(forceNewWebView: true), initialSettings: InAppWebViewSettings( mediaPlaybackRequiresUserGesture: false, allowsInlineMediaPlayback: true, geolocationEnabled: true, transparentBackground: true, useHybridComposition: true, // iOS: edge to edge (the page handles safe areas), no rubber-band scroll. contentInsetAdjustmentBehavior: ScrollViewContentInsetAdjustmentBehavior.NEVER, disallowOverScroll: true, allowsBackForwardNavigationGestures: false, // Sites, settings and strips live in localStorage / IndexedDB. domStorageEnabled: true, databaseEnabled: true, incognito: false, // Feels like an app, not a page: no pinch zoom. supportZoom: false, builtInZoomControls: false, useOnRenderProcessGone: true, ), onWebViewCreated: (controller) { _controller = controller; _armWatchdog(); controller.addJavaScriptHandler(handlerName: 'route', callback: _handleRoute); controller.addJavaScriptHandler(handlerName: 'keepAwake', callback: _handleKeepAwake); controller.addJavaScriptHandler(handlerName: 'haptic', callback: _handleHaptic); controller.addJavaScriptHandler(handlerName: 'saveFiles', callback: _handleSaveFiles); controller.addJavaScriptHandler(handlerName: 'shareFiles', callback: _handleShareFiles); controller.addJavaScriptHandler(handlerName: 'savePng', callback: _handleSavePng); controller.addJavaScriptHandler(handlerName: 'getLocation', callback: _handleGetLocation); }, onPermissionRequest: (controller, request) async { // The OS-level permissions were requested at start. return PermissionResponse( resources: request.resources, action: PermissionResponseAction.GRANT, ); }, onGeolocationPermissionsShowPrompt: (controller, origin) async { return GeolocationPermissionShowPromptResponse(origin: origin, allow: true, retain: true); }, onConsoleMessage: (controller, msg) => debugPrint('[web] ${msg.message}'), ); } return PopScope( canPop: false, onPopInvokedWithResult: (didPop, _) { if (!didPop) _onBack(); }, child: Scaffold( backgroundColor: const Color(0xFF04060B), body: Column( children: [ // Edge to edge; the page keeps clear of the system bars via --safe-top/--safe-bottom. Expanded(child: body), if (_tab != null) Directionality( textDirection: _rtl ? TextDirection.rtl : TextDirection.ltr, child: _TabBar(selected: _tab!, labels: _tabLabels, onSelect: _selectTab), ), ], ), ), ); } } class _TabSpec { const _TabSpec(this.id, this.label, this.cupertino, this.material, this.materialSelected); final String id; final String label; final IconData cupertino; final IconData material; final IconData materialSelected; } /// "New survey" is an action tab: it opens the survey flow, where the bar hides. /// The labels here are English fallbacks; the web app sends translated ones. const _tabs = [ _TabSpec('sites', 'Sites', CupertinoIcons.square_stack_3d_up, Icons.landscape_outlined, Icons.landscape), _TabSpec('new', 'New survey', CupertinoIcons.plus_circle, Icons.add_circle_outline, Icons.add_circle), _TabSpec('settings', 'Settings', CupertinoIcons.slider_horizontal_3, Icons.tune, Icons.tune), ]; /// Development only: extra query for the web app, set at build time, e.g. /// `flutter build ios --simulator --dart-define=SFZ_QUERY=skipWelcome`. const String _devQueryRaw = String.fromEnvironment('SFZ_QUERY'); const String _devQuery = _devQueryRaw == '' ? '' : '?$_devQueryRaw'; const _accent = Color(0xFFF5B544); const _muted = Color(0xFF93A0B4); const _barBg = Color(0xFF0A0D13); const _barBorder = Color(0xFF1E2634); /// iOS: own tab bar (below). Android: Material 3 navigation bar. Both in the /// app's dark palette with the amber accent; both pad for the home indicator. class _TabBar extends StatelessWidget { const _TabBar({required this.selected, required this.labels, required this.onSelect}); final int selected; final Map labels; final ValueChanged onSelect; @override Widget build(BuildContext context) { if (Platform.isIOS) return _IosTabBar(selected: selected, labels: labels, onSelect: onSelect); return NavigationBarTheme( data: NavigationBarThemeData( backgroundColor: _barBg, indicatorColor: const Color(0xFF2A2312), surfaceTintColor: Colors.transparent, labelTextStyle: WidgetStateProperty.resolveWith((states) => TextStyle( fontSize: 12, fontWeight: FontWeight.w600, color: states.contains(WidgetState.selected) ? _accent : _muted, )), iconTheme: WidgetStateProperty.resolveWith((states) => IconThemeData( color: states.contains(WidgetState.selected) ? _accent : _muted, )), ), child: DecoratedBox( decoration: const BoxDecoration(border: Border(top: BorderSide(color: _barBorder))), child: NavigationBar( selectedIndex: selected, onDestinationSelected: onSelect, height: 68, destinations: [ for (final t in _tabs) NavigationDestination( icon: Icon(t.material), selectedIcon: Icon(t.materialSelected), label: labels[t.id] ?? t.label, ), ], ), ), ); } } /// iOS tab bar: icons centred in the bar with the selected one on an amber-tinted /// capsule (as on Android), and only part of the home-indicator inset kept free — /// CupertinoTabBar pins the icons to the top edge and leaves a tall empty strip. class _IosTabBar extends StatelessWidget { const _IosTabBar({required this.selected, required this.labels, required this.onSelect}); final int selected; final Map labels; final ValueChanged onSelect; @override Widget build(BuildContext context) { final inset = MediaQuery.paddingOf(context).bottom; return Container( decoration: const BoxDecoration( color: _barBg, border: Border(top: BorderSide(color: _barBorder, width: 0.5)), ), padding: EdgeInsets.only(top: 8, bottom: inset > 0 ? inset - 14 : 8), child: Row( children: [ for (var i = 0; i < _tabs.length; i++) Expanded( child: Semantics( button: true, selected: i == selected, label: labels[_tabs[i].id] ?? _tabs[i].label, child: GestureDetector( behavior: HitTestBehavior.opaque, onTap: () => onSelect(i), child: ExcludeSemantics( child: Column( mainAxisSize: MainAxisSize.min, children: [ AnimatedContainer( duration: const Duration(milliseconds: 180), width: 58, height: 30, decoration: BoxDecoration( color: i == selected ? const Color(0xFF2A2312) : Colors.transparent, borderRadius: BorderRadius.circular(15), ), child: Icon(_tabs[i].cupertino, size: 22, color: i == selected ? _accent : _muted), ), const SizedBox(height: 3), Text( labels[_tabs[i].id] ?? _tabs[i].label, style: TextStyle( fontSize: 11, fontWeight: FontWeight.w600, color: i == selected ? _accent : _muted, ), ), ], ), ), ), ), ), ], ), ); } }