Guidance for AI coding agents working in this repository.
Status: since v1.1.0 the project is WebView-only. The GeckoView variant (
geckoIncluded,:app:gecko) was removed. Mentions of Gecko,gecko*flavors or the gecko module below describe releases before v1.1.0.
Simple Browser is an Android web browser for TV remotes (D-pad navigation, virtual cursor, tabs, bookmarks, voice search, downloads, history), with a touch interface for phones in the same APK. It renders pages with the system WebView (com.simplesoftware.browser). The GeckoView variant was removed in v1.1.0.
The official language of the project is English (code, comments, commit messages, documentation, and default UI strings).
Gradle (Kotlin DSL) with JDK 21. On Windows use gradlew.bat / .\gradlew.
Variants combine one flavor dimension with the build type: appstore = generic | google | foss. Examples:
./gradlew assembleGenericRelease./gradlew assembleGenericDebug./gradlew testGenericDebugUnitTest./gradlew :app:testGenericDebugUnitTest --tests "com.simplesoftware.browser.utils.FaviconExtractorTest"./gradlew :app:common:testDebugUnitTest- The release APK is universal (no ABI splits).
-PenableAbiSplitsremains supported but the release workflow does not use it. - Release signing reads the env vars
KEYSTORE_PATH,KEYSTORE_PASSWORD,KEY_ALIASandKEY_PASSWORD. WithoutKEYSTORE_PATH, release builds are unsigned. - App unit tests use Robolectric (
isIncludeAndroidResources = true). There are no instrumented tests. Browser core tests useFakeWebEngine(registered throughWebEngineFactory.initializeForTests) and an in-memory Room database (AppDatabase.setInstanceForTests). - Room schemas are exported to
app/schemasand committed.AppDatabaseMigrationTestbuilds databases of old versions from them, so a database version bump needs its schema exported (it is generated by the build) and a migration test. buildSrccompiles withallWarningsAsErrors = true.
:app: the base application. It holds the browser core (browserpackage, see below), the UI (activities, dialogs, settings), the RoomAppDatabase, the download service, the WebView engine (webengine/webview), the filter lists of ad blocking (browser/adblock) and auto-update.:app:common: an Android library used by:app. It holds the engine abstraction (webengine/WebEngine.ktandWebEngineFactory), theConfigprefs, the Room entity models,AppContext,ActiveModel/ActiveModelsRepository, and the cursor widgets (CursorLayout,CursorDrawerDelegate). Code shared by engines belongs here.:adblock: the ad blocker (it replaced the nativead-blocklibrary in theadblock-experimentbranch), a dependency of:apponly (see Ad blocking).AdblockBenchActivityofapp/src/debug, started with adb, measures it on the lists and requests put into its external files dir; build it with-PdebugNotDebuggable, ART runs debuggable apps slower. Plain Kotlin withoutandroid.*, so its tests run on the JVM (./gradlew :adblock:testDebugUnitTest;-PadblockLists=<dir>also parses the real*.txtlists of a directory, which are not in the repository).parser/FilterParserreads lists of the Adblock Plus syntax line by line intoNetworkFilters andCosmeticFilters; a filter with anything it does not support (an unknown option, scriptlets, procedural selectors,:has(), entities as the only domains) is skipped whole and counted inParseStatsby reason.ResourceTypeholds the request types as bits of a mask.psl/PublicSuffixListgives the site (registrable domain) of a host forthird-party: it loads the assetadblock/psl.txt, whichPublicSuffixListCompilermakes fromadblock/psl/public_suffix_list.dat(MPL-2.0; a new list is compiled with-PupdatePsl, the tests fail while the asset is older;.gitattributeskeeps its LF line ends), with hash tables of offsets over its bytes and no allocation per lookup.FilterCompilerturns the request filters into aFilterEngine: flat arrays (flags with the type bits, pattern offsets into one byte pool, domain lists as sorted 64-bit hashes) and fourengine/IndexTables (page exceptions,important, blocking with the important ones too, exceptions), where a filter is found by the hash of its host (||host^) or of its rarest whole token (hashed of its first 16 characters; urls are tokenized in their first 2048), or sits in the small bucket every request checks; a filter found by a token keeps where the token is in its pattern (bits of its flags), so the pattern is checked only where the url has the token; the page exceptions, the exceptions and the important filters are asked only after a blocking filter matched; patterns are matched byPatternMatcherwithout regular expressions, and a regex filter first needs its required literal (RegexLiterals) in the url, becausejava.util.regexgoes through ICU and JNI on Android. The engine is immutable and thread-safe (aThreadLocalscratch per thread, regexes compiled lazily into anAtomicReferenceArray), and its checks catch their own exceptions and block nothing. Element hiding filters (##,#@#) go intoengine/CosmeticIndex(built byCosmeticCompiler): the selectors of sites by the hash of each domain, the generic selectors that start with a class or an id by the hash of that name, and the rest (high generic) as one list; excluded domains (~site.com##) and the exceptions of a site (site.com#@#) apply to all of them, and an exception without domains drops its selector everywhere.FilterEngine.hidingStylesgives the CSS of a page (its site's selectors and the high generic ones, the latter cached, in rules of 50 selectors, so one bad selector loses only its rule) and whether to ask for the generic ones;$document/$elemhideexceptions of the page give nothing,$generichideonly the site's;genericHidingStylesgives the CSS of the generic selectors of the classes and ids a page has.engine/EngineFilewrites it atomically (temporary file, fsync, rename) with a header (magic,FORMAT_VERSION, the fingerprint of the lists, CRC32 of the body) and reads it with bulk copies; a file of another version, damaged or truncated is anAdblockFormatException. RaiseFORMAT_VERSIONwhenever what is written changes, andFilterCompiler.VERSIONwhenever the parser or the compiler give other arrays for the same lists (the app mixes it into the fingerprint of its lists, so older engine files are built again).-PadblockLists=<dir>with arequests.tsv(seetools/adblock-corpus) also runsEngineBenchmarkTest, and with-PadblockOracle=<file>(the decisions of @ghostery/adblocker for the same lists and requests, written bytools/adblock-corpus/oracle.mjs, which runs it under node outside the repository)OracleComparisonTest.buildSrc: convention pluginssimplesoftware.android.applicationandsimplesoftware.android.library(both inTvBroAndroidModulePlugin.kt). They apply AGP and set compileSdk, minSdk and targetSdk fromgradle/libs.versions.toml. The product flavors are declared inapp/build.gradle.kts. All dependency versions live in that version catalog.
Web engine plug-in mechanism. The app has one engine, the system WebView, chosen at build time: app/build.gradle.kts sets BuildConfig.WEB_ENGINE_CLASS to com.simplesoftware.browser.webengine.webview.WebViewWebEngine. Engines register themselves rather than being referenced directly. Each engine class has a companion object { init { WebEngineFactory.registerProvider(...) } }, and SimpleBrowser.initWebEngineStuff() triggers that registration with Class.forName(BuildConfig.WEB_ENGINE_CLASS). WebEngineFactory holds that one provider (registering another one fails) and initialize(), called from MainActivity, initializes it. There is no engine setting and no switching at runtime. Keep base-app code free of compile-time references to engine classes. All interaction goes through the WebEngine interface and WebEngineFactory. Common code must not check which engine is active either: engine-specific behavior goes through WebEngineProviderCallback hooks (incognito data isolation and cleanup, clearing the data of one site with clearSiteData/supportsSiteDataClearing, failure to create a view, supportsSetting for settings only some engines have, see EngineSpecificSetting) or WebEngine properties (for example stateFilePrefix of saved tab state files). BrowserTab.webEngine is created lazily; check isWebEngineCreated before touching the engines of all tabs.
Virtual cursor. The cursor is an optional engine capability: an engine that supports it implements VirtualCursorSupport (cursor vs. direct navigation mode, the CursorDrawerDelegate), and the UI reaches it only through webEngine.virtualCursor. The WebView engine wraps every WebViewEx (and its fullscreen view) in its own CursorLayout. The activity's tabs container (flWebViewContainer) is a plain FrameLayout. When another tab is shown, MainActivity.onRenderedTabChanged turns the grab and direct navigation modes off. CursorDrawerDelegate (movement, the selection keys, press and grab state) leaves the work to the classes next to it: CursorRenderer draws, a PointerEmulator talks to the page, CursorScroller scrolls at the edges (the engine's customScrollCallback, then the "scroll hack", a touch drag) and PinchZoomGesture zooms. Input reaches it through the DPADNavigationEventsAdapter of the surface, which gives it a direction vector (setDirection, each component in -1..1, (0, 0) stops) and forwards the selection keys (dispatchKeyEvent): the vector comes from one of two channels, the one engaged last (the other one while it is neutral): the D-pad (the direction keys held and the hats of game controllers, whole steps) or the left sticks (analog: the deflection past a round dead zone with a response curve, only while "Navigate with joystick sticks" is on, Config.disableMotionAxesDpadNavigation); the cursor's speed ramps up with the acceleration setting and is scaled by the vector, so a new vector steers it without stopping it. The adapter consumes all joystick motion, since the platform turns unhandled joystick motion into D-pad keys of its own, and ignores the D-pad keys made of motion (isSynthesizedFromMotion: a joystick source, or a fallback key of a game controller). The emulator is a finger (TouchEmulator) or a mouse (MouseEmulator: hover, primary button press and release with the ACTION_BUTTON_PRESS/RELEASE events WebView needs, wheel scrolling of the element under the cursor), chosen by CursorDrawerDelegate.pointerMode; the engine sets the mouse for pages in the desktop view (SiteViewSupport.desktopView). The cursor surface is a PointerTarget (CursorLayout): synthetic hover and wheel events skip its D-pad adapter, and it gives the pixels of one wheel click of its engine. Switching the mode or turning the cursor off cancels the press and the hover in flight.
Site view and site settings. Showing a site as on a desktop computer or as on a phone is an engine capability too: an engine implements SiteViewSupport (desktopView: a desktop User-Agent and a wide viewport; WebView builds them in DesktopView from the system User-Agent, with Google Chrome in place of Android WebView in the client hints), reached through webEngine.siteView. The view is kept per host (HostConfig.desktopView, null follows the default; like ad blocking, HostConfigRepository keeps these settings of all hosts in memory, loaded before the tabs, so engines ask synchronously). The default is Config.defaultDesktopView (Settings: Default site view), null following the interface: BrowserController.interfaceDesktopView, set by MainActivity, desktop on TV and mobile on phones. The core sets the view before it loads a url or restores a tab; for navigations of the page to another host engines ask EnginePolicies.isDesktopView (WebView starts the navigation again); a page that still starts in the view of another host loads again once (onPageStarted). The WebView engine always shows Google's sign-in pages in the mobile view (MobileViewPages, applied under the view the core set, which it keeps): Google refuses sign-in to WebView with a desktop User-Agent, because WebView sends the app's package in X-Requested-With, which current versions do not let an app turn off. The User-Agent setting (Settings, Sites; Config.userAgent, Auto, a few browsers of SettingsNavigator.USER_AGENT_PRESETS or a custom string) is null by default: the User-Agent then follows the view. One that is set goes to all pages (SiteViewSupport.userAgentOverride, set by the core with the view, BrowserController.onSiteViewSettingsChanged after a change) in place of the one of the view, which still sets the viewport; WebView keeps the client hints of the view (they can not be dropped once set) and the system User-Agent on MobileViewPages. WebEngine.userAgentString only tells the current one (for downloads). CurrentTabState.connection (SiteConnection: no site, secure, http, certificate error; a certificate error stays with its host until the user navigates or the tab shows another host) gives the site button its sliders or the warning sign in tbColorDsDanger (showSiteConnection), and the header of the site settings its connection line. The built-in home page has no site. The site settings are one view, SiteSettingsView, in three variants (siteSettingsVariant): the TV SitePanelView under the site button, the phone PhoneSiteSheet (from the site button of the pill or the site header of the menu sheet) and the site section of the PhoneMenuSheet (rows without icons, no Clear site data). Its rows call BrowserShell.Host (toggleSiteAdBlock, choosePopupBlockLevel, chooseSiteView, clearSiteData, the dialogs are in MainActivity); the page reloads and the panel or sheet stays open. Clear site data asks first and removes the cookies, stored data and cache of the site (BrowserController.clearSiteData), not its settings and history.
Shells: the TV and the phone UI. MainActivity does what both looks share (the browser core, intents, navigation, incognito, downloads, keys and Back) and leaves the look to a BrowserShell, which it creates in onCreate: TvShell (activity_main.xml: the bar of the redesign over the page, the virtual cursor) or PhoneShell (activity_main_phone.xml: touch only, the virtual cursor is turned off for every tab view, the bottom PhoneBar, which ScrollAwayBar slides away while the user scrolls the page down (touches are tracked by the tabs container, TouchTrackingFrameLayout), the PhoneMenuSheet, the PhoneSiteSheet, the PhoneTabSwitcher, the PhoneBookmarksView, the PhoneDownloadsView and the PhoneSettingsView over the window, the PhoneSnackbar over the page). The shell gets the activity as BrowserShell.Host and is told about the engine views, the current tab state, UI events, fullscreen and Back. UiModeSelector picks the shell from the Interface setting (Config.interfaceMode); on Auto, the phone UI is for devices that are not a TV, have no leanback feature, have a finger touch screen and are narrower than 600dp (no tablets for now). Changing the setting restarts the app. The activity is not recreated on rotation or size changes (configChanges), so the engine views stay; the phone window is drawn edge to edge and PhoneShell applies the insets. The phone settings have no Remote and cursor category (see Settings). The built-in home page has a layout for phones (a CSS media query in assets/pages/home/index.html).
Commands and Back. Browser actions triggered by the user from anywhere (hotkeys of ShortcutMgr, voice search) go through browser/BrowserCommands, which the activity implements; the buttons of the TV bar call BrowserController from the shell. The media keys (play/pause, stop, rewind, fast forward) go to the engine, which runs assets/media_controls.js in every frame (players are mostly in iframes of other sites): WebView injects it (started by webview_media.js, reporting to WebViewMediaControls); the script reports the media of its frame, MediaFrames picks the frame (the one with a fullscreen video, else the one that started playing last) and the command goes to that frame only (its reply proxy). Engines that implement MediaPlaybackSupport (webEngine.mediaPlayback) also give the state of that media (MediaState: playing, position, duration, whether it is in the fullscreen view, from the reports of the script, MediaReports) and seek in it. The TV shell uses them for the video mode (VideoModeController, no views): while the page shows a video in fullscreen the cursor is hidden and the keys control the video (Left and Right seek, faster while held, to where the key goes up; OK plays and pauses; Up and Down give the cursor back, and Back with that cursor hides it again, its callback is above the fullscreen one), with the seek bar VideoOsdView (it shows for a while when the video mode starts, longer when it has the hint of the built-in player). The shell gets the keys first (BrowserShell.dispatchKeyEvent), and in fullscreen Back never reaches the engine views: the back callbacks decide. The videos of the page that other apps can play (PageVideo: a file a media element plays, or the manifest of an HLS or DASH stream, never blob: media) are found by assets/page_videos.js in every frame: the media elements and, through a PerformanceObserver, the .m3u8 and .mpd files the page loads; WebView runs it with media_controls.js, and engines that implement PageVideosSupport (webEngine.pageVideosSupport) give them as a flow, the reports of the frames kept together by PageVideoList (one address once, the variants of an HLS stream not apart, cleared when the page changes). The TV bar has a Videos button with their number (dimmed without videos, as Back and Forward are); its VideosPanelView lists them, OK opens one in a player app chosen in the dialog of Android (ExternalVideoPlayer: the Referer of its frame, the User-Agent and the cookies of the engine, in Browser.EXTRA_HEADERS and the headers list of MX Player), its options also copy the address and download a file; the page keeps playing them as before. When one of them starts to play with sound in the page (mediaVideo; the script reports muted too, MediaState.muted), the TV shell shows a hint plate for a few seconds, PageVideoHintView at the top end where the Videos button is, also with the bar hidden; it takes no focus and no keys. Its rules are in PageVideoHintController (no views): it shows after the video has played for 3 s while nothing covers the page (the shell checks the bar, panels, menus, screens, the player and fullscreen on each redraw), never for short videos, at most once per page (the tab and its address without the fragment, kept in memory), and only while Config.pageVideoHint (Settings, Sites) is on. Back while it shows (its callback is just above the one of the menu) opens the bar, then the Videos panel at the row of that video (VideosPanelView.show with focusUrl), so Back, OK plays it in the built-in player; the row of the video the page plays says "Playing on the page". Every Back (the BACK/ESCAPE key, the system back callback, the B button of game controllers, the right and back buttons of a mouse) goes through BackNavigationEventsAdapter: one press often comes through more than one of these channels, so an event of another channel within a second of the last one taken is the same press; it also handles the "long press B" mode of game controllers in the direct navigation mode (remotes still go back on a short press). The adapter feeds MainActivity.screenBackDispatcher, an own OnBackPressedDispatcher of the screen: each overlay has an OnBackPressedCallback there that it enables while it is shown, registered in onCreate from the lowest priority (the menu) to the highest (the cursor modes, which come from VirtualCursorSupport.cursorModes). Voice input (VoiceSearchHelper; from Android 11 its own plate at the bottom center of the window, where toasts show, and its errors as toasts of the shell, BrowserShell.showMessage) is cancelled by Back: its callback is added after all the others. Never add overlay callbacks to the activity's onBackPressedDispatcher: it has one always enabled callback that goes to the adapter. When something else has already handled a Back press in progress (the fullscreen view of WebView leaves fullscreen on BACK down), call consumeCurrentPress().
Ad blocking. The engine of :adblock decides; browser/adblock/AdBlockService (one per browser process, AppContainer.adBlock, started by SimpleBrowser.initAdBlocking, never in :downloads) keeps it: filesDir/adblock holds lists.json (FilterListsStore: the lists turned on, the address of the user's own list, the updates of each list), lists/<id>.txt (the downloaded lists, kept to build the engine again without the network) and engine.bin. At start it loads engine.bin when its fingerprint (the compiler version and the files of the enabled lists) fits, else builds it from the lists in the background; BrowserController waits for the load (not a build) up to a second before restoring tabs. The engine is replaced by a write of a volatile reference. Lists (FilterListCatalog: EasyList, EasyPrivacy, one regional list, the system language's by default, and the user's own one) are downloaded by ListFetcher with conditional requests when their ! Expires: comes (1 to 7 days), right away on the first start, otherwise 30 s after start and then every 6 h while the process lives; a failed download keeps the list, its date and the engine and is tried again after 1 h, 6 h, then a day; a page of HTML is a failure. The service also deletes the file and the prefs of the native library. Engines never ask the callbacks of a tab: the app sets WebEngineFactory.adBlocker (EngineAdBlocker, implemented by AppEngineAdBlocker with the HostConfigRepository given once: the setting of the host of the tab's page, else Config.adBlockEnabled, never on the home page), asked for every request of every tab on the engine's threads. WebView gives it the Accept header (ResourceType.guessFromAccept: a mask of the types a request may be, never a ping) and the page of its tab: WebViewEx keeps the url of the main frame request before onPageStarted comes (and the page again when a navigation becomes a download); a blocked request gets an empty 403. WebView counts the blocks of the current tab only. Element hiding (no setting of its own, it follows the ad blocking of the tab's page; a frame of about:blank or about:srcdoc gets the selectors of that page) is assets/element_hiding.js in every frame: it puts the CSS of the page into one <style> at once, then collects the classes and ids of the elements (a MutationObserver, batches every 50 ms, each name once, at most 20000) and adds the CSS of their generic selectors. WebView runs it as a document start script (WebViewElementHiding, in onPageStarted and onPageFinished where DOCUMENT_START_SCRIPT is missing) that asks the synchronous @JavascriptInterface TVBroHiding, so the CSS is there before the elements; WebView runs no such script in frames of about:blank and about:srcdoc, so the script of their parent hides their elements (api.frames).
Proxy. The browser can go through an HTTP proxy (https sites through it with CONNECT) or a SOCKS5 one (Settings, Advanced; Config.proxyEnabled/proxyType/proxyHost/proxyPort, the login in Config.proxyUsername/proxyPassword, which are kept in the prefs file credentials.xml, left out of backups by backup_rules.xml and data_extraction_rules.xml). Config.proxy (net/ProxySettings.of) is the proxy in use: null while it is off or its address is not complete; only an HTTP proxy has a login (WebView can not log in to a SOCKS one). Local addresses never go through it (ProxySettings.BYPASS_DOMAINS and BYPASS_NETWORKS, the same rules for the engines and the app), and nothing falls back to a direct connection when it fails: pages show the network error. net/AppProxy (in :app:common) holds the proxy of the process (AppProxy.settings); browser/ProxySetup.start sets it from the settings first in SimpleBrowser.onCreate, and ProxySetup.apply (called by AppSettingsStore after each change) gives a changed proxy to the engine (WebEngineFactory.applyProxy, EngineSpecificSetting.PROXY) and reloads the current page, so it applies at once. The engine applies AppProxy.settings in initialize, before any tab loads: WebView with ProxyController (WebViewProxy, no DIRECT rule; it checks the rules itself). Never touch ProxyController or WebViewFeature before initialize: they load WebView, and the incognito process must give it its data directory first. The engine answers the login request of the proxy with the saved login unless it was refused (WebViewEx.onReceivedHttpAuthRequest for the proxy host). The app's own requests (filter lists, updates, favicons, downloads) open connections with AppProxy.open, never URL.openConnection(): a proxy given to the connection is the only one the HTTP client of Android (OkHttp 2.7) uses, while after the proxies of a ProxySelector fail it tries a direct connection. AppProxy.install sets the default ProxySelector (web schemes only; sockets such as the sync connect directly) for Media3, which opens its connections itself, so the built-in player may go directly when the proxy is down, and the default Authenticator, which answers only the proxies connections were opened with, once per request: OkHttp asks again without end while the proxy refuses the login of a tunnel. The login is never put on a request (Proxy-Authorization): the client does not move it to the CONNECT, so it would go through the tunnel to the server, also after a redirect to https. That client answers a 407 of a tunnel on the same connection, so the app's https requests through a proxy with a login need a proxy that keeps the connection after the 407 (Squid does). The downloads process does not see later changes of the settings: the proxy goes with each start and resume command (DownloadCommands.KEY_PROXY) and stays with that download (HttpDownloadTask). Utils.isLocalNetworkUrl still resolves the hosts of pages locally, and external players get no proxy.
Browser core and engine callbacks. browser/BrowserController (an ActiveModel) owns the tabs: their list, the current tab, persistence, opening/closing/switching, navigation, the engine events and the browsing history. It knows nothing about views: an activity attaches itself as BrowserController.TabViewHost, which creates engine views (createTabView) and provides the UI part of the engine callbacks (uiHost). The engine of the current tab gets a WebEngineCallbacks in onAttachToWindow; it is composed of three parts, all in webengine/WebEngineCallbacks.kt: TabEngineEvents (implemented by the controller), EnginePolicies (TabPolicies: dialogs and new windows blocking, the site view; ads are asked of WebEngineFactory.adBlocker, see Ad blocking) and EngineUiHost (implemented by the activity: menus, dialogs, fullscreen, page scrolling, permissions and file picking with result callbacks, downloads as DownloadRequest). The callbacks are set only while the tab is current, so background tabs report nothing. The UI renders BrowserController.currentTabState (StateFlow<CurrentTabState>) and handles one-time BrowserUiEvents from uiEvents (a channel with a single collector). Other core pieces: HomePageLinks (links of the built-in home page), VisitedHistoryLogger, HomePageUrl (resolves about:home, engines never get the alias), UrlRouter/UrlInputResolver/PopupBlockPolicy, Downloads.kt. Activities start other activities and ask for permissions through utils/launchForResult (the ActivityResult registry), never with request codes.
State models. Screens keep state in ActiveModel subclasses (for example BrowserController, SettingsModel, AutoUpdateModel and DownloadsModel). They get them through ActiveModelsRepository.get(Model::class, activity), not through AndroidX ViewModel. A model is released when every activity using it finishes. Older observable state uses the custom utils/observable types (ObservableValue and ObservableList); new code uses StateFlow/Flow (with immutable values: a StateFlow does not emit a value equal to the previous one).
Tabs. BrowserTab (in :app:common, engines get it) is a tab in memory: its engine, thumbnail and page state; it is read and changed on the main thread only. The database keeps TabEntity snapshots (toEntity()/fromEntity()), and browser/TabFilesStore keeps the files of tabs (engine states, WebP thumbnails), getting and returning file names without touching tabs. BrowserController.saveTab takes the snapshot when called and enqueues the write in tabWrites; the queue runs on the main thread, so the id and the file names given by earlier writes are applied there. A tab is saved when it stops or starts being the current one and when the activity pauses. BrowserController.navigate sets tab.url before the page starts; a navigation that becomes a download (any EngineUiHost.onDownloadRequested, seen by the controller through its wrapper of the UI host) gives the tab back BrowserTab.pageUrl, the page it shows (about:blank if none yet), so a restored tab does not download the link again.
Bookmarks. FavoriteItems are kept in folders: a folder is an item without a url, its contents point to it with parent (0 is the top level, FavoritesRepository.ROOT). The bookmarks of the built-in home page are the Home page folder (FavoritesRepository.HOME_PAGE, no row in the table: they are marked with homePageBookmark, hold no folders and are not in the top level). In a folder, folders come first, then bookmarks, each by order (the newest first among equal orders): new items go to the top, new home page bookmarks to the end. The home page shows the bookmarks of its folder in that order (a link's order is its place on the page) and leaves out those it has no room for; HomePageLinks.load() is called after bookmarks change. Use the repository (add, moveTo, move, delete with the contents of a folder), not the DAO. What the bookmarks screens show and do is in BookmarksNavigator (no views: a stack of screens, a folder, the form of a bookmark or folder, the choice of a folder, the search of all folders, the bookmarks files in Downloads and the ways to import one, rendered through its Host); the shells only draw it. Export and import use the HTML bookmarks file of Chrome, Firefox and Edge (data/BookmarksHtml, a pure reader and writer; the Home page folder is marked with TVBRO_HOME_PAGE on its H3); FavoritesRepository.importBookmarks holds the rules of the new folder and merge imports, and DeviceBookmarkFiles (the navigator's Files) saves to and lists Downloads as downloads do (MediaStore from Android 11, which lists only the app's own files there) and opens the system picker. The TV bar keeps Bookmarks, Downloads and Incognito as buttons; History, Phone sync and Settings are in the PopupMenuView of its ⋮ button (TvShell.showMoreMenu). The TV shell shows the bookmarks in BookmarksPanelView, under the star of the bar, with the row menus in a PopupMenuView (both are AnchoredOverlayViews, which keep the focus inside them while open). The phone shell shows it in PhoneBookmarksView over the whole window, with the actions of a row in a PhoneActionsSheet and reordering by dragging; the Bookmark button of the menu sheet adds the page, or opens its bookmark.
Downloads. DownloadService runs in its own process (:downloads, see the manifest), so downloads go on while the browser switches between its normal and :incognito processes (which kill each other) and both can start them; SimpleBrowser.onCreate initializes only the database and the notification channel there, and nothing in processes the app does not know (AppProcesses: an unreadable process name is taken for the browser). The browser processes reach it through AppContainer.downloadService (DownloadServiceClient): DownloadCommands (start, cancel, pause, resume) in Messages of a Messenger, which wait until the service is bound; the activity keeps it bound only while it is started and a download is in progress or a downloads screen or panel is shown (DownloadServiceNeed; a row a dead process left in progress counts, so the service starts and marks it), otherwise the process does not run. While a browser is bound, the service is started too (onBind/onRebind), and it stops itself only when nothing is bound, running or waiting for the database (stopIfIdle, a second after the last onUnbind): the launcher unbinds right after it sends a command, and a service that was only bound was destroyed before it handled it (its successor took the new row for one a dead process left). Nothing comes back through the binder: the database is the only state. DownloadLauncher inserts the row of a new download (Download.status: in progress, paused, done, failed, cancelled; error keeps a reason, see Download.Error) before it sends the start; the service writes the progress every second and the end, and on its start makes the downloads a dead process left in progress paused (resumable) or failed. AppDatabase is opened with multi-instance invalidation, so the Room flows of the browser processes see these writes; DownloadsModel turns them into DownloadItem snapshots with speeds and DownloadEvents (a download ended). Responses a web engine fetched itself and blob data cannot cross processes: the launcher copies them into a reliable pipe whose read end goes with the start command (its own copy is closed without a status, see DownloadServiceClient); a cut pipe fails the download. HttpDownloads requests files (redirects followed by hand, cookies only to the host of the site, no content encoding); a download is resumable when the server gives byte ranges and its size: pause keeps the file (pending in MediaStore on Android 11+) and resume asks for the rest with Range and If-Range (decideRange). Files go to the public Downloads directory, or to a folder the user chose (Settings, Advanced) with the picker of the Storage Access Framework (utils/DownloadFolder: a tree uri in Config.downloadFolderUri with a persisted grant, which the downloads process shares; the option is there only where some app takes ACTION_OPEN_DOCUMENT_TREE, many TVs have none). The folder goes with each start and resume command (DownloadCommands.KEY_FOLDER, as the proxy does); DownloadLauncher sends it only while the grant is kept and the folder is there (a removed USB drive), else tells the user and the file goes to Downloads; a lost grant does not come back, so it also resets the setting (the service falls back too when it can not create the document), and asks for the storage permission of Android 10 and older only for Downloads. A document is created with the type of its extension (providers add the extension of the type to other names) and loses resuming when its provider gives no seekable file. Download.filepath is one of three kinds, told by the path and not by the version of Android (utils/DownloadFiles): a path in Downloads (before Android 11), a MediaStore uri (Android 11+) or a document of the chosen folder (deleted with DocumentsContract.deleteDocument, never pending); go through DownloadFiles for its file. Cookies are never stored: resume and Download again take them from the engine of the current tab (BrowserShell.Host.downloadCommands). Incognito downloads keep no referer (the page they came from). What the downloads screens show and do is in DownloadsNavigator (no views; looks: the TV panel of the bar with the latest downloads, the TV screen and the phone page of all downloads with filters by Kind), its Device is DeviceDownloads (open, install, share, the Downloads folder through DownloadFileActions; Android TV sends intents no app handles to stubs that only show a toast, they count as none). The TV shell shows DownloadsPanelView under the Downloads button of the bar (with a badge of the active downloads) and DownloadsScreenView over the window; the phone shell shows PhoneDownloadsView; rows are bound by bindDownloadRow, captions made by DownloadRowText.
Built-in player. The TV shell plays the videos of pages (PageVideo) in a player of its own, on Media3 (ExoPlayer: HLS, DASH and files), because the engines draw video into the window (1080p on a 4K TV, at a high CPU cost in WebView) and the player gives it a SurfaceView layer of its own. It is a view over the whole window of the browser activity, PlayerScreenView, in the process of the page (normal or :incognito), not an activity. player/NativePlayer (no views) wraps ExoPlayer: it requests the video with the headers of the page (ExternalVideoPlayer.headers: the Referer of its frame, the User-Agent and the cookies of the engine) and tells its state as a flow. The keys are those of the video mode (a VideoModeController of its own, whose host takes Up and Down): Left and Right seek, OK plays and pauses, Down (and the Menu key, which a Shield and many TVs keep to themselves) opens the menu of the quality, the audio track, the subtitles and the speed (PlayerTracks, in a PopupMenuView of the player) and the repeat of the video (NativePlayer.looping, off for each video, not for live streams), which the seek bar tells with the hint "↓ Video settings", and Up does nothing; the media keys of the remote go to it while it is open (BrowserShell.onMediaCommand); Back closes the menu, then the player (its callback is the highest). OK on a row of the Videos panel opens it (the video the page plays goes on from where it is; its options keep the other app); in the video mode Down takes the fullscreen video of the page there, from where it is, when the engine knows its stream (PageVideosSupport.mediaVideo: PageVideoMatch of what media_controls.js reports the media plays and the videos of its frame; the seek bar shows the hint). The page pauses its media (MediaPlaybackSupport.pausePlayback) and leaves fullscreen when the player opens. An error offers the video to another app. With Config.matchFrameRate (Appearance, Screen; TV only, off by default) the player switches the display to the mode that fits the frame rate of the video track (DisplayModeMatcher, FrameRateSwitcher through the window's preferredDisplayModeId; Media3 then asks the surface for nothing) and gives the mode back when it closes or the activity pauses.
Home screen channels. On Android TV 8+ (HomeChannels.isSupported: a TvProvider; the settings show them only there and in the TV interface) the app can publish three preview channels of TvContract (channels package), each off by default (Settings, Search and home page, Android TV home screen): the bookmarks (Config.channelBookmarksSource: those of the home page, those right in one folder (channelBookmarksFolder, the top level too) or all of them, as FavoritesRepository.channelBookmarks gives them), the open tabs (16:9 posters cut from their thumbnail files; none while incognito mode is on) and the finished downloads. HomeChannels.sync makes the channels of the given kinds what the settings say: an enabled one is created (requestChannelBrowsable; turning one on in the settings asks the system dialog when it is not shown yet) and a disabled one deleted, found by COLUMN_INTERNAL_PROVIDER_ID (no ids in prefs, so cleared data or a race leaves nothing behind; duplicate channels and programs are deleted); ChannelPublisher writes only the programs that differ, and a weight (the launcher puts heavier programs first) follows the place in the list, so a program added at the end changes no other; downloads, whose new ones come first, weigh their id. Syncs run one at a time in all processes (a mutex and a FileLock on channels.lock). They run when MainActivity stops (after tabWrites, so the thumbnails are written), when a setting changes, and in :downloads when a download is done (Mode.UPDATE_EXISTING: its prefs may be stale, so it only refreshes a channel that is there). Posters are drawn by the app (ChannelPosters, in noBackupFilesDir like the secret of the links: the posters of tabs show the open pages; favicons only from the app's cache, no network; a file named by a hash of what it shows, since the launcher keeps images by uri) and served by the exported ChannelPostersProvider to the app and system apps only. A bookmark tile shows a tab with its url if there is one (MainActivity.channelBookmarkIntent), a tab tile switches to its tab (channelTabIntent), a download tile goes to ChannelLaunchActivity, which checks the HMAC token of the link (a secret file of the app) and opens the file as OK on its row does, else the downloads screen. The provider and that activity run in :downloads, so the launcher does not start the browser.
Settings. What the settings screens show and do is in SettingsNavigator (no views): six categories (Search and home page, Sites, Appearance, Remote and cursor, which only the TV interface has, Advanced, About), each a list of Sections of Rows (a Choice, segmented for 2 or 3 short options and else opened as a menu of options, a Toggle, a Slider, a Field of text with an optional button, an Action, the key of a ShortcutKey, a Link, Info). A row that depends on another setting is there only while it applies (the folder of downloads only where there is a picker of folders or one is chosen, the address of a custom search engine, the User-Agent string while Custom is chosen, the links or the address of the home page, the filter lists while ads are blocked, the update channel and a new version while updates are checked); the darkening of pages and the tracking protection only where the engine supports them, the updates only in the generic build, the frame rate and the hint about found videos only in the TV interface. Settings that are read when the app starts (interface, theme, darkening, engine debugging) are marked After restart, and the screens offer Restart now while one differs from the value the process started with (AppSettingsStore.rememberStartupValues, called in MainActivity.onCreate), so nothing exits the app by itself. The navigator reaches the settings through its Store (AppSettingsStore: Config, SettingsModel, the ad block and update models; it makes the checks of the engine and the build, and writes through the paths that apply a setting: SettingsModel.keepScreenOn, config.theme, setSearchEngineURL, BrowserController.onDefaultSiteViewChanged); SettingsShellCallback gives both shells the dialogs (turning engine debugging on asks first), the key capture (ShortcutKeyDialog, an AlertDialog with its own window, so keys do not reach the shortcuts of the activity; the navigation keys still move its focus), links in a new tab, the update dialog and the restart. Texts typed in fields are saved when the field loses the focus, on Done and when the screen closes. The TV shell shows SettingsScreenView over the window (Settings in the ⋮ menu of the bar): the categories on the left (the focused one is shown), its card on the right, its menus in the PopupMenuView of the shell (Item.checked marks the chosen option). The phone shell shows PhoneSettingsView (the list of categories, then the page of one; menus in the PhoneActionsSheet). Both draw the rows with SettingsRowsView, which keeps the view of each row by its id, so the focus stays when rows appear or go; the phone page lays ThemeOverlay.SimpleBrowser.Settings.Phone over it, which gives the tbSettings… size attributes their phone values (the TV ones are in Theme.SimpleBrowser). Switches, sliders and segments are drawn with ds_switch_*, ds_slider_* and ds_settings_segment_bg; there is no segmented button library.
History. VisitedHistoryLogger saves a visit (onVisited of the engine) after a few seconds, dropping the quick ones (redirects). A visit gets only a title received for its own url: engines report the visit when the page commits, before its title, and pages that change their url themselves (history.pushState) start no load, so BrowserController matches titles with the url of the engine (webEngine.url), not tab.url. What the history screens show and do is in HistoryNavigator (no views): the whole history is loaded when a screen opens (HistoryRepository.all(), trim keeps it small) and searched in memory (each word of the query in the title or the url, ignoring case also outside ASCII, which SQLite's LIKE does not fold), the options of a row, the selection mode (a long press) with Select all and Delete, Clear all. The TV shell shows HistoryScreenView over the window (History in the ⋮ menu of the bar), the phone shell PhoneHistoryView (its search field takes the place of the title); rows are bound by HistoryRowBinder, which marks the words found.
Favicons. FaviconsPool (in :app:common) gives the icon of a host: from memory, from its file in the cache dir (favicons/, named in HostConfig.favicon), else from the network, where FaviconExtractor reads the <link>s of the page's head and its web manifest (/favicon.ico is always the last candidate) and FaviconExtractor.rank orders them for TARGET_SIZE: the smallest at least that big, then the biggest from MIN_SHARP_SIZE, then those of unknown size, then the small ones; SVG is skipped (BitmapFactory can not decode it). Up to a few are downloaded until one is sharp enough; icons are kept at most MAX_STORED_SIZE. One load per host runs at a time in the pool's own scope (callers only wait, so a recycled row cancels nothing), at most a few fetch at once, and a host whose page gave none is not asked again for 10 minutes. The icon a web engine reports (WebView's onReceivedIcon, mostly 16–32 px) is only provisional: onEngineIcon shows it at once (get gives it, the tab is updated), looks at the page and keeps the bigger one. A saved icon below MIN_SHARP_SIZE whose file is older than a week is looked up again in the background (a failed look touches the file); the UI shows the new one when it asks again. Nothing is written while incognito mode is on. The app's requests here have timeouts, a browser User-Agent and follow redirects from http to https (FaviconExtractor.open).
Sync of a phone with a TV. A phone sends tabs and bookmarks to a paired TV over the local network (sync package, in :app, the same in both apps, so a phone of one app pairs with a TV of the other). The TV shell runs a SyncServer while the activity is started (on the same port each time if it is free, advertised with NSD by SyncDiscovery); the phone is only a client (SyncClient). Pairing: the TV screen TvSyncScreenView (Phone sync in the ⋮ menu of the bar) shows the QR code of a SyncLink (https://sb.robsoncassiano.software/sync#…: the addresses and port of the TV and a one-time secret in the fragment); the camera opens it in the app (the App Link filter of MainActivity, verified by public/.well-known/assetlinks.json of the tv-bro-web repository, which lists the four packages and their signing keys), or else the page public/sync/index.html of the site opens there and hands the link to the app as simplebrowser://sync#…; MainActivity gives it to BrowserShell.handleSyncLink, and a link that was used already is ignored (Android gives a recreated activity its first intent again). SyncChannel is the encrypted channel: a handshake in the clear (nonces, the pairing id), then JSON frames sealed with AES-GCM by keys derived with HKDF from the shared key (the secret of the QR code, then the pairing key the TV gives). Both sides keep the pairing in paired_devices (PairedDevicesRepository; the key is wrapped by a key of the Android keystore, SyncKeyStore, so restored backups do not carry it). Requests (SyncRequests): open tabs (http and https only), get all bookmarks, preview and replace bookmarks, send a file, forget. A TV tells the requests it handles (DeviceInfo.capabilities), so a new request is a capability and not a new PROTOCOL (it is in the keys and the QR link). Files (files.send, Send files on the phone page, chosen with the picker of the system; the TV takes them from paired phones without asking): the TV answers ready, the phone sends sealed frames of bytes (SyncChannel.sendBytes, in the order of the messages) and an empty one at the end, the TV answers with the name it saved; a TV that can not go on sends an error and closes the connection (the phone checks hasIncoming between chunks). The TV makes the name safe (safeFileName: no folders, freeFile builds a File of it before Android 11) and takes the type of the extension. PhoneFileReceiver saves them as downloads: DownloadLauncher.receive inserts the row (url tvbro-phone:<phone>, so it is not downloaded again and its caption shows the phone; not resumable) and gives the write end of the reliable pipe of StreamDownloadTask, which the session fills (closeWithError when the file did not come whole, so the service drops it); the TV answers when the row ends. The storage permission of Android 10 and older is asked for and the phone told to send again (it does not wait for the dialog). Bookmarks go both ways as a SyncBookmark tree of what the user chose (BookmarkSelection, from the bookmarks of the phone, or from the tree the TV gives for the phone to take): BookmarksReplacer makes a folder chosen in full the same on the device that gets it and only adds to a folder chosen in part. LocalBookmarks does it for both sides (the TV for a phone, the phone for bookmarks it takes): in one transaction, after a dry run that the phone showed to the user (refused if it would now change something else), keeping the bookmarks of before in a BookmarksBackup for Undo (on the TV screen of the pairing, and on the screen of a TV on the phone). The phone page is PhoneSyncView drawing PhoneSyncNavigator (Send to TV in the menu sheet); it asks for the local network permission first. Debug builds log the pairing link of the TV (SyncServer), which can be opened on a phone with adb shell am start -a android.intent.action.VIEW -d '<link>' when no camera can scan it; -PdebugApplicationIdSuffix=.dev installs a debug build next to a release one.
Global singletons. AppContext.get() and AppContext.provideConfig() (initialized in SimpleBrowser.onCreate) give :app:common code access to the Application and the Config SharedPreferences wrapper. The Room database (AppDatabase, its schema version and hand-written migrations are in singleton/AppDatabase.kt) is opened by AppContainer.database; the app and the UI reach the data only through the repositories of AppContainer.data (data package: tabs, history, favorites, downloads, host configs), never through DAOs. SimpleBrowser.container (AppContainer; code that only needs a Context uses AppContext.get(), not the SimpleBrowser instance) also holds the application-wide appScope and tabWrites, a SerialWriteQueue through which all tab database and file writes go: they run one by one and are not cancelled with the activity or the model. Code that exits the process (exitProcess) waits for tabWrites.awaitPending() first, asynchronously; to exit (and optionally restart) when MainActivity finishes, call SimpleBrowser.exitProcessAfterMainActivityFinish.
Flavors. BUILT_IN_AUTO_UPDATE (a BuildConfig field) is true only for generic. The auto-updater reads latest_version.json from the repo (release/beta channels). UpdateChecker compares latestVersionCode with BuildConfig.VERSION_CODE and downloads the channel's url (the generic APK). foss adds the .foss applicationId suffix.
Home page. about:home (Config.HOME_URL_ALIAS) is resolved by HomePageUrl in the core according to the home page mode; the built-in home page is Config.HOME_PAGE_URL. The page itself is in app/src/main/assets/pages/home (index.html and index.js, no inline scripts or handlers), and WebView serves it in shouldInterceptRequest under Config.HOME_PAGE_URL. When Config.HOME_REMOTE_SERVE is on, requests pass through to the network URL instead (the Cloudflare-hosted copy). The page talks to the app through the SimpleBrowser object added by WebView's AndroidJSInterface.
Error pages. The certificate warning of WebView (app/src/main/assets/pages/warning-certificate.html) and the load error page (app/common/src/main/assets/pages/error.html) are HTML templates drawn with the tokens of the design system (light and dark through prefers-color-scheme, a phone layout under 600px). The engine fills their {{name}} holes with ErrorPageTemplate.fill (escaped values: localized strings of :app:common, the host, the error) before loading them, so they need no bridge to show the error; only "Continue" of the certificate warning calls SimpleBrowser.reloadWithSslTrust(). LoadErrorPage.create fills the load error page for a LoadErrorKind (insecure, dangerous, crashed, network, generic: the state of the page, which picks its glyph and buttons); WebView maps its errors to it (WebViewLoadErrors). WebView has no way to restyle its own error page: WebViewEx.onReceivedError (main frame only, not for the certificate warning) keeps the page, and when WebView's error page finishes loading the page is written over it with document.write (WebViewLoadErrors.replaceDocumentScript), which adds no history entry; the script of the page is in a function (the globals of WebView's page stay) and sets TVBRO_errorPage, and when that is not set the page is loaded with loadDataWithBaseURL instead. Safe Browsing of WebView is always on (not tied to ad blocking); a hit of the main frame (onSafeBrowsingHit) is answered with backToSafety, so the load fails with ERROR_UNSAFE_RESOURCE and the page of a dangerous site shows the threat type. When the renderer of WebView dies (onRenderProcessGone, which returns true: false ends the app), the engine drops its view; the current tab tells the core (TabEngineEvents.onEngineViewLost), which attaches a new view, and the engine shows the crashed page for the lost url in it (Reload loads it again); a background tab gets a new view, restored from its saved state, when it is shown.
Look. Colors come from theme tokens: ?attr/tbColor… attributes (values/attrs.xml) that Theme.SimpleBrowser maps to the semantic palette in values/colors.xml (night values in values-night). Layouts and drawables use the attributes, never hex colors or palette colors directly; code uses Context.themeColor(R.attr…). Attributes need a themed (activity) context: do not inflate such views or drawables with the application context. A theme attribute does not resolve in android:drawable of a selector item (the drawable fails to load): put the color in a <color> or <shape> element inside the item. ThemeResourcesTest loads every drawable and color of the app with the app theme. The redesigned screens (the TV bar, the phone UI) use the tokens of the "Simple Browser" design system instead: ?attr/tbColorDs… attributes named as in its tokens.json (mapped to ds_… palette colors, night values in values-night; tbColorDsDanger is only for the glyphs of an insecure connection, never a fill), ds_… dimens, the Widget.SimpleBrowser.Text.Address/Toast/MenuItem/TabTitle/CountBadge styles and the ds_… state drawables (focused also when hovered by the cursor, selected when activated or selected). The other screens keep the older tbColor… palette until they are redesigned. Widgets get their look from styles in values/styles.xml, set with style="..." on each view: Widget.SimpleBrowser.Button/Widget.SimpleBrowser.ImageButton (the app button background; .Ds.Segment, .Ds.Standalone and .Ds.Field are the buttons of the redesigned bar, .Ds.CursorMenu the round buttons on the plate of the cursor menu) and Widget.SimpleBrowser.Text.* for text sizes (Headline, Title, Subtitle, Body, Caption, Badge; sizes in values/dimens.xml). These text styles set only textSize: a textAppearance would replace the default text color of the view. The theme sets no widget defaults (buttonStyle and others), so a view without a style keeps the platform look. Alert dialogs are the exception: Theme.SimpleBrowser sets alertDialogTheme to ThemeOverlay.SimpleBrowser.Dialog.Alert (the ds_dialog_bg window, ink text, Widget.SimpleBrowser.DialogButton buttons, ds_menu_row_bg list rows), so dialogs use androidx.appcompat.app.AlertDialog, never android.app.AlertDialog or ProgressDialog, which ignore it; DialogThemeTest checks the day and night looks. Repeated spacing values are dimens (settings_content_padding, list_item_padding_*). Icons are one vector per glyph with a role name (ic_back, ic_close, ic_favorites…): white paths and android:tint="@color/icon_tint", which gives the icon color and the disabled one for a disabled view, so there are no per-color copies or selectors swapping images. A view that needs another color sets app:tint with a token (tbColorIconSubtle for the bookmark edit and delete buttons). An icon needed at another size in a wrap_content button gets a layer-list wrapper with the size, not a fixed view size: the button is then rounded to pixels like other icons of that size.
Lists. Lists are RecyclerViews with focusable rows (Widget.SimpleBrowser.ListItem: focusable, list_item_bg_selector background); there is no ListView left. The rows of the settings are the exception: they are a form (SettingsRowsView, see Settings), not a list. History and downloads are lists grouped by days (widgets/datedlist): DatedListAdapter (a ListAdapter that builds the header rows from the items, diffed in the background; act on the new rows in the submitItems callback), StickyHeaderDecoration (the pinned header of the top day with its shadow; items that are isPinned make a group of their own before the days, like the downloads in progress), ListDividerDecoration (its color and height can be given), and StickyHeaderLayoutManager (scrolls a focused row out from under the pinned header). They are in a NearestFocusRecyclerView: focus coming into the list from another view (nextFocus... set to the list) goes to the row nearest to that view, as in a ListView, and a focus request made while the layout is pending keeps the row that got it.
Releases use the manual .github/workflows/release.yml workflow (workflow_dispatch with a version). It runs assembleGenericRelease, renames the APK to simple-browser-<version>-generic.apk, and publishes a GitHub release whose body is RELEASE_NOTES.md. A version bump touches versionCode/versionName in app/build.gradle.kts, latest_version.json and RELEASE_NOTES.md. The app reads latest_version.json from master on GitHub, so changes to it go live once merged. The channel has a single url (the generic APK), minAPI 24 and no urls.