web: migrate to canonical structure (domain/platform, Route/Navigation split, PwaActivity, ui one-composable)
- Commit
6198b6d4f2e5a904b421241a741fc6a15caab02f- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 19:47 UTC (3 months ago)
- Parents
28e8408
Diff
web/src/main/AndroidManifest.xml
diff --git a/web/src/main/AndroidManifest.xml b/web/src/main/AndroidManifest.xmlindex c630fa1354..3a1905a157 100644--- a/web/src/main/AndroidManifest.xml+++ b/web/src/main/AndroidManifest.xml@@ -51,7 +51,7 @@ </activity> <activity- android:name=".PwaActivity"+ android:name=".platform.PwaActivity" android:exported="true" android:theme="@style/Theme.Web" android:launchMode="singleTop"
web/src/main/java/com/vayunmathur/web/Navigation.kt
diff --git a/web/src/main/java/com/vayunmathur/web/Navigation.kt b/web/src/main/java/com/vayunmathur/web/Navigation.ktindex 8a2f3b4f66..53dbeddd5c 100644--- a/web/src/main/java/com/vayunmathur/web/Navigation.kt+++ b/web/src/main/java/com/vayunmathur/web/Navigation.kt@@ -1 +1,50 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/Navigation.kt' exists on disk, but not in 'stash@{0}'+package com.vayunmathur.web++import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.lifecycle.viewmodel.compose.viewModel+import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.openSettingsIfRequested+import com.vayunmathur.library.util.rememberNavBackStack+import com.vayunmathur.web.platform.WebViewModel+import com.vayunmathur.web.platform.WebViewModelFactory+import com.vayunmathur.web.ui.BookmarksPage+import com.vayunmathur.web.ui.BrowserPage+import com.vayunmathur.web.ui.DownloadsPage+import com.vayunmathur.web.ui.HistoryPage+import com.vayunmathur.web.ui.InstalledSitesPage+import com.vayunmathur.web.ui.SettingsPage+import com.vayunmathur.web.ui.ShieldsPage+import com.vayunmathur.web.ui.SiteDataPage++@Composable+internal fun AppRoot(+ factory: WebViewModelFactory,+ pendingExternalUrl: String?,+ onExternalUrlConsumed: () -> Unit,+) {+ val viewModel: WebViewModel = viewModel(factory = factory)+ LaunchedEffect(pendingExternalUrl) {+ if (pendingExternalUrl != null) {+ viewModel.externalIntentUrl(pendingExternalUrl)+ onExternalUrlConsumed()+ }+ }+ Navigation(viewModel)+}++@Composable+fun Navigation(viewModel: WebViewModel) {+ val backStack = rememberNavBackStack<Route>(Route.Browser)+ backStack.openSettingsIfRequested(Route.Settings)+ MainNavigation(backStack) {+ entry<Route.Browser> { BrowserPage(viewModel = viewModel, backStack = backStack) }+ entry<Route.History> { HistoryPage(viewModel = viewModel, backStack = backStack) }+ entry<Route.Bookmarks> { BookmarksPage(viewModel = viewModel, backStack = backStack) }+ entry<Route.Settings> { SettingsPage(viewModel = viewModel, backStack = backStack) }+ entry<Route.Downloads> { DownloadsPage(viewModel = viewModel, backStack = backStack) }+ entry<Route.SiteData> { SiteDataPage(viewModel = viewModel, backStack = backStack) }+ entry<Route.InstalledSites> { InstalledSitesPage(viewModel = viewModel, backStack = backStack) }+ entry<Route.Shields> { ShieldsPage(viewModel = viewModel, backStack = backStack) }+ }+}
web/src/main/java/com/vayunmathur/web/Route.kt
diff --git a/web/src/main/java/com/vayunmathur/web/Route.kt b/web/src/main/java/com/vayunmathur/web/Route.ktindex e9d09b4bdc..1f0d3d28f3 100644--- a/web/src/main/java/com/vayunmathur/web/Route.kt+++ b/web/src/main/java/com/vayunmathur/web/Route.kt@@ -1 +1,16 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/Route.kt' exists on disk, but not in 'stash@{0}'+package com.vayunmathur.web++import com.vayunmathur.library.util.NavKey+import kotlinx.serialization.Serializable++@Serializable+sealed interface Route : NavKey {+ @Serializable data object Browser : Route+ @Serializable data object History : Route+ @Serializable data object Bookmarks : Route+ @Serializable data object Settings : Route+ @Serializable data object Downloads : Route+ @Serializable data object SiteData : Route+ @Serializable data object InstalledSites : Route+ @Serializable data object Shields : Route+}
web/src/main/java/com/vayunmathur/web/data/ShieldSetting.kt
diff --git a/web/src/main/java/com/vayunmathur/web/data/ShieldSetting.kt b/web/src/main/java/com/vayunmathur/web/data/ShieldSetting.ktindex cdc1b47cfb..109bb9f7c2 100644--- a/web/src/main/java/com/vayunmathur/web/data/ShieldSetting.kt+++ b/web/src/main/java/com/vayunmathur/web/data/ShieldSetting.kt@@ -1,42 +1,42 @@-package com.vayunmathur.web.data--import androidx.room.Entity-import androidx.room.PrimaryKey-import com.vayunmathur.web.util.ShieldLevel-import com.vayunmathur.web.util.ShieldsSettings--/**- * Per-site shields override, keyed by host. Null fields inherit the global setting, so a- * site that only turns off cosmetic filtering still tracks later changes to the others.- * Host is the primary key — shields apply per registrable site, not per origin, matching- * Brave's own panel. Not a DatabaseItem.- */-@Entity-data class ShieldSetting(- @PrimaryKey val host: String,- val level: String? = null,- val blockTrackers: Boolean? = null,- val cosmeticFiltering: Boolean? = null,- val fingerprintProtection: Boolean? = null,- val httpsUpgrade: Boolean? = null,- val updatedAt: Long = System.currentTimeMillis(),-) {- fun toSettings(): ShieldsSettings = ShieldsSettings(- level = level?.let { runCatching { ShieldLevel.valueOf(it) }.getOrNull() },- blockTrackers = blockTrackers,- cosmeticFiltering = cosmeticFiltering,- fingerprintProtection = fingerprintProtection,- httpsUpgrade = httpsUpgrade,- )-- companion object {- fun from(host: String, settings: ShieldsSettings) = ShieldSetting(- host = host,- level = settings.level?.name,- blockTrackers = settings.blockTrackers,- cosmeticFiltering = settings.cosmeticFiltering,- fingerprintProtection = settings.fingerprintProtection,- httpsUpgrade = settings.httpsUpgrade,- )- }-}+package com.vayunmathur.web.data++import androidx.room.Entity+import androidx.room.PrimaryKey+import com.vayunmathur.web.domain.ShieldLevel+import com.vayunmathur.web.domain.ShieldsSettings++/**+ * Per-site shields override, keyed by host. Null fields inherit the global setting, so a+ * site that only turns off cosmetic filtering still tracks later changes to the others.+ * Host is the primary key — shields apply per registrable site, not per origin, matching+ * Brave's own panel. Not a DatabaseItem.+ */+@Entity+data class ShieldSetting(+ @PrimaryKey val host: String,+ val level: String? = null,+ val blockTrackers: Boolean? = null,+ val cosmeticFiltering: Boolean? = null,+ val fingerprintProtection: Boolean? = null,+ val httpsUpgrade: Boolean? = null,+ val updatedAt: Long = System.currentTimeMillis(),+) {+ fun toSettings(): ShieldsSettings = ShieldsSettings(+ level = level?.let { runCatching { ShieldLevel.valueOf(it) }.getOrNull() },+ blockTrackers = blockTrackers,+ cosmeticFiltering = cosmeticFiltering,+ fingerprintProtection = fingerprintProtection,+ httpsUpgrade = httpsUpgrade,+ )++ companion object {+ fun from(host: String, settings: ShieldsSettings) = ShieldSetting(+ host = host,+ level = settings.level?.name,+ blockTrackers = settings.blockTrackers,+ cosmeticFiltering = settings.cosmeticFiltering,+ fingerprintProtection = settings.fingerprintProtection,+ httpsUpgrade = settings.httpsUpgrade,+ )+ }+}
web/src/main/java/com/vayunmathur/web/domain/ShieldsSettings.kt
diff --git a/web/src/main/java/com/vayunmathur/web/domain/ShieldsSettings.kt b/web/src/main/java/com/vayunmathur/web/domain/ShieldsSettings.ktindex 7cd369d998..1a71faad6f 100644--- a/web/src/main/java/com/vayunmathur/web/domain/ShieldsSettings.kt+++ b/web/src/main/java/com/vayunmathur/web/domain/ShieldsSettings.kt@@ -1 +1,95 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/domain/ShieldsSettings.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.domain++/**+ * How hard shields work on a site. Mirrors Brave's block-mode selector.+ *+ * [AGGRESSIVE] is the default: it additionally farbles timezone and disables WebRTC,+ * both of which are effective against fingerprinting but break a minority of sites —+ * hence the per-site override in the shields panel.+ */+enum class ShieldLevel { OFF, STANDARD, AGGRESSIVE }++/**+ * A shields configuration.+ *+ * The global instance held by the view model has every field set. Per-site records leave+ * fields null to inherit the global value, so turning one shield off for a site does not+ * freeze the rest at their current values.+ */+data class ShieldsSettings(+ val level: ShieldLevel? = null,+ val blockTrackers: Boolean? = null,+ val cosmeticFiltering: Boolean? = null,+ val fingerprintProtection: Boolean? = null,+ val httpsUpgrade: Boolean? = null,+) {+ /** True when this per-site record says nothing and can be dropped from the database. */+ val isEmpty: Boolean+ get() = level == null && blockTrackers == null && cosmeticFiltering == null &&+ fingerprintProtection == null && httpsUpgrade == null++ companion object {+ /** Brave's "Aggressive" preset, applied on first run. */+ val AGGRESSIVE_DEFAULTS = ShieldsSettings(+ level = ShieldLevel.AGGRESSIVE,+ blockTrackers = true,+ cosmeticFiltering = true,+ fingerprintProtection = true,+ httpsUpgrade = true,+ )+ }+}++/** The resolved shields for one site — what the WebView client actually acts on. */+data class EffectiveShields(+ val level: ShieldLevel,+ val blockTrackers: Boolean,+ val cosmeticFiltering: Boolean,+ val fingerprintProtection: Boolean,+ /** Also farble timezone and remove `RTCPeerConnection`. */+ val aggressiveFingerprinting: Boolean,+ val httpsUpgrade: Boolean,+ /** Block plaintext navigations outright instead of silently downgrading. */+ val httpsOnly: Boolean,+) {+ val anyEnabled: Boolean+ get() = blockTrackers || cosmeticFiltering || fingerprintProtection || httpsUpgrade++ companion object {+ val OFF = EffectiveShields(+ level = ShieldLevel.OFF,+ blockTrackers = false,+ cosmeticFiltering = false,+ fingerprintProtection = false,+ aggressiveFingerprinting = false,+ httpsUpgrade = false,+ httpsOnly = false,+ )++ /**+ * Combines the global defaults with a site's overrides. A site setting always wins;+ * anything it leaves null falls back to the global value, then to the level's preset.+ */+ fun resolve(global: ShieldsSettings, site: ShieldsSettings? = null): EffectiveShields {+ val level = site?.level ?: global.level ?: ShieldLevel.AGGRESSIVE+ if (level == ShieldLevel.OFF) return OFF++ fun pick(+ selector: (ShieldsSettings) -> Boolean?,+ ): Boolean = site?.let(selector) ?: global.let(selector) ?: true++ val fingerprint = pick { it.fingerprintProtection }+ val https = pick { it.httpsUpgrade }+ val aggressive = level == ShieldLevel.AGGRESSIVE+ return EffectiveShields(+ level = level,+ blockTrackers = pick { it.blockTrackers },+ cosmeticFiltering = pick { it.cosmeticFiltering },+ fingerprintProtection = fingerprint,+ aggressiveFingerprinting = fingerprint && aggressive,+ httpsUpgrade = https,+ httpsOnly = https && aggressive,+ )+ }+ }+}
web/src/main/java/com/vayunmathur/web/domain/shields/ResourceTypes.kt
diff --git a/web/src/main/java/com/vayunmathur/web/domain/shields/ResourceTypes.kt b/web/src/main/java/com/vayunmathur/web/domain/shields/ResourceTypes.ktindex f7ddf017d9..ebce8f20cb 100644--- a/web/src/main/java/com/vayunmathur/web/domain/shields/ResourceTypes.kt+++ b/web/src/main/java/com/vayunmathur/web/domain/shields/ResourceTypes.kt@@ -1 +1,111 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/domain/shields/ResourceTypes.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.domain.shields++/**+ * Maps a WebView subresource request onto one of adblock-rust's request types.+ *+ * `WebResourceRequest` carries no resource type, so this reconstructs it the way+ * Chromium would have labelled the request: `Sec-Fetch-Dest` when the WebView sends it,+ * then the `Accept` header, then the URL's file extension. Getting this right matters+ * because a large share of filters are qualified with `$script`, `$image`, `$xhr` etc.+ *+ * Kept free of `android.*` so it can be unit tested on the JVM.+ */+object ResourceTypes {++ /** adblock-rust's fallback bucket, used when nothing more specific is known. */+ const val OTHER = "other"++ private val BY_FETCH_DEST = mapOf(+ "audio" to "media",+ "audioworklet" to "script",+ "document" to "document",+ "embed" to "object",+ "empty" to "xmlhttprequest",+ "font" to "font",+ "frame" to "subdocument",+ "iframe" to "subdocument",+ "image" to "image",+ "manifest" to OTHER,+ "object" to "object",+ "paintworklet" to "script",+ "report" to "other",+ "script" to "script",+ "serviceworker" to "script",+ "sharedworker" to "script",+ "style" to "stylesheet",+ "track" to OTHER,+ "video" to "media",+ "worker" to "script",+ "xslt" to "xlst",+ )++ private val BY_EXTENSION = mapOf(+ "js" to "script",+ "mjs" to "script",+ "css" to "stylesheet",+ "gif" to "image",+ "png" to "image",+ "jpg" to "image",+ "jpeg" to "image",+ "webp" to "image",+ "svg" to "image",+ "ico" to "image",+ "bmp" to "image",+ "avif" to "image",+ "woff" to "font",+ "woff2" to "font",+ "ttf" to "font",+ "otf" to "font",+ "eot" to "font",+ "mp3" to "media",+ "mp4" to "media",+ "webm" to "media",+ "ogg" to "media",+ "m4a" to "media",+ "wav" to "media",+ "m3u8" to "media",+ "json" to "xmlhttprequest",+ "html" to "subdocument",+ "htm" to "subdocument",+ )++ /**+ * @param isMainFrame from `WebResourceRequest.isForMainFrame`+ * @param headers from `WebResourceRequest.requestHeaders`, looked up case-insensitively+ */+ fun of(url: String, isMainFrame: Boolean, headers: Map<String, String>): String {+ if (isMainFrame) return "document"++ header(headers, "Sec-Fetch-Dest")?.lowercase()?.let { dest ->+ BY_FETCH_DEST[dest]?.let { return it }+ }+ fromAccept(header(headers, "Accept"))?.let { return it }+ return BY_EXTENSION[extensionOf(url)] ?: OTHER+ }++ private fun header(headers: Map<String, String>, name: String): String? =+ headers.entries.firstOrNull { it.key.equals(name, ignoreCase = true) }?.value++ /**+ * Chromium sends a distinctive `Accept` per destination. `text/html` is deliberately+ * not mapped: navigations already returned above, and an `Accept` of `text/html` on a+ * subresource is the generic default that XHR also sends.+ */+ private fun fromAccept(accept: String?): String? {+ val value = accept?.lowercase() ?: return null+ return when {+ value.startsWith("text/css") -> "stylesheet"+ value.startsWith("image/") -> "image"+ value.startsWith("audio/") || value.startsWith("video/") -> "media"+ value.contains("application/font") || value.contains("font/") -> "font"+ else -> null+ }+ }++ private fun extensionOf(url: String): String {+ val path = url.substringBefore('#').substringBefore('?')+ val lastSegment = path.substringAfterLast('/', "")+ if (!lastSegment.contains('.')) return ""+ return lastSegment.substringAfterLast('.').lowercase()+ }+}
web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt
diff --git a/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt b/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.ktindex 26313a2db0..0b8e6075c5 100644--- a/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt+++ b/web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt@@ -1 +1,93 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/domain/shields/UrlCleaner.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.domain.shields++/**+ * Brave's query-parameter stripping and HTTPS upgrading for top-level navigations.+ *+ * The engine's own `$removeparam` rules cover most tracking parameters, but they only+ * apply to requests it inspects. Brave additionally strips a fixed list on every+ * navigation, which is what this reproduces — it catches links pasted into the omnibox+ * and cross-site redirects that never reach a subresource check.+ *+ * Pure Kotlin (no `android.net.Uri`) so it runs in JVM unit tests.+ */+object UrlCleaner {++ /**+ * Exact parameter names Brave removes. Kept in sync with `brave-core`'s+ * `query_filter.cc` tracking-parameter list.+ */+ private val TRACKING_PARAMS = setOf(+ "fbclid", "gclid", "gclsrc", "dclid", "msclkid", "mc_eid", "mkt_tok",+ "igshid", "igsh", "twclid", "yclid", "ttclid", "rb_clickid", "s_cid",+ "wickedid", "oly_anon_id", "oly_enc_id", "vero_conv", "vero_id",+ "_hsenc", "_hsmi", "__hssc", "__hstc", "hsCtaTracking", "__s",+ "_openstat", "wt_zmc", "guccounter", "guce_referrer", "guce_referrer_sig",+ "cmpid", "os_ehash", "pk_campaign", "pk_kwd", "piwik_campaign", "piwik_kwd",+ "spm", "scm", "share_source", "share_medium", "share_plat", "share_tag",+ "share_session_id", "share_from", "unique_k", "vd_source",+ )++ /** Prefixes covering whole families: `utm_*`, `ga_*`, `hsa_*`, `matomo_*`. */+ private val TRACKING_PREFIXES = listOf("utm_", "ga_", "hsa_", "matomo_")++ private fun isTracking(name: String): Boolean {+ val lower = name.lowercase()+ return lower in TRACKING_PARAMS || TRACKING_PREFIXES.any { lower.startsWith(it) }+ }++ /**+ * Removes tracking parameters from [url], preserving parameter order, repeated keys+ * and the fragment. Returns [url] unchanged when there is nothing to strip, so callers+ * can compare by identity to decide whether a reload is warranted.+ */+ fun clean(url: String): String {+ val queryStart = url.indexOf('?')+ if (queryStart < 0) return url++ val fragmentStart = url.indexOf('#', queryStart)+ val query = if (fragmentStart < 0) {+ url.substring(queryStart + 1)+ } else {+ url.substring(queryStart + 1, fragmentStart)+ }+ if (query.isEmpty()) return url++ val kept = query.split('&').filter { param ->+ param.isNotEmpty() && !isTracking(param.substringBefore('='))+ }+ if (kept.size == query.split('&').count { it.isNotEmpty() }) return url++ val prefix = url.substring(0, queryStart)+ val fragment = if (fragmentStart < 0) "" else url.substring(fragmentStart)+ return if (kept.isEmpty()) prefix + fragment else "$prefix?${kept.joinToString("&")}$fragment"+ }++ /**+ * The `https://` form of an `http://` [url], or null when it is already secure or is+ * an address HTTPS cannot serve.+ *+ * localhost and bare IPs are left alone: they have no publicly trusted certificate and+ * upgrading them breaks local development servers, which is also Brave's behaviour.+ */+ fun httpsUpgrade(url: String): String? {+ if (!url.startsWith("http://", ignoreCase = true)) return null+ val host = hostOf(url)+ if (host.isEmpty() || host == "localhost" || host.endsWith(".localhost")) return null+ if (isIpLiteral(host)) return null+ return "https://" + url.substring("http://".length)+ }++ private fun hostOf(url: String): String {+ val afterScheme = url.substringAfter("://", "")+ val authority = afterScheme.substringBefore('/').substringBefore('?').substringBefore('#')+ return authority.substringAfter('@').substringBefore(':').lowercase()+ }++ private fun isIpLiteral(host: String): Boolean {+ if (host.startsWith("[")) return true // IPv6+ val octets = host.split('.')+ return octets.size == 4 && octets.all { part ->+ part.isNotEmpty() && part.all { it.isDigit() } && part.toInt() <= 255+ }+ }+}
web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt b/web/src/main/java/com/vayunmathur/web/platform/BrowserState.ktindex 495b59b343..91825a23b2 100644--- a/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt@@ -1 +1,110 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/BrowserState.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.platform++import android.net.Uri+import kotlinx.serialization.Serializable++@Serializable+data class BrowserTab(+ val id: String,+ val url: String = "",+ val title: String = "",+ val faviconUrl: String? = null,+ val isPrivate: Boolean = false,+)++val BrowserTab.isNewTab: Boolean+ get() = url.isBlank() || url == "about:blank"++enum class SearchEngine(+ val displayName: String,+ val searchUrl: String,+ val homepage: String,+) {+ GOOGLE("Google", "https://www.google.com/search?q=%s", "https://www.google.com"),+ DUCKDUCKGO("DuckDuckGo", "https://duckduckgo.com/?q=%s", "https://duckduckgo.com"),+ BING("Bing", "https://www.bing.com/search?q=%s", "https://www.bing.com"),+ BRAVE("Brave", "https://search.brave.com/search?q=%s", "https://search.brave.com"),+ STARTPAGE("Startpage", "https://www.startpage.com/do/search?q=%s", "https://www.startpage.com"),+ ECOSIA("Ecosia", "https://www.ecosia.org/search?q=%s", "https://www.ecosia.org"),+ QWANT("Qwant", "https://www.qwant.com/?q=%s", "https://www.qwant.com");++ fun buildQueryUrl(query: String): String =+ searchUrl.replace("%s", Uri.encode(query))++ companion object {+ val DEFAULT = DUCKDUCKGO+ fun fromName(name: String): SearchEngine =+ entries.find { it.name == name } ?: DEFAULT+ }+}++enum class CacheMode(val title: String, val description: String, val webSettingsValue: Int) {+ DEFAULT("Default", "Use HTTP cache as needed", android.webkit.WebSettings.LOAD_DEFAULT),+ CACHE_ELSE_NETWORK("Cache first", "Prefer cache, fastest", android.webkit.WebSettings.LOAD_CACHE_ELSE_NETWORK),+ NO_CACHE("No cache", "Always from network", android.webkit.WebSettings.LOAD_NO_CACHE),+ CACHE_ONLY("Offline", "Cache only, offline mode", android.webkit.WebSettings.LOAD_CACHE_ONLY);+}++enum class SitePermissionType(val key: String, val displayName: String) {+ CAMERA("camera", "Camera"),+ MICROPHONE("mic", "Microphone"),+ LOCATION("location", "Location"),+ NOTIFICATIONS("notifications", "Notifications")+}++object BrowserUtils {+ private val URL_LIKE = Regex(+ "^(https?://)?([a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}|localhost|\\d{1,3}(\\.\\d{1,3}){3})(:\\d+)?(/.*)?$"+ )++ /** Kept for migration only — new tabs use "" and search uses selected engine. */+ const val HOMEPAGE = "https://duckduckgo.com"++ /** Full address for display — no truncation. Keep prettyUrl() for subtitles. */+ fun displayFullUrl(url: String): String = url++ fun looksLikeUrl(text: String): Boolean {+ if (text.contains(" ")) return false+ val trimmed = text.trim()+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) return true+ return URL_LIKE.matches(trimmed)+ }++ /** Search or navigate using the selected engine. */+ fun toNavigationUrl(input: String, searchEngine: SearchEngine): String {+ val trimmed = input.trim()+ if (trimmed.isEmpty()) return searchEngine.homepage+ if (trimmed.startsWith("http://") || trimmed.startsWith("https://")) return trimmed+ if (looksLikeUrl(trimmed)) {+ return if (trimmed.startsWith("http")) trimmed else "https://$trimmed"+ }+ return searchEngine.buildQueryUrl(trimmed)+ }++ fun toNavigationUrl(input: String): String = toNavigationUrl(input, SearchEngine.DEFAULT)++ fun hostFromUrl(url: String): String {+ return try { Uri.parse(url).host ?: url } catch (_: Exception) { url }+ }++ fun originFromUrl(url: String): String {+ return try {+ val u = Uri.parse(url)+ val scheme = u.scheme ?: "https"+ val host = u.host ?: return url+ val port = if (u.port != -1) ":${u.port}" else ""+ "$scheme://$host$port"+ } catch (_: Exception) { url }+ }++ fun prettyUrl(url: String): String {+ if (url.isBlank()) return ""+ return try {+ val parsed = Uri.parse(url)+ val host = parsed.host ?: return url+ val path = parsed.path ?: ""+ val display = if (path.isEmpty() || path == "/") host else host + path+ if (display.length > 48) host else display+ } catch (_: Exception) { url }+ }+}
web/src/main/java/com/vayunmathur/web/platform/ExternalIntents.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/ExternalIntents.kt b/web/src/main/java/com/vayunmathur/web/platform/ExternalIntents.ktindex d673805cdf..d9ef20dea8 100644--- a/web/src/main/java/com/vayunmathur/web/platform/ExternalIntents.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/ExternalIntents.kt@@ -1 +1,58 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/ExternalIntents.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.platform++import android.content.ActivityNotFoundException+import android.content.Context+import android.content.Intent+import android.net.Uri+import java.net.URISyntaxException++/**+ * Handles navigations to non-web schemes (intent:, market:, tel:, mailto:, custom app links).+ *+ * intent:// URLs carry an encoded Intent payload plus an optional browser_fallback_url; they must be+ * decoded with [Intent.parseUri] rather than handed to ACTION_VIEW as raw data. When no app can+ * handle the intent we honor browser_fallback_url, then fall back to the Play Store for the target+ * package.+ *+ * @param loadFallback loads an http(s) URL back in the WebView (used for browser_fallback_url).+ * @return true if the navigation was consumed and the WebView should not load the URL itself.+ */+fun openExternalUri(context: Context, url: String, loadFallback: (String) -> Unit): Boolean {+ val intent = try {+ if (url.startsWith("intent:", ignoreCase = true)) {+ Intent.parseUri(url, Intent.URI_INTENT_SCHEME)+ } else {+ Intent(Intent.ACTION_VIEW, Uri.parse(url))+ }+ } catch (_: URISyntaxException) {+ return false+ }++ // Harden against web content targeting arbitrary internal components.+ intent.addCategory(Intent.CATEGORY_BROWSABLE)+ intent.component = null+ intent.selector = null+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)++ try {+ context.startActivity(intent)+ return true+ } catch (_: ActivityNotFoundException) {+ intent.getStringExtra("browser_fallback_url")?.takeIf { it.isNotBlank() }?.let {+ loadFallback(it)+ return true+ }+ intent.`package`?.let { pkg ->+ return try {+ context.startActivity(+ Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$pkg"))+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ )+ true+ } catch (_: ActivityNotFoundException) {+ false+ }+ }+ return false+ }+}
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 9c8d0c7b6e..ec6c98a070 100644--- a/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt@@ -1 +1,377 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/PwaActivity.kt' exists on disk, but not in 'stash@{14}'+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)+ }+ }+ )+ }+}
web/src/main/java/com/vayunmathur/web/platform/PwaHelper.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/PwaHelper.kt b/web/src/main/java/com/vayunmathur/web/platform/PwaHelper.ktindex 845101494b..ca40439806 100644--- a/web/src/main/java/com/vayunmathur/web/platform/PwaHelper.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/PwaHelper.kt@@ -1 +1,212 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/PwaHelper.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.platform++import android.content.Context+import android.content.Intent+import android.graphics.Bitmap+import android.graphics.Canvas+import android.graphics.Paint+import android.net.Uri+import android.util.Log+import androidx.core.content.pm.ShortcutInfoCompat+import androidx.core.content.pm.ShortcutManagerCompat+import androidx.core.graphics.drawable.IconCompat+import com.vayunmathur.library.image.ImageLoader+import com.vayunmathur.library.image.ImageRequest+import com.vayunmathur.library.image.ImageResult+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++data class PwaInfo(+ val name: String,+ val shortName: String = "",+ val iconUrl: String? = null,+ val faviconUrl: String? = null,+ val themeColor: String? = null,+ val backgroundColor: String? = null,+ val displayMode: String = "standalone",+ val startUrl: String? = null,+ val origin: String,+ val manifestUrl: String? = null,+ val hasManifest: Boolean = false,+)++object PwaHelper {+ private const val TAG = "PwaHelper"++ // JS probe - intentionally avoids Kotlin ${} templates by using string concatenation only.+ const val MANIFEST_PROBE_JS = "(function(){" ++ "try{" ++ "var origin=location.origin;" ++ "var title='';" ++ "try{var og=document.querySelector('meta[property=\"og:title\"]');title=(og&&og.content)?og.content.trim():(document.title||'').trim();}catch(e){title=document.title||'';}" ++ "var iconUrl=null,faviconUrl=null,themeColor=null,bgColor=null,displayMode='browser',startUrl=location.href,manifestUrl=null,hasManifest=false;" ++ "try{var tm=document.querySelector('meta[name=\"theme-color\"]');if(tm)themeColor=tm.content||null;}catch(e){}" ++ "try{var ms=document.querySelector('meta[name=\"msapplication-TileColor\"]');if(ms)bgColor=ms.content||null;}catch(e){}" ++ "try{var ml=document.querySelector('link[rel=\"manifest\"]');if(ml){manifestUrl=ml.href;hasManifest=!!manifestUrl;}}catch(e){}" ++ "function bestIcon(){" ++ "try{" ++ "var cands=[];var ls=document.querySelectorAll('link[rel*=\"icon\"]');" ++ "for(var i=0;i<ls.length;i++){var l=ls[i];var href=l.href;if(!href)continue;var rel=(l.rel||'').toLowerCase();var sizes=(l.getAttribute('sizes')||'').toLowerCase();var score=0;" ++ "if(rel.indexOf('apple-touch-icon')>=0)score=90;if(rel==='icon'||rel.indexOf('icon')>=0)score=Math.max(score,70);" ++ "if(sizes.indexOf('192')>=0||sizes.indexOf('512')>=0)score+=40;if(sizes.indexOf('180')>=0)score+=20;" ++ "if(href.indexOf('192')>=0||href.indexOf('512')>=0)score+=25;if(href.endsWith('.png'))score+=10;" ++ "cands.push({href:href,score:score});}" ++ "if(cands.length===0)return null;cands.sort(function(a,b){return b.score-a.score;});return cands[0].href;" ++ "}catch(e){return null;}}" ++ "try{var il=document.querySelector('link[rel=\"icon\"], link[rel=\"shortcut icon\"]');if(il)faviconUrl=il.href||null;}catch(e){}" ++ "var best=bestIcon();if(best)iconUrl=best;if(!iconUrl&&faviconUrl)iconUrl=faviconUrl;" ++ "return JSON.stringify({title:title,name:'',shortName:'',iconUrl:iconUrl,faviconUrl:faviconUrl,themeColor:themeColor,bgColor:bgColor,displayMode:displayMode,startUrl:startUrl,manifestUrl:manifestUrl,hasManifest:hasManifest,origin:origin});" ++ "}catch(e){try{return JSON.stringify({title:document.title||'',origin:location.origin||''});}catch(e2){return null;}}})();"++ fun parseProbeJson(escapedJson: String?): PwaInfo? {+ if (escapedJson.isNullOrBlank()) return null+ var s = escapedJson.trim()+ if (s.startsWith("\"") && s.endsWith("\"")) {+ s = s.substring(1, s.length - 1).replace("\\\"", "\"").replace("\\\\", "\\").replace("\\/", "/")+ }+ if (s.isBlank() || s == "null") return null+ fun strField(key: String): String? {+ val m = Regex("\"" + key + "\"\\s*:\\s*\"((?:\\\\\"|[^\"])*)\"").find(s) ?: return null+ return m.groupValues[1].replace("\\\"", "\"").replace("\\\\", "\\").replace("\\/", "/")+ }+ val title = strField("title") ?: ""+ val name = strField("name")?.ifBlank { null } ?: title+ val shortName = strField("shortName") ?: ""+ val iconUrl = strField("iconUrl")+ val faviconUrl = strField("faviconUrl")+ val themeColor = strField("themeColor")+ val bgColor = strField("bgColor")+ val displayMode = strField("displayMode") ?: "browser"+ val startUrl = strField("startUrl")+ val manifestUrl = strField("manifestUrl")+ val origin = strField("origin") ?: ""+ val hasManifest = Regex("\"hasManifest\"\\s*:\\s*(true|false)").find(s)?.groupValues?.get(1) == "true"+ if (origin.isBlank() && name.isBlank() && title.isBlank() && iconUrl == null) return null+ return PwaInfo(+ name = name.ifBlank { title },+ shortName = shortName,+ iconUrl = iconUrl,+ faviconUrl = faviconUrl,+ themeColor = themeColor,+ backgroundColor = bgColor,+ displayMode = displayMode,+ startUrl = startUrl,+ origin = origin.ifBlank { startUrl ?: "" },+ manifestUrl = manifestUrl,+ hasManifest = hasManifest,+ )+ }++ fun displayTitle(info: PwaInfo?, fallbackTitle: String, fallbackUrl: String): String {+ val n = info?.name?.ifBlank { null } ?: info?.shortName?.ifBlank { null }+ val t = fallbackTitle.ifBlank { null }+ val host = runCatching { BrowserUtils.hostFromUrl(fallbackUrl) }.getOrNull()?.takeIf { it.isNotBlank() }+ return (n ?: t ?: host ?: "Site").take(48)+ }++ fun isPinSupported(context: Context): Boolean =+ ShortcutManagerCompat.isRequestPinShortcutSupported(context)++ fun shortcutId(url: String): String = try {+ val origin = BrowserUtils.originFromUrl(url)+ "pwa_" + origin.hashCode() + "_" + url.hashCode()+ } catch (_: Exception) {+ "pwa_" + url.hashCode()+ }++ fun createPwaIntent(context: Context, url: String, title: String?): Intent {+ return Intent(context, com.vayunmathur.web.platform.PwaActivity::class.java).apply {+ action = Intent.ACTION_VIEW+ data = Uri.parse(url)+ putExtra(com.vayunmathur.web.platform.PwaActivity.EXTRA_URL, url)+ putExtra(com.vayunmathur.web.platform.PwaActivity.EXTRA_TITLE, title)+ addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)+ }+ }++ suspend fun loadIconBitmap(context: Context, iconUrl: String?): Bitmap? {+ if (iconUrl.isNullOrBlank()) return null+ return withContext(Dispatchers.IO) {+ try {+ val loader = ImageLoader.get(context)+ val req = ImageRequest.Builder(context)+ .data(iconUrl)+ .allowHardware(false)+ .size(192)+ .build()+ val result = loader.execute(req)+ val bitmap = (result as? ImageResult.Success)?.bitmap ?: return@withContext null+ bitmap.copy(Bitmap.Config.ARGB_8888, false) ?: bitmap+ } catch (e: Exception) {+ Log.w(TAG, "loadIconBitmap failed " + iconUrl, e)+ null+ }+ }+ }++ fun textIconBitmap(title: String, sizePx: Int = 192): Bitmap {+ val bmp = Bitmap.createBitmap(sizePx, sizePx, Bitmap.Config.ARGB_8888)+ val canvas = Canvas(bmp)+ val hash = title.hashCode()+ val rr = 80 + (hash shr 16 and 0x7F)+ val gg = 80 + (hash shr 8 and 0x7F)+ val bb = 80 + (hash and 0x7F)+ val bg = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ color = android.graphics.Color.rgb(rr, gg, bb)+ }+ val radius = sizePx * 0.28f+ canvas.drawRoundRect(0f, 0f, sizePx.toFloat(), sizePx.toFloat(), radius, radius, bg)+ val tp = Paint(Paint.ANTI_ALIAS_FLAG).apply {+ color = android.graphics.Color.WHITE+ textSize = sizePx * 0.52f+ textAlign = Paint.Align.CENTER+ isFakeBoldText = true+ }+ val letter = title.trim().firstOrNull()?.uppercase() ?: "W"+ val x = sizePx / 2f+ val y = sizePx / 2f - (tp.descent() + tp.ascent()) / 2f+ canvas.drawText(letter, x, y, tp)+ return bmp+ }++ suspend fun requestPinShortcut(+ context: Context,+ url: String,+ title: String,+ iconUrl: String?,+ faviconUrl: String? = null,+ ): Boolean {+ if (!isPinSupported(context)) return false+ return withContext(Dispatchers.Main) {+ try {+ val id = shortcutId(url)+ val intent = createPwaIntent(context, url, title)+ val shortLabel = title.takeIf { it.isNotBlank() }?.take(10) ?: BrowserUtils.hostFromUrl(url).take(10)+ val longLabel = title.ifBlank { url }.take(48)++ var bmp = loadIconBitmap(context, iconUrl)+ if (bmp == null && !faviconUrl.isNullOrBlank()) bmp = loadIconBitmap(context, faviconUrl)+ if (bmp == null) {+ try {+ val origin = BrowserUtils.originFromUrl(url)+ bmp = loadIconBitmap(context, origin + "/favicon.ico")+ } catch (_: Exception) {}+ }+ val finalBmp = bmp ?: textIconBitmap(title)+ val icon = IconCompat.createWithAdaptiveBitmap(finalBmp)++ val info = ShortcutInfoCompat.Builder(context, id)+ .setShortLabel(shortLabel)+ .setLongLabel(longLabel)+ .setIntent(intent)+ .setIcon(icon)+ .build()++ ShortcutManagerCompat.requestPinShortcut(context, info, null)+ } catch (e: Exception) {+ Log.e(TAG, "requestPinShortcut failed", e)+ false+ }+ }+ }+}
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 eaa55e9ff0..611c137957 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt@@ -1 +1,826 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt' exists on disk, but not in 'stash@{14}'+@file:OptIn(kotlin.uuid.ExperimentalUuidApi::class)++package com.vayunmathur.web.platform++import kotlin.uuid.Uuid+import android.content.Context+import android.net.Uri+import android.util.Log+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.setValue+import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.vayunmathur.web.data.Bookmark+import com.vayunmathur.web.data.BookmarkFolder+import com.vayunmathur.web.data.DownloadEntry+import com.vayunmathur.web.data.HistoryEntry+import com.vayunmathur.web.data.InstalledSite+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.platform.shields.FarblingConfig+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import kotlinx.serialization.encodeToString+import kotlinx.serialization.json.Json++private const val TAG = "WebViewModel"+private const val P_SAVED_TABS = "web_saved_tabs"+private const val P_ACTIVE_TAB = "web_active_tab_id"+private const val P_CACHE_MODE = "web_cache_mode"+private const val P_JS_ENABLED = "web_js_enabled"+private const val P_BLOCK_THIRD_PARTY = "web_block_third_party"+private const val P_DESKTOP_MODE = "web_desktop_mode"+private const val P_SEARCH_ENGINE = "web_search_engine"+private const val P_SHIELD_LEVEL = "web_shield_level"+private const val P_SHIELD_TRACKERS = "web_shield_trackers"+private const val P_SHIELD_COSMETIC = "web_shield_cosmetic"+private const val P_SHIELD_FINGERPRINT = "web_shield_fingerprint"+private const val P_SHIELD_HTTPS = "web_shield_https"++data class PermissionPrompt(+ val id: String = Uuid.random().toString(),+ val origin: String,+ val types: List<SitePermissionType>,+ val onGrant: (List<SitePermissionType>) -> Unit,+ val onDeny: () -> Unit,+)++class WebViewModel(+ private val repository: WebRepository,+ private val context: Context,+ /** Identifies this window's independent tab set; the default window keeps the legacy pref keys. */+ private val windowId: String = DEFAULT_WINDOW_ID,+ /** An incognito window: every tab is private and nothing is persisted. */+ val incognito: Boolean = false,+ /**+ * Site exceptions read before the UI was allowed to render. Seeding them here rather+ * than waiting for [ShieldSettingDao.allFlow] is what stops the first page of a cold+ * start from being farbled on a site the user turned shields off for.+ */+ initialShieldSettings: List<ShieldSetting> = emptyList(),+) : ViewModel() {++ companion object {+ const val DEFAULT_WINDOW_ID = "main"+ }++ // Persistence keys are namespaced per window; the default window keeps the legacy keys for back-compat.+ private val savedTabsKey = if (windowId == DEFAULT_WINDOW_ID) P_SAVED_TABS else "${P_SAVED_TABS}_$windowId"+ private val activeTabKey = if (windowId == DEFAULT_WINDOW_ID) P_ACTIVE_TAB else "${P_ACTIVE_TAB}_$windowId"++ private fun blankTab() = BrowserTab(id = Uuid.random().toString(), url = "", isPrivate = incognito)++ val tabs = mutableStateListOf<BrowserTab>()+ var activeTabId by mutableStateOf<String?>(null)+ private set++ var omniboxText by mutableStateOf("")+ var omniboxFocused by mutableStateOf(false)+ var searchDraft by mutableStateOf("")++ var searchEngine by mutableStateOf(SearchEngine.DEFAULT)+ val homepage: String get() = searchEngine.homepage++ var cacheMode by mutableStateOf(CacheMode.DEFAULT)+ var jsEnabled by mutableStateOf(true)+ var blockThirdPartyCookies by mutableStateOf(false)+ var desktopMode by mutableStateOf(false)++ /** Global Brave Shields defaults; per-site overrides live in [shieldSettings]. */+ var shields by mutableStateOf(ShieldsSettings.AGGRESSIVE_DEFAULTS)+ private set++ private val _bookmarks = MutableStateFlow<List<Bookmark>>(emptyList())+ val bookmarks: StateFlow<List<Bookmark>> = _bookmarks++ private val _folders = MutableStateFlow<List<BookmarkFolder>>(emptyList())+ val folders: StateFlow<List<BookmarkFolder>> = _folders++ private val _history = MutableStateFlow<List<HistoryEntry>>(emptyList())+ val history: StateFlow<List<HistoryEntry>> = _history++ private val _sitePermissions = MutableStateFlow<List<SitePermission>>(emptyList())+ val sitePermissions: StateFlow<List<SitePermission>> = _sitePermissions++ private val _storageInfos = MutableStateFlow<List<StorageInfo>>(emptyList())+ val storageInfos: StateFlow<List<StorageInfo>> = _storageInfos++ private val _downloads = MutableStateFlow<List<DownloadEntry>>(emptyList())+ val downloads: StateFlow<List<DownloadEntry>> = _downloads++ private val _installedSites = MutableStateFlow<List<InstalledSite>>(emptyList())+ val installedSites: StateFlow<List<InstalledSite>> = _installedSites++ private val _shieldSettings = MutableStateFlow(initialShieldSettings)+ val shieldSettings: StateFlow<List<ShieldSetting>> = _shieldSettings++ /**+ * Per-host overrides mirrored synchronously because `shouldInterceptRequest` runs on the+ * render thread and cannot wait on a coroutine or a database read.+ */+ private val shieldOverrides = java.util.concurrent.ConcurrentHashMap<String, ShieldsSettings>()+ .apply { initialShieldSettings.forEach { put(it.host, it.toSettings()) } }++ /**+ * Blocked-request tallies. The counting side is hit from the render thread, so the+ * authoritative totals live in a concurrent map and only the UI mirror is a snapshot+ * state ΓÇö writing Compose state off the main thread is not safe.+ */+ private val blockedTotals = java.util.concurrent.ConcurrentHashMap<String, java.util.concurrent.atomic.AtomicInteger>()+ private val blockedPublishPending = java.util.concurrent.ConcurrentHashMap<String, Boolean>()+ private val blockedCounts = mutableStateMapOf<String, Int>()+ private val mainHandler = android.os.Handler(android.os.Looper.getMainLooper())++ /** Whether the shields panel is open; the host it targets is always the active tab's. */+ var showShieldsPanel by mutableStateOf(false)++ var pendingPermissionPrompt by mutableStateOf<PermissionPrompt?>(null)+ private set++ var pendingGeolocationPrompt by mutableStateOf<Triple<String, () -> Unit, () -> Unit>?>(null)+ private set++ var pendingFileChooser by mutableStateOf<Pair<android.webkit.ValueCallback<Array<Uri>>, android.webkit.WebChromeClient.FileChooserParams>?>(null)+ private set++ var showTabSwitcher by mutableStateOf(false)++ private val tabTitles = mutableMapOf<String, String>()+ private val tabProgress = mutableMapOf<String, Float>()+ private val tabCanGoBack = mutableMapOf<String, Boolean>()+ private val tabCanGoForward = mutableMapOf<String, Boolean>()+ private val tabCurrentUrl = mutableMapOf<String, String>()++ // PWA / installed site detection per tab+ val pwaInfos = mutableStateMapOf<String, PwaInfo>()++ private val json = Json { ignoreUnknownKeys = true }++ init {+ viewModelScope.launch {+ withContext(Dispatchers.IO) {+ try {+ val sp = context.getSharedPreferences("web_prefs", Context.MODE_PRIVATE)+ // Incognito windows never restore persisted tabs ΓÇö they start fresh and private.+ val savedTabs = if (incognito) null else sp.getString(savedTabsKey, null)+ val activeId = if (incognito) null else sp.getString(activeTabKey, null)+ val cacheModeName = sp.getString(P_CACHE_MODE, null)+ val searchEngineName = sp.getString(P_SEARCH_ENGINE, null)+ val js = sp.getBoolean(P_JS_ENABLED, true)+ val blockThird = sp.getBoolean(P_BLOCK_THIRD_PARTY, false)+ val desktop = sp.getBoolean(P_DESKTOP_MODE, false)+ val defaults = ShieldsSettings.AGGRESSIVE_DEFAULTS+ val savedShields = ShieldsSettings(+ level = sp.getString(P_SHIELD_LEVEL, null)+ ?.let { runCatching { ShieldLevel.valueOf(it) }.getOrNull() }+ ?: defaults.level,+ blockTrackers = sp.getBoolean(P_SHIELD_TRACKERS, true),+ cosmeticFiltering = sp.getBoolean(P_SHIELD_COSMETIC, true),+ fingerprintProtection = sp.getBoolean(P_SHIELD_FINGERPRINT, true),+ httpsUpgrade = sp.getBoolean(P_SHIELD_HTTPS, true),+ )+ withContext(Dispatchers.Main) {+ shields = savedShields+ cacheModeName?.let { runCatching { CacheMode.valueOf(it) }.getOrNull()?.let { cm -> cacheMode = cm } }+ searchEngineName?.let { runCatching { SearchEngine.valueOf(it) }.getOrNull()?.let { se -> searchEngine = se } }+ jsEnabled = js+ blockThirdPartyCookies = blockThird+ desktopMode = desktop++ // Capture any tabs that were already created (e.g., from an external intent arriving before restore finishes)+ val preExisting = tabs.toList()+ val preExistingActive = activeTabId++ val decodedSaved: List<BrowserTab>? = if (savedTabs != null) {+ runCatching { json.decodeFromString<List<BrowserTab>>(savedTabs) }.getOrNull()?.takeIf { it.isNotEmpty() }+ } else null++ when {+ decodedSaved != null -> {+ if (preExisting.isNotEmpty()) {+ // Merge: keep saved tabs + any extra tabs created before restore (like external URL)+ val decodedIds = decodedSaved.map { it.id }.toSet()+ val extras = preExisting.filter { it.id !in decodedIds }+ tabs.clear()+ tabs.addAll(decodedSaved)+ if (extras.isNotEmpty()) {+ tabs.addAll(extras)+ // If the active tab was one of the extras, keep it active (new tab wins)+ if (preExistingActive != null && extras.any { it.id == preExistingActive }) {+ activeTabId = preExistingActive+ } else {+ activeTabId = activeId ?: tabs.firstOrNull()?.id+ }+ } else {+ activeTabId = activeId ?: tabs.firstOrNull()?.id+ }+ } else {+ tabs.clear()+ tabs.addAll(decodedSaved)+ activeTabId = activeId ?: tabs.firstOrNull()?.id+ }+ }+ preExisting.isNotEmpty() -> {+ // No saved tabs but we already have tabs (external intent race) -> keep them+ if (activeTabId == null) activeTabId = preExisting.firstOrNull()?.id+ }+ else -> {+ // No saved and no pre-existing -> will create blank below+ }+ }++ if (tabs.isEmpty()) {+ val tab = blankTab()+ tabs.add(tab)+ activeTabId = tab.id+ } else {+ // Migrate legacy new-tabs that were saved as duckduckgo.com -> blank New Tab+ val migrated = tabs.map { t ->+ val isHomepage = t.url == BrowserUtils.HOMEPAGE || t.url == "${BrowserUtils.HOMEPAGE}/"+ val isPlaceholderTitle = t.title.isBlank() || t.title == BrowserUtils.HOMEPAGE || t.title == "${BrowserUtils.HOMEPAGE}/"+ if (isHomepage && isPlaceholderTitle) t.copy(url = "", title = "") else t+ }+ if (migrated != tabs.toList()) {+ tabs.clear()+ tabs.addAll(migrated)+ }+ // Ensure active id is still valid after migration+ if (activeTabId == null || tabs.none { it.id == activeTabId }) {+ activeTabId = activeId ?: tabs.firstOrNull()?.id+ }+ }+ activeTab?.let {+ omniboxText = if (it.url.isBlank() || it.url == "about:blank") "" else it.url+ searchDraft = omniboxText+ }+ }+ } catch (e: Exception) {+ Log.e(TAG, "Failed to load prefs", e)+ withContext(Dispatchers.Main) {+ if (tabs.isEmpty()) {+ val tab = blankTab()+ tabs.add(tab)+ activeTabId = tab.id+ }+ }+ }+ }+ }++ viewModelScope.launch { repository.allBookmarksFlow().collect { _bookmarks.value = it } }+ viewModelScope.launch { repository.bookmarkFoldersFlow().collect { _folders.value = it } }+ viewModelScope.launch { repository.allHistoryFlow().collect { _history.value = it } }+ viewModelScope.launch { repository.allSitePermissionsFlow().collect { _sitePermissions.value = it } }+ viewModelScope.launch { repository.allStorageInfosFlow().collect { _storageInfos.value = it } }+ viewModelScope.launch { repository.allDownloadsFlow().collect { _downloads.value = it } }+ viewModelScope.launch { repository.allInstalledSitesFlow().collect { _installedSites.value = it } }+ viewModelScope.launch {+ repository.allShieldSettingsFlow().collect { settings ->+ _shieldSettings.value = settings+ shieldOverrides.clear()+ settings.forEach { shieldOverrides[it.host] = it.toSettings() }+ }+ }+ }++ // ---- Brave Shields ----++ /**+ * Resolved shields for [host]. Safe to call from the WebView render thread: it only+ * touches the concurrent override map, never the Compose-backed tab list.+ *+ * @param isPrivate the owning tab is private, which forces the full aggressive preset+ */+ fun shieldsFor(host: String, isPrivate: Boolean = false): EffectiveShields {+ if (isPrivate || incognito) {+ return EffectiveShields.resolve(ShieldsSettings.AGGRESSIVE_DEFAULTS)+ }+ return EffectiveShields.resolve(shields, shieldOverrides[host])+ }++ /**+ * Snapshot of the farbling decision for every site, for the document-start script.+ * Changes to this are what force a script re-registration.+ */+ fun farblingConfig(): FarblingConfig = FarblingConfig.of(shields, shieldOverrides.toMap())++ fun updateShields(settings: ShieldsSettings) {+ shields = settings+ persistPrefs()+ }++ fun updateSiteShields(host: String, settings: ShieldsSettings) {+ if (host.isBlank()) return+ // Mirror immediately so the next request sees it without waiting for Room.+ if (settings.isEmpty) shieldOverrides.remove(host) else shieldOverrides[host] = settings+ viewModelScope.launch {+ if (settings.isEmpty) {+ repository.deleteShieldSettingHost(host)+ } else {+ repository.upsertShieldSetting(ShieldSetting.from(host, settings))+ }+ }+ }++ fun clearSiteShields() {+ shieldOverrides.clear()+ viewModelScope.launch { repository.clearAllShieldSettings() }+ }++ /** Called from the render thread on every blocked request; coalesces UI updates. */+ fun onRequestBlocked(tabId: String) {+ blockedTotals.computeIfAbsent(tabId) { java.util.concurrent.atomic.AtomicInteger() }+ .incrementAndGet()+ if (blockedPublishPending.putIfAbsent(tabId, true) == null) {+ mainHandler.post {+ blockedPublishPending.remove(tabId)+ blockedCounts[tabId] = blockedTotals[tabId]?.get() ?: 0+ }+ }+ }++ fun resetBlockedCount(tabId: String) {+ blockedTotals.remove(tabId)+ blockedCounts[tabId] = 0+ }++ fun blockedCount(tabId: String): Int = blockedCounts[tabId] ?: 0++ val activeTab: BrowserTab? get() = tabs.find { it.id == activeTabId }++ fun onTabUrlChange(tabId: String, url: String) {+ tabCurrentUrl[tabId] = url+ updateTab(tabId) { it.copy(url = url) }+ persistTabs()+ if (tabId == activeTabId && !omniboxFocused) {+ omniboxText = if (url.isBlank() || url == "about:blank") "" else url+ }+ if (url.startsWith("http")) {+ val origin = BrowserUtils.originFromUrl(url)+ val host = BrowserUtils.hostFromUrl(url)+ viewModelScope.launch {+ val existing = repository.storageInfoByOrigin(origin)+ if (existing == null) {+ repository.upsertStorageInfo(StorageInfo(origin = origin, host = host, lastSeen = System.currentTimeMillis()))+ } else {+ repository.upsertStorageInfo(existing.copy(lastSeen = System.currentTimeMillis(), host = host))+ }+ }+ }+ }++ fun onTabTitleChange(tabId: String, title: String) {+ tabTitles[tabId] = title+ updateTab(tabId) { it.copy(title = title) }+ persistTabs()+ }++ fun getTabTitle(tabId: String): String = tabTitles[tabId] ?: tabs.find { it.id == tabId }?.title ?: ""++ fun onPwaInfoDetected(tabId: String, info: PwaInfo) {+ pwaInfos[tabId] = info+ }++ fun onTabProgress(tabId: String, progress: Float) { tabProgress[tabId] = progress }+ fun onTabCanGoBack(tabId: String, value: Boolean) { tabCanGoBack[tabId] = value }+ fun onTabCanGoForward(tabId: String, value: Boolean) { tabCanGoForward[tabId] = value }++ fun getProgress(tabId: String) = tabProgress[tabId] ?: 0f+ fun getCanGoBack(tabId: String) = tabCanGoBack[tabId] ?: false+ fun getCanGoForward(tabId: String) = tabCanGoForward[tabId] ?: false+ fun getCurrentUrl(tabId: String) = tabCurrentUrl[tabId] ?: tabs.find { it.id == tabId }?.url ?: ""+ fun getPwaInfo(tabId: String) = pwaInfos[tabId]++ private fun updateTab(tabId: String, transform: (BrowserTab) -> BrowserTab) {+ val idx = tabs.indexOfFirst { it.id == tabId }+ if (idx >= 0) tabs[idx] = transform(tabs[idx])+ }++ fun newTab(url: String = "", makeActive: Boolean = true, isPrivate: Boolean = false) {+ // Every tab in an incognito window is private, regardless of the caller's request.+ val tab = BrowserTab(id = Uuid.random().toString(), url = url, isPrivate = isPrivate || incognito)+ tabs.add(tab)+ if (makeActive) {+ activeTabId = tab.id+ omniboxFocused = false+ omniboxText = if (url.isBlank() || url == "about:blank") "" else url+ searchDraft = if (url.isBlank() || url == "about:blank") "" else url+ }+ persistTabs()+ }++ fun closeTab(tabId: String) {+ val idx = tabs.indexOfFirst { it.id == tabId }+ if (idx < 0) return+ tabs.removeAt(idx)+ tabTitles.remove(tabId)+ tabProgress.remove(tabId)+ tabCanGoBack.remove(tabId)+ tabCanGoForward.remove(tabId)+ tabCurrentUrl.remove(tabId)+ blockedCounts.remove(tabId)+ blockedTotals.remove(tabId)+ pwaInfos.remove(tabId)+ if (activeTabId == tabId) {+ activeTabId = when {+ tabs.isEmpty() -> {+ val tab = blankTab()+ tabs.add(tab)+ tab.id+ }+ idx < tabs.size -> tabs[idx].id+ else -> tabs.last().id+ }+ val cur = activeTab+ omniboxText = if (cur == null || cur.url.isBlank() || cur.url == "about:blank") "" else cur.url+ searchDraft = omniboxText+ }+ persistTabs()+ }++ fun switchToTab(tabId: String) {+ activeTabId = tabId+ val cur = activeTab+ omniboxText = if (cur == null || cur.url.isBlank() || cur.url == "about:blank") "" else cur.url+ searchDraft = omniboxText+ showTabSwitcher = false+ persistTabs()+ }++ fun navigateActiveTab(input: String) {+ val active = activeTab ?: return+ val dest = BrowserUtils.toNavigationUrl(input, searchEngine)+ onTabUrlChange(active.id, dest)+ omniboxFocused = false+ }++ fun recordHistoryVisit(url: String, title: String) {+ if (url.isBlank() || url == "about:blank" || url.startsWith("data:")) return+ if (activeTab?.isPrivate == true) return+ viewModelScope.launch {+ runCatching { repository.upsertHistory(HistoryEntry(url = url, title = title)) }+ .onFailure { Log.e(TAG, "recordHistory", it) }+ }+ }++ fun addBookmark(url: String, title: String, folderId: Long? = null) {+ viewModelScope.launch { runCatching { repository.upsertBookmark(Bookmark(url = url, title = title, folderId = folderId)) } }+ }++ fun removeBookmark(bookmark: Bookmark) {+ viewModelScope.launch { repository.deleteBookmark(bookmark) }+ }++ fun createFolder(name: String) {+ viewModelScope.launch { runCatching { repository.upsertBookmarkFolder(BookmarkFolder(name = name)) } }+ }++ fun deleteFolder(folder: BookmarkFolder) {+ viewModelScope.launch {+ runCatching {+ repository.deleteBookmarksByFolder(folder.id)+ repository.deleteBookmarkFolder(folder)+ }+ }+ }++ fun clearHistory() {+ viewModelScope.launch { repository.clearAllHistory() }+ }++ fun updateCacheMode(mode: CacheMode) {+ cacheMode = mode+ persistPrefs()+ }++ fun updateSearchEngine(engine: SearchEngine) {+ searchEngine = engine+ persistPrefs()+ }++ fun updateJsEnabled(enabled: Boolean) {+ jsEnabled = enabled+ persistPrefs()+ }++ fun updateBlockThirdParty(block: Boolean) {+ blockThirdPartyCookies = block+ persistPrefs()+ }++ fun updateDesktopMode(enabled: Boolean) {+ desktopMode = enabled+ persistPrefs()+ }++ // ---- PWA / Installed sites ----+ fun installAsPwa(+ tabId: String,+ url: String,+ pwaInfo: PwaInfo?,+ onResult: (Boolean) -> Unit = {}+ ) {+ viewModelScope.launch {+ try {+ val origin = BrowserUtils.originFromUrl(url)+ val id = PwaHelper.shortcutId(url)+ val title = PwaHelper.displayTitle(pwaInfo, tabs.find { it.id == tabId }?.title ?: "", url)+ val entry = InstalledSite(+ id = id,+ url = url,+ title = title,+ shortName = pwaInfo?.shortName ?: "",+ iconUrl = pwaInfo?.iconUrl,+ faviconUrl = pwaInfo?.faviconUrl,+ themeColor = pwaInfo?.themeColor,+ backgroundColor = pwaInfo?.backgroundColor,+ displayMode = pwaInfo?.displayMode ?: "standalone",+ startUrl = pwaInfo?.startUrl ?: url,+ origin = origin,+ )+ repository.upsertInstalledSite(entry)+ val accepted = PwaHelper.requestPinShortcut(+ context = context,+ url = url,+ title = title,+ iconUrl = entry.iconUrl,+ faviconUrl = entry.faviconUrl,+ )+ onResult(accepted)+ } catch (e: Exception) {+ Log.e(TAG, "installAsPwa failed", e)+ onResult(false)+ }+ }+ }++ fun removeInstalledSite(id: String) {+ viewModelScope.launch { repository.deleteInstalledSiteById(id) }+ }++ // ---- Site permissions ----+ fun requestWebPermission(+ origin: String,+ types: List<SitePermissionType>,+ grant: (List<SitePermissionType>) -> Unit,+ deny: () -> Unit+ ) {+ viewModelScope.launch {+ val saved = repository.sitePermissionByOrigin(origin)+ val (toAsk, preGranted) = if (saved != null) {+ val determined = types.mapNotNull { t ->+ when (t) {+ SitePermissionType.CAMERA -> saved.cameraAllowed?.let { t to it }+ SitePermissionType.MICROPHONE -> saved.microphoneAllowed?.let { t to it }+ SitePermissionType.LOCATION -> saved.locationAllowed?.let { t to it }+ SitePermissionType.NOTIFICATIONS -> saved.notificationsAllowed?.let { t to it }+ }+ }+ val grantedFromSaved = determined.filter { it.second }.map { it.first }+ val remaining = types.filter { type -> determined.none { it.first == type } }+ remaining to grantedFromSaved+ } else {+ types to emptyList()+ }++ if (toAsk.isEmpty()) {+ if (preGranted.isNotEmpty()) {+ withContext(Dispatchers.Main) { grant(preGranted) }+ } else {+ withContext(Dispatchers.Main) { deny() }+ }+ return@launch+ }++ withContext(Dispatchers.Main) {+ pendingPermissionPrompt = PermissionPrompt(+ origin = origin,+ types = toAsk,+ onGrant = { grantedNow ->+ persistPermission(origin, grantedNow, toAsk)+ grant(preGranted + grantedNow)+ },+ onDeny = {+ persistPermission(origin, emptyList(), toAsk)+ if (preGranted.isNotEmpty()) grant(preGranted) else deny()+ }+ )+ }+ }+ }++ private fun persistPermission(origin: String, granted: List<SitePermissionType>, requested: List<SitePermissionType>) {+ viewModelScope.launch {+ val existing = repository.sitePermissionByOrigin(origin) ?: SitePermission(origin = origin)+ var updated = existing+ requested.forEach { t ->+ val isGranted = t in granted+ updated = when (t) {+ SitePermissionType.CAMERA -> updated.copy(cameraAllowed = isGranted)+ SitePermissionType.MICROPHONE -> updated.copy(microphoneAllowed = isGranted)+ SitePermissionType.LOCATION -> updated.copy(locationAllowed = isGranted)+ SitePermissionType.NOTIFICATIONS -> updated.copy(notificationsAllowed = isGranted)+ }+ }+ repository.upsertSitePermission(updated.copy(updatedAt = System.currentTimeMillis()))+ }+ }++ fun clearPermissionPrompt() { pendingPermissionPrompt = null }++ fun requestGeolocation(origin: String, onAllow: () -> Unit, onDeny: () -> Unit) {+ viewModelScope.launch {+ val saved = repository.sitePermissionByOrigin(origin)+ when (saved?.locationAllowed) {+ true -> { withContext(Dispatchers.Main) { onAllow() }; return@launch }+ false -> { withContext(Dispatchers.Main) { onDeny() }; return@launch }+ null -> {}+ }+ withContext(Dispatchers.Main) {+ pendingGeolocationPrompt = Triple(origin, onAllow, onDeny)+ }+ }+ }++ fun grantGeolocation(origin: String) {+ pendingGeolocationPrompt?.let { (orig, allow, _) ->+ persistPermission(orig, listOf(SitePermissionType.LOCATION), listOf(SitePermissionType.LOCATION))+ allow()+ }+ pendingGeolocationPrompt = null+ }++ fun denyGeolocation() {+ pendingGeolocationPrompt?.let { (orig, _, deny) ->+ persistPermission(orig, emptyList(), listOf(SitePermissionType.LOCATION))+ deny()+ }+ pendingGeolocationPrompt = null+ }++ fun requestFileChooser(+ callback: android.webkit.ValueCallback<Array<Uri>>,+ params: android.webkit.WebChromeClient.FileChooserParams+ ) {+ pendingFileChooser = callback to params+ }++ fun clearFileChooser() {+ pendingFileChooser?.first?.onReceiveValue(null)+ pendingFileChooser = null+ }++ fun deliverFileChooserResult(uris: Array<Uri>?) {+ pendingFileChooser?.first?.onReceiveValue(uris)+ pendingFileChooser = null+ }++ fun updateStorageFootprint(+ origin: String,+ cookieCount: Int,+ hasLocalStorage: Boolean,+ hasIndexedDb: Boolean,+ hasServiceWorker: Boolean,+ estBytes: Long+ ) {+ viewModelScope.launch {+ val existing = repository.storageInfoByOrigin(origin)+ val info = if (existing != null) {+ existing.copy(+ cookieCount = cookieCount,+ hasLocalStorage = hasLocalStorage || existing.hasLocalStorage,+ hasIndexedDb = hasIndexedDb || existing.hasIndexedDb,+ hasServiceWorker = hasServiceWorker || existing.hasServiceWorker,+ estimatedBytes = if (estBytes > 0) estBytes else existing.estimatedBytes,+ lastSeen = System.currentTimeMillis()+ )+ } else {+ StorageInfo(+ origin = origin,+ host = BrowserUtils.hostFromUrl(origin),+ cookieCount = cookieCount,+ hasLocalStorage = hasLocalStorage,+ hasIndexedDb = hasIndexedDb,+ hasServiceWorker = hasServiceWorker,+ estimatedBytes = estBytes,+ lastSeen = System.currentTimeMillis()+ )+ }+ repository.upsertStorageInfo(info)+ }+ }++ fun clearSiteData(origin: String) {+ viewModelScope.launch {+ repository.deleteStorageInfoOrigin(origin)+ repository.deleteSitePermissionOrigin(origin)+ }+ }++ fun clearAllSiteData() {+ viewModelScope.launch {+ repository.clearAllStorageInfos()+ repository.clearAllSitePermissions()+ }+ }++ fun revokePermission(origin: String, type: SitePermissionType) {+ viewModelScope.launch {+ val existing = repository.sitePermissionByOrigin(origin) ?: return@launch+ val updated = when (type) {+ SitePermissionType.CAMERA -> existing.copy(cameraAllowed = null)+ SitePermissionType.MICROPHONE -> existing.copy(microphoneAllowed = null)+ SitePermissionType.LOCATION -> existing.copy(locationAllowed = null)+ SitePermissionType.NOTIFICATIONS -> existing.copy(notificationsAllowed = null)+ }+ if (updated.cameraAllowed == null && updated.microphoneAllowed == null && updated.locationAllowed == null && updated.notificationsAllowed == null) {+ repository.deleteSitePermission(updated)+ } else {+ repository.upsertSitePermission(updated.copy(updatedAt = System.currentTimeMillis()))+ }+ }+ }++ fun addDownload(url: String, fileName: String, mime: String?, length: Long) {+ viewModelScope.launch {+ repository.upsertDownload(DownloadEntry(url = url, fileName = fileName, mimeType = mime, contentLength = length))+ }+ }++ fun clearAllDownloads() {+ viewModelScope.launch { repository.clearAllDownloads() }+ }++ fun onClearedPersist() { persistTabsSync() }++ override fun onCleared() {+ onClearedPersist()+ super.onCleared()+ }++ private fun persistTabs() {+ viewModelScope.launch(Dispatchers.IO) { persistTabsSync() }+ }++ private fun persistTabsSync() {+ // Incognito windows leave no trace on disk.+ if (incognito) return+ try {+ val sp = context.getSharedPreferences("web_prefs", Context.MODE_PRIVATE)+ val toSave = tabs.filter { !it.isPrivate }+ sp.edit()+ .putString(savedTabsKey, json.encodeToString(toSave))+ .putString(activeTabKey, activeTabId)+ .apply()+ } catch (e: Exception) { Log.e(TAG, "persistTabs failed", e) }+ }++ private fun persistPrefs() {+ viewModelScope.launch(Dispatchers.IO) {+ try {+ val sp = context.getSharedPreferences("web_prefs", Context.MODE_PRIVATE)+ sp.edit()+ .putString(P_CACHE_MODE, cacheMode.name)+ .putString(P_SEARCH_ENGINE, searchEngine.name)+ .putBoolean(P_JS_ENABLED, jsEnabled)+ .putBoolean(P_BLOCK_THIRD_PARTY, blockThirdPartyCookies)+ .putBoolean(P_DESKTOP_MODE, desktopMode)+ .putString(P_SHIELD_LEVEL, shields.level?.name)+ .putBoolean(P_SHIELD_TRACKERS, shields.blockTrackers != false)+ .putBoolean(P_SHIELD_COSMETIC, shields.cosmeticFiltering != false)+ .putBoolean(P_SHIELD_FINGERPRINT, shields.fingerprintProtection != false)+ .putBoolean(P_SHIELD_HTTPS, shields.httpsUpgrade != false)+ .apply()+ } catch (e: Exception) { Log.e(TAG, "persistPrefs failed", e) }+ }+ }++ fun externalIntentUrl(url: String) {+ // Per product requirement: external links from other apps always open a new tab.+ newTab(url = url, makeActive = true)+ }+}++class WebViewModelFactory(+ private val repository: WebRepository,+ private val context: Context,+ private val windowId: String = WebViewModel.DEFAULT_WINDOW_ID,+ private val incognito: Boolean = false,+ private val initialShieldSettings: List<ShieldSetting> = emptyList(),+) : androidx.lifecycle.ViewModelProvider.Factory {+ @Suppress("UNCHECKED_CAST")+ override fun <T : androidx.lifecycle.ViewModel> create(modelClass: Class<T>): T {+ if (modelClass.isAssignableFrom(WebViewModel::class.java)) {+ return WebViewModel(repository, context, windowId, incognito, initialShieldSettings) as T+ }+ throw IllegalArgumentException("Unknown ViewModel $modelClass")+ }+}
web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsEngine.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsEngine.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsEngine.ktindex 3a14e2611b..b5485c542f 100644--- a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsEngine.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsEngine.kt@@ -1 +1,145 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsEngine.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.platform.shields++import android.content.Context+import android.util.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import org.brotli.dec.BrotliInputStream+import java.io.File++private const val TAG = "ShieldsEngine"+private const val ASSET_DIR = "shields"+private const val CACHE_DIR = "shields"+private const val CACHE_FILE = "engine.dat"+private const val CACHE_VERSION_FILE = "engine.version"++/** Outcome of [ShieldsEngine.check] for one network request. */+@Serializable+data class ShieldsCheck(+ val blocked: Boolean = false,+ val important: Boolean = false,+ val exception: Boolean = false,+ /** `data:` URL holding the uBO resource body named by a `$redirect` rule. */+ val redirect: String? = null,+ /** The URL with `$removeparam` parameters stripped. Only meaningful when not blocked. */+ val rewritten: String? = null,+)++/** Everything needed to prepare a page before it starts loading. */+@Serializable+data class CosmeticResources(+ val hide: List<String> = emptyList(),+ val procedural: List<String> = emptyList(),+ val exceptions: List<String> = emptyList(),+ val script: String = "",+ @SerialName("generichide") val genericHide: Boolean = false,+)++/**+ * Process-wide handle on Brave's adblock engine.+ *+ * Parsing ~8 MB of filter lists takes seconds, so [load] deserializes a cached snapshot+ * whenever the bundled assets have not changed, and only reparses (then rewrites the+ * snapshot) after an asset update.+ *+ * Until [ready] flips true every query returns null and callers must fail open:+ * `shouldInterceptRequest` runs on the render thread and blocking it stalls the page.+ */+object ShieldsEngine {++ @Volatile+ private var handle: Long = 0++ @Volatile+ private var loading = false++ val ready: Boolean get() = handle != 0L++ private val json = Json { ignoreUnknownKeys = true }++ suspend fun load(context: Context) {+ if (ready || loading || !ShieldsNative.isAvailable) return+ loading = true+ try {+ withContext(Dispatchers.IO) {+ val app = context.applicationContext+ val version = app.assets.open("$ASSET_DIR/version.txt").use {+ it.readBytes().decodeToString().trim()+ }+ val resources = readBrotliAsset(app, "resources.json")+ val cacheDir = File(app.filesDir, CACHE_DIR)+ val cache = File(cacheDir, CACHE_FILE)+ val cachedVersion = File(cacheDir, CACHE_VERSION_FILE)++ var built = 0L+ if (cache.isFile && cachedVersion.isFile && cachedVersion.readText().trim() == version) {+ built = ShieldsNative.nativeCreateFromCache(cache.readBytes(), resources)+ if (built == 0L) Log.w(TAG, "engine cache rejected, reparsing lists")+ }+ if (built == 0L) {+ built = ShieldsNative.nativeCreate(readBrotliAsset(app, "filters.txt"), resources)+ if (built != 0L) writeCache(cacheDir, cache, cachedVersion, built, version)+ }+ handle = built+ }+ } catch (e: Exception) {+ Log.e(TAG, "load failed — shields stay open", e)+ } finally {+ loading = false+ }+ }++ private fun writeCache(dir: File, cache: File, versionFile: File, handle: Long, version: String) {+ try {+ val snapshot = ShieldsNative.nativeSerialize(handle) ?: return+ dir.mkdirs()+ cache.writeBytes(snapshot)+ versionFile.writeText(version)+ } catch (e: Exception) {+ Log.w(TAG, "could not cache engine snapshot", e)+ }+ }++ private fun readBrotliAsset(context: Context, name: String): String =+ BrotliInputStream(context.assets.open("$ASSET_DIR/$name.br")).use {+ it.readBytes().decodeToString()+ }++ /**+ * Should the request for [url], issued by the page at [sourceUrl], be blocked?+ * Returns null while the engine is still loading, which means "allow".+ */+ fun check(url: String, sourceUrl: String, requestType: String): ShieldsCheck? {+ val h = handle+ if (h == 0L) return null+ val raw = ShieldsNative.nativeCheck(h, url, sourceUrl, requestType) ?: return null+ return runCatching { json.decodeFromString<ShieldsCheck>(raw) }.getOrNull()+ }++ fun cosmetic(url: String): CosmeticResources? {+ val h = handle+ if (h == 0L) return null+ val raw = ShieldsNative.nativeCosmeticResources(h, url) ?: return null+ return runCatching { json.decodeFromString<CosmeticResources>(raw) }.getOrNull()+ }++ /** Generic hide rules matching classes and ids that only appeared after page load. */+ fun hiddenClassIdSelectors(+ classes: List<String>,+ ids: List<String>,+ exceptions: List<String>,+ ): List<String> {+ val h = handle+ if (h == 0L) return emptyList()+ val raw = ShieldsNative.nativeHiddenClassIdSelectors(+ h,+ json.encodeToString(classes),+ json.encodeToString(ids),+ json.encodeToString(exceptions),+ ) ?: return emptyList()+ return runCatching { json.decodeFromString<List<String>>(raw) }.getOrDefault(emptyList())+ }+}
web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsInjection.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsInjection.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsInjection.ktindex c373d24f24..bc929f552d 100644--- a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsInjection.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsInjection.kt@@ -1 +1,203 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsInjection.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.platform.shields++import android.content.Context+import com.vayunmathur.web.domain.EffectiveShields+import com.vayunmathur.web.domain.ShieldsSettings++/**+ * Whether to farble, resolved for every site up front.+ *+ * The document-start script runs before anything can tell it what page it is on, so the+ * decision has to travel with it: [enabled]/[aggressive] are the global defaults and+ * [overrides] carries the handful of hosts the user changed.+ */+data class FarblingConfig(+ val enabled: Boolean,+ val aggressive: Boolean,+ val overrides: Map<String, Pair<Boolean?, Boolean?>>,+) {+ fun toJson(): String = buildString {+ append("{\"enabled\":").append(enabled)+ append(",\"aggressive\":").append(aggressive)+ append(",\"overrides\":{")+ overrides.entries.forEachIndexed { index, (host, flags) ->+ if (index > 0) append(',')+ append(ShieldsInjection.jsString(host)).append(":{")+ append("\"enabled\":").append(flags.first?.toString() ?: "null")+ append(",\"aggressive\":").append(flags.second?.toString() ?: "null")+ append('}')+ }+ append("}}")+ }++ companion object {+ /** Builds the config from the global defaults plus every per-site record. */+ fun of(global: ShieldsSettings, sites: Map<String, ShieldsSettings>): FarblingConfig {+ val effective = EffectiveShields.resolve(global)+ return FarblingConfig(+ enabled = effective.fingerprintProtection,+ aggressive = effective.aggressiveFingerprinting,+ overrides = sites.mapValues { (_, site) ->+ val resolved = EffectiveShields.resolve(global, site)+ resolved.fingerprintProtection to resolved.aggressiveFingerprinting+ },+ )+ }+ }+}++/**+ * Builds the JavaScript that shields inject into every page.+ *+ * Two things have to happen before the page's own scripts run: fingerprint farbling+ * (useless afterwards, since a script could have already read the true values) and the+ * cosmetic stylesheet (otherwise ad slots flash before being hidden). Both are packed+ * into a single document-start script.+ */+internal object ShieldsInjection {++ /** Name of the object [ShieldsWebViewClient] exposes for the second cosmetic pass. */+ const val COSMETIC_CHANNEL = "shieldsCosmetic"++ private const val FARBLE_ASSET = "shields/farble.js"++ @Volatile+ private var farbleSource: String? = null++ private fun farble(context: Context): String =+ farbleSource ?: synchronized(this) {+ farbleSource ?: context.applicationContext.assets+ .open(FARBLE_ASSET)+ .use { it.readBytes().decodeToString() }+ .also { farbleSource = it }+ }++ /**+ * The fingerprinting payload, registered once per WebView at creation.+ *+ * This has to be a document-start script and it has to be registered *before* the+ * navigation: `addDocumentStartJavaScript` only affects documents that start loading+ * after the call, so registering it from `onPageStarted` would leave the very first+ * page unprotected. That rules out baking the current URL into it, so the script+ * decides per origin at runtime from [config] and derives its own seed.+ */+ fun farbling(context: Context, config: FarblingConfig, sessionSalt: Int): String = buildString {+ append("(function(){")+ append("if(window.__shieldsFarbled)return;")+ append("var host=location.hostname||'';")+ append("var cfg=").append(config.toJson()).append(";")+ append("var o=cfg.overrides[host];")+ append("var on=(o&&typeof o.enabled==='boolean')?o.enabled:cfg.enabled;")+ append("if(!on)return;")+ append("window.__shieldsFarbled=true;")+ append("var agg=(o&&typeof o.aggressive==='boolean')?o.aggressive:cfg.aggressive;")+ // Seed = session salt mixed with the hostname, so it is stable for this site in+ // this session and unrelated to any other site or run.+ append("var h=").append(sessionSalt).append("|0;")+ append("for(var i=0;i<host.length;i++){h=(h*31+host.charCodeAt(i))|0;}")+ append("window.__shieldsSeed=h>>>0;window.__shieldsAggressive=agg;")+ append("try{").append(farble(context)).append("}catch(e){}")+ append("})();")+ }++ /**+ * The per-page cosmetic payload. Unlike farbling this depends on the URL, so it is+ * applied once the navigation is known; arriving a few milliseconds late only means a+ * hidden element may flash, never that protection is lost.+ */+ fun cosmetic(resources: CosmeticResources?): String {+ if (resources == null) return ""+ return buildString {+ append("(function(){if(window.__shieldsCosmetic)return;window.__shieldsCosmetic=true;")+ if (resources.hide.isNotEmpty()) {+ append("try{").append(hideCss(resources.hide)).append("}catch(e){}")+ }+ if (resources.script.isNotEmpty()) {+ append("try{").append(resources.script).append("}catch(e){}")+ }+ if (!resources.genericHide) {+ append("try{").append(observer(resources.exceptions)).append("}catch(e){}")+ }+ append("})();")+ }+ }++ /**+ * Injects `selectors { display: none !important }` as a stylesheet.+ *+ * Split into chunks because a single rule with tens of thousands of selectors is slow+ * to match and some engines cap selector-list length.+ */+ fun hideCss(selectors: List<String>): String {+ if (selectors.isEmpty()) return ""+ val rules = selectors.chunked(SELECTORS_PER_RULE).joinToString("\n") {+ it.joinToString(",") + "{display:none !important;}"+ }+ return buildString {+ append("(function(){var s=document.getElementById('__shields_css__');")+ append("if(!s){s=document.createElement('style');s.id='__shields_css__';")+ append("(document.head||document.documentElement).appendChild(s);}")+ append("s.appendChild(document.createTextNode(").append(jsString(rules)).append("));})();")+ }+ }++ private const val SELECTORS_PER_RULE = 128++ /**+ * Brave's second cosmetic pass: generic hide rules are far too numerous to inject+ * wholesale, so the page reports the classes and ids it actually uses and the engine+ * replies with only the rules that could match.+ */+ private fun observer(exceptions: List<String>): String = buildString {+ append("(function(){var ch=window.").append(COSMETIC_CHANNEL).append(";if(!ch)return;")+ append("var seenC={},seenI={},pending=false;")+ append("var exc=").append(jsonArray(exceptions)).append(";")+ append("function collect(root){")+ append("if(!root||root.nodeType!==1)return;")+ append("var all=root.querySelectorAll?root.querySelectorAll('[class],[id]'):[];")+ append("var nodes=[root];for(var i=0;i<all.length;i++)nodes.push(all[i]);")+ append("for(var n=0;n<nodes.length;n++){var el=nodes[n];")+ append("if(el.id&&!seenI[el.id])seenI[el.id]=1;")+ append("var cl=el.classList;if(cl)for(var c=0;c<cl.length;c++){if(!seenC[cl[c]])seenC[cl[c]]=1;}}")+ append("schedule();}")+ append("function schedule(){if(pending)return;pending=true;")+ // Batch a frame's worth of mutations into one JNI round trip.+ append("(window.requestIdleCallback||window.setTimeout)(function(){pending=false;")+ append("var c=Object.keys(seenC),i=Object.keys(seenI);seenC={};seenI={};")+ append("if(c.length||i.length)ch.postMessage(JSON.stringify({classes:c,ids:i,exceptions:exc}));")+ append("},1);}")+ append("ch.onmessage=function(e){try{var sel=JSON.parse(e.data);")+ append("if(sel.length)applyHide(sel);}catch(err){}};")+ append("function applyHide(sel){var s=document.getElementById('__shields_css2__');")+ append("if(!s){s=document.createElement('style');s.id='__shields_css2__';")+ append("(document.head||document.documentElement).appendChild(s);}")+ append("s.appendChild(document.createTextNode(sel.join(',')+'{display:none !important;}'));}")+ append("collect(document.documentElement);")+ append("new MutationObserver(function(muts){for(var m=0;m<muts.length;m++){")+ append("var added=muts[m].addedNodes;for(var a=0;a<added.length;a++)collect(added[a]);")+ append("if(muts[m].type==='attributes')collect(muts[m].target);}})")+ append(".observe(document.documentElement,{childList:true,subtree:true,")+ append("attributes:true,attributeFilter:['class','id']});})();")+ }++ private fun jsonArray(values: List<String>): String =+ values.joinToString(",", "[", "]") { jsString(it) }++ /** JS string literal. `<` is escaped so the payload survives being parsed inside a page. */+ internal fun jsString(value: String): String = buildString {+ append('"')+ for (c in value) {+ when (c) {+ '"' -> append("\\\"")+ '\\' -> append("\\\\")+ '\n' -> append("\\n")+ '\r' -> append("\\r")+ '\u2028' -> append("\\u2028")+ '\u2029' -> append("\\u2029")+ '<' -> append("\\u003c")+ else -> append(c)+ }+ }+ append('"')+ }+}
web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsNative.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsNative.kt b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsNative.ktindex f3c81b0dcc..cb686fdf0f 100644--- a/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsNative.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsNative.kt@@ -1 +1,47 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsNative.kt' exists on disk, but not in 'stash@{14}'+package com.vayunmathur.web.platform.shields++/**+ * JNI bridge to Brave's adblock engine (`libweb_shields.so`, built from+ * `web/src/main/rust/`). [isAvailable] is false when the native lib is missing for the+ * current ABI, which makes [ShieldsEngine] fail open rather than break every page.+ *+ * Handles are opaque; 0 means "no engine". Every call is safe to make from any thread —+ * the Rust `Engine` is `Send + Sync` — but they are all blocking, so only [nativeCheck]+ * belongs on the WebView render thread.+ */+internal object ShieldsNative {++ val isAvailable: Boolean =+ try {+ System.loadLibrary("web_shields")+ true+ } catch (t: Throwable) {+ android.util.Log.e("ShieldsNative", "System.loadLibrary(web_shields) failed", t)+ false+ }++ /** Parses `filters` (Adblock Plus syntax) and returns an engine handle, or 0. */+ external fun nativeCreate(filters: String, resourcesJson: String): Long++ /** Restores an engine from [nativeSerialize] output. Returns 0 if the format changed. */+ external fun nativeCreateFromCache(cache: ByteArray, resourcesJson: String): Long++ /** Snapshot of the parsed filter data, for [nativeCreateFromCache]. */+ external fun nativeSerialize(handle: Long): ByteArray?++ /** `{"blocked","important","exception","redirect","rewritten"}` — see [ShieldsCheck]. */+ external fun nativeCheck(handle: Long, url: String, sourceUrl: String, requestType: String): String?++ /** `{"hide","procedural","exceptions","script","generichide"}` — see [CosmeticResources]. */+ external fun nativeCosmeticResources(handle: Long, url: String): String?++ /** JSON array of extra hide selectors for classes/ids that appeared after load. */+ external fun nativeHiddenClassIdSelectors(+ handle: Long,+ classesJson: String,+ idsJson: String,+ exceptionsJson: String,+ ): String?++ external fun nativeDestroy(handle: Long)+}
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 8aa3f3db25..5877e765a7 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 +1,240 @@-fatal: path 'web/src/main/java/com/vayunmathur/web/platform/shields/ShieldsWebViewClient.kt' exists on disk, but not in 'stash@{14}'+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("")+}
web/src/main/java/com/vayunmathur/web/ui/BookmarksPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BookmarksPage.kt b/web/src/main/java/com/vayunmathur/web/ui/BookmarksPage.ktindex 41cb2f1aa3..e92189c50e 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BookmarksPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BookmarksPage.kt@@ -1,313 +1,313 @@-package com.vayunmathur.web.ui--import androidx.compose.ui.res.stringResource-import com.vayunmathur.web.R-import androidx.compose.foundation.ExperimentalFoundationApi-import androidx.compose.foundation.combinedClickable-import androidx.compose.foundation.layout.Arrangement-import androidx.compose.foundation.layout.Box-import androidx.compose.foundation.layout.Column-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.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.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.Alignment-import androidx.compose.ui.Modifier-import androidx.compose.ui.text.style.TextOverflow-import androidx.compose.ui.unit.dp-import androidx.lifecycle.compose.collectAsStateWithLifecycle-import com.vayunmathur.library.ui.R as UiR-import com.vayunmathur.library.ui.ConfirmDialog-import com.vayunmathur.library.ui.EmptyState-import com.vayunmathur.library.ui.AlertDialog-import com.vayunmathur.library.ui.DropdownMenu-import com.vayunmathur.library.ui.DropdownMenuItem-import com.vayunmathur.library.ui.ExperimentalMaterial3Api-import com.vayunmathur.library.ui.FilterChip-import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconFolder-import com.vayunmathur.library.ui.IconNavigation-import com.vayunmathur.library.ui.MaterialTheme-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.web.Route-import com.vayunmathur.library.util.NavBackStack-import com.vayunmathur.web.data.Bookmark-import com.vayunmathur.web.data.BookmarkFolder-import com.vayunmathur.web.util.BrowserUtils-import com.vayunmathur.web.util.WebViewModel--@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)-@Composable-fun BookmarksPage(- viewModel: WebViewModel,- backStack: NavBackStack<Route>,-) {- val bookmarks by viewModel.bookmarks.collectAsStateWithLifecycle()- val folders by viewModel.folders.collectAsStateWithLifecycle()-- BookmarksScreen(- bookmarks = bookmarks,- folders = folders,- navigationIcon = { IconNavigation(backStack) },- onOpen = { bm ->- viewModel.externalIntentUrl(bm.url)- backStack.pop()- },- onDelete = { viewModel.removeBookmark(it) },- onCreateFolder = { viewModel.createFolder(it) },- onDeleteFolder = { viewModel.deleteFolder(it) },- )-}--/**- * The bookmark list, with no ViewModel and no back stack so it can be rendered from a- * `@Preview` — see `src/screenshotTest`, which is where the store listing images come from.- * [navigationIcon] is a slot because "up" is navigation, not state.- */-@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)-@Composable-fun BookmarksScreen(- bookmarks: List<Bookmark>,- folders: List<BookmarkFolder>,- navigationIcon: @Composable () -> Unit = {},- onOpen: (Bookmark) -> Unit = {},- onDelete: (Bookmark) -> Unit = {},- onCreateFolder: (String) -> Unit = {},- onDeleteFolder: (BookmarkFolder) -> Unit = {},-) {- var selectedFolder by remember { mutableStateOf<Long?>(null) }- var showNewFolderDialog by remember { mutableStateOf(false) }- var newFolderName by remember { mutableStateOf("") }- var showDeleteDialog by remember { mutableStateOf<Bookmark?>(null) }- var showFolderDeleteDialog by remember { mutableStateOf<BookmarkFolder?>(null) }-- val filtered = remember(bookmarks, selectedFolder) {- if (selectedFol
Diff truncated.