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'; /// 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:8080 (a secure context, so the /// WebView's camera, motion sensors and geolocation work), /// * 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 { static const _files = MethodChannel('sfzenith/files'); final InAppLocalhostServer _server = InAppLocalhostServer( documentRoot: 'assets/web', port: 8080, ); InAppWebViewController? _controller; bool _ready = false; String? _error; /// 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(); _boot(); } Future _boot() async { 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(); if (!_server.isRunning()) await _server.start(); if (mounted) setState(() => _ready = true); } catch (e) { if (mounted) setState(() => _error = 'Could not start: $e'); } } @override void dispose() { _server.close(); super.dispose(); } 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'}; } /// 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 { 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')"); } /// 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: Text(_error!, textAlign: TextAlign.center), ), ); } else if (!_ready) { // Same colour as the native splash, so the hand-over does not flash. body = const SizedBox.expand(); } else { body = InAppWebView( initialUrlRequest: URLRequest(url: WebUri('http://localhost:8080/index.html$_devQuery')), initialUserScripts: UnmodifiableListView([ UserScript(source: _insetsScript(), injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START), ]), onLoadStop: (controller, url) => _pushInsets(), 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, ), onWebViewCreated: (controller) { _controller = controller; 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); }, 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, ), ), ], ), ), ), ), ), ], ), ); } }