waiting for ios review
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart' show rootBundle;
|
||||
|
||||
/// Serves the bundled web build (assets/web) on http://localhost:[port].
|
||||
///
|
||||
/// Replaces flutter_inappwebview's InAppLocalhostServer, whose start() never
|
||||
/// completes when the port is taken (the app then stays on a dark screen):
|
||||
/// * binds with `shared: true`, so a second Flutter engine in the same
|
||||
/// process (Android can start a second activity instance) can serve too;
|
||||
/// * retries for a while, then throws, so the shell can show an error;
|
||||
/// * [healthy] / [ensureRunning] detect a socket the OS took away while the
|
||||
/// app was suspended (iOS) and bind again.
|
||||
///
|
||||
/// The port is part of the page origin: localStorage and IndexedDB (the
|
||||
/// user's sites) belong to it. Never change it after release.
|
||||
class LocalServer {
|
||||
LocalServer({this.port = 47391, this.documentRoot = 'assets/web/'});
|
||||
|
||||
final int port;
|
||||
final String documentRoot;
|
||||
HttpServer? _server;
|
||||
|
||||
String get origin => 'http://localhost:$port';
|
||||
|
||||
Future<void> start({Duration timeout = const Duration(seconds: 8)}) async {
|
||||
if (_server != null) return;
|
||||
final deadline = DateTime.now().add(timeout);
|
||||
Object? lastError;
|
||||
while (true) {
|
||||
try {
|
||||
final server = await HttpServer.bind(InternetAddress.loopbackIPv4, port, shared: true);
|
||||
_server = server;
|
||||
server.listen(
|
||||
_handle,
|
||||
onError: (Object _) {},
|
||||
onDone: () {
|
||||
if (identical(_server, server)) _server = null;
|
||||
},
|
||||
cancelOnError: false,
|
||||
);
|
||||
return;
|
||||
} catch (e) {
|
||||
lastError = e;
|
||||
if (DateTime.now().isAfter(deadline)) break;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 400));
|
||||
}
|
||||
}
|
||||
throw Exception('Local server could not use port $port: $lastError');
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
final s = _server;
|
||||
_server = null;
|
||||
try {
|
||||
await s?.close(force: true);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// True when index.html can be fetched right now.
|
||||
Future<bool> healthy() async {
|
||||
if (_server == null) return false;
|
||||
final client = HttpClient()..connectionTimeout = const Duration(seconds: 1);
|
||||
try {
|
||||
final req = await client.getUrl(Uri.parse('$origin/index.html')).timeout(const Duration(seconds: 2));
|
||||
final res = await req.close().timeout(const Duration(seconds: 2));
|
||||
await res.drain<void>();
|
||||
return res.statusCode == 200;
|
||||
} catch (_) {
|
||||
return false;
|
||||
} finally {
|
||||
client.close(force: true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Binds again if the server is gone or not answering.
|
||||
Future<void> ensureRunning() async {
|
||||
if (await healthy()) return;
|
||||
await stop();
|
||||
await start();
|
||||
}
|
||||
|
||||
Future<void> _handle(HttpRequest request) async {
|
||||
final res = request.response;
|
||||
try {
|
||||
var path = Uri.decodeFull(request.uri.path);
|
||||
if (path.startsWith('/')) path = path.substring(1);
|
||||
if (path.isEmpty || path.endsWith('/')) path += 'index.html';
|
||||
if (path.split('/').contains('..')) {
|
||||
res.statusCode = HttpStatus.forbidden;
|
||||
return;
|
||||
}
|
||||
final data = await rootBundle.load('$documentRoot$path');
|
||||
res.headers.contentType = _contentType(path);
|
||||
res.headers.set(HttpHeaders.cacheControlHeader, 'no-cache');
|
||||
res.add(data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes));
|
||||
} catch (_) {
|
||||
res.statusCode = HttpStatus.notFound;
|
||||
} finally {
|
||||
try {
|
||||
await res.close();
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
static ContentType _contentType(String path) {
|
||||
final ext = path.contains('.') ? path.substring(path.lastIndexOf('.') + 1).toLowerCase() : '';
|
||||
switch (ext) {
|
||||
case 'html':
|
||||
return ContentType('text', 'html', charset: 'utf-8');
|
||||
case 'js':
|
||||
case 'mjs':
|
||||
return ContentType('text', 'javascript', charset: 'utf-8');
|
||||
case 'css':
|
||||
return ContentType('text', 'css', charset: 'utf-8');
|
||||
case 'json':
|
||||
case 'webmanifest':
|
||||
return ContentType('application', 'json', charset: 'utf-8');
|
||||
case 'wasm':
|
||||
return ContentType('application', 'wasm');
|
||||
case 'svg':
|
||||
return ContentType('image', 'svg+xml');
|
||||
case 'png':
|
||||
return ContentType('image', 'png');
|
||||
case 'jpg':
|
||||
case 'jpeg':
|
||||
return ContentType('image', 'jpeg');
|
||||
case 'ico':
|
||||
return ContentType('image', 'x-icon');
|
||||
case 'woff':
|
||||
return ContentType('font', 'woff');
|
||||
case 'woff2':
|
||||
return ContentType('font', 'woff2');
|
||||
case 'txt':
|
||||
return ContentType('text', 'plain', charset: 'utf-8');
|
||||
default:
|
||||
return ContentType('application', 'octet-stream');
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
-13
@@ -11,12 +11,16 @@ 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:8080 (a secure context, so the
|
||||
/// WebView's camera, motion sensors and geolocation work),
|
||||
/// * 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
|
||||
@@ -81,18 +85,20 @@ class WebShell extends StatefulWidget {
|
||||
State<WebShell> createState() => _WebShellState();
|
||||
}
|
||||
|
||||
class _WebShellState extends State<WebShell> {
|
||||
class _WebShellState extends State<WebShell> with WidgetsBindingObserver {
|
||||
static const _files = MethodChannel('sfzenith/files');
|
||||
|
||||
final InAppLocalhostServer _server = InAppLocalhostServer(
|
||||
documentRoot: 'assets/web',
|
||||
port: 8080,
|
||||
);
|
||||
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;
|
||||
|
||||
/// Selected tab while the bar is shown; null = hidden (survey flow, welcome).
|
||||
int? _tab;
|
||||
|
||||
@@ -103,27 +109,79 @@ class _WebShellState extends State<WebShell> {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
_boot();
|
||||
}
|
||||
|
||||
Future<void> _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();
|
||||
if (!_server.isRunning()) await _server.start();
|
||||
await _server.start();
|
||||
if (mounted) setState(() => _ready = true);
|
||||
} catch (e) {
|
||||
if (mounted) setState(() => _error = 'Could not start: $e');
|
||||
if (mounted) setState(() => _error = 'SkyContour could not start.\n\n$e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_server.close();
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
_server.stop();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed && _ready) _recover();
|
||||
}
|
||||
|
||||
/// Back from the background: iOS may have taken the server's socket and
|
||||
/// killed the page's process while the app was suspended.
|
||||
Future<void> _recover({bool forceNewWebView = false}) async {
|
||||
if (_recovering) 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;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _pageAlive() async {
|
||||
final c = _controller;
|
||||
if (c == null) return false;
|
||||
try {
|
||||
final n = await c
|
||||
.evaluateJavascript(source: "(document.getElementById('root') || {}).childElementCount || 0")
|
||||
.timeout(const Duration(seconds: 2));
|
||||
return n is num && n > 0;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
void _newWebView() {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_controller = null;
|
||||
_webKey = UniqueKey();
|
||||
});
|
||||
}
|
||||
|
||||
/// The page itself failed to load (server not answering): bind again, retry a few times.
|
||||
void _onMainFrameError() {
|
||||
if (_loadRetries >= 3) return;
|
||||
_loadRetries++;
|
||||
Future<void>.delayed(Duration(milliseconds: 400 * _loadRetries), () => _recover(forceNewWebView: true));
|
||||
}
|
||||
|
||||
Future<String> _saveOne(_WebFile f) async {
|
||||
final args = {'name': f.name, 'mime': f.mime, 'bytes': f.bytes};
|
||||
try {
|
||||
@@ -246,7 +304,25 @@ class _WebShellState extends State<WebShell> {
|
||||
body = Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Text(_error!, textAlign: TextAlign.center),
|
||||
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;
|
||||
if (_ready) {
|
||||
_recover(forceNewWebView: true);
|
||||
} else {
|
||||
_boot();
|
||||
}
|
||||
},
|
||||
child: const Text('Try again'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
} else if (!_ready) {
|
||||
@@ -254,11 +330,21 @@ class _WebShellState extends State<WebShell> {
|
||||
body = const SizedBox.expand();
|
||||
} else {
|
||||
body = InAppWebView(
|
||||
initialUrlRequest: URLRequest(url: WebUri('http://localhost:8080/index.html$_devQuery')),
|
||||
key: _webKey,
|
||||
initialUrlRequest: URLRequest(url: WebUri('${_server.origin}/index.html$_devQuery')),
|
||||
initialUserScripts: UnmodifiableListView([
|
||||
UserScript(source: _insetsScript(), injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START),
|
||||
]),
|
||||
onLoadStop: (controller, url) => _pushInsets(),
|
||||
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,
|
||||
@@ -276,6 +362,7 @@ class _WebShellState extends State<WebShell> {
|
||||
// Feels like an app, not a page: no pinch zoom.
|
||||
supportZoom: false,
|
||||
builtInZoomControls: false,
|
||||
useOnRenderProcessGone: true,
|
||||
),
|
||||
onWebViewCreated: (controller) {
|
||||
_controller = controller;
|
||||
|
||||
Reference in New Issue
Block a user