Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,32 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

<!-- Forwarded to a page only after the user allows it in the browser's own dialog. -->
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<!-- Android 11+ package visibility: resolve web and app links we hand off. -->
<queries>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="https" />
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="http" />
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="market" />
</intent>
<intent>
<action android:name="android.intent.action.VIEW" />
<data android:scheme="mailto" />
</intent>
</queries>

<!-- TV support: leanback is optional so the same APK installs on phones and tablets. -->
<uses-feature
android:name="android.software.leanback"
Expand Down
11 changes: 11 additions & 0 deletions app/src/main/java/com/bansify/browser/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import com.bansify.browser.browser.WebViewPool
import com.bansify.browser.ui.BrowserApp
import com.bansify.browser.viewmodel.BrowserViewModel

Expand All @@ -15,6 +16,9 @@ class MainActivity : ComponentActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Hand the saved WebView state to the pool before the first tab is composed, so a
// rotation or a process restore keeps scroll position, form input and history.
WebViewPool.pendingState = savedInstanceState?.getBundle("webview_pool_state")
enableEdgeToEdge()
handleIncomingIntent(intent)

Expand All @@ -23,6 +27,13 @@ class MainActivity : ComponentActivity() {
}
}

override fun onSaveInstanceState(outState: Bundle) {
val poolState = Bundle()
WebViewPool.active?.saveStateTo(poolState)
outState.putBundle("webview_pool_state", poolState)
super.onSaveInstanceState(outState)
}

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
Expand Down
74 changes: 74 additions & 0 deletions app/src/main/java/com/bansify/browser/browser/AdBlocker.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package com.bansify.browser.browser

import android.content.Context
import android.webkit.WebResourceResponse
import com.bansify.browser.R
import java.io.ByteArrayInputStream
import java.util.concurrent.atomic.AtomicLong

/**
* Host-based ad and tracker blocker.
*
* The list ships with the app (`res/raw/adblock_hosts.txt`) so blocking works offline and
* nothing about the pages you open leaves the device. It is a curated starter list of
* well-known ad, analytics and tracker hosts — not a full EasyList replacement — and every
* entry is matched on the host name only, so a CDN that also serves site assets is never
* touched.
*
* A request is blocked when its host equals an entry or is a subdomain of one. Main-frame
* requests are never blocked: the page the user asked for always loads.
*/
class AdBlocker(private val context: Context) {

private var hosts: Set<String> = emptySet()

companion object {
private val blocked = AtomicLong(0)

/** Requests blocked since the app started, across every tab. */
fun blockedCount(): Long = blocked.get()

fun resetBlockedCount() {
blocked.set(0)
}
}

private fun ensureLoaded(): Set<String> {
val cached = hosts
if (cached.isNotEmpty()) return cached
val loaded = runCatching {
context.resources.openRawResource(R.raw.adblock_hosts).bufferedReader().useLines { lines ->
lines.map { it.trim().lowercase() }
.filter { it.isNotEmpty() && !it.startsWith("#") }
.toSet()
}
}.getOrDefault(emptySet())
hosts = loaded
return loaded
}

fun isBlockedHost(host: String?): Boolean {
if (host.isNullOrBlank()) return false
val list = ensureLoaded()
if (list.isEmpty()) return false
var candidate = host.lowercase().trimEnd('.')
while (true) {
if (list.contains(candidate)) return true
val dot = candidate.indexOf('.')
if (dot < 0 || dot == candidate.length - 1) return false
candidate = candidate.substring(dot + 1)
}
}

fun shouldBlock(url: String, isForMainFrame: Boolean): Boolean {
if (isForMainFrame) return false
val host = runCatching { android.net.Uri.parse(url).host }.getOrNull() ?: return false
val blockedNow = isBlockedHost(host)
if (blockedNow) blocked.incrementAndGet()
return blockedNow
}

/** Empty 200 that stops the request without an error dialog on the page. */
fun emptyResponse(): WebResourceResponse =
WebResourceResponse("text/plain", "utf-8", ByteArrayInputStream(ByteArray(0)))
}
140 changes: 140 additions & 0 deletions app/src/main/java/com/bansify/browser/browser/WebViewPool.kt
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ import android.os.Message
import android.os.Environment
import android.view.View
import android.view.ViewGroup
import android.os.Bundle
import android.webkit.CookieManager
import android.webkit.GeolocationPermissions
import android.webkit.PermissionRequest
import android.webkit.SafeBrowsingResponse
import android.webkit.WebResourceResponse
import android.webkit.JsPromptResult
import android.webkit.JsResult
import android.webkit.URLUtil
Expand All @@ -31,6 +36,7 @@ import com.bansify.browser.data.BrowserSettings
import com.bansify.browser.data.BrowserTab
import com.bansify.browser.data.JsDialogState
import com.bansify.browser.data.SafeBrowsingLevel
import com.bansify.browser.data.SitePermission
import com.bansify.browser.data.ThirdPartyCookiePolicy
import java.io.File

Expand All @@ -42,6 +48,14 @@ class WebViewPool(
private val context: Context,
private val callbacks: Callbacks
) {

private val adBlocker = AdBlocker(context)

init {
active = this
}

fun adBlockerInstance(): AdBlocker = adBlocker
interface Callbacks {
fun onPageStarted(tabId: String, url: String)
fun onPageFinished(tabId: String, url: String, title: String, canGoBack: Boolean, canGoForward: Boolean)
Expand All @@ -66,6 +80,22 @@ class WebViewPool(
/** The renderer process for this tab died (crash or OOM); the WebView is already gone. */
fun onRendererGone(tabId: String, didCrash: Boolean)

/** A site asked for camera/mic/location. Answer through [onResult]. */
fun onSitePermissionRequest(
tabId: String,
origin: String,
permission: SitePermission,
onResult: (Boolean) -> Unit
)

/** Safe Browsing flagged this page; the caller must answer the response. */
fun onSafeBrowsingHit(
tabId: String,
url: String,
threatType: Int,
response: SafeBrowsingResponse
)

fun onExternalUrlError(message: String)
}

Expand All @@ -78,6 +108,15 @@ class WebViewPool(
private var currentSettings: BrowserSettings = BrowserSettings()

companion object {
/** Live pool for the process, so the activity can save WebView state on rotation/kill. */
@Volatile
var active: WebViewPool? = null
private set

/** State handed back by the activity after a configuration change or process restore. */
@Volatile
var pendingState: Bundle? = null

private const val DESKTOP_USER_AGENT =
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
}
Expand Down Expand Up @@ -296,6 +335,18 @@ class WebViewPool(

fun destroyAll() {
webViews.keys.toList().forEach { destroyTab(it) }
if (active === this) active = null
}

/** Writes every live WebView's navigation state into [outState] for a later restore. */
fun saveStateTo(outState: Bundle) {
webViews.forEach { (tabId, webView) ->
runCatching {
val state = Bundle()
webView.saveState(state)
outState.putBundle("wv_state_$tabId", state)
}
}
}

/**
Expand Down Expand Up @@ -372,6 +423,35 @@ class WebViewPool(
}

webView.webViewClient = object : WebViewClient() {
override fun shouldInterceptRequest(
view: WebView?,
request: WebResourceRequest?
): WebResourceResponse? {
if (request == null) return null
if (!currentSettings.adBlockEnabled) return null
val url = request.url?.toString() ?: return null
return if (adBlocker.shouldBlock(url, request.isForMainFrame)) {
adBlocker.emptyResponse()
} else {
null
}
}

override fun onSafeBrowsingHit(
view: WebView?,
request: WebResourceRequest?,
threatType: Int,
callback: SafeBrowsingResponse?
) {
if (callback == null) return
callbacks.onSafeBrowsingHit(
tabId = tab.id,
url = request?.url?.toString().orEmpty(),
threatType = threatType,
response = callback
)
}

override fun shouldOverrideUrlLoading(
view: WebView?,
request: WebResourceRequest?
Expand Down Expand Up @@ -548,6 +628,59 @@ class WebViewPool(
return true
}

override fun onPermissionRequest(request: PermissionRequest?) {
val req = request ?: return
val origin = runCatching { Uri.parse(req.origin.toString()).host }
.getOrNull()
.orEmpty()
val wanted = buildList {
if (req.resources.contains(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) {
add(SitePermission.CAMERA)
}
if (req.resources.contains(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) {
add(SitePermission.MICROPHONE)
}
}
if (wanted.isEmpty()) {
req.deny()
return
}
val granted = mutableSetOf<String>()
var outstanding = wanted.size
wanted.forEach { permission ->
callbacks.onSitePermissionRequest(tab.id, origin, permission) { allowed ->
synchronized(granted) {
if (allowed) {
when (permission) {
SitePermission.CAMERA -> granted.add(PermissionRequest.RESOURCE_VIDEO_CAPTURE)
SitePermission.MICROPHONE -> granted.add(PermissionRequest.RESOURCE_AUDIO_CAPTURE)
else -> Unit
}
}
outstanding -= 1
if (outstanding == 0) {
if (granted.isEmpty()) {
req.deny()
} else {
req.grant(granted.toTypedArray())
}
}
}
}
}
}

override fun onGeolocationPermissionsShowPrompt(
origin: String?,
callback: GeolocationPermissions.Callback?
) {
if (origin == null || callback == null) return
val host = runCatching { Uri.parse(origin).host }.getOrNull().orEmpty()
callbacks.onSitePermissionRequest(tab.id, host, SitePermission.LOCATION) { allowed ->
callback.invoke(origin, allowed, true)
}
}

override fun onCreateWindow(
view: WebView?,
isDialog: Boolean,
Expand Down Expand Up @@ -602,6 +735,10 @@ class WebViewPool(
)
}

pendingState?.getBundle("wv_state_$tab.id")?.let { saved ->
runCatching { webView.restoreState(saved) }
}

return webView
}

Expand Down Expand Up @@ -630,6 +767,9 @@ class WebViewPool(
ws.cacheMode = if (tab.isIncognito) WebSettings.LOAD_NO_CACHE else WebSettings.LOAD_DEFAULT
// window.open() / target=_blank land in onCreateWindow below instead of a dead end.
ws.setSupportMultipleWindows(true)
// Websites ask for geolocation through onGeolocationPermissionsShowPrompt; the user
// decides, never the page.
ws.setGeolocationEnabled(true)

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ws.safeBrowsingEnabled = settings.safeBrowsingLevel != SafeBrowsingLevel.NONE
Expand Down
7 changes: 6 additions & 1 deletion app/src/main/java/com/bansify/browser/data/BrowserModels.kt
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,11 @@ data class BrowserSettings(
val forceEnableZoom: Boolean = false,
val simplifiedViewEnabled: Boolean = false,
val askWhereToSaveDownloads: Boolean = false,
val showRecentCardsOnNtp: Boolean = true
val showRecentCardsOnNtp: Boolean = true,
/** Host-based ad and tracker blocking, on by default, user can turn it off in Settings. */
val adBlockEnabled: Boolean = true,
/** Ask the user before a site gets camera, microphone or location. */
val sitePermissionPromptsEnabled: Boolean = true
)

data class BrowserTab(
Expand Down Expand Up @@ -153,6 +157,7 @@ enum class SettingsSubScreen(val title: String) {
ADDRESS_BAR("Address bar"),
PRIVACY_SECURITY("Privacy and security"),
SAFE_BROWSING("Safe Browsing"),
BLOCKING_PERMISSIONS("Ad blocking and permissions"),
THIRD_PARTY_COOKIES("Third-party cookies"),
SAFETY_CHECK("Safety check"),
DEFAULT_BROWSER("Default browser"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ class BrowserPreferences(private val context: Context) {
val COOKIES_ENABLED = booleanPreferencesKey("cookies_enabled")
val POPUPS_ALLOWED = booleanPreferencesKey("popups_allowed")
val LOAD_IMAGES = booleanPreferencesKey("load_images")
val AD_BLOCK_ENABLED = booleanPreferencesKey("ad_block_enabled")
val SITE_PERMISSION_PROMPTS = booleanPreferencesKey("site_permission_prompts")
val DEFAULT_DESKTOP_SITE = booleanPreferencesKey("default_desktop_site")
val MEDIA_AUTOPLAY = booleanPreferencesKey("media_autoplay")
val TEXT_ZOOM_PERCENT = intPreferencesKey("text_zoom_percent")
Expand Down Expand Up @@ -89,6 +91,8 @@ class BrowserPreferences(private val context: Context) {
cookiesEnabled = prefs[Keys.COOKIES_ENABLED] ?: true,
popupsAllowed = prefs[Keys.POPUPS_ALLOWED] ?: false,
loadImagesEnabled = prefs[Keys.LOAD_IMAGES] ?: true,
adBlockEnabled = prefs[Keys.AD_BLOCK_ENABLED] ?: true,
sitePermissionPromptsEnabled = prefs[Keys.SITE_PERMISSION_PROMPTS] ?: true,
defaultDesktopSite = prefs[Keys.DEFAULT_DESKTOP_SITE] ?: false,
mediaAutoplayEnabled = prefs[Keys.MEDIA_AUTOPLAY] ?: true,
textZoomPercent = prefs[Keys.TEXT_ZOOM_PERCENT] ?: 100,
Expand Down Expand Up @@ -135,6 +139,8 @@ class BrowserPreferences(private val context: Context) {
prefs[Keys.COOKIES_ENABLED] = updated.cookiesEnabled
prefs[Keys.POPUPS_ALLOWED] = updated.popupsAllowed
prefs[Keys.LOAD_IMAGES] = updated.loadImagesEnabled
prefs[Keys.AD_BLOCK_ENABLED] = updated.adBlockEnabled
prefs[Keys.SITE_PERMISSION_PROMPTS] = updated.sitePermissionPromptsEnabled
prefs[Keys.DEFAULT_DESKTOP_SITE] = updated.defaultDesktopSite
prefs[Keys.MEDIA_AUTOPLAY] = updated.mediaAutoplayEnabled
prefs[Keys.TEXT_ZOOM_PERCENT] = updated.textZoomPercent
Expand Down
Loading
Loading