engedelyek

This commit is contained in:
sagiferi
2026-10-27 21:31:27 +01:00
parent 29528f561b
commit 4a016fb1d1
7 changed files with 137 additions and 32 deletions
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -8,7 +8,7 @@
<meta name="theme-color" content="#0A0D13" />
<style>html, body { background: #04060B; }</style>
<title>SkyContour</title>
<script type="module" crossorigin src="/assets/index-BCj7raNO.js"></script>
<script type="module" crossorigin src="/assets/index-CTxI8k6G.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-De78_CBu.css">
</head>
<body>
+81
View File
@@ -1,8 +1,11 @@
import CoreLocation
import Flutter
import UIKit
@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
private let location = OneShotLocation()
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
@@ -29,6 +32,16 @@ import UIKit
}
}
}
if let registrar = engineBridge.pluginRegistry.registrar(forPlugin: "SfzenithLocation") {
let channel = FlutterMethodChannel(name: "sfzenith/location", binaryMessenger: registrar.messenger())
channel.setMethodCallHandler { [location] call, result in
guard call.method == "getLocation" else {
result(FlutterMethodNotImplemented)
return
}
location.request(result)
}
}
}
/// Saves into the app's Documents folder, which the Files app shows under
@@ -50,3 +63,71 @@ import UIKit
return "Files › SkyContour › \(target.lastPathComponent)"
}
}
/// One location fix for the web app. The WebView's navigator.geolocation shows
/// its own "localhost would like to use your location" alert on every launch
/// (WKWebView has no API to remember the answer); the app itself already holds
/// the when-in-use permission, so ask Core Location directly.
final class OneShotLocation: NSObject, CLLocationManagerDelegate {
private let manager = CLLocationManager()
private var pending: [FlutterResult] = []
private var timer: Timer?
override init() {
super.init()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
}
/// Answers {lat, lon, accuracy, alt?} or a FlutterError (denied, unavailable, timeout).
func request(_ result: @escaping FlutterResult) {
pending.append(result)
if pending.count > 1 { return } // a fix is already on its way
timer = Timer.scheduledTimer(withTimeInterval: 20, repeats: false) { [weak self] _ in
self?.finish(FlutterError(code: "timeout", message: "No location fix", details: nil))
}
switch manager.authorizationStatus {
case .notDetermined:
manager.requestWhenInUseAuthorization()
case .authorizedWhenInUse, .authorizedAlways:
manager.requestLocation()
default:
finish(FlutterError(code: "denied", message: "Location permission denied", details: nil))
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
guard !pending.isEmpty else { return }
switch manager.authorizationStatus {
case .notDetermined:
break
case .authorizedWhenInUse, .authorizedAlways:
manager.requestLocation()
default:
finish(FlutterError(code: "denied", message: "Location permission denied", details: nil))
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let loc = locations.last else { return }
var out: [String: Any] = [
"lat": loc.coordinate.latitude,
"lon": loc.coordinate.longitude,
"accuracy": loc.horizontalAccuracy,
]
if loc.verticalAccuracy >= 0 { out["alt"] = loc.altitude }
finish(out)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
finish(FlutterError(code: "unavailable", message: error.localizedDescription, details: nil))
}
private func finish(_ value: Any?) {
timer?.invalidate()
timer = nil
let callbacks = pending
pending = []
callbacks.forEach { $0(value) }
}
}
+15
View File
@@ -88,6 +88,7 @@ class WebShell extends StatefulWidget {
class _WebShellState extends State<WebShell> with WidgetsBindingObserver {
static const _files = MethodChannel('sfzenith/files');
static const _location = MethodChannel('sfzenith/location');
final LocalServer _server = LocalServer();
@@ -271,6 +272,19 @@ class _WebShellState extends State<WebShell> with WidgetsBindingObserver {
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<dynamic> _handleGetLocation(List<dynamic> args) async {
if (!Platform.isIOS) return {'unsupported': true};
try {
return await _location.invokeMapMethod<String, dynamic>('getLocation');
} on PlatformException catch (e) {
return {'error': e.code};
}
}
/// Screen stays on while the web app captures (WebView has no Wake Lock API).
Future<dynamic> _handleKeepAwake(List<dynamic> args) async {
final on = args.isNotEmpty && args[0] == true;
@@ -431,6 +445,7 @@ class _WebShellState extends State<WebShell> with WidgetsBindingObserver {
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.
+1 -1
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+6
version: 1.0.1+7
environment:
sdk: ^3.11.1
+28 -19
View File
@@ -3,32 +3,41 @@ import { IconBack, IconPin, IconCompass, IconChevronRight, IconSun } from '../co
import { latText, lonText } from '../lib/format'
import { startCamera, startOrientation } from '../lib/camera'
import { errText } from '../lib/wasm'
import { EMBEDDED, nativeCall } from '../lib/files'
import { t } from '../i18n'
const canLocate = () => EMBEDDED || !!navigator.geolocation
const located = (latDeg, lonDeg, elevM, accuracyM) => ({
status: 'ok', error: '', loc: { latDeg, lonDeg, elevM: typeof elevM === 'number' ? elevM : null, accuracyM },
})
const unavailable = () => ({ status: 'error', loc: null, error: t('setup.geoUnavailable') })
/** One fix → the hook's state ({status, loc, error}). */
async function fetchLocation() {
if (EMBEDDED) {
// iOS shell: Core Location with the app's own permission (the WebView
// would ask "localhost …" again on every launch). Android answers
// {unsupported}: its WebView geolocation is already granted for good.
const r = await nativeCall('getLocation')
if (r && typeof r.lat === 'number') return located(r.lat, r.lon, r.alt, r.accuracy)
if (r && r.error) return unavailable()
}
if (!navigator.geolocation) return { status: 'error', loc: null, error: t('setup.noGeo') }
return new Promise((resolve) => navigator.geolocation.getCurrentPosition(
(p) => resolve(located(p.coords.latitude, p.coords.longitude, p.coords.altitude, p.coords.accuracy)),
() => resolve(unavailable()),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 60000 },
))
}
function useLocation() {
const [state, setState] = useState(() => (navigator.geolocation
const [state, setState] = useState(() => (canLocate()
? { status: 'locating', loc: null, error: '' }
: { status: 'error', loc: null, error: t('setup.noGeo') }))
const locate = useCallback(() => {
if (!navigator.geolocation) return
navigator.geolocation.getCurrentPosition(
(p) => setState({
status: 'ok',
error: '',
loc: {
latDeg: p.coords.latitude,
lonDeg: p.coords.longitude,
elevM: p.coords.altitude,
accuracyM: p.coords.accuracy,
},
}),
() => setState({ status: 'error', loc: null, error: t('setup.geoUnavailable') }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 60000 },
)
}, [])
const locate = useCallback(() => { fetchLocation().then(setState) }, [])
useEffect(() => { locate() }, [locate])
const refresh = () => {
if (!navigator.geolocation) return
if (!canLocate()) return
setState((s) => ({ ...s, status: 'locating', error: '' }))
locate()
}