|
| 1 | +/* |
| 2 | + * Copyright (c) 2025, MapTiler |
| 3 | + * All rights reserved. |
| 4 | + * SPDX-License-Identifier: BSD 3-Clause |
| 5 | + */ |
| 6 | + |
| 7 | +package com.maptiler.maptilersdk.bridge |
| 8 | + |
| 9 | +import android.content.Context |
| 10 | +import android.webkit.WebView |
| 11 | +import com.maptiler.maptilersdk.MTConfig |
| 12 | +import com.maptiler.maptilersdk.logging.MTLogLevel |
| 13 | +import com.maptiler.maptilersdk.logging.MTLogType |
| 14 | +import com.maptiler.maptilersdk.logging.MTLogger |
| 15 | +import kotlinx.coroutines.CompletableDeferred |
| 16 | +import kotlinx.coroutines.Dispatchers |
| 17 | +import kotlinx.coroutines.withContext |
| 18 | + |
| 19 | +internal interface WebViewExecutorDelegate { |
| 20 | + fun onNavigationFinished(url: String) |
| 21 | +} |
| 22 | + |
| 23 | +internal class WebViewExecutor( |
| 24 | + context: Context, |
| 25 | +) : WebViewManagerDelegate { |
| 26 | + private val exceptionKey = "WKJavaScriptExceptionMessage" |
| 27 | + private var webView: WebView? = null |
| 28 | + private val webViewManager: WebViewManager = |
| 29 | + WebViewManager(context).apply { |
| 30 | + delegate = this@WebViewExecutor |
| 31 | + } |
| 32 | + |
| 33 | + var delegate: WebViewExecutorDelegate? = null |
| 34 | + |
| 35 | + init { |
| 36 | + webView = webViewManager.getAttachableWebView() |
| 37 | + webView?.isVerticalScrollBarEnabled = false |
| 38 | + } |
| 39 | + |
| 40 | + fun getWebView(): WebView? = webView |
| 41 | + |
| 42 | + suspend fun execute(command: MTCommand): MTBridgeReturnType = |
| 43 | + withContext(Dispatchers.Main) { |
| 44 | + val webView = webView ?: throw MTError.BridgeNotLoaded |
| 45 | + val isVerbose = MTConfig.logLevel == MTLogLevel.Debug(true) |
| 46 | + |
| 47 | + val deferred = CompletableDeferred<MTBridgeReturnType>() |
| 48 | + webView.evaluateJavascript(command.toJS()) { result -> |
| 49 | + try { |
| 50 | + if (result == null) { |
| 51 | + if (isVerbose) { |
| 52 | + MTLogger.log("$command completed with unsupported return type.", MTLogType.WARNING) |
| 53 | + } |
| 54 | + |
| 55 | + deferred.complete(MTBridgeReturnType.UnsupportedType) |
| 56 | + } else { |
| 57 | + try { |
| 58 | + val parsedResult = MTBridgeReturnType.from(result) |
| 59 | + deferred.complete(parsedResult) |
| 60 | + } catch (e: Exception) { |
| 61 | + deferred.completeExceptionally(MTError.InvalidResultType(result)) |
| 62 | + } |
| 63 | + } |
| 64 | + } catch (e: Exception) { |
| 65 | + if (isVerbose) { |
| 66 | + MTLogger.log("Bridging error occurred for $command: ${e.message}", MTLogType.ERROR) |
| 67 | + } |
| 68 | + |
| 69 | + deferred.completeExceptionally(MTError.Unknown(e.message ?: "Unknown error")) |
| 70 | + } |
| 71 | + } |
| 72 | + |
| 73 | + return@withContext deferred.await() |
| 74 | + } |
| 75 | + |
| 76 | + override fun onNavigationFinished(url: String) { |
| 77 | + delegate?.onNavigationFinished(url) |
| 78 | + } |
| 79 | +} |
0 commit comments