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
16 changes: 11 additions & 5 deletions app/src/main/java/com/bansify/browser/browser/UrlUtils.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,15 @@ object UrlUtils {
fun resolveInputToUrl(
rawInput: String,
searchEngine: SearchEngine,
httpsFirst: Boolean
httpsFirst: Boolean,
customTemplate: String? = null
): String {
val trimmed = rawInput.trim()
if (trimmed.isEmpty()) return BrowserTab.NEW_TAB_URL

// Disallow javascript: injection from Omnibox for safety
if (trimmed.startsWith("javascript:", ignoreCase = true)) {
return buildSearchUrl(trimmed, searchEngine)
return buildSearchUrl(trimmed, searchEngine, customTemplate)
}

if (trimmed.equals("about:blank", ignoreCase = true) ||
Expand Down Expand Up @@ -57,12 +58,17 @@ object UrlUtils {
}
}

return buildSearchUrl(trimmed, searchEngine)
return buildSearchUrl(trimmed, searchEngine, customTemplate)
}

fun buildSearchUrl(query: String, searchEngine: SearchEngine): String {
fun buildSearchUrl(
query: String,
searchEngine: SearchEngine,
customTemplate: String? = null
): String {
val encoded = URLEncoder.encode(query.trim(), "UTF-8")
return searchEngine.queryUrlTemplate.replace("%s", encoded)
val template = customTemplate?.takeIf { it.contains("%s") } ?: searchEngine.queryUrlTemplate
return template.replace("%s", encoded)
}

fun extractDisplayHost(url: String): String {
Expand Down
22 changes: 22 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 @@ -56,6 +56,23 @@ class WebViewPool(
}

fun adBlockerInstance(): AdBlocker = adBlocker

/**
* Gives the visible tab the important renderer priority and demotes the rest, so a stack of
* background tabs is reclaimed by the system before the tab the user is reading.
*/
fun updateRendererPriorities(activeTabId: String?) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
webViews.forEach { (tabId, webView) ->
runCatching {
if (tabId == activeTabId) {
webView.setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_IMPORTANT, false)
} else {
webView.setRendererPriorityPolicy(WebView.RENDERER_PRIORITY_BOUND, true)
}
}
}
}
interface Callbacks {
fun onPageStarted(tabId: String, url: String)
fun onPageFinished(tabId: String, url: String, title: String, canGoBack: Boolean, canGoForward: Boolean)
Expand Down Expand Up @@ -114,6 +131,9 @@ class WebViewPool(
private var popupCounter = 0
private var currentSettings: BrowserSettings = BrowserSettings()

/** Hosts the user allowed ads on; kept in sync by the UI so interception stays synchronous. */
var adsAllowedFor: (String) -> Boolean = { false }

companion object {
/** Live pool for the process, so the activity can save WebView state on rotation/kill. */
@Volatile
Expand Down Expand Up @@ -438,6 +458,8 @@ class WebViewPool(
if (request == null) return null
if (!currentSettings.adBlockEnabled) return null
val url = request.url?.toString() ?: return null
val host = request.url?.host.orEmpty()
if (host.isNotBlank() && adsAllowedFor(host)) return null
return if (adBlocker.shouldBlock(url, request.isForMainFrame)) {
adBlocker.emptyResponse()
} else {
Expand Down
23 changes: 20 additions & 3 deletions app/src/main/java/com/bansify/browser/data/BrowserModels.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ enum class SearchEngine(
BING("Bing", "bing.com", "https://www.bing.com/search?q=%s"),
YAHOO("Yahoo!", "search.yahoo.com", "https://search.yahoo.com/search?p=%s"),
BRAVE("Brave Search", "search.brave.com", "https://search.brave.com/search?q=%s"),
ECOSIA("Ecosia", "ecosia.org", "https://www.ecosia.org/search?q=%s")
ECOSIA("Ecosia", "ecosia.org", "https://www.ecosia.org/search?q=%s"),
CUSTOM("Custom", "", "https://www.google.com/search?q=%s")
}

enum class ThemeMode(val label: String) {
Expand Down Expand Up @@ -107,8 +108,24 @@ data class BrowserSettings(
/** 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
)
val sitePermissionPromptsEnabled: Boolean = true,
/** Name shown for a user-supplied search engine. */
val customSearchName: String = "",
/** Query template for the custom engine; %s is replaced with the query. */
val customSearchTemplate: String = ""
) {
/** Template to use for searches: the custom one when selected and valid, else the engine's. */
val effectiveSearchTemplate: String
get() = if (searchEngine == SearchEngine.CUSTOM &&
customSearchTemplate.contains("%s")
) {
customSearchTemplate
} else if (searchEngine == SearchEngine.CUSTOM) {
SearchEngine.GOOGLE.queryUrlTemplate
} else {
searchEngine.queryUrlTemplate
}
}

data class BrowserTab(
val id: String = UUID.randomUUID().toString(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ class BrowserPreferences(private val context: Context) {
val LOAD_IMAGES = booleanPreferencesKey("load_images")
val AD_BLOCK_ENABLED = booleanPreferencesKey("ad_block_enabled")
val SITE_PERMISSION_PROMPTS = booleanPreferencesKey("site_permission_prompts")
val CUSTOM_SEARCH_NAME = stringPreferencesKey("custom_search_name")
val CUSTOM_SEARCH_TEMPLATE = stringPreferencesKey("custom_search_template")
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 @@ -93,6 +95,8 @@ class BrowserPreferences(private val context: Context) {
loadImagesEnabled = prefs[Keys.LOAD_IMAGES] ?: true,
adBlockEnabled = prefs[Keys.AD_BLOCK_ENABLED] ?: true,
sitePermissionPromptsEnabled = prefs[Keys.SITE_PERMISSION_PROMPTS] ?: true,
customSearchName = prefs[Keys.CUSTOM_SEARCH_NAME] ?: "",
customSearchTemplate = prefs[Keys.CUSTOM_SEARCH_TEMPLATE] ?: "",
defaultDesktopSite = prefs[Keys.DEFAULT_DESKTOP_SITE] ?: false,
mediaAutoplayEnabled = prefs[Keys.MEDIA_AUTOPLAY] ?: true,
textZoomPercent = prefs[Keys.TEXT_ZOOM_PERCENT] ?: 100,
Expand Down Expand Up @@ -141,6 +145,8 @@ class BrowserPreferences(private val context: Context) {
prefs[Keys.LOAD_IMAGES] = updated.loadImagesEnabled
prefs[Keys.AD_BLOCK_ENABLED] = updated.adBlockEnabled
prefs[Keys.SITE_PERMISSION_PROMPTS] = updated.sitePermissionPromptsEnabled
prefs[Keys.CUSTOM_SEARCH_NAME] = updated.customSearchName
prefs[Keys.CUSTOM_SEARCH_TEMPLATE] = updated.customSearchTemplate
prefs[Keys.DEFAULT_DESKTOP_SITE] = updated.defaultDesktopSite
prefs[Keys.MEDIA_AUTOPLAY] = updated.mediaAutoplayEnabled
prefs[Keys.TEXT_ZOOM_PERCENT] = updated.textZoomPercent
Expand Down
31 changes: 31 additions & 0 deletions app/src/main/java/com/bansify/browser/data/SitePermissions.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,37 @@ class SitePermissionStore(private val context: Context) {

private companion object {
val DECISIONS = stringPreferencesKey("decisions")
val ADS_ALLOWED = stringPreferencesKey("ads_allowed")
}

/** Hosts where the user turned ad blocking off. */
val adBlockAllowlist: Flow<Set<String>> = context.sitePermissionDataStore.data.map { prefs ->
prefs[ADS_ALLOWED].orEmpty()
.split(',')
.map { it.trim() }
.filter { it.isNotEmpty() }
.toSet()
}

suspend fun allowAds(host: String) {
if (host.isBlank()) return
context.sitePermissionDataStore.edit { prefs ->
val current = prefs[ADS_ALLOWED].orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }.toMutableSet()
current.add(host)
prefs[ADS_ALLOWED] = current.joinToString(",")
}
}

suspend fun disallowAds(host: String) {
context.sitePermissionDataStore.edit { prefs ->
val current = prefs[ADS_ALLOWED].orEmpty().split(',').map { it.trim() }.filter { it.isNotEmpty() }.toMutableSet()
current.remove(host)
prefs[ADS_ALLOWED] = current.joinToString(",")
}
}

suspend fun clearAdBlockAllowlist() {
context.sitePermissionDataStore.edit { prefs -> prefs.remove(ADS_ALLOWED) }
}

val decisions: Flow<List<SitePermissionDecision>> = context.sitePermissionDataStore.data.map { prefs ->
Expand Down
37 changes: 36 additions & 1 deletion app/src/main/java/com/bansify/browser/ui/BrowserApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ fun BrowserApp(viewModel: BrowserViewModel) {
val safeBrowsingWarning by viewModel.safeBrowsingWarning.collectAsStateWithLifecycle()
val sitePermissionDecisions by viewModel.sitePermissionDecisions.collectAsStateWithLifecycle()
val downloadProgress by viewModel.downloadProgress.collectAsStateWithLifecycle()
val adBlockAllowlist by viewModel.adBlockAllowlist.collectAsStateWithLifecycle()
val bookmarks by viewModel.bookmarks.collectAsStateWithLifecycle()
val history by viewModel.history.collectAsStateWithLifecycle()
val downloads by viewModel.downloads.collectAsStateWithLifecycle()
Expand Down Expand Up @@ -303,6 +304,16 @@ fun BrowserApp(viewModel: BrowserViewModel) {
webViewPool.updateSettingsForAll(tabs, settings)
}

LaunchedEffect(adBlockAllowlist) {
val allowed = adBlockAllowlist
webViewPool.adsAllowedFor = { host -> allowed.contains(host) }
}

// Background tabs are demoted so the visible one keeps its renderer.
LaunchedEffect(activeTab.id) {
webViewPool.updateRendererPriorities(activeTab.id)
}

// Incognito tabs must not show up in the recents thumbnail or a screenshot.
val hasIncognitoTab = tabs.any { it.isIncognito }
DisposableEffect(hasIncognitoTab) {
Expand Down Expand Up @@ -644,6 +655,27 @@ fun BrowserApp(viewModel: BrowserViewModel) {
if (!activeTab.isNewTab) shareText(activeTab.title, activeTab.url)
},
onFindInPage = { viewModel.setFindInPageActive(true) },
onPrint = {
val wv = webViewPool.getWebViewIfExists(activeTab.id)
val printManager = context.getSystemService(Context.PRINT_SERVICE) as? android.print.PrintManager
if (wv != null && printManager != null) {
val jobName = activeTab.title.ifBlank { "Bansify Browser" }
runCatching {
printManager.print(
jobName,
wv.createPrintDocumentAdapter(jobName),
android.print.PrintAttributes.Builder().build()
)
}.onFailure { viewModel.showSnackbar("Printing is not available") }
} else {
viewModel.showSnackbar("Nothing to print on this page")
}
},
onAllowAdsOnThisSite = { viewModel.allowAdsForActiveTab() },
showAllowAds = settings.adBlockEnabled && !activeTab.isNewTab &&
!adBlockAllowlist.contains(
runCatching { android.net.Uri.parse(activeTab.url).host }.getOrNull().orEmpty()
),
onTranslate = { viewModel.setTranslateSheetVisible(true) },
onReadingMode = { openReadingModeForCurrentTab() },
onAddToHomeScreen = { pinCurrentPageToHomeScreen() },
Expand Down Expand Up @@ -810,7 +842,10 @@ fun BrowserApp(viewModel: BrowserViewModel) {
sitePermissionDecisions = sitePermissionDecisions,
onResetAdBlockCount = { AdBlocker.resetBlockedCount() },
onForgetSitePermission = { origin -> viewModel.forgetSitePermission(origin) },
onForgetAllSitePermissions = { viewModel.forgetAllSitePermissions() }
onForgetAllSitePermissions = { viewModel.forgetAllSitePermissions() },
adBlockAllowlist = adBlockAllowlist,
onDisallowAds = { host -> viewModel.disallowAds(host) },
onClearAdsAllowlist = { viewModel.clearAdBlockAllowlist() }
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ import androidx.compose.material.icons.outlined.Devices
import androidx.compose.material.icons.outlined.Download
import androidx.compose.material.icons.outlined.DownloadDone
import androidx.compose.material.icons.outlined.FindInPage
import androidx.compose.material.icons.outlined.Print
import androidx.compose.material.icons.outlined.Shield
import androidx.compose.material.icons.outlined.HelpOutline
import androidx.compose.material.icons.outlined.History
import androidx.compose.material.icons.outlined.Settings
Expand Down Expand Up @@ -102,6 +104,9 @@ fun ChromeOverflowMenu(
onRecentTabs: () -> Unit,
onShare: () -> Unit,
onFindInPage: () -> Unit,
onPrint: () -> Unit = {},
onAllowAdsOnThisSite: () -> Unit = {},
showAllowAds: Boolean = false,
onTranslate: () -> Unit,
onReadingMode: () -> Unit,
onAddToHomeScreen: () -> Unit,
Expand Down Expand Up @@ -384,6 +389,28 @@ fun ChromeOverflowMenu(
}
)

ChromeMenuRow(
icon = Icons.Outlined.Print,
label = "Print",
testTag = "menu_print",
onClick = {
onDismiss()
onPrint()
}
)

if (showAllowAds) {
ChromeMenuRow(
icon = Icons.Outlined.Shield,
label = "Allow ads on this site",
testTag = "menu_allow_ads",
onClick = {
onDismiss()
onAllowAdsOnThisSite()
}
)
}

ChromeMenuRow(
icon = Icons.Outlined.Translate,
label = "Translate...",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,10 @@ fun SettingsScreen(
sitePermissionDecisions: List<com.bansify.browser.data.SitePermissionDecision> = emptyList(),
onResetAdBlockCount: () -> Unit = {},
onForgetSitePermission: (String) -> Unit = {},
onForgetAllSitePermissions: () -> Unit = {}
onForgetAllSitePermissions: () -> Unit = {},
adBlockAllowlist: Set<String> = emptySet(),
onDisallowAds: (String) -> Unit = {},
onClearAdsAllowlist: () -> Unit = {}
) {
BackHandler { onBack() }

Expand Down Expand Up @@ -144,7 +147,10 @@ fun SettingsScreen(
sitePermissionDecisions = sitePermissionDecisions,
onResetAdBlockCount = onResetAdBlockCount,
onForgetSitePermission = onForgetSitePermission,
onForgetAllSitePermissions = onForgetAllSitePermissions
onForgetAllSitePermissions = onForgetAllSitePermissions,
adBlockAllowlist = adBlockAllowlist,
onDisallowAds = onDisallowAds,
onClearAdsAllowlist = onClearAdsAllowlist
)
return
}
Expand Down
Loading
Loading