web: fix build after canonical migration
- Commit
76a74f4cc1d73458ca751c1fbc92ec12e878a13f- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 21:47 UTC (3 months ago)
- Parents
3f43a43
Diff
web/src/main/java/com/vayunmathur/web/MainActivity.kt
diff --git a/web/src/main/java/com/vayunmathur/web/MainActivity.kt b/web/src/main/java/com/vayunmathur/web/MainActivity.ktindex b8eb8a0414..94e881c225 100644--- a/web/src/main/java/com/vayunmathur/web/MainActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/MainActivity.kt@@ -1,151 +1,151 @@-package com.vayunmathur.web--import android.content.Intent-import android.os.Bundle-import androidx.activity.ComponentActivity-import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.lifecycle.lifecycleScope-import com.vayunmathur.library.network.NetworkClient-import com.vayunmathur.library.network.TrustBundle-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.library.util.OfflineAware-import com.vayunmathur.web.data.WebRepository-import com.vayunmathur.web.domain.shields.ShieldsEngine-import com.vayunmathur.web.platform.WebViewModel-import com.vayunmathur.web.platform.WebViewModelFactory-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext--class MainActivity : ComponentActivity() {-- private val readyState = mutableStateOf(false)- private var factoryState by mutableStateOf<WebViewModelFactory?>(null)- private val externalUrlState = mutableStateOf<String?>(null)-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- // SYSTEM permissive browser: any host + user CAs for MITM debug/corp proxies (per user exception)- NetworkClient.init(this, TrustBundle.SYSTEM)- enableEdgeToEdge()- // Parses ~8 MB of filter lists off the main thread. Shields fail open until it lands.- lifecycleScope.launch { ShieldsEngine.load(applicationContext) }-- // Each task (window) carries its own window id + incognito flag so it keeps an independent tab set.- val windowId = intent?.getStringExtra(EXTRA_WINDOW_ID) ?: WebViewModel.DEFAULT_WINDOW_ID- val incognito = intent?.getBooleanExtra(EXTRA_INCOGNITO, false) ?: false-- // Reap tab-sets left behind by windows the user has since closed (swiped from Recents).- pruneClosedWindowTabs()-- lifecycleScope.launch(Dispatchers.IO) {- val repository = WebRepository.get(applicationContext)- val factory = WebViewModelFactory(- repository = repository,- context = applicationContext,- windowId = windowId,- incognito = incognito,- initialShieldSettings = repository.allShieldSettings(),- )- withContext(Dispatchers.Main) {- factoryState = factory- readyState.value = true- handleIntentUrl(intent)- }- }-- setContent {- DynamicTheme {- OfflineAware {- Box(Modifier.fillMaxSize()) {- if (!readyState.value || factoryState == null) {- Box(Modifier.fillMaxSize())- } else {- AppRoot(factoryState!!, externalUrlState.value) {- externalUrlState.value = null- }- }- }- }- }- }- }-- override fun onNewIntent(intent: Intent) {- super.onNewIntent(intent)- handleIntentUrl(intent)- }-- private fun handleIntentUrl(intent: Intent?) {- intent ?: return- val raw = when (intent.action) {- Intent.ACTION_VIEW -> intent.dataString- Intent.ACTION_SEND -> intent.getStringExtra(Intent.EXTRA_TEXT)- else -> null- } ?: return-- val url = extractHttpUrl(raw) ?: return- externalUrlState.value = url- }-- private fun extractHttpUrl(text: String): String? {- val trimmed = text.trim()- if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {- val match = Regex("https?://\\S+").find(trimmed)- return match?.value ?: trimmed.substringBefore(" ")- }- Regex("https?://\\S+").find(trimmed)?.let { return it.value }- return null- }-- /**- * Removes persisted tab-sets whose window is no longer a live task. Each non-incognito window- * stores its tabs under keys suffixed with its window id (see [WebViewModel]); when the user- * swipes a window out of Recents those keys would otherwise linger forever.- */- private fun pruneClosedWindowTabs() {- // Must mirror WebViewModel's namespaced key format: "<P_SAVED_TABS>_<windowId>" etc.- val savedTabsPrefix = "web_saved_tabs_"- val activeTabPrefix = "web_active_tab_id_"- lifecycleScope.launch(Dispatchers.IO) {- try {- val am = getSystemService(ACTIVITY_SERVICE) as? android.app.ActivityManager ?: return@launch- val liveWindowIds = am.appTasks.mapNotNull { task ->- val base = runCatching { task.taskInfo?.baseIntent }.getOrNull()- base?.getStringExtra(EXTRA_WINDOW_ID)- ?: base?.data?.takeIf { it.scheme == "web-window" }?.host- }.toSet()-- val sp = getSharedPreferences("web_prefs", MODE_PRIVATE)- val editor = sp.edit()- var changed = false- for (key in sp.all.keys) {- val windowId = when {- key.startsWith(savedTabsPrefix) -> key.removePrefix(savedTabsPrefix)- key.startsWith(activeTabPrefix) -> key.removePrefix(activeTabPrefix)- else -> null- } ?: continue- if (windowId !in liveWindowIds) {- editor.remove(key)- changed = true- }- }- if (changed) editor.apply()- } catch (e: Exception) {- android.util.Log.e("MainActivity", "pruneClosedWindowTabs failed", e)- }- }- }-- companion object {- const val EXTRA_WINDOW_ID = "com.vayunmathur.web.WINDOW_ID"- const val EXTRA_INCOGNITO = "com.vayunmathur.web.INCOGNITO"- }-}+package com.vayunmathur.web++import android.content.Intent+import android.os.Bundle+import androidx.activity.ComponentActivity+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.lifecycle.lifecycleScope+import com.vayunmathur.library.network.NetworkClient+import com.vayunmathur.library.network.TrustBundle+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.library.util.OfflineAware+import com.vayunmathur.web.data.WebRepository+import com.vayunmathur.web.platform.shields.ShieldsEngine+import com.vayunmathur.web.platform.WebViewModel+import com.vayunmathur.web.platform.WebViewModelFactory+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++class MainActivity : ComponentActivity() {++ private val readyState = mutableStateOf(false)+ private var factoryState by mutableStateOf<WebViewModelFactory?>(null)+ private val externalUrlState = mutableStateOf<String?>(null)++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ // SYSTEM permissive browser: any host + user CAs for MITM debug/corp proxies (per user exception)+ NetworkClient.init(this, TrustBundle.SYSTEM)+ enableEdgeToEdge()+ // Parses ~8 MB of filter lists off the main thread. Shields fail open until it lands.+ lifecycleScope.launch { ShieldsEngine.load(applicationContext) }++ // Each task (window) carries its own window id + incognito flag so it keeps an independent tab set.+ val windowId = intent?.getStringExtra(EXTRA_WINDOW_ID) ?: WebViewModel.DEFAULT_WINDOW_ID+ val incognito = intent?.getBooleanExtra(EXTRA_INCOGNITO, false) ?: false++ // Reap tab-sets left behind by windows the user has since closed (swiped from Recents).+ pruneClosedWindowTabs()++ lifecycleScope.launch(Dispatchers.IO) {+ val repository = WebRepository.get(applicationContext)+ val factory = WebViewModelFactory(+ repository = repository,+ context = applicationContext,+ windowId = windowId,+ incognito = incognito,+ initialShieldSettings = repository.allShieldSettings(),+ )+ withContext(Dispatchers.Main) {+ factoryState = factory+ readyState.value = true+ handleIntentUrl(intent)+ }+ }++ setContent {+ DynamicTheme {+ OfflineAware {+ Box(Modifier.fillMaxSize()) {+ if (!readyState.value || factoryState == null) {+ Box(Modifier.fillMaxSize())+ } else {+ AppRoot(factoryState!!, externalUrlState.value) {+ externalUrlState.value = null+ }+ }+ }+ }+ }+ }+ }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ handleIntentUrl(intent)+ }++ private fun handleIntentUrl(intent: Intent?) {+ intent ?: return+ val raw = when (intent.action) {+ Intent.ACTION_VIEW -> intent.dataString+ Intent.ACTION_SEND -> intent.getStringExtra(Intent.EXTRA_TEXT)+ else -> null+ } ?: return++ val url = extractHttpUrl(raw) ?: return+ externalUrlState.value = url+ }++ private fun extractHttpUrl(text: String): String? {+ val trimmed = text.trim()+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {+ val match = Regex("https?://\\S+").find(trimmed)+ return match?.value ?: trimmed.substringBefore(" ")+ }+ Regex("https?://\\S+").find(trimmed)?.let { return it.value }+ return null+ }++ /**+ * Removes persisted tab-sets whose window is no longer a live task. Each non-incognito window+ * stores its tabs under keys suffixed with its window id (see [WebViewModel]); when the user+ * swipes a window out of Recents those keys would otherwise linger forever.+ */+ private fun pruneClosedWindowTabs() {+ // Must mirror WebViewModel's namespaced key format: "<P_SAVED_TABS>_<windowId>" etc.+ val savedTabsPrefix = "web_saved_tabs_"+ val activeTabPrefix = "web_active_tab_id_"+ lifecycleScope.launch(Dispatchers.IO) {+ try {+ val am = getSystemService(ACTIVITY_SERVICE) as? android.app.ActivityManager ?: return@launch+ val liveWindowIds = am.appTasks.mapNotNull { task ->+ val base = runCatching { task.taskInfo?.baseIntent }.getOrNull()+ base?.getStringExtra(EXTRA_WINDOW_ID)+ ?: base?.data?.takeIf { it.scheme == "web-window" }?.host+ }.toSet()++ val sp = getSharedPreferences("web_prefs", MODE_PRIVATE)+ val editor = sp.edit()+ var changed = false+ for (key in sp.all.keys) {+ val windowId = when {+ key.startsWith(savedTabsPrefix) -> key.removePrefix(savedTabsPrefix)+ key.startsWith(activeTabPrefix) -> key.removePrefix(activeTabPrefix)+ else -> null+ } ?: continue+ if (windowId !in liveWindowIds) {+ editor.remove(key)+ changed = true+ }+ }+ if (changed) editor.apply()+ } catch (e: Exception) {+ android.util.Log.e("MainActivity", "pruneClosedWindowTabs failed", e)+ }+ }+ }++ companion object {+ const val EXTRA_WINDOW_ID = "com.vayunmathur.web.WINDOW_ID"+ const val EXTRA_INCOGNITO = "com.vayunmathur.web.INCOGNITO"+ }+}
web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt b/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.ktindex ec6c98a070..65893297e8 100644--- a/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt@@ -1,377 +1,377 @@-package com.vayunmathur.web.platform--import android.Manifest-import android.annotation.SuppressLint-import android.content.Intent-import android.content.pm.PackageManager-import android.net.Uri-import android.os.Bundle-import android.view.ViewGroup-import android.webkit.CookieManager-import android.webkit.DownloadListener-import android.webkit.GeolocationPermissions-import android.webkit.PermissionRequest-import android.webkit.WebChromeClient-import android.webkit.WebResourceRequest-import android.webkit.WebSettings-import android.webkit.WebView-import androidx.activity.ComponentActivity-import androidx.activity.compose.BackHandler-import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.compose.setContent-import androidx.activity.enableEdgeToEdge-import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.statusBarsPadding-import androidx.compose.runtime.Composable-import androidx.compose.runtime.getValue-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Modifier-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.viewinterop.AndroidView-import androidx.core.content.ContextCompat-import androidx.lifecycle.lifecycleScope-import kotlinx.coroutines.launch-import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.web.platform.shields.FarblingConfig-import com.vayunmathur.web.platform.shields.ShieldsEngine-import com.vayunmathur.web.platform.shields.ShieldsWebViewClient-import com.vayunmathur.web.ui.applySystemDarkMode-import com.vayunmathur.web.domain.EffectiveShields-import com.vayunmathur.web.domain.ShieldsSettings--class PwaActivity : ComponentActivity() {-- companion object {- const val EXTRA_URL = "pwa_url"- const val EXTRA_TITLE = "pwa_title"- }-- private val initialUrlState = mutableStateOf<String?>(null)- private val titleState = mutableStateOf<String?>(null)-- override fun onCreate(savedInstanceState: Bundle?) {- super.onCreate(savedInstanceState)- enableEdgeToEdge()- // Installed sites get the same shields as the browser; loading is a no-op if the- // engine is already up in this process.- lifecycleScope.launch { ShieldsEngine.load(applicationContext) }- handleIntent(intent)- setContent {- DynamicTheme {- val url = initialUrlState.value- if (url.isNullOrBlank()) {- Box(Modifier.fillMaxSize())- } else {- PwaBrowser(- initialUrl = url,- title = titleState.value,- modifier = Modifier.fillMaxSize()- )- }- }- }- }-- override fun onNewIntent(intent: Intent) {- super.onNewIntent(intent)- handleIntent(intent)- }-- private fun handleIntent(intent: Intent?) {- intent ?: return- val urlFromExtra = intent.getStringExtra(EXTRA_URL)- val urlFromData = intent.dataString ?: intent.getStringExtra(Intent.EXTRA_TEXT)- val url = urlFromExtra ?: extractHttpUrl(urlFromData ?: "") ?: return- initialUrlState.value = url- titleState.value = intent.getStringExtra(EXTRA_TITLE)- }-- private fun extractHttpUrl(text: String): String? {- val trimmed = text.trim()- if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {- val match = Regex("https?://\\S+").find(trimmed)- return match?.value ?: trimmed.substringBefore(" ")- }- Regex("https?://\\S+").find(trimmed)?.let { return it.value }- return null- }-}--@SuppressLint("SetJavaScriptEnabled")-@Composable-private fun PwaBrowser(- initialUrl: String,- title: String?,- modifier: Modifier = Modifier,-) {- val context = LocalContext.current- val activity = context as? ComponentActivity-- var currentTitle by remember { mutableStateOf(title ?: "") }- var webViewRef by remember { mutableStateOf<WebView?>(null) }-- // For permission handling- var pendingSysPermissionRequest by remember { mutableStateOf<PermissionRequest?>(null) }- var pendingGeoCallback by remember { mutableStateOf<Pair<String, GeolocationPermissions.Callback>?>(null) }-- val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->- if (granted) {- pendingSysPermissionRequest?.grant(pendingSysPermissionRequest?.resources ?: emptyArray())- } else {- pendingSysPermissionRequest?.deny()- }- pendingSysPermissionRequest = null- }- val micLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->- if (granted) {- pendingSysPermissionRequest?.grant(pendingSysPermissionRequest?.resources ?: emptyArray())- } else {- pendingSysPermissionRequest?.deny()- }- pendingSysPermissionRequest = null- }- val multiLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->- val allGranted = result.values.all { it }- if (allGranted) {- pendingSysPermissionRequest?.grant(pendingSysPermissionRequest?.resources ?: emptyArray())- } else {- pendingSysPermissionRequest?.deny()- }- pendingSysPermissionRequest = null- }- val locationLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->- val granted = result[Manifest.permission.ACCESS_FINE_LOCATION] == true ||- result[Manifest.permission.ACCESS_COARSE_LOCATION] == true- val pair = pendingGeoCallback- if (granted) {- pair?.second?.invoke(pair.first, true, false)- } else {- pair?.second?.invoke(pair.first, false, false)- }- pendingGeoCallback = null- }-- val multiDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->- // deliver to pending file chooser- @Suppress("UNCHECKED_CAST")- (webViewRef?.tag as? android.webkit.ValueCallback<Array<Uri>>)?.onReceiveValue(- uris.toTypedArray().takeIf { it.isNotEmpty() }- )- webViewRef?.tag = null- }- val singleDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->- @Suppress("UNCHECKED_CAST")- (webViewRef?.tag as? android.webkit.ValueCallback<Array<Uri>>)?.onReceiveValue(- uri?.let { arrayOf(it) }- )- webViewRef?.tag = null- }-- BackHandler {- val wv = webViewRef- if (wv != null && wv.canGoBack()) {- wv.goBack()- } else {- activity?.finish()- }- }-- Box(modifier = modifier.fillMaxSize().statusBarsPadding()) {- AndroidView(- modifier = Modifier.fillMaxSize(),- factory = { ctx ->- WebView(ctx).apply {- layoutParams = ViewGroup.LayoutParams(- ViewGroup.LayoutParams.MATCH_PARENT,- ViewGroup.LayoutParams.MATCH_PARENT- )- val cookieManager = CookieManager.getInstance()- cookieManager.setAcceptCookie(true)- cookieManager.setAcceptThirdPartyCookies(this, true)-- settings.javaScriptEnabled = true- settings.javaScriptCanOpenWindowsAutomatically = true- settings.domStorageEnabled = true- settings.databaseEnabled = true- settings.cacheMode = WebSettings.LOAD_DEFAULT- settings.allowFileAccess = true- settings.allowContentAccess = true- settings.offscreenPreRaster = true- settings.setSupportZoom(true)- settings.builtInZoomControls = true- settings.displayZoomControls = false- settings.useWideViewPort = true- settings.loadWithOverviewMode = true- settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE- settings.setGeolocationEnabled(true)- @Suppress("DEPRECATION")- try {- settings.setGeolocationDatabasePath(ctx.filesDir.absolutePath)- } catch (_: Exception) {}- settings.setSupportMultipleWindows(true)- settings.mediaPlaybackRequiresUserGesture = false- settings.applySystemDarkMode()- try {- val compat = Class.forName("androidx.webkit.WebSettingsCompat")- val feature = Class.forName("androidx.webkit.WebViewFeature")- val isSupported = feature.getMethod("isFeatureSupported", String::class.java)- .invoke(null, "SAFE_BROWSING_ENABLE") as Boolean- if (isSupported) {- compat.getMethod(- "setSafeBrowsingEnabled",- WebSettings::class.java,- Boolean::class.javaPrimitiveType- ).invoke(null, settings, true)- }- } catch (_: Exception) {}-- setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimeType, _ ->- val fileName = android.webkit.URLUtil.guessFileName(url, contentDisposition, mimeType)- try {- val dm = ctx.getSystemService(android.app.DownloadManager::class.java)- val request = android.app.DownloadManager.Request(Uri.parse(url)).apply {- setMimeType(mimeType)- addRequestHeader("User-Agent", userAgent)- setDescription("Downloading $fileName")- setTitle(fileName)- setNotificationVisibility(android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)- setDestinationInExternalPublicDir(android.os.Environment.DIRECTORY_DOWNLOADS, fileName)- }- dm.enqueue(request)- } catch (_: Exception) {- try {- ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {- addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)- })- } catch (_: Exception) {}- }- })-- webViewClient = object : ShieldsWebViewClient(- context = ctx,- // Installed sites have no shields panel, so they always run the- // aggressive preset the browser ships with.- shieldsFor = { EffectiveShields.resolve(ShieldsSettings.AGGRESSIVE_DEFAULTS) },- ) {- override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {- val scheme = request.url.scheme ?: return false- if (scheme !in setOf("http", "https", "about", "data", "blob", "javascript")) {- return com.vayunmathur.web.util.openExternalUri(- ctx,- request.url.toString(),- ) { fallback -> view.loadUrl(fallback) }- }- // For PWA: stay inside same origin; external origins still load but that is okay.- return super.shouldOverrideUrlLoading(view, request)- }-- override fun onPageFinished(view: WebView, url: String?) {- CookieManager.getInstance().flush()- val t = view.title?.takeIf { it.isNotBlank() } ?: url ?: ""- if (t.isNotBlank()) currentTitle = t- }- }-- webChromeClient = object : WebChromeClient() {- override fun onReceivedTitle(view: WebView, t: String?) {- if (!t.isNullOrBlank()) currentTitle = t- }-- override fun onGeolocationPermissionsShowPrompt(- origin: String,- callback: GeolocationPermissions.Callback- ) {- val hasFine = ContextCompat.checkSelfPermission(- ctx,- Manifest.permission.ACCESS_FINE_LOCATION- ) == PackageManager.PERMISSION_GRANTED- val hasCoarse = ContextCompat.checkSelfPermission(- ctx,- Manifest.permission.ACCESS_COARSE_LOCATION- ) == PackageManager.PERMISSION_GRANTED- if (!hasFine && !hasCoarse) {- pendingGeoCallback = origin to callback- locationLauncher.launch(- arrayOf(- Manifest.permission.ACCESS_FINE_LOCATION,- Manifest.permission.ACCESS_COARSE_LOCATION- )- )- } else {- callback.invoke(origin, true, false)- }- }-- override fun onPermissionRequest(request: PermissionRequest) {- val resources = request.resources- val needsCamera = resources.contains(PermissionRequest.RESOURCE_VIDEO_CAPTURE)- val needsMic = resources.contains(PermissionRequest.RESOURCE_AUDIO_CAPTURE)- if (!needsCamera && !needsMic) {- request.grant(resources)- return- }- val hasCamera = if (needsCamera) {- ContextCompat.checkSelfPermission(ctx, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED- } else true- val hasMic = if (needsMic) {- ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED- } else true- if (!hasCamera || !hasMic) {- pendingSysPermissionRequest = request- when {- needsCamera && needsMic -> multiLauncher.launch(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO))- needsCamera -> cameraLauncher.launch(Manifest.permission.CAMERA)- needsMic -> micLauncher.launch(Manifest.permission.RECORD_AUDIO)- }- return- }- request.grant(resources)- }-- override fun onShowFileChooser(- webView: WebView,- filePathCallback: android.webkit.ValueCallback<Array<Uri>>,- fileChooserParams: FileChooserParams- ): Boolean {- // store callback in tag for launchers to use- webViewRef?.tag = filePathCallback- val mimeTypes = try { fileChooserParams.acceptTypes.toList() } catch (_: Exception) { emptyList<String>() }- val allowMultiple = try { fileChooserParams.mode == FileChooserParams.MODE_OPEN_MULTIPLE } catch (_: Exception) { false }- try {- if (allowMultiple) {- multiDocLauncher.launch(- mimeTypes.filter { it.isNotBlank() }.toTypedArray().takeIf { it.isNotEmpty() } ?: arrayOf("*/*")- )- } else {- val mt = mimeTypes.firstOrNull { it.isNotBlank() } ?: "*/*"- singleDocLauncher.launch(arrayOf(mt))- }- } catch (_: Exception) {- filePathCallback.onReceiveValue(null)- webViewRef?.tag = null- }- return true- }- }-- // Before the first load: document-start scripts do not apply retroactively.- (webViewClient as ShieldsWebViewClient)- .installFarbling(this, FarblingConfig.of(ShieldsSettings.AGGRESSIVE_DEFAULTS, emptyMap()))- loadUrl(initialUrl)- }.also {- webViewRef = it- }- },- update = { wv ->- webViewRef = wv- if ((wv.url ?: "") != initialUrl && wv.url.isNullOrBlank()) {- wv.loadUrl(initialUrl)- }- }- )- }-}+package com.vayunmathur.web.platform++import android.Manifest+import android.annotation.SuppressLint+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Bundle+import android.view.ViewGroup+import android.webkit.CookieManager+import android.webkit.DownloadListener+import android.webkit.GeolocationPermissions+import android.webkit.PermissionRequest+import android.webkit.WebChromeClient+import android.webkit.WebResourceRequest+import android.webkit.WebSettings+import android.webkit.WebView+import androidx.activity.ComponentActivity+import androidx.activity.compose.BackHandler+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.compose.setContent+import androidx.activity.enableEdgeToEdge+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.statusBarsPadding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.viewinterop.AndroidView+import androidx.core.content.ContextCompat+import androidx.lifecycle.lifecycleScope+import kotlinx.coroutines.launch+import com.vayunmathur.library.ui.DynamicTheme+import com.vayunmathur.web.platform.shields.FarblingConfig+import com.vayunmathur.web.platform.shields.ShieldsEngine+import com.vayunmathur.web.platform.shields.ShieldsWebViewClient+import com.vayunmathur.web.ui.applySystemDarkMode+import com.vayunmathur.web.domain.EffectiveShields+import com.vayunmathur.web.domain.ShieldsSettings++class PwaActivity : ComponentActivity() {++ companion object {+ const val EXTRA_URL = "pwa_url"+ const val EXTRA_TITLE = "pwa_title"+ }++ private val initialUrlState = mutableStateOf<String?>(null)+ private val titleState = mutableStateOf<String?>(null)++ override fun onCreate(savedInstanceState: Bundle?) {+ super.onCreate(savedInstanceState)+ enableEdgeToEdge()+ // Installed sites get the same shields as the browser; loading is a no-op if the+ // engine is already up in this process.+ lifecycleScope.launch { ShieldsEngine.load(applicationContext) }+ handleIntent(intent)+ setContent {+ DynamicTheme {+ val url = initialUrlState.value+ if (url.isNullOrBlank()) {+ Box(Modifier.fillMaxSize())+ } else {+ PwaBrowser(+ initialUrl = url,+ title = titleState.value,+ modifier = Modifier.fillMaxSize()+ )+ }+ }+ }+ }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ handleIntent(intent)+ }++ private fun handleIntent(intent: Intent?) {+ intent ?: return+ val urlFromExtra = intent.getStringExtra(EXTRA_URL)+ val urlFromData = intent.dataString ?: intent.getStringExtra(Intent.EXTRA_TEXT)+ val url = urlFromExtra ?: extractHttpUrl(urlFromData ?: "") ?: return+ initialUrlState.value = url+ titleState.value = intent.getStringExtra(EXTRA_TITLE)+ }++ private fun extractHttpUrl(text: String): String? {+ val trimmed = text.trim()+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) {+ val match = Regex("https?://\\S+").find(trimmed)+ return match?.value ?: trimmed.substringBefore(" ")+ }+ Regex("https?://\\S+").find(trimmed)?.let { return it.value }+ return null+ }+}++@SuppressLint("SetJavaScriptEnabled")+@Composable+private fun PwaBrowser(+ initialUrl: String,+ title: String?,+ modifier: Modifier = Modifier,+) {+ val context = LocalContext.current+ val activity = context as? ComponentActivity++ var currentTitle by remember { mutableStateOf(title ?: "") }+ var webViewRef by remember { mutableStateOf<WebView?>(null) }++ // For permission handling+ var pendingSysPermissionRequest by remember { mutableStateOf<PermissionRequest?>(null) }+ var pendingGeoCallback by remember { mutableStateOf<Pair<String, GeolocationPermissions.Callback>?>(null) }++ val cameraLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ if (granted) {+ pendingSysPermissionRequest?.grant(pendingSysPermissionRequest?.resources ?: emptyArray())+ } else {+ pendingSysPermissionRequest?.deny()+ }+ pendingSysPermissionRequest = null+ }+ val micLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ if (granted) {+ pendingSysPermissionRequest?.grant(pendingSysPermissionRequest?.resources ?: emptyArray())+ } else {+ pendingSysPermissionRequest?.deny()+ }+ pendingSysPermissionRequest = null+ }+ val multiLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->+ val allGranted = result.values.all { it }+ if (allGranted) {+ pendingSysPermissionRequest?.grant(pendingSysPermissionRequest?.resources ?: emptyArray())+ } else {+ pendingSysPermissionRequest?.deny()+ }+ pendingSysPermissionRequest = null+ }+ val locationLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { result ->+ val granted = result[Manifest.permission.ACCESS_FINE_LOCATION] == true ||+ result[Manifest.permission.ACCESS_COARSE_LOCATION] == true+ val pair = pendingGeoCallback+ if (granted) {+ pair?.second?.invoke(pair.first, true, false)+ } else {+ pair?.second?.invoke(pair.first, false, false)+ }+ pendingGeoCallback = null+ }++ val multiDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->+ // deliver to pending file chooser+ @Suppress("UNCHECKED_CAST")+ (webViewRef?.tag as? android.webkit.ValueCallback<Array<Uri>>)?.onReceiveValue(+ uris.toTypedArray().takeIf { it.isNotEmpty() }+ )+ webViewRef?.tag = null+ }+ val singleDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->+ @Suppress("UNCHECKED_CAST")+ (webViewRef?.tag as? android.webkit.ValueCallback<Array<Uri>>)?.onReceiveValue(+ uri?.let { arrayOf(it) }+ )+ webViewRef?.tag = null+ }++ BackHandler {+ val wv = webViewRef+ if (wv != null && wv.canGoBack()) {+ wv.goBack()+ } else {+ activity?.finish()+ }+ }++ Box(modifier = modifier.fillMaxSize().statusBarsPadding()) {+ AndroidView(+ modifier = Modifier.fillMaxSize(),+ factory = { ctx ->+ WebView(ctx).apply {+ layoutParams = ViewGroup.LayoutParams(+ ViewGroup.LayoutParams.MATCH_PARENT,+ ViewGroup.LayoutParams.MATCH_PARENT+ )+ val cookieManager = CookieManager.getInstance()+ cookieManager.setAcceptCookie(true)+ cookieManager.setAcceptThirdPartyCookies(this, true)++ settings.javaScriptEnabled = true+ settings.javaScriptCanOpenWindowsAutomatically = true+ settings.domStorageEnabled = true+ settings.databaseEnabled = true+ settings.cacheMode = WebSettings.LOAD_DEFAULT+ settings.allowFileAccess = true+ settings.allowContentAccess = true+ settings.offscreenPreRaster = true+ settings.setSupportZoom(true)+ settings.builtInZoomControls = true+ settings.displayZoomControls = false+ settings.useWideViewPort = true+ settings.loadWithOverviewMode = true+ settings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE+ settings.setGeolocationEnabled(true)+ @Suppress("DEPRECATION")+ try {+ settings.setGeolocationDatabasePath(ctx.filesDir.absolutePath)+ } catch (_: Exception) {}+ settings.setSupportMultipleWindows(true)+ settings.mediaPlaybackRequiresUserGesture = false+ settings.applySystemDarkMode()+ try {+ val compat = Class.forName("androidx.webkit.WebSettingsCompat")+ val feature = Class.forName("androidx.webkit.WebViewFeature")+ val isSupported = feature.getMethod("isFeatureSupported", String::class.java)+ .invoke(null, "SAFE_BROWSING_ENABLE") as Boolean+ if (isSupported) {+ compat.getMethod(+ "setSafeBrowsingEnabled",+ WebSettings::class.java,+ Boolean::class.javaPrimitiveType+ ).invoke(null, settings, true)+ }+ } catch (_: Exception) {}++ setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimeType, _ ->+ val fileName = android.webkit.URLUtil.guessFileName(url, contentDisposition, mimeType)+ try {+ val dm = ctx.getSystemService(android.app.DownloadManager::class.java)+ val request = android.app.DownloadManager.Request(Uri.parse(url)).apply {+ setMimeType(mimeType)+ addRequestHeader("User-Agent", userAgent)+ setDescription("Downloading $fileName")+ setTitle(fileName)+ setNotificationVisibility(android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)+ setDestinationInExternalPublicDir(android.os.Environment.DIRECTORY_DOWNLOADS, fileName)+ }+ dm.enqueue(request)+ } catch (_: Exception) {+ try {+ ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).apply {+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ })+ } catch (_: Exception) {}+ }+ })++ webViewClient = object : ShieldsWebViewClient(+ context = ctx,+ // Installed sites have no shields panel, so they always run the+ // aggressive preset the browser ships with.+ shieldsFor = { EffectiveShields.resolve(ShieldsSettings.AGGRESSIVE_DEFAULTS) },+ ) {+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {+ val scheme = request.url.scheme ?: return false+ if (scheme !in setOf("http", "https", "about", "data", "blob", "javascript")) {+ return com.vayunmathur.web.platform.openExternalUri(+ ctx,+ request.url.toString(),+ ) { fallback -> view.loadUrl(fallback) }+ }+ // For PWA: stay inside same origin; external origins still load but that is okay.+ return super.shouldOverrideUrlLoading(view, request)+ }++ override fun onPageFinished(view: WebView, url: String?) {+ CookieManager.getInstance().flush()+ val t = view.title?.takeIf { it.isNotBlank() } ?: url ?: ""+ if (t.isNotBlank()) currentTitle = t+ }+ }++ webChromeClient = object : WebChromeClient() {+ override fun onReceivedTitle(view: WebView, t: String?) {+ if (!t.isNullOrBlank()) currentTitle = t+ }++ override fun onGeolocationPermissionsShowPrompt(+ origin: String,+ callback: GeolocationPermissions.Callback+ ) {+ val hasFine = ContextCompat.checkSelfPermission(+ ctx,+ Manifest.permission.ACCESS_FINE_LOCATION+ ) == PackageManager.PERMISSION_GRANTED+ val hasCoarse = ContextCompat.checkSelfPermission(+ ctx,+ Manifest.permission.ACCESS_COARSE_LOCATION+ ) == PackageManager.PERMISSION_GRANTED+ if (!hasFine && !hasCoarse) {+ pendingGeoCallback = origin to callback+ locationLauncher.launch(+ arrayOf(+ Manifest.permission.ACCESS_FINE_LOCATION,+ Manifest.permission.ACCESS_COARSE_LOCATION+ )+ )+ } else {+ callback.invoke(origin, true, false)+ }+ }++ override fun onPermissionRequest(request: PermissionRequest) {+ val resources = request.resources+ val needsCamera = resources.contains(PermissionRequest.RESOURCE_VIDEO_CAPTURE)+ val needsMic = resources.contains(PermissionRequest.RESOURCE_AUDIO_CAPTURE)+ if (!needsCamera && !needsMic) {+ request.grant(resources)+ return+ }+ val hasCamera = if (needsCamera) {+ ContextCompat.checkSelfPermission(ctx, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED+ } else true+ val hasMic = if (needsMic) {+ ContextCompat.checkSelfPermission(ctx, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED+ } else true+ if (!hasCamera || !hasMic) {+ pendingSysPermissionRequest = request+ when {+ needsCamera && needsMic -> multiLauncher.launch(arrayOf(Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO))+ needsCamera -> cameraLauncher.launch(Manifest.permission.CAMERA)+ needsMic -> micLauncher.launch(Manifest.permission.RECORD_AUDIO)+ }+ return+ }+ request.grant(resources)+ }++ override fun onShowFileChooser(+ webView: WebView,+ filePathCallback: android.webkit.ValueCallback<Array<Uri>>,+ fileChooserParams: FileChooserParams+ ): Boolean {+ // store callback in tag for launchers to use+ webViewRef?.tag = filePathCallback+ val mimeTypes = try { fileChooserParams.acceptTypes.toList() } catch (_: Exception) { emptyList<String>() }+ val allowMultiple = try { fileChooserParams.mode == FileChooserParams.MODE_OPEN_MULTIPLE } catch (_: Exception) { false }+ try {+ if (allowMultiple) {+ multiDocLauncher.launch(+ mimeTypes.filter { it.isNotBlank() }.toTypedArray().takeIf { it.isNotEmpty() } ?: arrayOf("*/*")+ )+ } else {+ val mt = mimeTypes.firstOrNull { it.isNotBlank() } ?: "*/*"+ singleDocLauncher.launch(arrayOf(mt))+ }+ } catch (_: Exception) {+ filePathCallback.onReceiveValue(null)+ webViewRef?.tag = null+ }+ return true+ }+ }++ // Before the first load: document-start scripts do not apply retroactively.+ (webViewClient as ShieldsWebViewClient)+ .installFarbling(this, FarblingConfig.of(ShieldsSettings.AGGRESSIVE_DEFAULTS, emptyMap()))+ loadUrl(initialUrl)+ }.also {+ webViewRef = it+ }+ },+ update = { wv ->+ webViewRef = wv+ if ((wv.url ?: "") != initialUrl && wv.url.isNullOrBlank()) {+ wv.loadUrl(initialUrl)+ }+ }+ )+ }+}
web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.ktindex 611c137957..ba0d631618 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt@@ -22,6 +22,9 @@ import com.vayunmathur.web.data.SitePermission import com.vayunmathur.web.data.WebRepository import com.vayunmathur.web.data.ShieldSetting import com.vayunmathur.web.data.StorageInfo+import com.vayunmathur.web.domain.EffectiveShields+import com.vayunmathur.web.domain.ShieldLevel+import com.vayunmathur.web.domain.ShieldsSettings import com.vayunmathur.web.platform.shields.FarblingConfig import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow
web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.ktindex 5877e765a7..4a0b090add 100644--- a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt@@ -1,240 +1,242 @@-package com.vayunmathur.web.platform.shields--import android.content.Context-import android.graphics.Bitmap-import android.net.Uri-import android.util.Log-import android.webkit.WebResourceRequest-import android.webkit.WebResourceResponse-import android.webkit.WebView-import android.webkit.WebViewClient-import androidx.webkit.JavaScriptReplyProxy-import androidx.webkit.ScriptHandler-import androidx.webkit.WebMessageCompat-import androidx.webkit.WebViewCompat-import androidx.webkit.WebViewFeature-import com.vayunmathur.web.domain.EffectiveShields-import kotlinx.serialization.Serializable-import kotlinx.serialization.json.Json-import java.io.ByteArrayInputStream-import java.util.Base64-import kotlin.random.Random--private const val TAG = "ShieldsWebViewClient"--/** Empty bodies returned for blocked requests, by resource type. */-private val EMPTY_GIF: ByteArray = Base64.getDecoder()- .decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")--@Serializable-private data class CosmeticQuery(- val classes: List<String> = emptyList(),- val ids: List<String> = emptyList(),- val exceptions: List<String> = emptyList(),-)--/**- * A [WebViewClient] that applies Brave Shields.- *- * Subclasses add the host's own navigation and title plumbing; everything shields-related- * lives here so `WebViewBrowser` and `PwaActivity` cannot drift apart. Subclasses that- * override [onPageStarted] or [shouldOverrideUrlLoading] **must** call through to super.- *- * @param shieldsFor resolved shields for a host, consulted per request- * @param onBlocked called on the render thread each time a request is blocked- * @param onNavigate asks the host to load a URL shields rewrote (HTTPS upgrade, param strip)- */-open class ShieldsWebViewClient(- private val context: Context,- private val shieldsFor: (host: String) -> EffectiveShields,- private val onBlocked: (pageUrl: String, blockedUrl: String) -> Unit = { _, _ -> },- private val onNavigate: (WebView, String) -> Unit = { view, url -> view.loadUrl(url) },-) : WebViewClient() {-- /**- * The document the current subresources belong to. `WebResourceRequest` has no- * initiator, so first-party detection depends entirely on tracking this.- */- @Volatile- private var pageUrl: String = ""-- /** Per-session salt; combined with the site's host it gives Brave's per-origin seed. */- private val sessionSalt: Int = Random.nextInt()-- private val json = Json { ignoreUnknownKeys = true }-- /** URLs this client already rewrote, so the reload does not bounce forever. */- private var lastRewritten: String? = null-- private var cosmeticChannelInstalled = false- private var farbleHandle: ScriptHandler? = null- private var installedFarbling: String? = null-- /**- * Installs the fingerprinting defence on [view].- *- * Must be called before the first `loadUrl`: `addDocumentStartJavaScript` only applies- * to documents that begin loading after registration, and farbling is worthless once- * the page has read the real values. Re-registering after a settings change is cheap- * — the previous script handle is removed first.- */- fun installFarbling(view: WebView, config: FarblingConfig) {- if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) return- val script = ShieldsInjection.farbling(context, config, sessionSalt)- if (script == installedFarbling) return- runCatching {- farbleHandle?.remove()- farbleHandle = WebViewCompat.addDocumentStartJavaScript(view, script, setOf("*"))- installedFarbling = script- }.onFailure { Log.w(TAG, "farbling script rejected", it) }- }-- // ---------------------------------------------------------------- network-- override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {- val url = request.url.toString()- val scheme = request.url.scheme?.lowercase()- if (scheme != "http" && scheme != "https") return null-- if (request.isForMainFrame) {- pageUrl = url- return null- }-- val source = pageUrl.ifEmpty { url }- val shields = shieldsFor(hostOf(source))- if (!shields.blockTrackers) return null-- val type = ResourceTypes.of(url, isMainFrame = false, headers = request.requestHeaders)- val result = ShieldsEngine.check(url, source, type) ?: return null- if (!result.blocked) return null-- onBlocked(source, url)- return result.redirect?.let { dataUrlResponse(it) } ?: emptyResponse(type)- }-- /**- * An empty 200 rather than a failure: a blocked script that 404s can send a page down- * an error path, whereas an empty body usually just no-ops. The content type has to- * match what the element expected or the browser logs a MIME error and, for images,- * shows a broken-image placeholder.- */- private fun emptyResponse(type: String): WebResourceResponse {- val (mime, body) = when (type) {- "image" -> "image/gif" to EMPTY_GIF- "script" -> "application/javascript" to ByteArray(0)- "stylesheet" -> "text/css" to ByteArray(0)- "media" -> "video/mp4" to ByteArray(0)- "xmlhttprequest" -> "application/json" to ByteArray(0)- "subdocument" -> "text/html" to ByteArray(0)- else -> "text/plain" to ByteArray(0)- }- return WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(body))- }-- /** Serves the body of a `$redirect` rule, which the engine hands back as a data URL. */- private fun dataUrlResponse(dataUrl: String): WebResourceResponse? = try {- val header = dataUrl.substringBefore(',', "")- val payload = dataUrl.substringAfter(',', "")- val mime = header.removePrefix("data:").substringBefore(';').ifEmpty { "text/plain" }- val bytes = if (header.endsWith(";base64")) {- Base64.getDecoder().decode(payload)- } else {- Uri.decode(payload).toByteArray()- }- WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(bytes))- } catch (e: Exception) {- Log.w(TAG, "malformed redirect resource", e)- null- }-- // ------------------------------------------------------------- navigation-- override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {- if (!request.isForMainFrame) return false- val url = request.url.toString()- val rewritten = rewrite(url, shieldsFor(hostOf(url)))- if (rewritten != null && rewritten != url) {- lastRewritten = rewritten- onNavigate(view, rewritten)- return true- }- return false- }-- /**- * The HTTPS upgrade and parameter strip Brave applies to top-level navigations.- * Returns null when the URL is already clean.- */- private fun rewrite(url: String, shields: EffectiveShields): String? {- if (url == lastRewritten) return null- var result = url- if (shields.httpsUpgrade) {- UrlCleaner.httpsUpgrade(result)?.let { result = it }- }- if (shields.blockTrackers) {- result = UrlCleaner.clean(result)- }- return if (result == url) null else result- }-- override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {- super.onPageStarted(view, url, favicon)- url ?: return- pageUrl = url- if (url == lastRewritten) lastRewritten = null- applyShields(view, url)- }-- // -------------------------------------------------------------- injection-- /**- * Applies the cosmetic payload for the document that just started loading.- *- * Farbling is not done here — see [installFarbling]. Hide rules are URL-specific and- * only cosmetic, so evaluating them at page start is soon enough.- */- private fun applyShields(view: WebView, url: String) {- if (!url.startsWith("http")) return- val shields = shieldsFor(hostOf(url))- if (!shields.cosmeticFiltering) return-- installCosmeticChannel(view)- val script = ShieldsInjection.cosmetic(ShieldsEngine.cosmetic(url))- if (script.isNotEmpty()) view.evaluateJavascript(script, null)- }-- /**- * Wires the page's `MutationObserver` to [ShieldsEngine.hiddenClassIdSelectors] so- * generic hide rules can be resolved for classes and ids that appear after load.- */- private fun installCosmeticChannel(view: WebView) {- if (cosmeticChannelInstalled) return- if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return- runCatching {- WebViewCompat.addWebMessageListener(- view,- ShieldsInjection.COSMETIC_CHANNEL,- setOf("*"),- { _, message, _, isMainFrame, reply -> onCosmeticQuery(message, isMainFrame, reply) },- )- cosmeticChannelInstalled = true- }.onFailure { Log.w(TAG, "cosmetic channel unavailable", it) }- }-- private fun onCosmeticQuery(- message: WebMessageCompat,- isMainFrame: Boolean,- reply: JavaScriptReplyProxy,- ) {- if (!isMainFrame) return- val raw = message.data ?: return- val query = runCatching { json.decodeFromString<CosmeticQuery>(raw) }.getOrNull() ?: return- val selectors = ShieldsEngine.hiddenClassIdSelectors(query.classes, query.ids, query.exceptions)- if (selectors.isEmpty()) return- runCatching { reply.postMessage(json.encodeToString(selectors)) }- }-- private fun hostOf(url: String): String =- runCatching { Uri.parse(url).host.orEmpty() }.getOrDefault("")-}+package com.vayunmathur.web.platform.shields++import android.content.Context+import android.graphics.Bitmap+import android.net.Uri+import android.util.Log+import android.webkit.WebResourceRequest+import android.webkit.WebResourceResponse+import android.webkit.WebView+import android.webkit.WebViewClient+import androidx.webkit.JavaScriptReplyProxy+import androidx.webkit.ScriptHandler+import androidx.webkit.WebMessageCompat+import androidx.webkit.WebViewCompat+import androidx.webkit.WebViewFeature+import com.vayunmathur.web.domain.EffectiveShields+import com.vayunmathur.web.domain.shields.ResourceTypes+import com.vayunmathur.web.domain.shields.UrlCleaner+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import java.io.ByteArrayInputStream+import java.util.Base64+import kotlin.random.Random++private const val TAG = "ShieldsWebViewClient"++/** Empty bodies returned for blocked requests, by resource type. */+private val EMPTY_GIF: ByteArray = Base64.getDecoder()+ .decode("R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7")++@Serializable+private data class CosmeticQuery(+ val classes: List<String> = emptyList(),+ val ids: List<String> = emptyList(),+ val exceptions: List<String> = emptyList(),+)++/**+ * A [WebViewClient] that applies Brave Shields.+ *+ * Subclasses add the host's own navigation and title plumbing; everything shields-related+ * lives here so `WebViewBrowser` and `PwaActivity` cannot drift apart. Subclasses that+ * override [onPageStarted] or [shouldOverrideUrlLoading] **must** call through to super.+ *+ * @param shieldsFor resolved shields for a host, consulted per request+ * @param onBlocked called on the render thread each time a request is blocked+ * @param onNavigate asks the host to load a URL shields rewrote (HTTPS upgrade, param strip)+ */+open class ShieldsWebViewClient(+ private val context: Context,+ private val shieldsFor: (host: String) -> EffectiveShields,+ private val onBlocked: (pageUrl: String, blockedUrl: String) -> Unit = { _, _ -> },+ private val onNavigate: (WebView, String) -> Unit = { view, url -> view.loadUrl(url) },+) : WebViewClient() {++ /**+ * The document the current subresources belong to. `WebResourceRequest` has no+ * initiator, so first-party detection depends entirely on tracking this.+ */+ @Volatile+ private var pageUrl: String = ""++ /** Per-session salt; combined with the site's host it gives Brave's per-origin seed. */+ private val sessionSalt: Int = Random.nextInt()++ private val json = Json { ignoreUnknownKeys = true }++ /** URLs this client already rewrote, so the reload does not bounce forever. */+ private var lastRewritten: String? = null++ private var cosmeticChannelInstalled = false+ private var farbleHandle: ScriptHandler? = null+ private var installedFarbling: String? = null++ /**+ * Installs the fingerprinting defence on [view].+ *+ * Must be called before the first `loadUrl`: `addDocumentStartJavaScript` only applies+ * to documents that begin loading after registration, and farbling is worthless once+ * the page has read the real values. Re-registering after a settings change is cheap+ * — the previous script handle is removed first.+ */+ fun installFarbling(view: WebView, config: FarblingConfig) {+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) return+ val script = ShieldsInjection.farbling(context, config, sessionSalt)+ if (script == installedFarbling) return+ runCatching {+ farbleHandle?.remove()+ farbleHandle = WebViewCompat.addDocumentStartJavaScript(view, script, setOf("*"))+ installedFarbling = script+ }.onFailure { Log.w(TAG, "farbling script rejected", it) }+ }++ // ---------------------------------------------------------------- network++ override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {+ val url = request.url.toString()+ val scheme = request.url.scheme?.lowercase()+ if (scheme != "http" && scheme != "https") return null++ if (request.isForMainFrame) {+ pageUrl = url+ return null+ }++ val source = pageUrl.ifEmpty { url }+ val shields = shieldsFor(hostOf(source))+ if (!shields.blockTrackers) return null++ val type = ResourceTypes.of(url, isMainFrame = false, headers = request.requestHeaders)+ val result = ShieldsEngine.check(url, source, type) ?: return null+ if (!result.blocked) return null++ onBlocked(source, url)+ return result.redirect?.let { dataUrlResponse(it) } ?: emptyResponse(type)+ }++ /**+ * An empty 200 rather than a failure: a blocked script that 404s can send a page down+ * an error path, whereas an empty body usually just no-ops. The content type has to+ * match what the element expected or the browser logs a MIME error and, for images,+ * shows a broken-image placeholder.+ */+ private fun emptyResponse(type: String): WebResourceResponse {+ val (mime, body) = when (type) {+ "image" -> "image/gif" to EMPTY_GIF+ "script" -> "application/javascript" to ByteArray(0)+ "stylesheet" -> "text/css" to ByteArray(0)+ "media" -> "video/mp4" to ByteArray(0)+ "xmlhttprequest" -> "application/json" to ByteArray(0)+ "subdocument" -> "text/html" to ByteArray(0)+ else -> "text/plain" to ByteArray(0)+ }+ return WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(body))+ }++ /** Serves the body of a `$redirect` rule, which the engine hands back as a data URL. */+ private fun dataUrlResponse(dataUrl: String): WebResourceResponse? = try {+ val header = dataUrl.substringBefore(',', "")+ val payload = dataUrl.substringAfter(',', "")+ val mime = header.removePrefix("data:").substringBefore(';').ifEmpty { "text/plain" }+ val bytes = if (header.endsWith(";base64")) {+ Base64.getDecoder().decode(payload)+ } else {+ Uri.decode(payload).toByteArray()+ }+ WebResourceResponse(mime, "utf-8", 200, "OK", emptyMap(), ByteArrayInputStream(bytes))+ } catch (e: Exception) {+ Log.w(TAG, "malformed redirect resource", e)+ null+ }++ // ------------------------------------------------------------- navigation++ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {+ if (!request.isForMainFrame) return false+ val url = request.url.toString()+ val rewritten = rewrite(url, shieldsFor(hostOf(url)))+ if (rewritten != null && rewritten != url) {+ lastRewritten = rewritten+ onNavigate(view, rewritten)+ return true+ }+ return false+ }++ /**+ * The HTTPS upgrade and parameter strip Brave applies to top-level navigations.+ * Returns null when the URL is already clean.+ */+ private fun rewrite(url: String, shields: EffectiveShields): String? {+ if (url == lastRewritten) return null+ var result = url+ if (shields.httpsUpgrade) {+ UrlCleaner.httpsUpgrade(result)?.let { result = it }+ }+ if (shields.blockTrackers) {+ result = UrlCleaner.clean(result)+ }+ return if (result == url) null else result+ }++ override fun onPageStarted(view: WebView, url: String?, favicon: Bitmap?) {+ super.onPageStarted(view, url, favicon)+ url ?: return+ pageUrl = url+ if (url == lastRewritten) lastRewritten = null+ applyShields(view, url)+ }++ // -------------------------------------------------------------- injection++ /**+ * Applies the cosmetic payload for the document that just started loading.+ *+ * Farbling is not done here — see [installFarbling]. Hide rules are URL-specific and+ * only cosmetic, so evaluating them at page start is soon enough.+ */+ private fun applyShields(view: WebView, url: String) {+ if (!url.startsWith("http")) return+ val shields = shieldsFor(hostOf(url))+ if (!shields.cosmeticFiltering) return++ installCosmeticChannel(view)+ val script = ShieldsInjection.cosmetic(ShieldsEngine.cosmetic(url))+ if (script.isNotEmpty()) view.evaluateJavascript(script, null)+ }++ /**+ * Wires the page's `MutationObserver` to [ShieldsEngine.hiddenClassIdSelectors] so+ * generic hide rules can be resolved for classes and ids that appear after load.+ */+ private fun installCosmeticChannel(view: WebView) {+ if (cosmeticChannelInstalled) return+ if (!WebViewFeature.isFeatureSupported(WebViewFeature.WEB_MESSAGE_LISTENER)) return+ runCatching {+ WebViewCompat.addWebMessageListener(+ view,+ ShieldsInjection.COSMETIC_CHANNEL,+ setOf("*"),+ { _, message, _, isMainFrame, reply -> onCosmeticQuery(message, isMainFrame, reply) },+ )+ cosmeticChannelInstalled = true+ }.onFailure { Log.w(TAG, "cosmetic channel unavailable", it) }+ }++ private fun onCosmeticQuery(+ message: WebMessageCompat,+ isMainFrame: Boolean,+ reply: JavaScriptReplyProxy,+ ) {+ if (!isMainFrame) return+ val raw = message.data ?: return+ val query = runCatching { json.decodeFromString<CosmeticQuery>(raw) }.getOrNull() ?: return+ val selectors = ShieldsEngine.hiddenClassIdSelectors(query.classes, query.ids, query.exceptions)+ if (selectors.isEmpty()) return+ runCatching { reply.postMessage(json.encodeToString(selectors)) }+ }++ private fun hostOf(url: String): String =+ runCatching { Uri.parse(url).host.orEmpty() }.getOrDefault("")+}
web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.ktindex 6375550e71..3f33322dc8 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt@@ -1,853 +1,853 @@-package com.vayunmathur.web.ui--import androidx.compose.ui.res.pluralStringResource-import androidx.compose.ui.res.stringResource-import com.vayunmathur.web.R-import android.webkit.WebView-import androidx.activity.compose.BackHandler-import androidx.activity.compose.rememberLauncherForActivityResult-import androidx.activity.result.contract.ActivityResultContracts-import androidx.compose.foundation.background-import androidx.compose.foundation.clickable-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-import androidx.compose.foundation.layout.PaddingValues-import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.Spacer-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.fillMaxWidth-import androidx.compose.foundation.layout.height-import androidx.compose.foundation.layout.padding-import androidx.compose.foundation.layout.size-import androidx.compose.foundation.layout.width-import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.shape.CircleShape-import androidx.compose.foundation.shape.RoundedCornerShape-import androidx.compose.foundation.text.KeyboardActions-import androidx.compose.foundation.text.KeyboardOptions-import androidx.compose.runtime.Composable-import androidx.compose.runtime.LaunchedEffect-import androidx.compose.runtime.getValue-import androidx.compose.runtime.key-import androidx.compose.runtime.mutableStateMapOf-import androidx.compose.runtime.mutableStateOf-import androidx.compose.runtime.remember-import androidx.compose.runtime.setValue-import androidx.compose.ui.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.clip-import androidx.compose.ui.focus.FocusRequester-import androidx.compose.ui.focus.focusRequester-import androidx.compose.ui.platform.LocalContext-import androidx.compose.ui.platform.LocalFocusManager-import androidx.compose.ui.platform.LocalSoftwareKeyboardController-import androidx.compose.ui.text.input.ImeAction-import androidx.compose.ui.text.style.TextOverflow-import androidx.compose.ui.unit.dp-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.ExternalIntents-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.ui.AlertDialog-import com.vayunmathur.library.ui.Card-import com.vayunmathur.library.ui.CardDefaults-import com.vayunmathur.library.ui.CommonSearchBar-import com.vayunmathur.library.ui.DropdownMenu-import com.vayunmathur.library.ui.DropdownMenuItem-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.HorizontalDivider-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.LinearProgressIndicator-import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton-import com.vayunmathur.library.ui.OutlinedTextField-import com.vayunmathur.library.ui.Scaffold-import com.vayunmathur.library.ui.Surface-import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton-import com.vayunmathur.library.ui.TopAppBar-import com.vayunmathur.library.ui.TopAppBarDefaults-import com.vayunmathur.library.ui.IconAdd-import com.vayunmathur.library.ui.IconArrowForward-import com.vayunmathur.library.ui.IconBack-import com.vayunmathur.library.ui.IconClose-import com.vayunmathur.library.ui.IconMoreVert-import com.vayunmathur.library.ui.IconSearch-import com.vayunmathur.library.ui.IconShield-import com.vayunmathur.web.Route-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.web.platform.shields.ShieldsWebViewClient-import com.vayunmathur.web.platform.BrowserUtils-import com.vayunmathur.web.platform.PwaHelper-import com.vayunmathur.web.platform.PwaInfo-import com.vayunmathur.web.platform.WebViewModel-import com.vayunmathur.web.platform.isNewTab--@OptIn(ExperimentalMaterial3Api::class)-@Composable-fun BrowserPage(- viewModel: WebViewModel,- backStack: NavBackStack<Route>,-) {- val context = LocalContext.current- val focusManager = LocalFocusManager.current- val keyboardController = LocalSoftwareKeyboardController.current- val webViewPool = remember { mutableStateMapOf<String, WebView>() }-- LaunchedEffect(viewModel.tabs.size) {- if (viewModel.tabs.isEmpty()) viewModel.newTab()- }-- val activeTab = viewModel.activeTab- val canGoBack = activeTab?.let { viewModel.getCanGoBack(it.id) } ?: false- val canGoForward = activeTab?.let { viewModel.getCanGoForward(it.id) } ?: false- val progress = activeTab?.let { viewModel.getProgress(it.id) } ?: 0f- val isNewTabActive = activeTab?.isNewTab ?: true-- val bookmarks by viewModel.bookmarks.collectAsStateWithLifecycle()- val history by viewModel.history.collectAsStateWithLifecycle()- val isCurrentBookmarked = activeTab?.url?.let { url -> url.isNotBlank() && bookmarks.any { it.url == url } } ?: false-- val shieldHost = activeTab?.url?.takeIf { it.startsWith("http") }?.let { BrowserUtils.hostFromUrl(it) }- // Navigating away from the site the panel describes has to close it, otherwise it would- // silently start editing a different host's settings.- LaunchedEffect(shieldHost) { viewModel.showShieldsPanel = false }-- val multiDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->- viewModel.deliverFileChooserResult(uris.toTypedArray().takeIf { it.isNotEmpty() })- }- val singleDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->- viewModel.deliverFileChooserResult(uri?.let { arrayOf(it) })- }-- var showMenu by remember { mutableStateOf(false) }- var showInstallDialog by remember { mutableStateOf(false) }- var linkContextMenuUrl by remember { mutableStateOf<String?>(null) }- val searchFocusRequester = remember { FocusRequester() }-- BackHandler(enabled = viewModel.showTabSwitcher) { viewModel.showTabSwitcher = false }- BackHandler(enabled = !viewModel.showTabSwitcher && viewModel.omniboxFocused) {- viewModel.omniboxFocused = false- focusManager.clearFocus()- }- BackHandler(enabled = !viewModel.showTabSwitcher && !viewModel.omniboxFocused && canGoBack) {- activeTab?.let { tab -> webViewPool[tab.id]?.goBack() }- }-- LaunchedEffect(viewModel.omniboxFocused) {- if (viewModel.omniboxFocused) {- // Let the new Scaffold compose before requesting focus- kotlinx.coroutines.delay(100)- try { searchFocusRequester.requestFocus() } catch (_: Exception) {}- keyboardController?.show()- }- }-- val currentDraft = viewModel.searchDraft- val filteredBookmarks = remember(currentDraft, bookmarks) {- if (currentDraft.isBlank()) bookmarks.take(5)- else bookmarks.filter { it.url.contains(currentDraft, true) || it.title.contains(currentDraft, true) }.take(8)- }- val filteredHistory = remember(currentDraft, history) {- if (currentDraft.isBlank()) history.take(10)- else history.filter { it.url.contains(currentDraft, true) || it.title.contains(currentDraft, true) }.take(15)- }-- Box(Modifier.fillMaxSize()) {- if (viewModel.omniboxFocused) {- Scaffold(- topBar = {- TopAppBar(- navigationIcon = {- IconButton(onClick = {- focusManager.clearFocus()- viewModel.omniboxFocused = false- }) { IconBack() }- },- title = {- OutlinedTextField(- value = viewModel.searchDraft,- onValueChange = { viewModel.searchDraft = it },- modifier = Modifier- .fillMaxWidth()- .focusRequester(searchFocusRequester),- placeholder = { Text(stringResource(R.string.search_or_enter_address)) },- leadingIcon = { IconSearch() },- trailingIcon = if (viewModel.searchDraft.isNotEmpty()) {- {- IconButton(onClick = { viewModel.searchDraft = "" }) { IconClose() }- }- } else null,- shape = RoundedCornerShape(28.dp),- singleLine = true,- keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),- keyboardActions = KeyboardActions(onSearch = {- if (viewModel.searchDraft.isNotBlank()) {- viewModel.navigateActiveTab(viewModel.searchDraft)- focusManager.clearFocus()- viewModel.omniboxFocused = false- }- })- )- }- )- }- ) { paddingValues ->- LazyColumn(- modifier = Modifier- .fillMaxSize()- .padding(paddingValues),- verticalArrangement = Arrangement.spacedBy(2.dp),- contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp)- ) {- if (currentDraft.isNotBlank()) {- item {- ListItem(- headlineContent = { Text(currentDraft, maxLines = 1, overflow = TextOverflow.Ellipsis) },- supportingContent = {- Text(- text = BrowserUtils.hostFromUrl(- BrowserUtils.toNavigationUrl(currentDraft, viewModel.searchEngine)- ),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- maxLines = 1,- overflow = TextOverflow.Ellipsis- )- },- leadingContent = { IconSearch() },- modifier = Modifier.clickable {- viewModel.navigateActiveTab(currentDraft)- focusManager.clearFocus()- viewModel.omniboxFocused = false- }- )- }- item { HorizontalDivider(Modifier.padding(vertical = 4.dp)) }- }-- if (filteredBookmarks.isNotEmpty()) {- item {- Text(- stringResource(R.string.bookmarks),- style = MaterialTheme.typography.titleSmall,- color = MaterialTheme.colorScheme.primary,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp)- )- }- items(filteredBookmarks, key = { "bm-${it.id}" }) { bm ->- ListItem(- headlineContent = {- Text(- bm.title.ifBlank { bm.url },- maxLines = 1,- overflow = TextOverflow.Ellipsis,- style = MaterialTheme.typography.bodyMedium- )- },- supportingContent = {- Text(- BrowserUtils.prettyUrl(bm.url),- maxLines = 1,- overflow = TextOverflow.Ellipsis,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- },- leadingContent = { IconSearch() },- modifier = Modifier.clickable {- viewModel.navigateActiveTab(bm.url)- focusManager.clearFocus()- viewModel.omniboxFocused = false- }- )- }- }-- if (filteredHistory.isNotEmpty()) {- item {- Text(- stringResource(R.string.history),- style = MaterialTheme.typography.titleSmall,- color = MaterialTheme.colorScheme.primary,- modifier = Modifier.padding(horizontal = 16.dp, vertical = 6.dp).padding(top = if (filteredBookmarks.isNotEmpty()) 12.dp else 0.dp)- )- }- items(filteredHistory, key = { "h-${it.id}" }) { h ->- ListItem(- headlineContent = {- Text(- h.title.ifBlank { h.url },- maxLines = 1,- overflow = TextOverflow.Ellipsis,- style = MaterialTheme.typography.bodyMedium- )- },- supportingContent = {- Text(- BrowserUtils.prettyUrl(h.url),- maxLines = 1,- overflow = TextOverflow.Ellipsis,- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant- )- },- leadingContent = { IconSearch() },- modifier = Modifier.clickable {- viewModel.navigateActiveTab(h.url)- focusManager.clearFocus()- viewModel.omniboxFocused = false- }- )- }- }- }- }- } else {- BrowserChrome(- omniboxText = viewModel.omniboxText,- tabCount = viewModel.tabs.size,- canGoBack = canGoBack,- canGoForward = canGoForward,- progress = if (activeTab != null && !isNewTabActive) progress else 0f,- onBack = { if (canGoBack) activeTab?.let { webViewPool[it.id]?.goBack() } },- onForward = { if (canGoForward) activeTab?.let { webViewPool[it.id]?.goForward() } },- onOmniboxClick = {- val full = activeTab?.url?.let { if (it.isBlank() || it == "about:blank") "" else it } ?: ""- viewModel.searchDraft = full- viewModel.omniboxFocused = true- },- onTabSwitcherClick = { viewModel.showTabSwitcher = true },- shieldHost = shieldHost,- blockedCount = activeTab?.let { viewModel.blockedCount(it.id) } ?: 0,- onShieldClick = { viewModel.showShieldsPanel = true },- onMenuClick = { showMenu = true },- menu = {- DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {- if (!isNewTabActive) {- DropdownMenuItem(- text = { Text(stringResource(R.string.reload)) },- onClick = {- showMenu = false- activeTab?.let { webViewPool[it.id]?.reload() }- }- )- }-- if (activeTab != null && !isNewTabActive) {- val pwa = viewModel.getPwaInfo(activeTab.id)- val pinSupported = PwaHelper.isPinSupported(context)- val label = if (pwa?.hasManifest == true) "Install app" else "Add to Home screen"- DropdownMenuItem(- text = { Text(label) },- onClick = {- showMenu = false- showInstallDialog = true- },- enabled = activeTab.url.isNotBlank() && activeTab.url.startsWith("http") && pinSupported- )- }- DropdownMenuItem(- text = { Text(if (isCurrentBookmarked) "Remove bookmark" else "Add bookmark") },- onClick = {- showMenu = false- activeTab?.let { tab ->- if (tab.url.isBlank()) return@let- if (isCurrentBookmarked) {- bookmarks.find { it.url == tab.url }?.let { viewModel.removeBookmark(it) }- } else viewModel.addBookmark(tab.url, tab.title.ifBlank { tab.url })- }- }- )- DropdownMenuItem(text = { Text(stringResource(UiR.string.share)) }, onClick = {- showMenu = false- activeTab?.let { tab ->- if (tab.url.isBlank()) return@let- val sendIntent = android.content.Intent().apply {- action = android.content.Intent.ACTION_SEND- putExtra(android.content.Intent.EXTRA_TEXT, tab.url)- type = "text/plain"- }- ExternalIntents.launch(context, android.content.Intent.createChooser(sendIntent, context.getString(R.string.share_link)))- }- })- DropdownMenuItem(text = { Text(stringResource(R.string.new_tab)) }, onClick = { showMenu = false; viewModel.newTab() })- DropdownMenuItem(text = { Text(stringResource(R.string.new_private_tab)) }, onClick = { showMenu = false; viewModel.newTab(isPrivate = true) })- DropdownMenuItem(text = { Text(stringResource(R.string.history)) }, onClick = { showMenu = false; backStack.add(Route.History) })- DropdownMenuItem(text = { Text(stringResource(R.string.bookmarks)) }, onClick = { showMenu = false; backStack.add(Route.Bookmarks) })- DropdownMenuItem(text = { Text(stringResource(R.string.downloads)) }, onClick = { showMenu = false; backStack.add(Route.Downloads) })- DropdownMenuItem(text = { Text(stringResource(R.string.installed_apps)) }, onClick = { showMenu = false; backStack.add(Route.InstalledSites) })- DropdownMenuItem(text = { Text(stringResource(R.string.site_data)) }, onClick = { showMenu = false; backStack.add(Route.SiteData) })- DropdownMenuItem(text = { Text(stringResource(UiR.string.settings)) }, onClick = { showMenu = false; backStack.add(Route.Settings) })- }- },- ) { paddingValues ->- Column(Modifier.fillMaxSize().padding(paddingValues)) {- if (isNewTabActive) {- QuickAccess(- bookmarks = bookmarks.take(12),- history = history.take(8),- onOpenUrl = { url -> activeTab?.let { viewModel.onTabUrlChange(it.id, url) } },- modifier = Modifier.fillMaxSize()- )- } else if (activeTab != null) {- Box(Modifier.fillMaxSize()) {- // Force a new WebViewBrowser composition per tabId so the AndroidView- // factory runs and loads the new URL immediately. Without this, the- // same AndroidView instance is reused across tab switches and the old- // page remains visible until an update triggers, causing topbar/content- // mismatch when an external intent opens a new tab.- key(activeTab.id) {- WebViewBrowser(- tabId = activeTab.id,- initialUrl = activeTab.url,- viewModel = viewModel,- webViewPool = webViewPool,- onRequestNewTab = { url -> viewModel.newTab(url = url) },- onLinkLongPress = { url -> linkContextMenuUrl = url },- modifier = Modifier.fillMaxSize()- )- }- }- }- }- }- }-- if (viewModel.showTabSwitcher) {- TabSwitcher(- tabs = viewModel.tabs,- activeTabId = viewModel.activeTabId,- onSwitch = { viewModel.switchToTab(it) },- onClose = { viewModel.closeTab(it) },- onNewTab = { viewModel.newTab(isPrivate = viewModel.incognito || viewModel.activeTab?.isPrivate == true) },- onNewIncognitoTab = { viewModel.newTab(isPrivate = true) },- onNewWindow = {- viewModel.showTabSwitcher = false- com.vayunmathur.web.platform.launchNewWebWindow(context, incognito = false)- },- onNewIncognitoWindow = {- viewModel.showTabSwitcher = false- com.vayunmathur.web.platform.launchNewWebWindow(context, incognito = true)- },- isIncognitoWindow = viewModel.incognito || viewModel.activeTab?.isPrivate == true,- onDismiss = { viewModel.showTabSwitcher = false },- modifier = Modifier.fillMaxSize()- )- }-- if (viewModel.showShieldsPanel && shieldHost != null) {- ShieldsPanel(- host = shieldHost,- blockedCount = activeTab?.let { viewModel.blockedCount(it.id) } ?: 0,- viewModel = viewModel,- onReload = {- activeTab?.let { tab ->- webViewPool[tab.id]?.let { webView ->- // Re-register before reloading, not after: document-start scripts- // only apply to documents that start loading after the call.- (webView.webViewClient as? ShieldsWebViewClient)- ?.installFarbling(webView, viewModel.farblingConfig())- webView.reload()- }- }- },- onDismiss = { viewModel.showShieldsPanel = false },- )- }-- viewModel.pendingPermissionPrompt?.let { prompt ->- PermissionPromptSheet(- origin = prompt.origin,- types = prompt.types,- onGrant = { granted ->- prompt.onGrant(granted)- viewModel.clearPermissionPrompt()- },- onDeny = {- prompt.onDeny()- viewModel.clearPermissionPrompt()- }- )- }-- viewModel.pendingGeolocationPrompt?.let { (origin, _, _) ->- GeolocationPromptSheet(- origin = origin,- onAllow = { viewModel.grantGeolocation(origin) },- onDeny = { viewModel.denyGeolocation() }- )- }-- viewModel.pendingFileChooser?.let { (_, params) ->- val mimeTypes = try { params.acceptTypes.toList() } catch (_: Exception) { emptyList() }- val allowMultiple = try { params.mode == android.webkit.WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE } catch (_: Exception) { false }- FileChooserSheet(- mimeTypes = mimeTypes,- onFiles = { uris ->- if (uris == null) viewModel.clearFileChooser() else viewModel.deliverFileChooserResult(uris)- },- onCancel = { viewModel.clearFileChooser() },- onTriggerPicker = {- try {- if (allowMultiple) {- multiDocLauncher.launch(mimeTypes.filter { it.isNotBlank() }.toTypedArray().takeIf { it.isNotEmpty() } ?: arrayOf("*/*"))- } else {- val mt = mimeTypes.firstOrNull { it.isNotBlank() } ?: "*/*"- singleDocLauncher.launch(arrayOf(mt))- }- } catch (_: Exception) { viewModel.clearFileChooser() }- }- )- }-- linkContextMenuUrl?.let { linkUrl ->- LinkContextMenu(- url = linkUrl,- onDismiss = { linkContextMenuUrl = null },- onCopyLink = {- com.vayunmathur.library.ui.ExternalIntents.copyToClipboard(- context,- linkUrl,- linkUrl,- )- com.vayunmathur.library.util.AppMessages.show(context.getString(R.string.link_copied))- },- onShareLink = {- com.vayunmathur.library.ui.ExternalIntents.shareText(- context,- linkUrl,- context.getString(R.string.share_link),- )- },- onOpenInNewTab = { viewModel.newTab(url = linkUrl) },- )- }-- if (showInstallDialog) {- val tabId = activeTab?.id- val url = activeTab?.url ?: ""- val pwa = tabId?.let { viewModel.getPwaInfo(it) }- val fallbackTitle = tabId?.let { viewModel.getTabTitle(it).ifBlank { activeTab?.title ?: "" } } ?: ""- val defaultTitle = PwaHelper.displayTitle(pwa, fallbackTitle, url)- var draftTitle by remember(url, defaultTitle) { mutableStateOf(defaultTitle) }-- AlertDialog(- onDismissRequest = { showInstallDialog = false },- title = { Text(if (pwa?.hasManifest == true) "Install app?" else "Add to Home screen?") },- text = {- Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {- Text(- if (pwa?.hasManifest == true)- "This site has a web manifest — install as standalone app."- else- "Create pinned shortcut that opens in standalone mode (PwaActivity). Works for any site via best icon (apple-touch-icon, 192x192).",- style = MaterialTheme.typography.bodyMedium- )- Surface(shape = RoundedCornerShape(12.dp), color = MaterialTheme.colorScheme.surfaceVariant, modifier = Modifier.fillMaxWidth()) {- Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(4.dp)) {- Text(BrowserUtils.prettyUrl(url), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 2, overflow = TextOverflow.Ellipsis)- if (pwa?.iconUrl != null) {- Text(stringResource(R.string.icon, pwa.iconUrl.take(64)), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant, maxLines = 1, overflow = TextOverflow.Ellipsis)- }- if (pwa?.themeColor != null) {- Text(stringResource(R.string.theme, pwa.themeColor), style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- }- }- OutlinedTextField(- value = draftTitle,- onValueChange = { draftTitle = it },- label = { Text(stringResource(R.string.app_name_2)) },- singleLine = true,- modifier = Modifier.fillMaxWidth()- )- }- },- confirmButton = {- TextButton(- onClick = {- val finalTitle = draftTitle.ifBlank { defaultTitle }- showInstallDialog = false- if (tabId != null && url.startsWith("http")) {- viewModel.installAsPwa(- tabId = tabId,- url = url,- pwaInfo = pwa?.copy(name = finalTitle) ?: PwaInfo(- name = finalTitle,- origin = BrowserUtils.originFromUrl(url),- startUrl = url- )- )- }- },- enabled = draftTitle.isNotBlank() || defaultTitle.isNotBlank()- ) { Text(stringResource(UiR.string.add)) }- },- dismissButton = {- TextButton(onClick = { showInstallDialog = false }) { Text(stringResource(UiR.string.cancel)) }- }- )- }- }-}--@OptIn(ExperimentalMaterial3Api::class)-@Composable-private fun BrowserChrome(- omniboxText: String,- tabCount: Int,- canGoBack: Boolean = false,- canGoForward: Boolean = false,- progress: Float = 0f,- onBack: () -> Unit = {},- onForward: () -> Unit = {},- onOmniboxClick: () -> Unit = {},- onTabSwitcherClick: () -> Unit = {},- shieldHost: String? = null,- blockedCount: Int = 0,- onShieldClick: () -> Unit = {},- onMenuClick: () -> Unit = {},- menu: @Composable () -> Unit = {},- content: @Composable (PaddingValues) -> Unit,-) {- Scaffold(- topBar = {- Column {- TopAppBar(- navigationIcon = {- Row(verticalAlignment = Alignment.CenterVertically) {- IconButton(onClick = onBack, enabled = canGoBack) { IconBack() }- IconButton(onClick = onForward, enabled = canGoForward) { IconArrowForward() }- }- },- title = {- DisplayOnlyAddressPill(- fullUrl = omniboxText,- onClick = onOmniboxClick,- modifier = Modifier.fillMaxWidth()- )- },- actions = {- if (shieldHost != null) {- ShieldChip(blockedCount = blockedCount, onClick = onShieldClick)- Spacer(Modifier.width(4.dp))- }- Surface(- shape = RoundedCornerShape(20.dp),- color = MaterialTheme.colorScheme.secondaryContainer,- modifier = Modifier- .clip(RoundedCornerShape(20.dp))- .clickable(onClick = onTabSwitcherClick)- ) {- Text(- text = tabCount.toString(),- style = MaterialTheme.typography.labelLarge,- modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)- )- }- Spacer(Modifier.width(4.dp))- IconButton(onClick = onMenuClick) { IconMoreVert() }- menu()- },- colors = TopAppBarDefaults.topAppBarColors(containerColor = MaterialTheme.colorScheme.surface)- )- if (progress in 0.01f..0.99f) {- LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth().height(2.dp))- }- }- },- content = content,- )-}--/**- * Toolbar shield. Shows the number of requests blocked on the current page, which is the- * only feedback the user gets that shields are doing anything.- */-@Composable-private fun ShieldChip(blockedCount: Int, onClick: () -> Unit) {- Surface(- shape = RoundedCornerShape(20.dp),- color = MaterialTheme.colorScheme.secondaryContainer,- modifier = Modifier.clip(RoundedCornerShape(20.dp)).clickable(onClick = onClick),- ) {- Row(- Modifier.padding(horizontal = 10.dp, vertical = 8.dp),- verticalAlignment = Alignment.CenterVertically,- ) {- IconShield(Modifier.size(18.dp))- if (blockedCount > 0) {- Spacer(Modifier.width(4.dp))- Text(blockedCount.toString(), style = MaterialTheme.typography.labelLarge)- }- }- }-}--@Composable-private fun DisplayOnlyAddressPill(- fullUrl: String,- onClick: () -> Unit,- modifier: Modifier = Modifier,-) {- // Now matches CommonSearchBar visually: OutlinedTextField 28dp rounded, search icon, same padding.- Box(modifier = modifier) {- OutlinedTextField(- value = fullUrl,- onValueChange = {},- readOnly = true,- placeholder = { Text(stringResource(R.string.search_or_enter_address)) },- leadingIcon = { IconSearch() },- singleLine = true,- shape = RoundedCornerShape(28.dp),- modifier = Modifier.fillMaxWidth()- )- // Overlay to handle tap without focusing the field- Box(- Modifier- .matchParentSize()- .clip(RoundedCornerShape(28.dp))- .clickable(onClick = onClick)- )- }-}--@Composable-private fun QuickAccess(- bookmarks: List<com.vayunmathur.web.data.Bookmark>,- history: List<com.vayunmathur.web.data.HistoryEntry>,- onOpenUrl: (String) -> Unit,- modifier: Modifier = Modifier,-) {- LazyColumn(- modifier = modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(16.dp),- verticalArrangement = Arrangement.spacedBy(16.dp)- ) {- if (bookmarks.isNotEmpty()) {- item { Text(stringResource(R.string.bookmarks), style = MaterialTheme.typography.titleMedium) }- item {- androidx.compose.foundation.lazy.LazyRow(horizontalArrangement = Arrangement.spacedBy(12.dp), contentPadding = PaddingValues(end = 16.dp)) {- items(bookmarks, key = { it.id }) { bm ->- Card(- modifier = Modifier.width(140.dp).clickable { onOpenUrl(bm.url) },- colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer)- ) {- Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {- Box(Modifier.size(28.dp).clip(CircleShape).background(MaterialTheme.colorScheme.surface), contentAlignment = Alignment.Center) {- Text(bm.title.take(1).uppercase().ifBlank { "B" }, style = MaterialTheme.typography.titleSmall)- }- Text(bm.title.ifBlank { BrowserUtils.hostFromUrl(bm.url) }, maxLines = 2, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall)- }- }- }- }- }- }- if (history.isNotEmpty()) {- item { Text(stringResource(R.string.recent), style = MaterialTheme.typography.titleMedium) }- items(history, key = { it.id }) { entry ->- Row(- modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).clickable { onOpenUrl(entry.url) }.padding(12.dp),- verticalAlignment = Alignment.CenterVertically- ) {- Surface(shape = CircleShape, color = MaterialTheme.colorScheme.surfaceVariant, modifier = Modifier.size(36.dp)) {- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- Text(entry.title.take(1).uppercase().ifBlank { "H" }, style = MaterialTheme.typography.titleSmall)- }- }- Spacer(Modifier.width(12.dp))- Column(Modifier.weight(1f)) {- Text(entry.title.ifBlank { entry.url }, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)- Text(BrowserUtils.prettyUrl(entry.url), maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- }- }- }- item {- Text(- stringResource(R.string.blank_new_tab_tap_the_address_pill_to_se),- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- modifier = Modifier.padding(top = 16.dp)- )- }- }-}--/** Already stateless — public only so the store-listing previews can render it. */-@Composable-private fun TabSwitcher(- tabs: List<com.vayunmathur.web.util.BrowserTab>,- activeTabId: String?,- onSwitch: (String) -> Unit,- onClose: (String) -> Unit,- onNewTab: () -> Unit,- onNewIncognitoTab: () -> Unit = {},- onNewWindow: () -> Unit = onNewTab,- onNewIncognitoWindow: () -> Unit = onNewIncognitoTab,- onDismiss: () -> Unit,- modifier: Modifier = Modifier,- isIncognitoWindow: Boolean = tabs.find { it.id == activeTabId }?.isPrivate == true,-) {- Box(modifier = modifier.fillMaxSize().background(MaterialTheme.colorScheme.background.copy(alpha = 0.98f))) {- Column(Modifier.fillMaxSize()) {- TopAppBar(- title = { Text(pluralStringResource(R.plurals.tabs, tabs.size, tabs.size)) },- navigationIcon = { com.vayunmathur.library.ui.IconButton(onClick = onDismiss) { IconClose() } },- actions = { com.vayunmathur.library.ui.IconButton(onClick = onNewTab) { IconAdd() } }- )- LazyColumn(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- items(tabs, key = { it.id }) { tab ->- val isActive = tab.id == activeTabId- val displayTitle = when {- tab.isNewTab -> "New Tab"- tab.title.isNotBlank() -> tab.title- else -> BrowserUtils.prettyUrl(tab.url).ifBlank { "New Tab" }- }- val displayUrl = if (tab.isNewTab) "" else tab.url- Card(- modifier = Modifier.fillMaxWidth().clickable { onSwitch(tab.id) },- colors = CardDefaults.cardColors(containerColor = if (isActive) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceVariant),- shape = RoundedCornerShape(16.dp)- ) {- Row(Modifier.fillMaxWidth().padding(12.dp), verticalAlignment = Alignment.CenterVertically) {- Column(Modifier.weight(1f)) {- Row(verticalAlignment = Alignment.CenterVertically) {- if (tab.isPrivate) Text(stringResource(R.string.private_prefix), style = MaterialTheme.typography.labelSmall)- Text(displayTitle, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleSmall)- }- if (displayUrl.isNotBlank()) {- Text(displayUrl, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- }- com.vayunmathur.library.ui.IconButton(onClick = { onClose(tab.id) }) { IconClose() }- }- }- }- item {- Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedButton(- onClick = {- if (isIncognitoWindow) onNewIncognitoTab() else onNewTab()- },- modifier = Modifier.fillMaxWidth()- ) {- Text(- stringResource(- if (isIncognitoWindow) R.string.new_incognito_tab else R.string.new_tab- )- )- }- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedButton(onClick = onNewWindow, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.new_window)) }- OutlinedButton(onClick = onNewIncognitoWindow, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.new_incognito_window)) }- }- }- }- }- }- }-}+package com.vayunmathur.web.ui++import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import com.vayunmathur.web.R+import android.webkit.WebView+import androidx.activity.compose.BackHandler+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.background+import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.layout.width+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.foundation.text.KeyboardActions+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.key+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.clip+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalFocusManager+import androidx.compose.ui.platform.LocalSoftwareKeyboardController+import androidx.compose.ui.text.input.ImeAction+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import androidx.lifecycle.compose.collectAsStateWithLifecycle+import com.vayunmathur.library.ui.ExternalIntents+import com.vayunmathur.library.ui.R as UiR+import com.vayunmathur.library.ui.AlertDialog+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.CommonSearchBar+import com.vayunmathur.library.ui.DropdownMenu+import com.vayunmathur.library.ui.DropdownMenuItem+import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.HorizontalDivider+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.LinearProgressIndicator+import com.vayunmathur.library.ui.ListItem+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Scaffold+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.TopAppBarDefaults+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconArrowForward+import com.vayunmathur.library.ui.IconBack+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.IconMoreVert+import com.vayunmathur.library.ui.IconSearch+import com.vayunmathur.library.ui.IconShield+import com.vayunmathur.web.Route+import com.vayunmathur.library.util.NavBackStack+import com.vayunmathur.web.platform.shields.ShieldsWebViewClient+import com.vayunmathur.web.platform.BrowserUtils+import com.vayunmathur.web.platform.PwaHelper+import com.vayunmathur.web.platform.PwaInfo+import com.vayunmathur.web.platform.WebViewModel+import com.vayunmathur.web.platform.isNewTab++@OptIn(ExperimentalMaterial3Api::class)+@Composable+fun BrowserPage(+ viewModel: WebViewModel,+ backStack: NavBackStack<Route>,+) {+ val context = LocalContext.current+ val focusManager = LocalFocusManager.current+ val keyboardController = LocalSoftwareKeyboardController.current+ val webViewPool = remember { mutableStateMapOf<String, WebView>() }++ LaunchedEffect(viewModel.tabs.size) {+ if (viewModel.tabs.isEmpty()) viewModel.newTab()+ }++ val activeTab = viewModel.activeTab+ val canGoBack = activeTab?.let { viewModel.getCanGoBack(it.id) } ?: false+ val canGoForward = activeTab?.let { viewModel.getCanGoForward(it.id) } ?: false+ val progress = activeTab?.let { viewModel.getProgress(it.id) } ?: 0f+ val isNewTabActive = activeTab?.isNewTab ?: true++ val bookmarks by viewModel.bookmarks.collectAsStateWithLifecycle()+ val history by viewModel.history.collectAsStateWithLifecycle()+ val isCurrentBookmarked = activeTab?.url?.let { url -> url.isNotBlank() && bookmarks.any { it.url == url } } ?: false++ val shieldHost = activeTab?.url?.takeIf { it.startsWith("http") }?.let { BrowserUtils.hostFromUrl(it) }+ // Navigating away from the site the panel describes has to close it, otherwise it would+ // silently start editing a different host's settings.+ LaunchedEffect(shieldHost) { viewModel.showShieldsPanel = false }++ val multiDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->+ viewModel.deliverFileChooserResult(uris.toTypedArray().takeIf { it.isNotEmpty() })+ }+ val singleDocLauncher = rememberLauncherForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->+ viewModel.deliverFileChooserResult(uri?.let { arrayOf(it) })+ }++ var showMenu by remember { mutableStateOf(false) }+ var showInstallDialog by remember { mutableStateOf(false) }+ var linkContextMenuUrl by remember { mutableStateOf<String?>(null) }+ val searchFocusRequester = remember { FocusRequester() }++ BackHandler(enabled = viewModel.showTabSwitcher) { viewModel.showTabSwitcher = false }+ BackHandler(enabled = !viewModel.showTabSwitcher && viewModel.omniboxFocused) {+ viewModel.omniboxFocused = false+ focusManager.clearFocus()+ }+ BackHandler(enabled = !viewModel.showTabSwitcher && !viewModel.omniboxFocused && canGoBack) {+ activeTab?.let { tab -> webViewPool[tab.id]?.goBack() }+ }++ LaunchedEffect(viewModel.omniboxFocused) {+ if (viewModel.omniboxFocused) {+ // Let the new Scaffold compose before requesting focus+ kotlinx.coroutines.delay(100)+ try { searchFocusRequester.requestFocus() } catch (_: Exception) {}+ keyboardController?.show()+ }+ }++ val currentDraft = viewModel.searchDraft+ val filteredBookmarks = remember(currentDraft, bookmarks) {+ if (currentDraft.isBlank()) bookmarks.take(5)+ else bookmarks.filter { it.url.contains(currentDraft, true) || it.title.contains(currentDraft, true) }.take(8)+ }+ val filteredHistory = remember(currentDraft, history) {+ if (currentDraft.isBlank()) history.take(10)+ else history.filter { it.url.contains(currentDraft, true) || it.title.contains(currentDraft, true) }.take(15)+ }++ Box(Modifier.fillMaxSize()) {+ if (viewModel.omniboxFocused) {+ Scaffold(+ topBar = {+ TopAppBar(+ navigationIcon = {+ IconButton(onClick = {+ focusManager.clearFocus()+ viewModel.omniboxFocused = false+ }) { IconBack() }+ },+ title = {+ OutlinedTextField(+ value = viewModel.searchDraft,+ onValueChange = { viewModel.searchDraft = it },+ modifier = Modifier+ .fillMaxWidth()+ .focusRequester(searchFocusRequester),+ placeholder = { Text(stringResource(R.string.search_or_enter_address)) },+ leadingIcon = { IconSearch() },+ trailingIcon = if (viewModel.searchDraft.isNotEmpty()) {+ {+ IconButton(onClick = { viewModel.searchDraft = "" }) { IconClose() }+ }+ } else null,+ shape = RoundedCornerShape(28.dp),+ singleLine = true,+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search),+ keyboardActions = KeyboardActions(onSearch = {+ if (viewModel.searchDraft.isNotBlank()) {+ viewModel.navigateActiveTab(viewModel.searchDraft)+ focusManager.clearFocus()+ viewModel.omniboxFocused = false+ }+ })+ )+ }+ )+ }+ ) { paddingValues ->+ LazyColumn(+ modifier = Modifier+ .fillMaxSize()+ .padding(paddingValues),+ verticalArrangement = Arrangement.spacedBy(2.dp),+ contentPadding = PaddingValues(top = 8.dp, bottom = 24.dp)+ ) {+ if (currentDraft.isNotBlank()) {+ item {+ ListItem(+ headlineContent = { Text(currentDraft, maxLines = 1, overflow = TextOverflow.Ellipsis) },+ supportingContent = {+ Text(+ text = BrowserUtils.hostFromUrl(+ BrowserUtils.toNavigationUrl(currentDraft, viewModel.searchEngine)+ ),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ maxLines = 1,+ overflow = TextOverflow.Ellipsis+ )+ },+ leadingContent = { IconSearch() },+ modifier = Modifier.clickable {+ viewModel.navigateActiveTab(currentDraft)+ focusManager.clearFocus()+ viewModel.omniboxFocused = false+ }+ )+ }+ item { HorizontalDivider(Modifier.padding(vertical = 4.dp)) }+ }++ if (filteredBookmarks.isNotEmpty()) {+ item {+ Text(+ stringResource(R.string.bookmarks),+ style = Mat
Diff truncated.