web: tab grid with previews, site icons and gestures
- Commit
fede07b62efd60211d33e67600eea0cffd189bf6- Author
- vayun-mathur <[email protected]>
- When
- 2026-09-04 06:19 UTC (3 months ago)
- Parents
23a983d
Diff
metadata_data/photos/web/1.png
diff --git a/metadata_data/photos/web/1.png b/metadata_data/photos/web/1.pngindex 1c07f6abf6..b2cd5f6b66 100644Binary files a/metadata_data/photos/web/1.png and b/metadata_data/photos/web/1.png differ
metadata_data/photos/web/2.png
diff --git a/metadata_data/photos/web/2.png b/metadata_data/photos/web/2.pngindex 53e9bb44e6..610dbba461 100644Binary files a/metadata_data/photos/web/2.png and b/metadata_data/photos/web/2.png differ
web/src/main/java/com/vayunmathur/web/MainActivity.kt
diff --git a/web/src/main/java/com/vayunmathur/web/MainActivity.kt b/web/src/main/java/com/vayunmathur/web/MainActivity.ktindex 0349309556..2b3399bbde 100644--- a/web/src/main/java/com/vayunmathur/web/MainActivity.kt+++ b/web/src/main/java/com/vayunmathur/web/MainActivity.kt@@ -19,7 +19,10 @@ import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.TrustBundle import com.vayunmathur.library.ui.DynamicTheme import com.vayunmathur.library.util.OfflineAware+import com.vayunmathur.web.data.FaviconStore+import com.vayunmathur.web.data.TabThumbnailStore import com.vayunmathur.web.data.WebRepository+import com.vayunmathur.web.platform.BrowserTab import com.vayunmathur.web.platform.shields.ShieldsEngine import com.vayunmathur.web.platform.shields.ShieldsServiceWorkerClient import com.vayunmathur.web.platform.WebViewModel@@ -27,6 +30,7 @@ import com.vayunmathur.web.platform.WebViewModelFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json class MainActivity : ComponentActivity() { @@ -44,6 +48,9 @@ class MainActivity : ComponentActivity() { // Before any WebView exists: service-worker fetches bypass the WebViewClient entirely. ShieldsServiceWorkerClient.registerOnce(applicationContext) + TabThumbnailStore.init(applicationContext)+ FaviconStore.init(applicationContext)+ // Each task (window) carries its own window id + incognito flag so it keeps an independent tab set. val windowId = intent?.getStringExtra(EXTRA_WINDOW_ID) ?: WebViewModel.DEFAULT_WINDOW_ID val incognito = intent?.getBooleanExtra(EXTRA_INCOGNITO, false) ?: false@@ -147,7 +154,7 @@ class MainActivity : ComponentActivity() { val sp = getSharedPreferences("web_prefs", MODE_PRIVATE) val editor = sp.edit()- var changed = false+ val removedKeys = mutableSetOf<String>() for (key in sp.all.keys) { val windowId = when { key.startsWith(savedTabsPrefix) -> key.removePrefix(savedTabsPrefix)@@ -156,10 +163,26 @@ class MainActivity : ComponentActivity() { } ?: continue if (windowId !in liveWindowIds) { editor.remove(key)- changed = true+ removedKeys.add(key) } }- if (changed) editor.apply()+ if (removedKeys.isNotEmpty()) editor.apply()++ // Whatever tab sets survived the prune are the only tabs that can still be+ // shown, so every other thumbnail file is unreachable.+ val json = Json { ignoreUnknownKeys = true }+ val liveTabIds = sp.all+ .filterKeys { it == "web_saved_tabs" || it.startsWith(savedTabsPrefix) }+ .filterKeys { it !in removedKeys }+ .values+ .filterIsInstance<String>()+ .flatMap { saved ->+ runCatching { json.decodeFromString<List<BrowserTab>>(saved) }+ .getOrDefault(emptyList())+ .map { it.id }+ }+ .toSet()+ TabThumbnailStore.retainOnly(liveTabIds) } catch (e: Exception) { android.util.Log.e("MainActivity", "pruneClosedWindowTabs failed", e) }
web/src/main/java/com/vayunmathur/web/data/FaviconStore.kt
diff --git a/web/src/main/java/com/vayunmathur/web/data/FaviconStore.kt b/web/src/main/java/com/vayunmathur/web/data/FaviconStore.ktnew file mode 100644index 0000000000..40268dd868--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/data/FaviconStore.kt@@ -0,0 +1,132 @@+package com.vayunmathur.web.data++import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.util.Log+import androidx.compose.runtime.mutableStateMapOf+import com.vayunmathur.web.platform.BrowserUtils+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File+import java.security.MessageDigest+import java.util.concurrent.ConcurrentHashMap+import kotlin.math.max++private const val TAG = "FaviconStore"+private const val DIR_NAME = "favicons"+private const val EXT = ".webp"+private const val QUALITY = 90++/** Long edge of a stored icon, in pixels. Sites serve up to 256px; nothing here renders that big. */+private const val ICON_MAX_DIM = 64++/**+ * Site icons, keyed by host.+ *+ * Host rather than tab id so the tab grid and the new-tab recents list read the same store —+ * a recents entry is usually not an open tab and has no tab id to look up.+ *+ * Icons come only from `WebChromeClient.onReceivedIcon` on pages the user actually visited.+ * Deliberately no `/favicon.ico` fetch and no third-party favicon service: either would turn+ * rendering a list of hosts into a network request per host, and the recents list would then+ * announce browsing history the user never re-opened.+ *+ * Private tabs and incognito windows are memory-only, mirroring `persistTabsSync`. Persisted+ * icons live in `filesDir`, not `cacheDir`, so they survive a cache eviction.+ */+object FaviconStore {++ /** Snapshot state so an icon arriving mid-session recomposes whoever asked for it. */+ private val cache = mutableStateMapOf<String, Bitmap?>()++ private val loading = ConcurrentHashMap.newKeySet<String>()++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile+ private var appContext: Context? = null++ fun init(context: Context) {+ appContext = context.applicationContext+ }++ /**+ * The icon for [host] ("news.ycombinator.com" — no scheme, no port), or null if the user+ * has never loaded a page there. Compose-observable; a miss starts a disk read that+ * recomposes the caller if it finds something. Main thread only.+ */+ fun forHost(host: String): Bitmap? {+ val key = host.lowercase()+ if (key.isBlank()) return null+ if (cache.containsKey(key)) return cache[key]+ loadFromDisk(key)+ return null+ }++ /** [forHost] for callers holding a full URL. */+ fun forUrl(url: String): Bitmap? = forHost(BrowserUtils.hostFromUrl(url))++ /**+ * Records the icon a page reported. The bitmap is published to memory immediately so the+ * current session sees it, then downscaled and written off the main thread.+ */+ fun put(url: String, icon: Bitmap, isPrivate: Boolean) {+ if (!url.startsWith("http")) return+ val host = BrowserUtils.hostFromUrl(url).lowercase()+ if (host.isBlank()) return+ cache[host] = icon+ scope.launch {+ val scaled = runCatching { downscale(icon) }.getOrDefault(icon)+ if (scaled !== icon) withContext(Dispatchers.Main) { cache[host] = scaled }+ if (isPrivate) return@launch+ val file = fileFor(host) ?: return@launch+ runCatching {+ file.parentFile?.mkdirs()+ file.outputStream().use { scaled.compress(Bitmap.CompressFormat.WEBP_LOSSY, QUALITY, it) }+ }.onFailure { Log.w(TAG, "favicon write failed", it) }+ }+ }++ private fun loadFromDisk(host: String) {+ // Bail before recording anything if there is no usable file path: caching a negative+ // here would make the entry permanently absent, even after [init] later supplies a+ // context.+ val file = fileFor(host) ?: return+ if (!loading.add(host)) return+ scope.launch {+ val bitmap = runCatching {+ file.takeIf { it.exists() }?.let { BitmapFactory.decodeFile(it.absolutePath) }+ }.getOrNull()+ withContext(Dispatchers.Main) {+ // A page may have reported its icon while the read was in flight; that is+ // newer than anything on disk, so it wins.+ if (!cache.containsKey(host)) cache[host] = bitmap+ loading.remove(host)+ }+ }+ }++ private fun downscale(icon: Bitmap): Bitmap {+ val longEdge = max(icon.width, icon.height)+ if (longEdge <= ICON_MAX_DIM || longEdge == 0) return icon+ val scale = ICON_MAX_DIM.toFloat() / longEdge+ return Bitmap.createScaledBitmap(+ icon,+ max(1, (icon.width * scale).toInt()),+ max(1, (icon.height * scale).toInt()),+ true,+ )+ }++ /** Hosts can be punycode, very long, or contain characters a filename cannot. */+ private fun fileFor(host: String): File? {+ val context = appContext ?: return null+ val digest = MessageDigest.getInstance("SHA-256").digest(host.toByteArray())+ val name = digest.joinToString("") { "%02x".format(it) }+ return File(File(context.filesDir, DIR_NAME), name + EXT)+ }+}
web/src/main/java/com/vayunmathur/web/data/TabThumbnailStore.kt
diff --git a/web/src/main/java/com/vayunmathur/web/data/TabThumbnailStore.kt b/web/src/main/java/com/vayunmathur/web/data/TabThumbnailStore.ktnew file mode 100644index 0000000000..8b2a9dc9d2--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/data/TabThumbnailStore.kt@@ -0,0 +1,131 @@+package com.vayunmathur.web.data++import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.util.Log+import android.webkit.WebView+import androidx.compose.runtime.mutableStateMapOf+import com.vayunmathur.web.platform.captureThumb+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.io.File+import java.util.concurrent.ConcurrentHashMap++private const val TAG = "TabThumbnailStore"+private const val DIR_NAME = "tab-thumbs"+private const val EXT = ".webp"+private const val QUALITY = 70++/** Tab ids are UUIDs; anything else is refused rather than turned into a file path. */+private val SAFE_ID = Regex("[A-Za-z0-9_-]{1,64}")++/**+ * Page thumbnails, keyed by tab id.+ *+ * Process-wide rather than per-[com.vayunmathur.web.platform.WebViewModel] because the cache+ * directory is shared by every window and has to be reaped from `MainActivity`, before any+ * view model exists.+ *+ * Private tabs and incognito windows are memory-only, mirroring `persistTabsSync`.+ */+object TabThumbnailStore {++ /**+ * Snapshot state so a capture that lands later recomposes the grid. A null value means+ * "looked on disk, nothing there" and stops [get] from re-reading on every recomposition.+ */+ private val cache = mutableStateMapOf<String, Bitmap?>()++ /** Disk reads in flight, so a grid of tiles asking at once only reads each file once. */+ private val loading = ConcurrentHashMap.newKeySet<String>()++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ @Volatile+ private var appContext: Context? = null++ fun init(context: Context) {+ appContext = context.applicationContext+ }++ /**+ * The thumbnail for [tabId], or null when there isn't one yet — a tab restored from a cold+ * start has no WebView to draw until it is visited. Compose-observable; a miss starts a+ * disk read that recomposes the caller if it finds something. Main thread only.+ */+ fun get(tabId: String): Bitmap? {+ if (cache.containsKey(tabId)) return cache[tabId]+ loadFromDisk(tabId)+ return null+ }++ /**+ * Draws [webView] and stores the result. The draw has to happen on the main thread and on+ * the caller's frame — that is the whole point, it is what makes the tile match what the+ * user is looking at — but compressing and writing it are handed off.+ */+ fun capture(tabId: String, webView: WebView, isPrivate: Boolean) {+ val bitmap = captureThumb(webView) ?: return+ cache[tabId] = bitmap+ if (isPrivate) return+ val file = fileFor(tabId) ?: return+ scope.launch {+ runCatching {+ file.parentFile?.mkdirs()+ file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.WEBP_LOSSY, QUALITY, it) }+ }.onFailure { Log.w(TAG, "thumbnail write failed", it) }+ }+ }++ /** Drops a closed tab's thumbnail from memory and disk. */+ fun remove(tabId: String) {+ cache.remove(tabId)+ val file = fileFor(tabId) ?: return+ scope.launch { runCatching { file.delete() } }+ }++ /**+ * Deletes cached thumbnails for tabs that no longer exist in any window. Without this the+ * directory keeps a file per tab the user has ever opened.+ */+ fun retainOnly(liveTabIds: Set<String>) {+ val dir = dir() ?: return+ scope.launch {+ runCatching {+ dir.listFiles()?.forEach { file ->+ if (file.name.removeSuffix(EXT) !in liveTabIds) file.delete()+ }+ }.onFailure { Log.w(TAG, "thumbnail reap failed", it) }+ }+ }++ private fun loadFromDisk(tabId: String) {+ // Bail before recording anything if there is no usable file path: caching a negative+ // here would make the entry permanently absent, even after [init] later supplies a+ // context.+ val file = fileFor(tabId) ?: return+ if (!loading.add(tabId)) return+ scope.launch {+ val bitmap = runCatching {+ file.takeIf { it.exists() }?.let { BitmapFactory.decodeFile(it.absolutePath) }+ }.getOrNull()+ withContext(Dispatchers.Main) {+ // A capture may have landed while the read was in flight; it is newer than+ // anything on disk, so it wins.+ if (!cache.containsKey(tabId)) cache[tabId] = bitmap+ loading.remove(tabId)+ }+ }+ }++ private fun dir(): File? = appContext?.let { File(it.cacheDir, DIR_NAME) }++ private fun fileFor(tabId: String): File? {+ if (!SAFE_ID.matches(tabId)) return null+ return dir()?.let { File(it, tabId + EXT) }+ }+}
web/src/main/java/com/vayunmathur/web/platform/ThumbnailCapture.kt
diff --git a/web/src/main/java/com/vayunmathur/web/platform/ThumbnailCapture.kt b/web/src/main/java/com/vayunmathur/web/platform/ThumbnailCapture.ktnew file mode 100644index 0000000000..bff2346f38--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/platform/ThumbnailCapture.kt@@ -0,0 +1,38 @@+package com.vayunmathur.web.platform++import android.graphics.Bitmap+import android.graphics.Canvas+import android.view.View+import kotlin.math.max++/** Long edge of a stored thumbnail, in pixels. */+const val THUMB_MAX_DIM = 512++/**+ * Draws [view] into a downscaled bitmap, or null if it has never been laid out.+ *+ * PixelCopy is wrong here twice over: it reads the window's surface, so it would capture the+ * Compose chrome painted over the WebView rather than the page, and it only works on views+ * attached to a window, while the pool holds detached ones. `getDrawingCache` is deprecated+ * and allocates at full resolution on the main thread.+ *+ * Must run on the main thread — `View.draw` is not thread safe. Draws straight at the target+ * scale so there is no full-size intermediate to resize afterwards.+ */+fun captureThumb(view: View): Bitmap? {+ val width = view.width+ val height = view.height+ if (width <= 0 || height <= 0) return null+ val scale = (THUMB_MAX_DIM.toFloat() / max(width, height)).coerceAtMost(1f)+ return runCatching {+ val bitmap = Bitmap.createBitmap(+ max(1, (width * scale).toInt()),+ max(1, (height * scale).toInt()),+ Bitmap.Config.ARGB_8888,+ )+ val canvas = Canvas(bitmap)+ canvas.scale(scale, scale)+ view.draw(canvas)+ bitmap+ }.getOrNull()+}
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 ce1edbc007..80f3ac6678 100644--- a/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt+++ b/web/src/main/java/com/vayunmathur/web/platform/WebViewModel.kt@@ -5,8 +5,10 @@ package com.vayunmathur.web.platform import kotlin.uuid.Uuid import android.content.Context import android.content.pm.PackageManager+import android.graphics.Bitmap import android.net.Uri import android.util.Log+import android.webkit.WebView import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateMapOf@@ -17,9 +19,11 @@ 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.FaviconStore import com.vayunmathur.web.data.HistoryEntry import com.vayunmathur.web.data.InstalledSite import com.vayunmathur.web.data.SitePermission+import com.vayunmathur.web.data.TabThumbnailStore import com.vayunmathur.web.data.WebRepository import com.vayunmathur.web.data.ShieldSetting import com.vayunmathur.web.data.StorageInfo@@ -186,6 +190,12 @@ class WebViewModel( private val json = Json { ignoreUnknownKeys = true } + /**+ * Resolves a tab's live WebView. `BrowserPage` owns the pool, so tab-lifecycle code here+ * has no other way to reach the view it needs to draw before a tab stops being active.+ */+ private var liveWebViews: ((String) -> WebView?)? = null+ init { viewModelScope.launch { withContext(Dispatchers.IO) {@@ -380,6 +390,31 @@ class WebViewModel( fun blockedCount(tabId: String): Int = blockedCounts[tabId] ?: 0 + // ---- Thumbnails and favicons ----++ fun setWebViewLookup(lookup: ((String) -> WebView?)?) { liveWebViews = lookup }++ /** The tab's page thumbnail, or null when there isn't one yet. Compose-observable. */+ fun thumbnailFor(tabId: String): Bitmap? = TabThumbnailStore.get(tabId)++ /** The site icon for [url]'s host, or null if that host has never been visited. */+ fun faviconFor(url: String): Bitmap? = FaviconStore.forUrl(url)++ fun captureThumbnail(tabId: String, webView: WebView) {+ val tab = tabs.find { it.id == tabId } ?: return+ // A blank new tab would store a white rectangle, which reads worse than the+ // placeholder the grid draws when there is no thumbnail at all.+ if (tab.isNewTab) return+ TabThumbnailStore.capture(tabId, webView, incognito || tab.isPrivate)+ }++ /** Draws the tab that is about to stop being active, so its tile is not left stale. */+ private fun captureActiveTab() {+ val id = activeTabId ?: return+ val webView = liveWebViews?.invoke(id) ?: return+ captureThumbnail(id, webView)+ }+ val activeTab: BrowserTab? get() = tabs.find { it.id == activeTabId } fun onTabUrlChange(tabId: String, url: String) {@@ -431,6 +466,7 @@ class WebViewModel( } fun newTab(url: String = "", makeActive: Boolean = true, isPrivate: Boolean = false) {+ if (makeActive) captureActiveTab() // 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)@@ -455,6 +491,7 @@ class WebViewModel( blockedCounts.remove(tabId) blockedTotals.remove(tabId) pwaInfos.remove(tabId)+ TabThumbnailStore.remove(tabId) if (activeTabId == tabId) { activeTabId = when { tabs.isEmpty() -> {@@ -472,7 +509,18 @@ class WebViewModel( persistTabs() } + /**+ * Tab order is the persisted order — [persistTabsSync] writes the list as it stands — so a+ * reorder needs nothing beyond moving the entry and saving.+ */+ fun moveTab(from: Int, to: Int) {+ if (from == to || from !in tabs.indices || to !in tabs.indices) return+ tabs.add(to, tabs.removeAt(from))+ persistTabs()+ }+ fun switchToTab(tabId: String) {+ if (tabId != activeTabId) captureActiveTab() activeTabId = tabId val cur = activeTab omniboxText = if (cur == null || cur.url.isBlank() || cur.url == "about:blank") "" else cur.url
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 e3f38f84a5..78801f8444 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BookmarksPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BookmarksPage.kt@@ -82,7 +82,7 @@ fun BookmarksPage( */ @OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class) @Composable-private fun BookmarksScreen(+internal fun BookmarksScreen( bookmarks: List<Bookmark>, folders: List<BookmarkFolder>, navigationIcon: @Composable () -> Unit = {},
web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.ktindex 7cb29eb2a4..7686a83f45 100644--- a/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/BrowserPage.kt@@ -1,6 +1,5 @@ package com.vayunmathur.web.ui -import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import com.vayunmathur.web.R import android.webkit.WebView@@ -27,11 +26,11 @@ import androidx.compose.foundation.layout.statusBars import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items-import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.key@@ -67,7 +66,6 @@ import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.LinearProgressIndicator import com.vayunmathur.library.ui.ListItem import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.OutlinedTextField import com.vayunmathur.library.ui.Scaffold import com.vayunmathur.library.ui.Surface@@ -75,7 +73,6 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.TopAppBar import com.vayunmathur.library.ui.TopAppBarDefaults-import com.vayunmathur.library.ui.IconAdd import com.vayunmathur.library.ui.IconArrowForward import com.vayunmathur.library.ui.IconBack import com.vayunmathur.library.ui.IconClose@@ -92,6 +89,7 @@ import com.vayunmathur.web.platform.PwaInfo import com.vayunmathur.web.platform.WebPermissions import com.vayunmathur.web.platform.WebViewModel import com.vayunmathur.web.platform.isNewTab+import com.vayunmathur.web.ui.components.SiteIcon @OptIn(ExperimentalMaterial3Api::class) @Composable@@ -104,6 +102,14 @@ fun BrowserPage( val keyboardController = LocalSoftwareKeyboardController.current val webViewPool = remember { mutableStateMapOf<String, WebView>() } + // The view model captures a thumbnail of a tab as it stops being active, and the live+ // WebViews only exist here. Cleared on dispose so the pool's WebViews are not kept alive+ // by the longer-lived view model.+ DisposableEffect(Unit) {+ viewModel.setWebViewLookup { tabId -> webViewPool[tabId] }+ onDispose { viewModel.setWebViewLookup(null) }+ }+ LaunchedEffect(viewModel.tabs.size) { if (viewModel.tabs.isEmpty()) viewModel.newTab() }@@ -368,7 +374,12 @@ fun BrowserPage( viewModel.searchDraft = full viewModel.omniboxFocused = true },- onTabSwitcherClick = { viewModel.showTabSwitcher = true },+ onTabSwitcherClick = {+ // Before the switcher opens, so the active tile shows the page as the user+ // left it rather than wherever it was when it last finished loading.+ activeTab?.let { tab -> webViewPool[tab.id]?.let { viewModel.captureThumbnail(tab.id, it) } }+ viewModel.showTabSwitcher = true+ }, shieldHost = shieldHost, blockedCount = activeTab?.let { viewModel.blockedCount(it.id) } ?: 0, onShieldClick = { viewModel.showShieldsPanel = true },@@ -439,6 +450,7 @@ fun BrowserPage( bookmarks = bookmarks.take(12), history = history.take(8), onOpenUrl = { url -> activeTab?.let { viewModel.onTabUrlChange(it.id, url) } },+ faviconFor = viewModel::faviconFor, modifier = Modifier.fillMaxSize() ) } else if (activeTab != null) {@@ -471,6 +483,7 @@ fun BrowserPage( activeTabId = viewModel.activeTabId, onSwitch = { viewModel.switchToTab(it) }, onClose = { viewModel.closeTab(it) },+ onReorder = { from, to -> viewModel.moveTab(from, to) }, onNewTab = { viewModel.newTab(isPrivate = viewModel.incognito || viewModel.activeTab?.isPrivate == true) }, onNewIncognitoTab = { viewModel.newTab(isPrivate = true) }, onNewWindow = {@@ -483,7 +496,9 @@ fun BrowserPage( }, isIncognitoWindow = viewModel.incognito || viewModel.activeTab?.isPrivate == true, onDismiss = { viewModel.showTabSwitcher = false },- modifier = Modifier.fillMaxSize()+ modifier = Modifier.fillMaxSize(),+ thumbnailFor = viewModel::thumbnailFor,+ faviconFor = viewModel::faviconFor, ) } @@ -656,7 +671,7 @@ fun BrowserPage( @OptIn(ExperimentalMaterial3Api::class) @Composable-private fun BrowserChrome(+internal fun BrowserChrome( omniboxText: String, tabCount: Int, canGoBack: Boolean = false,@@ -810,11 +825,12 @@ private fun DisplayOnlyAddressPill( } @Composable-private fun QuickAccess(+internal fun QuickAccess( bookmarks: List<com.vayunmathur.web.data.Bookmark>, history: List<com.vayunmathur.web.data.HistoryEntry>, onOpenUrl: (String) -> Unit, modifier: Modifier = Modifier,+ faviconFor: (String) -> android.graphics.Bitmap? = { null }, ) { LazyColumn( modifier = modifier.fillMaxSize().background(MaterialTheme.colorScheme.background).padding(16.dp),@@ -830,9 +846,12 @@ private fun QuickAccess( colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.secondaryContainer) ) { Column(Modifier.padding(12.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {- Box(Modifier.size(28.dp).clip(CircleShape).background(MaterialTheme.colorScheme.surface), contentAlignment = Alignment.Center) {- Text(bm.title.take(1).uppercase().ifBlank { "B" }, style = MaterialTheme.typography.titleSmall)- }+ SiteIcon(+ icon = faviconFor(bm.url),+ label = bm.title.ifBlank { BrowserUtils.hostFromUrl(bm.url) },+ modifier = Modifier.size(28.dp),+ containerColor = MaterialTheme.colorScheme.surface,+ ) Text(bm.title.ifBlank { BrowserUtils.hostFromUrl(bm.url) }, maxLines = 2, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall) } }@@ -847,11 +866,11 @@ private fun QuickAccess( modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(12.dp)).clickable { onOpenUrl(entry.url) }.padding(12.dp), verticalAlignment = Alignment.CenterVertically ) {- Surface(shape = CircleShape, color = MaterialTheme.colorScheme.surfaceVariant, modifier = Modifier.size(36.dp)) {- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {- Text(entry.title.take(1).uppercase().ifBlank { "H" }, style = MaterialTheme.typography.titleSmall)- }- }+ SiteIcon(+ icon = faviconFor(entry.url),+ label = entry.title.ifBlank { BrowserUtils.hostFromUrl(entry.url) },+ modifier = Modifier.size(36.dp),+ ) Spacer(Modifier.width(12.dp)) Column(Modifier.weight(1f)) { Text(entry.title.ifBlank { entry.url }, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodyMedium)@@ -870,78 +889,3 @@ private fun QuickAccess( } } }--/** Already stateless — public only so the store-listing previews can render it. */-@Composable-private fun TabSwitcher(- tabs: List<com.vayunmathur.web.platform.BrowserTab>,- activeTabId: String?,- onSwitch: (String) -> Unit,- onClose: (String) -> Unit,- onNewTab: () -> Unit,- onNewIncognitoTab: () -> Unit = {},- onNewWindow: () -> Unit = onNewTab,- onNewIncognitoWindow: () -> Unit = onNewIncognitoTab,- onDismiss: () -> Unit,- modifier: Modifier = Modifier,- isIncognitoWindow: Boolean = tabs.find { it.id == activeTabId }?.isPrivate == true,-) {- Box(modifier = modifier.fillMaxSize().background(MaterialTheme.colorScheme.background.copy(alpha = 0.98f))) {- Column(Modifier.fillMaxSize()) {- TopAppBar(- title = { Text(pluralStringResource(R.plurals.tabs, tabs.size, tabs.size)) },- navigationIcon = { com.vayunmathur.library.ui.IconButton(onClick = onDismiss) { IconClose() } },- actions = { com.vayunmathur.library.ui.IconButton(onClick = onNewTab) { IconAdd() } }- )- LazyColumn(Modifier.fillMaxSize().padding(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- items(tabs, key = { it.id }) { tab ->- val isActive = tab.id == activeTabId- val displayTitle = when {- tab.isNewTab -> "New Tab"- tab.title.isNotBlank() -> tab.title- else -> BrowserUtils.prettyUrl(tab.url).ifBlank { "New Tab" }- }- val displayUrl = if (tab.isNewTab) "" else tab.url- Card(- modifier = Modifier.fillMaxWidth().clickable { onSwitch(tab.id) },- colors = CardDefaults.cardColors(containerColor = if (isActive) MaterialTheme.colorScheme.secondaryContainer else MaterialTheme.colorScheme.surfaceVariant),- shape = RoundedCornerShape(16.dp)- ) {- Row(Modifier.fillMaxWidth().padding(12.dp), verticalAlignment = Alignment.CenterVertically) {- Column(Modifier.weight(1f)) {- Row(verticalAlignment = Alignment.CenterVertically) {- if (tab.isPrivate) Text(stringResource(R.string.private_prefix), style = MaterialTheme.typography.labelSmall)- Text(displayTitle, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.titleSmall)- }- if (displayUrl.isNotBlank()) {- Text(displayUrl, maxLines = 1, overflow = TextOverflow.Ellipsis, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)- }- }- com.vayunmathur.library.ui.IconButton(onClick = { onClose(tab.id) }) { IconClose() }- }- }- }- item {- Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedButton(- onClick = {- if (isIncognitoWindow) onNewIncognitoTab() else onNewTab()- },- modifier = Modifier.fillMaxWidth()- ) {- Text(- stringResource(- if (isIncognitoWindow) R.string.new_incognito_tab else R.string.new_tab- )- )- }- Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {- OutlinedButton(onClick = onNewWindow, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.new_window)) }- OutlinedButton(onClick = onNewIncognitoWindow, modifier = Modifier.weight(1f)) { Text(stringResource(R.string.new_incognito_window)) }- }- }- }- }- }- }-}
web/src/main/java/com/vayunmathur/web/ui/TabSwitcher.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/TabSwitcher.kt b/web/src/main/java/com/vayunmathur/web/ui/TabSwitcher.ktnew file mode 100644index 0000000000..fde13fd389--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/TabSwitcher.kt@@ -0,0 +1,205 @@+package com.vayunmathur.web.ui++import android.graphics.Bitmap+import androidx.compose.animation.core.animate+import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.grid.GridCells+import androidx.compose.foundation.lazy.grid.GridItemSpan+import androidx.compose.foundation.lazy.grid.LazyVerticalGrid+import androidx.compose.foundation.lazy.grid.items+import androidx.compose.foundation.lazy.grid.rememberLazyGridState+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableFloatStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.graphicsLayer+import androidx.compose.ui.layout.onSizeChanged+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.compose.ui.zIndex+import com.vayunmathur.library.ui.HorizontalFlick+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Motion+import com.vayunmathur.library.ui.OutlinedButton+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TopAppBar+import com.vayunmathur.library.ui.itemMotion+import com.vayunmathur.library.ui.rememberHaptics+import com.vayunmathur.library.ui.rememberReorderableLazyGridState+import com.vayunmathur.library.ui.reorderGridDragHandle+import com.vayunmathur.web.R+import com.vayunmathur.web.platform.BrowserTab+import com.vayunmathur.web.ui.components.TabTile+import kotlinx.coroutines.launch+import kotlin.math.abs++/** Fixed rather than adaptive: two columns is what makes a tile big enough to recognise a page in. */+private const val COLUMNS = 2++/** How far across itself a tile has to travel before letting go of it closes the tab. */+private const val FLICK_FRACTION = 0.4f++/**+ * The alternative to [FLICK_FRACTION], in px/s: a short, fast throw means the same thing as a long,+ * slow drag. This is the only thing release velocity decides — never *which* gesture happened.+ */+private const val FLICK_VELOCITY = 1200f++/** How long the flicked tile takes to finish leaving, before the tab is actually closed. */+private const val FLICK_OUT_MILLIS = 150++/**+ * The tab switcher: every open tab as a square showing the top of its page.+ *+ * Stateless, so the store-listing previews can render it with literal tabs. [thumbnailFor] and+ * [faviconFor] default to supplying nothing, which is also what a real device gives on a cold+ * start — see [TabTile] for why that is the case worth getting right.+ *+ * Two gestures share each tile, and which one happens is settled by intent at the start rather+ * than by velocity at release: a long press picks the tile up to reorder it, a clearly horizontal+ * drag flicks it closed, and a vertical one is left alone so the grid scrolls. Releasing mid-motion+ * is normal when reordering, so a scheme that read the release would close tabs that were being+ * moved — and closing a tab cannot be undone.+ *+ * Flicking is suppressed when there is only one tab, because closing the last tab immediately+ * creates a blank one, which would appear under the finger and read as the flick having failed.+ * The close button stays on every tile regardless: it is the affordance that works with TalkBack.+ */+@Composable+fun TabSwitcher(+ tabs: List<BrowserTab>,+ activeTabId: String?,+ onSwitch: (String) -> Unit,+ onClose: (String) -> Unit,+ onNewTab: () -> Unit,+ onDismiss: () -> Unit,+ modifier: Modifier = Modifier,+ onReorder: (from: Int, to: Int) -> Unit = { _, _ -> },+ onNewIncognitoTab: () -> Unit = {},+ onNewWindow: () -> Unit = onNewTab,+ onNewIncognitoWindow: () -> Unit = onNewIncognitoTab,+ isIncognitoWindow: Boolean = tabs.find { it.id == activeTabId }?.isPrivate == true,+ thumbnailFor: (String) -> Bitmap? = { null },+ faviconFor: (String) -> Bitmap? = { null },+) {+ val haptics = rememberHaptics()+ val gridState = rememberLazyGridState()+ val reorderState = rememberReorderableLazyGridState(gridState) { from, to ->+ onReorder(from.index, to.index)+ }+ Box(modifier = modifier.fillMaxSize().background(MaterialTheme.colorScheme.background.copy(alpha = 0.98f))) {+ Column(Modifier.fillMaxSize()) {+ TopAppBar(+ title = { Text(pluralStringResource(R.plurals.tabs, tabs.size, tabs.size)) },+ navigationIcon = { IconButton(onClick = onDismiss) { IconClose() } },+ actions = { IconButton(onClick = onNewTab) { IconAdd() } }+ )+ LazyVerticalGrid(+ columns = GridCells.Fixed(COLUMNS),+ state = gridState,+ modifier = Modifier.fillMaxSize(),+ contentPadding = PaddingValues(8.dp),+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ items(tabs, key = { it.id }) { tab ->+ val scope = rememberCoroutineScope()+ var flickX by remember { mutableFloatStateOf(0f) }+ var widthPx by remember { mutableFloatStateOf(0f) }+ val dragging = reorderState.draggingKey == tab.id+ val motion = itemMotion(Motion.reorder())+ // The dragged tile follows the finger, so it cannot also be laid out by the+ // grid's placement animation; the rest glide aside on the reorder spec.+ val itemModifier = if (dragging) {+ Modifier.zIndex(1f).graphicsLayer {+ val translation = reorderState.draggingItemTranslation+ translationX = translation.x+ translationY = translation.y+ }+ } else {+ motion.graphicsLayer {+ translationX = flickX+ alpha = 1f - (abs(flickX) / size.width.coerceAtLeast(1f)).coerceIn(0f, 1f) * 0.6f+ }+ }+ TabTile(+ tab = tab,+ isActive = tab.id == activeTabId,+ thumbnail = thumbnailFor(tab.id),+ favicon = faviconFor(tab.url),+ onSwitch = { onSwitch(tab.id) },+ onClose = { onClose(tab.id) },+ modifier = itemModifier.onSizeChanged { widthPx = it.width.toFloat() },+ gestureModifier = Modifier.reorderGridDragHandle(+ reorderState = reorderState,+ key = tab.id,+ itemCount = tabs.size,+ onDragStarted = { haptics.longPress() },+ onSwap = { haptics.tick() },+ onDragStopped = { haptics.confirm() },+ horizontalFlick = HorizontalFlick(+ enabled = { tabs.size > 1 },+ onDrag = { flickX = it },+ onRelease = { dx, velocity ->+ val thrown = abs(velocity) > FLICK_VELOCITY && velocity * dx > 0f+ val far = widthPx > 0f && abs(dx) > widthPx * FLICK_FRACTION+ scope.launch {+ if (thrown || far) {+ val exit = if (dx < 0f) -widthPx else widthPx+ animate(flickX, exit, animationSpec = Motion.close(FLICK_OUT_MILLIS)) { v, _ ->+ flickX = v+ }+ onClose(tab.id)+ } else {+ animate(flickX, 0f, animationSpec = Motion.drop()) { v, _ -> flickX = v }+ }+ }+ },+ ),+ ),+ )+ }+ item(span = { GridItemSpan(maxLineSpan) }) {+ Column(+ Modifier.fillMaxWidth().padding(top = 8.dp),+ verticalArrangement = Arrangement.spacedBy(8.dp),+ ) {+ OutlinedButton(+ onClick = { if (isIncognitoWindow) onNewIncognitoTab() else onNewTab() },+ modifier = Modifier.fillMaxWidth()+ ) {+ Text(+ stringResource(+ if (isIncognitoWindow) R.string.new_incognito_tab else R.string.new_tab+ )+ )+ }+ Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = onNewWindow, modifier = Modifier.weight(1f)) {+ Text(stringResource(R.string.new_window))+ }+ OutlinedButton(onClick = onNewIncognitoWindow, modifier = Modifier.weight(1f)) {+ Text(stringResource(R.string.new_incognito_window))+ }+ }+ }+ }+ }+ }+ }+}
web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.ktindex b593f4291d..7f0e53eb26 100644--- a/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt+++ b/web/src/main/java/com/vayunmathur/web/ui/WebViewBrowser.kt@@ -37,6 +37,7 @@ import com.vayunmathur.library.ui.findActivity import com.vayunmathur.library.ui.openAppSettings import com.vayunmathur.library.ui.rememberMultiplePermissionRequest import com.vayunmathur.library.ui.rememberPermissionRequest+import com.vayunmathur.web.data.FaviconStore import com.vayunmathur.web.platform.shields.FarblingConfig import com.vayunmathur.web.platform.shields.ShieldsWebViewClient import com.vayunmathur.web.platform.BrowserUtils@@ -211,7 +212,8 @@ fun WebViewBrowser( // The tab a WebView belongs to never changes, so capture privacy once instead // of reading the Compose tab list from the render thread.- val isPrivateTab = viewModel.tabs.find { it.id == tabId }?.isPrivate == true+ val isPrivateTab = viewModel.incognito ||+ viewModel.tabs.find { it.id == tabId }?.isPrivate == true webViewClient = object : ShieldsWebViewClient( context = ctx,@@ -277,6 +279,7 @@ fun WebViewBrowser( } } }+ viewModel.captureThumbnail(tabId, view) } override fun doUpdateVisitedHistory(view: WebView, url: String?, isReload: Boolean) {@@ -295,6 +298,11 @@ fun WebViewBrowser( if (!title.isNullOrBlank()) viewModel.onTabTitleChange(tabId, title) } + override fun onReceivedIcon(view: WebView, icon: Bitmap?) {+ val url = view.url ?: return+ if (icon != null) FaviconStore.put(url, icon, isPrivateTab)+ }+ override fun onGeolocationPermissionsShowPrompt( origin: String, callback: GeolocationPermissions.Callback
web/src/main/java/com/vayunmathur/web/ui/components/SiteIcon.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/components/SiteIcon.kt b/web/src/main/java/com/vayunmathur/web/ui/components/SiteIcon.ktnew file mode 100644index 0000000000..c2c0a91fae--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/components/SiteIcon.kt@@ -0,0 +1,53 @@+package com.vayunmathur.web.ui.components++import android.graphics.Bitmap+import androidx.compose.foundation.Image+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.text.TextStyle+import com.vayunmathur.library.ui.IconGlobe+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Surface+import com.vayunmathur.library.ui.Text++/**+ * A site's icon, with the initial-in-a-circle everything used before it as the fallback.+ *+ * Icons are only ever captured from pages the user has actually loaded, so a host the user has+ * not visited since the feature existed has none — and a tab restored from a cold start has none+ * either. Both are ordinary states rather than errors, which is why the fallback is part of this+ * composable instead of something the caller decides to draw.+ *+ * [label] is the text the initial is taken from, normally the title with the host behind it.+ */+@Composable+fun SiteIcon(+ icon: Bitmap?,+ label: String,+ modifier: Modifier = Modifier,+ containerColor: Color = MaterialTheme.colorScheme.surfaceVariant,+ textStyle: TextStyle = MaterialTheme.typography.titleSmall,+) {+ if (icon != null) {+ Image(+ bitmap = icon.asImageBitmap(),+ contentDescription = null,+ modifier = modifier,+ contentScale = ContentScale.Fit,+ )+ return+ }+ Surface(shape = CircleShape, color = containerColor, modifier = modifier) {+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ val initial = label.trim().firstOrNull()?.uppercase()+ if (initial != null) Text(initial, style = textStyle) else IconGlobe(Modifier.fillMaxSize(0.6f))+ }+ }+}
web/src/main/java/com/vayunmathur/web/ui/components/TabTile.kt
diff --git a/web/src/main/java/com/vayunmathur/web/ui/components/TabTile.kt b/web/src/main/java/com/vayunmathur/web/ui/components/TabTile.ktnew file mode 100644index 0000000000..3961063d47--- /dev/null+++ b/web/src/main/java/com/vayunmathur/web/ui/components/TabTile.kt@@ -0,0 +1,133 @@+package com.vayunmathur.web.ui.components++import android.graphics.Bitmap+import androidx.compose.foundation.Image+import androidx.compose.foundation.background+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.aspectRatio+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.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.graphics.asImageBitmap+import androidx.compose.ui.layout.ContentScale+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.CardDefaults+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconClose+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.web.R+import com.vayunmathur.web.platform.BrowserTab+import com.vayunmathur.web.platform.BrowserUtils+import com.vayunmathur.web.platform.isNewTab++/**+ * One square in the tab switcher: a favicon-and-title header with the page preview below it.+ *+ * [thumbnail] is null far more often than it is not — a tab restored from a cold start has no+ * WebView to draw, a page rendering its content on the GPU captures blank so nothing is stored,+ * and the store-listing previews run with no device at all. So the empty state is the one this+ * has to look right in, not an afterthought.+ *+ * The preview is cropped from the top rather than fitted: a page is far taller than a square, and+ * scaling the whole thing down to fit would show a stripe of unreadable text floating in+ * letterboxing. The top of the page is the part the user recognises.+ *+ * With no preview the body is left as bare tint: the header already carries the favicon and title,+ * so drawing the icon again below it only says the same thing twice.+ *+ * [gestureModifier] goes on the content rather than on the card, and has to: on the `Main` pass the+ * inner node is offered each event first, so a gesture that claims the tile can consume the UP+ * before the card reads it as a tap.+ *+ * The close button is deeper again, which is what keeps it out of that gesture: it consumes the+ * DOWN before [gestureModifier] is offered it, so a press on the X cannot also pick the tile up.+ */+@Composable+fun TabTile(+ tab: BrowserTab,+ isActive: Boolean,+ thumbnail: Bitmap?,+ favicon: Bitmap?,+ onSwitch: () -> Unit,+ onClose: () -> Unit,+ modifier: Modifier = Modifier,+ gestureModifier: Modifier = Modifier,+) {+ val newTabLabel = stringResource(R.string.new_tab)+ val displayTitle = when {+ tab.isNewTab -> newTabLabel+ tab.title.isNotBlank() -> tab.title+ else -> BrowserUtils.prettyUrl(tab.url).ifBlank { newTabLabel }+ }+ Card(+ onClick = onSwitch,+ modifier = modifier.aspectRatio(1f),+ shape = MaterialTheme.shapes.large,+ colors = CardDefaults.cardColors(+ containerColor = if (isActive) {+ MaterialTheme.colorScheme.secondaryContainer+ } else {+ MaterialTheme.colorScheme.surfaceVariant+ }+ ),+ ) {+ Column(Modifier.fillMaxSize().then(gestureModifier)) {+ // Height is left to the close button's touch target rather than fixed, so the+ // header cannot end up shorter than the thing it has to contain.+ Row(+ modifier = Modifier.fillMaxWidth().padding(start = 10.dp),+ verticalAlignment = Alignment.CenterVertically,+ ) {+ SiteIcon(+ icon = favicon,+ label = displayTitle,+ modifier = Modifier.size(18.dp),+ containerColor = MaterialTheme.colorScheme.surface,+ textStyle = MaterialTheme.typography.labelSmall,+ )+ Spacer(Modifier.width(8.dp))+ if (tab.isPrivate) {+ Text(stringResource(R.string.private_prefix), style = MaterialTheme.typography.labelSmall)+ }+ Text(+ text = displayTitle,+ modifier = Modifier.weight(1f),+ maxLines = 1,+ overflow = TextOverflow.Ellipsis,+ style = MaterialTheme.typography.labelLarge,+ )+ IconButton(onClick = onClose) {+ IconClose(Modifier.size(18.dp))+ }+ }+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .weight(1f)+ .background(MaterialTheme.colorScheme.surfaceContainerHighest),+ ) {+ if (thumbnail != null) {+ Image(+ bitmap = thumbnail.asImageBitmap(),+ contentDescription = null,+ modifier = Modifier.fillMaxSize(),+ alignment = Alignment.TopCenter,+ contentScale = ContentScale.Crop,+ )+ }+ }+ }+ }+}