From 9ad922348b140695c9914e05e582c533a797eef1 Mon Sep 17 00:00:00 2001 From: The412Banner Date: Mon, 21 Sep 2026 23:03:57 -0400 Subject: [PATCH] Bannerlator's File Manager, a cog per launch mode with HDR10, leftover-process sweep, the drawer's Steam menu The file picker is now Bannerlator's File Manager itself (files/FileManagerScreen.kt, carried over whole with its rail, favourites, grid/list, copy/cut/paste, rename, delete, properties) minus what has no meaning without a Wine container: run, add to shortcuts, C:/Z: drives, the archive unpacker. StorageRoots, CollapsibleRail, FavoritesStore, PeIconExtractor, OutlinedAlertDialog and MenuStyle come with it unchanged; FileOps carries the progress copy/move. A Files tile opens it; its pick mode chooses the ROMs folder and imports drivers. Play and Desktop each get a cog: resolution cap (1080p default, 900p, 720p, panel), shape, HDR10, the mode's Linux runtime driver, the display driver, touch, and per mode the on-screen controls + audio (Steam) or the renderer (desktop). The Graphics drivers and Audio tiles are gone into them. HDR10: HdrSupport reads the panel's HDR types; the switch is greyed with the reason unless HDR10 is listed. On, the activity feeds the compositor's gate (nativeSetHdrDisplay + nativeSetHdrRequest), turns zero-copy on, sets BANNER_WAYLAND_HDR=1, and the session gets BL_HDR=1 (gamescope --hdr-enabled) and DXVK_HDR=1. OrphanReaper kills every process of our uid but the app at session start and on an app crash: a tree left by a killed app held the rootfs, the GPU and Steam's lock, and the next session never came up (Thor Pro report). The drawer gains Steam menu, which sends the Guide button. --- README.md | 43 +- app/build.gradle | 5 + app/src/main/AndroidManifest.xml | 5 + .../com/steamdeck/launcher/MainActivity.kt | 102 +- .../com/steamdeck/launcher/SessionActivity.kt | 45 +- .../launcher/files/CollapsibleRail.kt | 449 ++++ .../launcher/files/FavoritesStore.kt | 60 + .../launcher/files/FileManagerActivity.kt | 35 + .../launcher/files/FileManagerScreen.kt | 2102 +++++++++++++++++ .../com/steamdeck/launcher/files/FileOps.kt | 130 + .../launcher/files/FilePickerActivity.kt | 18 +- .../launcher/files/FilePickerScreen.kt | 283 --- .../com/steamdeck/launcher/files/MenuStyle.kt | 30 + .../launcher/files/OutlinedAlertDialog.kt | 54 + .../launcher/files/PeIconExtractor.kt | 277 +++ .../launcher/session/CrashHandler.kt | 2 + .../launcher/session/OrphanReaper.kt | 51 + .../launcher/session/SessionPrefs.kt | 36 + .../launcher/session/SessionService.kt | 17 +- .../launcher/session/SessionState.kt | 3 + .../com/steamdeck/launcher/ui/AudioDialog.kt | 69 - .../com/steamdeck/launcher/ui/DriverDialog.kt | 140 -- .../com/steamdeck/launcher/ui/MainScreen.kt | 70 +- .../launcher/ui/ModeSettingsDialog.kt | 214 ++ .../steamdeck/launcher/ui/SessionOverlay.kt | 5 + .../steamdeck/launcher/wayland/HdrSupport.kt | 67 + .../main/res/drawable/icon_menu_container.xml | 5 + .../overlay/usr/local/bin/bannerlator-session | 3 + 28 files changed, 3754 insertions(+), 566 deletions(-) create mode 100644 app/src/main/java/com/steamdeck/launcher/files/CollapsibleRail.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/files/FavoritesStore.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/files/FileManagerActivity.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/files/FileManagerScreen.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/files/FileOps.kt delete mode 100644 app/src/main/java/com/steamdeck/launcher/files/FilePickerScreen.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/files/MenuStyle.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/files/OutlinedAlertDialog.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/files/PeIconExtractor.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/session/OrphanReaper.kt delete mode 100644 app/src/main/java/com/steamdeck/launcher/ui/AudioDialog.kt delete mode 100644 app/src/main/java/com/steamdeck/launcher/ui/DriverDialog.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt create mode 100644 app/src/main/java/com/steamdeck/launcher/wayland/HdrSupport.kt create mode 100644 app/src/main/res/drawable/icon_menu_container.xml diff --git a/README.md b/README.md index cd1d6795a5..e9eea42c8c 100644 --- a/README.md +++ b/README.md @@ -59,7 +59,10 @@ ledger rather than a feature list — where something has not been run on hardwa | The session log folder | ✅ proven — all of it written, including this app's own log | | Session folder finished after a crash or a kill | ⚠️ built: crash handler + next-start sweep; not yet forced on a device | | ROMs folder and Storage in the session's home | ⚠️ built; not yet opened from an emulator on a device | -| The in-app file picker | ⚠️ built; not yet used on a device | +| The File Manager (Bannerlator's) and its pick mode | ⚠️ built; not yet used on a device | +| The cog beside Play / Desktop: resolution, shape, HDR, drivers, touch, audio, renderer | ⚠️ built; the resolution cap and HDR not yet seen on a device | +| Leftover session processes swept at the next start | ⚠️ built; not yet forced on a device | +| The drawer's "Steam menu" (Guide) | ⚠️ built; not yet tried | | Stopping a competing Steam client | ⚠️ it is asked to stop and says so, but one that restarts itself from boot wins the race — uninstall it | | DirectAudio for games, and the microphone | ⚠️ wired and the modules load; voice not yet confirmed in Steam's tester | | Client and game core masks | ⚠️ applied and logged; no measured difference yet | @@ -179,9 +182,17 @@ folder now carries two entries every session: `/root/ROMs` once and it is the same folder in every session after. Both are the live folders, not copies: a save an emulator writes next to its ROM lands on the -phone. Choosing is done in the app's own file picker, the one Bannerlator's File Manager offers -in pick mode - every mounted card in a drive menu, folders first, an up-arrow that stops at the -card's root - and the same picker is what imports a graphics driver. +phone. + +### Files + +**Files** on the main screen is Bannerlator's File Manager, carried over whole: grid and list, +sort, search, multi-select, copy / cut / paste with conflict handling and a cancellable progress +bar, rename, delete, new folder, properties (read-only and hidden), favourites, and a locations +rail with every mounted card, Downloads, the ROMs folder and the session logs. Its pick mode is +what chooses the ROMs folder and imports a driver. What is not here is what has no meaning without +a Wine container: running a file, adding it to shortcuts, the C: / Z: drives and the archive +unpacker. ## Pointer @@ -296,10 +307,27 @@ installs a requested build when the next session starts (several hundred MB), pa pressure-vessel like Valve's, and it then appears in Steam under Properties → Compatibility for any game. The dialog queues or cancels a request and removes an installed build. +## The cog beside Play and Desktop + +Each launch button has a cog, and everything that only matters for that one mode lives behind it, +so the main screen keeps only what applies to both: **resolution** (up to 1080p by default, 900p or +720p for a lighter session, or the panel's own), the display **shape**, **HDR10 output**, the +**Linux runtime driver** for that mode and the shared **display driver**, **touch**, and for Steam +the on-screen controls and audio, for the desktop its renderer. + +**HDR10** is a switch that is greyed out, with the reason, on a panel that does not list HDR10 — +the compositor's HDR gate is decided from the display's own word (`android.view.Display`), once, +when the compositor starts. On, the compositor offers `wp_color_manager_v1` with BT.2020 + PQ and +10-bit buffers, gamescope is started with `--hdr-enabled` and speaks the same protocol to it, and +games get `DXVK_HDR=1`; a game that renders HDR then reaches the panel as HDR on its own display +layer, tagged BT2020_PQ. The compositor lives for the whole app process, so a change applies after +the app is fully closed and opened again. ⚠️ Wired end to end; not yet seen on a device from this +app (Bannerlator proved the same compositor path on a Fold). + ## Graphics drivers Two drivers, two lists, because a zip for one cannot serve the other — the same split Bannerlator's -Contents screen makes: +Contents screen makes. Both are chosen in the cog beside Play / Desktop: - **Linux runtime driver** — the glibc Turnip everything *inside* the runtime renders on: the Steam client's UI, every game it launches, and in desktop mode every program on the desktop. Import a @@ -396,6 +424,11 @@ stands then, which still holds the entry unless the device rebooted. A finished scripts and the compositor need somewhere to - but into the app's cache, and they are deleted when the session ends, so nothing accumulates in Downloads. +A session's process tree is also swept at the next start: proot, gamescope and Steam outlive an +app that was killed or crashed, holding the rootfs, the GPU and Steam's lock, and the next session +then never came up until the app was force-stopped (a Thor Pro report). Anything under the app's +uid other than the app itself is a leftover at that point, and `app.log` lists what was killed. + `device.txt` is written before the session starts, so a session that dies in its first second still says what it ran on: model, SoC, Android and kernel, cores and their ceilings, RAM, the GPU as KGSL names it, the panel, **which driver each half of the session chose**, the runtime version, diff --git a/app/build.gradle b/app/build.gradle index 180bee3b54..aebb8542d9 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -106,4 +106,9 @@ dependencies { implementation 'androidx.compose.ui:ui' implementation 'androidx.compose.material3:material3' implementation 'androidx.activity:activity-compose:1.8.2' + // The File Manager, Bannerlator's: its icon set, image thumbnails and the coroutines it + // copies on. Same versions as Bannerlator so the screen stays a straight copy. + implementation 'androidx.compose.material:material-icons-extended' + implementation 'io.coil-kt:coil-compose:2.6.0' + implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3' } diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index a571023575..a2892c17d8 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -55,6 +55,11 @@ fixed-shape window instead and STRETCHES it onto the other panel — the app never sees a size change, so nothing it does can help. --> + + (null) private var offline by mutableStateOf(false) private var protonRows by mutableStateOf>(emptyList()) - private var showDrivers by mutableStateOf(false) - private var showAudio by mutableStateOf(false) private var showPerformance by mutableStateOf(false) private var clientOverride by mutableStateOf(false) private var clientCores by mutableStateOf>(emptySet()) @@ -113,6 +112,15 @@ class MainActivity : ComponentActivity() { romsDir = path } } + // The mode whose settings dialog is open, with what it shows; refreshed by openModeSettings(). + private var settingsMode by mutableStateOf(null) + private var resolutionCap by mutableStateOf(1080) + private var shapeMode by mutableStateOf(SessionPrefs.SHAPE_AUTO) + private var hdrOn by mutableStateOf(false) + private var hdrReason by mutableStateOf(null) + private var touchMode by mutableStateOf(SessionPrefs.TOUCH_AUTO) + private var oscMode by mutableStateOf(SessionPrefs.OSC_AUTO) + private var renderer by mutableStateOf("pixman") private var romsDir by mutableStateOf(null) private var logsEnabled by mutableStateOf(true) private var showRoms by mutableStateOf(false) @@ -145,10 +153,11 @@ class MainActivity : ComponentActivity() { onRuntime = { onRuntimeButton() }, onFrameGen = { showFrameGen = true }, onProtons = { refreshProtons(); showProtons = true }, - onDrivers = { refreshDrivers(); showDrivers = true }, - onAudio = { directAudio = SessionPrefs.directAudio(this); mic = SessionPrefs.micEnabled(this); showAudio = true }, + onSteamSettings = { openModeSettings(SessionService.MODE_STEAM) }, + onDesktopSettings = { openModeSettings(SessionService.MODE_DESKTOP) }, onPerformance = { refreshCores(); showPerformance = true }, onRoms = { showRoms = true }, + onFiles = { startActivity(Intent(this, com.steamdeck.launcher.files.FileManagerActivity::class.java)) }, onLogs = { SessionPrefs.setLogsEnabled(this, !SessionPrefs.logsEnabled(this)) logsEnabled = SessionPrefs.logsEnabled(this) @@ -177,31 +186,47 @@ class MainActivity : ComponentActivity() { onRemove = { id -> ProtonExtras.tools.first { it.id == id }.let { ProtonExtras.remove(this, it) }; refreshProtons() }, onDismiss = { showProtons = false }, ) - if (showDrivers) DriverDialog( - linuxRows = linuxRows, linuxSteam = linuxSteam, linuxDesktop = linuxDesktop, - androidRows = androidRows, androidSelected = androidSelected, - onSelectLinux = { mode, id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() }, - onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) }, - onRemoveLinux = { id -> LinuxVulkanDriverManager(this).removeDriver(id); refreshDrivers() }, - onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() }, - onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) }, - onRemoveAndroid = { id -> TurnipDriver(this).remove(id); refreshDrivers() }, - onDismiss = { showDrivers = false }, - ) - if (showAudio) AudioDialog( - directAudio = directAudio, mic = mic, - onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on }, - onMic = { on -> - SessionPrefs.setMicEnabled(this, on) - mic = on - // The session checks the grant itself at start; asking here means the - // answer is in before the first session that wants it. - if (on && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { - requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2) - } - }, - onDismiss = { showAudio = false }, - ) + settingsMode?.let { mode -> + ModeSettingsDialog( + ModeSettings( + mode = mode, resolutionCap = resolutionCap, shapeMode = shapeMode, + hdr = hdrOn, hdrReason = hdrReason, + linuxRows = linuxRows, + linuxSelected = if (mode == SessionService.MODE_STEAM) linuxSteam else linuxDesktop, + androidRows = androidRows, androidSelected = androidSelected, + touchMode = touchMode, + oscMode = if (mode == SessionService.MODE_STEAM) oscMode else null, + directAudio = if (mode == SessionService.MODE_STEAM) directAudio else null, + mic = if (mode == SessionService.MODE_STEAM) mic else null, + renderer = if (mode == SessionService.MODE_DESKTOP) renderer else null, + ), + ModeSettingsActions( + onResolution = { cap -> SessionPrefs.setResolutionCap(this, mode, cap); resolutionCap = cap }, + onShape = { shape -> SessionPrefs.setShapeMode(this, shape); shapeMode = shape }, + onHdr = { on -> SessionPrefs.setHdr(this, mode, on); hdrOn = on }, + onSelectLinux = { id -> SessionPrefs.setLinuxDriver(this, mode, id); refreshDrivers() }, + onImportLinux = { pickLinuxDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a Linux runtime driver (-Linux zip)")) }, + onRemoveLinux = { id -> LinuxVulkanDriverManager(this).removeDriver(id); refreshDrivers() }, + onSelectAndroid = { id -> SessionPrefs.setAndroidDriver(this, id); refreshDrivers() }, + onImportAndroid = { pickAndroidDriver.launch(InAppFilePicker.buildIntent(this, ZIP_EXT, "Choose a display driver (AdrenoTools zip)")) }, + onRemoveAndroid = { id -> TurnipDriver(this).remove(id); refreshDrivers() }, + onTouch = { t -> SessionPrefs.setTouchMode(this, t); touchMode = t }, + onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o }, + onDirectAudio = { on -> SessionPrefs.setDirectAudio(this, on); directAudio = on }, + onMic = { on -> + SessionPrefs.setMicEnabled(this, on) + mic = on + // The session checks the grant itself at start; asking here means the + // answer is in before the first session that wants it. + if (on && checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), 2) + } + }, + onRenderer = { r -> SessionPrefs.setDesktopRenderer(this, r); renderer = r }, + onDismiss = { settingsMode = null }, + ), + ) + } if (showPerformance) PerformanceDialog( cores = CpuCores.all.map { c -> CoreRow(c, "cpu$c" + (CpuCores.maxGhz(c)?.let { String.format(java.util.Locale.US, " · %.1f GHz", it) } ?: "")) }, clientOverride = clientOverride, clientCores = clientCores, gameCores = gameCores, @@ -293,6 +318,21 @@ class MainActivity : ComponentActivity() { } /** Both driver lists as the dialog shows them, re-read from disk so an import or removal shows at once. */ + /** Everything the mode's cog shows, read fresh, then the dialog. */ + private fun openModeSettings(mode: String) { + refreshDrivers() + resolutionCap = SessionPrefs.resolutionCap(this, mode) + shapeMode = SessionPrefs.shapeMode(this) + hdrOn = SessionPrefs.hdr(this, mode) + hdrReason = com.steamdeck.launcher.wayland.HdrSupport.probe(this).reason + touchMode = SessionPrefs.touchMode(this) + oscMode = SessionPrefs.oscMode(this) + directAudio = SessionPrefs.directAudio(this) + mic = SessionPrefs.micEnabled(this) + renderer = SessionPrefs.desktopRenderer(this) + settingsMode = mode + } + private fun refreshDrivers() { val lm = LinuxVulkanDriverManager(this) linuxRows = LinuxVulkanDriver.optionValues(this).map { id -> diff --git a/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt b/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt index f88f38180a..ea44333ccf 100644 --- a/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/steamdeck/launcher/SessionActivity.kt @@ -37,6 +37,7 @@ import com.steamdeck.launcher.session.PerfHud import com.steamdeck.launcher.session.ProtonExtras import com.steamdeck.launcher.session.SessionPrefs import com.steamdeck.launcher.session.SessionPaths +import com.steamdeck.launcher.wayland.HdrSupport import com.steamdeck.launcher.session.SessionService import com.steamdeck.launcher.session.SessionState import com.steamdeck.launcher.ui.CursorOverlay @@ -158,6 +159,16 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onHud = { on -> SessionPrefs.setHudEnabled(this@SessionActivity, on); hudOn = on; hud.refresh() }, onFrameGen = { showFrameGen = true }, onKeyboard = { drawerOpen = false; keyboard?.toggle() }, + onSteamMenu = if (SessionState.mode == SessionService.MODE_STEAM) ({ + // The Guide button, the way the on-screen ◉ sends it: a device with no + // Xbox button, or a pad the client hides the controls for, has no other + // way to open the client's menu in a game. + drawerOpen = false + padBridge?.applyTouch { st -> st.setPressed(com.steamdeck.launcher.input.GamepadState.IDX_BUTTON_MODE, true) } + Handler(Looper.getMainLooper()).postDelayed({ + padBridge?.applyTouch { st -> st.setPressed(com.steamdeck.launcher.input.GamepadState.IDX_BUTTON_MODE, false) } + }, 90) + }) else null, onProtons = { refreshProtons(); showProtons = true }, onOsc = { val next = when (SessionPrefs.oscMode(this@SessionActivity)) { @@ -285,6 +296,31 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { Log.w(TAG, "could not point the compositor's log at $waylandLog", e) } } + // HDR10: the gate is decided once, when the compositor starts (it lives for the whole app + // process), from the panel's own word and the mode's setting. Zero-copy presentation is + // what puts an HDR frame on a display layer tagged BT2020_PQ, so it is turned on with it. + if (!CompositorHost.isStarted) { + val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM + val probe = HdrSupport.probe(this) + WaylandCompositor.nativeSetHdrDisplay( + probe.displayId, probe.name, probe.formats, probe.hdr10, + probe.maxLuminance, probe.maxAverageLuminance, probe.minLuminance, + probe.ratioAvailable, probe.ratio, Build.VERSION.SDK_INT, + ) + val wanted = SessionPrefs.hdr(this, mode) + val on = wanted && probe.reason == null + SessionState.hdr = on + if (on) { + try { android.system.Os.setenv("BANNER_WAYLAND_HDR", "1", true) } catch (e: Exception) { Log.w(TAG, "BANNER_WAYLAND_HDR", e) } + WaylandCompositor.nativeSetZeroCopy(true) + } + WaylandCompositor.nativeSetHdrRequest( + if (on) WaylandCompositor.HDR_MODE_ON else WaylandCompositor.HDR_MODE_OFF, + "$mode session settings" + (if (wanted && !on) " (refused: ${probe.reason})" else ""), + on, on, + ) + Log.i(TAG, "hdr: " + (if (on) "on" else if (wanted) "wanted but ${probe.reason}" else "off") + " · display ${probe.formats.ifEmpty { "SDR" }}") + } CompositorHost.startOrAttach( holder.surface, runtimeDir.path, driverId?.let { turnip.driverPath(it) }, driverId?.let { turnip.libraryName(it) }, @@ -344,9 +380,12 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { // compositor letterboxes onto a squarer panel. val aspect = if (SessionPrefs.shapeMode(this) == SessionPrefs.SHAPE_WIDE) 16f / 9f else maxOf(panelW / panelH, 16f / 9f) - // 1080 tall at most: the client's CEF is the heaviest thing in the session, and above - // 1080p it costs frames for nothing anyone can see on a handheld panel. - val height = minOf(panelH, 1080f).toInt() + // 1080 tall at most by default: the client's CEF is the heaviest thing in the session, and + // above 1080p it costs frames for nothing anyone can see on a handheld panel. The mode's + // settings (the cog beside Play / Desktop) can lower the cap or lift it to the panel. + val mode = intent.getStringExtra(SessionService.EXTRA_MODE) ?: SessionService.MODE_STEAM + val cap = SessionPrefs.resolutionCap(this, mode) + val height = (if (cap <= 0) panelH else minOf(panelH, cap.toFloat())).toInt() val width = (height * aspect).toInt() // Odd sizes upset the scaler; both dimensions even is what every mode here would be. return Pair(width and 1.inv(), height and 1.inv()) diff --git a/app/src/main/java/com/steamdeck/launcher/files/CollapsibleRail.kt b/app/src/main/java/com/steamdeck/launcher/files/CollapsibleRail.kt new file mode 100644 index 0000000000..abae129305 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/CollapsibleRail.kt @@ -0,0 +1,449 @@ +package com.steamdeck.launcher.files + +import android.content.res.Configuration +import androidx.compose.animation.core.animateDpAsState +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.clickable +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Badge +import androidx.compose.material3.BadgedBox +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.painterResource +import androidx.annotation.DrawableRes +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp + +/** One tappable entry in a [CollapsibleRail] (a container tab, a file-manager location, …). */ +data class RailItem( + val label: String, + val icon: ImageVector, + val selected: Boolean, + /** >0 shows a small accent count badge on the item's icon (expanded and collapsed). */ + val badge: Int = 0, + // onClick stays LAST so existing call sites can pass it as a trailing lambda; badge is an + // optional named param before it (default 0). + val onClick: () -> Unit, +) + +/** A group of [RailItem]s under an optional small section header (STORAGE / QUICK / FAVORITES …). */ +data class RailSection(val header: String?, val items: List) + +/** + * The tiny under-icon label for a COLLAPSED rail item. The rail width never changes, so labels must + * fit the narrow (~58dp) column: multi-word names wrap to a second line; single words too long to + * fit are abbreviated; short ones pass through. (Explicit abbreviations first, then a length guard.) + */ +private fun collapsedLabel(label: String): String { + when (label) { + "ENVIROMENT" -> return "ENVIRON" // the app's existing (mis)spelling, kept uppercase + "WIN COMPONENTS" -> return "WIN COMP" + "Downloads" -> return "Downlds" + } + if (label.contains(' ')) return label // multi-word → wraps to 2 lines + return if (label.length > 9) label.take(8) + "…" else label +} + +/** A rail item's 20dp icon, with a small accent count badge on its corner when [badge] > 0. */ +@Composable +private fun RailItemIcon(item: RailItem, tint: androidx.compose.ui.graphics.Color) { + if (item.badge > 0) { + BadgedBox( + badge = { + Badge( + containerColor = MaterialTheme.colorScheme.primary, + contentColor = MaterialTheme.colorScheme.onPrimary, + ) { Text(if (item.badge > 9) "9+" else item.badge.toString(), fontSize = 8.sp) } + }, + ) { + Icon(item.icon, contentDescription = item.label, tint = tint, modifier = Modifier.size(20.dp)) + } + } else { + Icon(item.icon, contentDescription = item.label, tint = tint, modifier = Modifier.size(20.dp)) + } +} + +/** A secondary link shown under the header (e.g. "What is all this?", "Reset to app defaults"). */ +data class RailLink(val label: String, val icon: ImageVector, val onClick: () -> Unit) + +/** + * State for a [CollapsibleRail], with the app-wide unified rule: + * - PORTRAIT → always collapsed (icon-only), the toggle is HIDDEN and it can never expand. + * - LANDSCAPE → expanded by default; the user's collapse choice is remembered PER-SCREEN + * ([screenKey]) and is NOT overridden by rotation. portrait→landscape restores that choice. + * + * Backed by rememberSaveable (survives process death) and by the fact the app UI activity keeps + * orientation in configChanges (no recreate) so the selected item / fields / scroll are preserved. + */ +class RailState internal constructor( + val collapsed: Boolean, + /** True in portrait: the rail is locked collapsed and must not show an expand toggle. */ + val portraitLocked: Boolean, + val onToggle: () -> Unit, +) + +@Composable +fun rememberRailState(screenKey: String): RailState { + val context = LocalContext.current + val prefs = remember { androidx.preference.PreferenceManager.getDefaultSharedPreferences(context) } + val isLandscape = LocalConfiguration.current.orientation == Configuration.ORIENTATION_LANDSCAPE + + val choseKey = "rail_${screenKey}_userChose" + val collapsedKey = "rail_${screenKey}_collapsed" + + // Keep the landscape choice in saveable state regardless of orientation so portrait→landscape + // restores it. In portrait we simply report collapsed+locked and ignore it. + var userChose by rememberSaveable(screenKey) { mutableStateOf(prefs.getBoolean(choseKey, false)) } + var landscapeCollapsed by rememberSaveable(screenKey) { + mutableStateOf(if (prefs.getBoolean(choseKey, false)) prefs.getBoolean(collapsedKey, false) else false) + } + + if (!isLandscape) { + return RailState(collapsed = true, portraitLocked = true, onToggle = {}) + } + return RailState( + collapsed = landscapeCollapsed, + portraitLocked = false, + onToggle = { + landscapeCollapsed = !landscapeCollapsed + userChose = true + prefs.edit() + .putBoolean(choseKey, true) + .putBoolean(collapsedKey, landscapeCollapsed) + .apply() + }, + ) +} + +/** + * The shared collapsible left rail (mockup "Option 3"): app glyph + title, optional links, and the + * navigation items, replacing a top tab bar so content runs full height beside it. Width animates + * 190dp ↔ 58dp. When collapsed it is icon-only (the caller surfaces the active item's name over the + * content). Used by the container editors, File Manager and Save Manager. + * + * [footer] is an optional slot pinned to the bottom of the rail (a weighted spacer pushes it down), + * for a persistent per-screen summary (e.g. the Save Manager's "N games need syncing" line). The + * caller renders whatever it wants there and can key it off [RailState.collapsed] to go icon-only. + */ +@Composable +fun CollapsibleRail( + state: RailState, + title: String, + sections: List, + modifier: Modifier = Modifier, + links: List = emptyList(), + footer: (@Composable ColumnScope.() -> Unit)? = null, + // Optional header glyph (a themed drawable). When null the rail shows its plain solid square. + // Used by the container editors to show the wine-glass container icon; other rails leave it null. + @DrawableRes headerIcon: Int? = null, + // When true each item gets a rounded outlined-button look (the selected one takes the accent + // border + accent-dim fill), matching the File Manager's "New Folder" button. Off by default so + // the container/save rails keep their lighter flat rows (5 stacked outlined tabs read too heavy). + outlinedItems: Boolean = false, +) { + val collapsed = state.collapsed + val width by animateDpAsState(if (collapsed) 58.dp else 190.dp, label = "railWidth") + + Column( + modifier = modifier + .width(width) + .fillMaxHeight() + .background(MaterialTheme.colorScheme.surfaceContainerHigh) + ) { + // ── Header: app glyph + title + collapse handle (handle hidden when portrait-locked) ── + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = if (collapsed) Arrangement.Center else Arrangement.Start, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = if (collapsed) 0.dp else 10.dp, vertical = 8.dp) + ) { + if (headerIcon != null) { + Icon( + painter = painterResource(headerIcon), + contentDescription = title, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp), + ) + } else { + Box( + modifier = Modifier + .size(22.dp) + .clip(RoundedCornerShape(6.dp)) + .background(MaterialTheme.colorScheme.primary) + ) + } + if (!collapsed) { + Spacer(Modifier.width(9.dp)) + Text( + title, + color = MaterialTheme.colorScheme.onSurface, + fontSize = 13.sp, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + if (!state.portraitLocked) { + IconButton(onClick = state.onToggle, modifier = Modifier.size(28.dp)) { + Text("‹‹", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp) + } + } + } + } + // Collapsed (landscape only) → an expand handle; portrait is locked with no handle. + if (collapsed && !state.portraitLocked) { + IconButton(onClick = state.onToggle, modifier = Modifier.fillMaxWidth().height(24.dp)) { + Text("››", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp) + } + } + + // ── Links ── + if (links.isNotEmpty()) { + if (collapsed) { + Row(horizontalArrangement = Arrangement.Center, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + links.forEach { link -> + IconButton(onClick = link.onClick, modifier = Modifier.size(32.dp)) { + Icon(link.icon, link.label, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp)) + } + } + } + } else { + links.forEach { link -> + TextButton(onClick = link.onClick, modifier = Modifier.padding(start = 4.dp)) { + Icon(link.icon, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(15.dp)) + Spacer(Modifier.width(6.dp)) + Text(link.label, fontSize = 11.sp) + } + } + } + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)) + + // ── Sections + items (SCROLLABLE so a tall rail — e.g. many File Manager favourites — is + // fully reachable in both orientations; the header above and footer below stay pinned) ── + Column( + modifier = Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + ) { + sections.forEach { section -> + if (!collapsed && section.header != null) { + Text( + section.header, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f), + fontSize = 9.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 0.6.sp, + modifier = Modifier.padding(start = 14.dp, top = 10.dp, bottom = 2.dp), + ) + } else if (collapsed && section.header != null && section != sections.first()) { + HorizontalDivider( + color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f), + modifier = Modifier.padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + section.items.forEach { item -> + val active = item.selected + // Outlined variant: each item is a rounded outlined button; selected = accent border + + // accent-dim fill. Flat variant (default): a simple accent-tinted highlight for selected. + val shape = RoundedCornerShape(9.dp) + val base = Modifier.fillMaxWidth() + val styled = if (outlinedItems) { + base + .padding(horizontal = 6.dp, vertical = 3.dp) + .clip(shape) + .background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.16f) else MaterialTheme.colorScheme.surface.copy(alpha = 0.4f)) + .border( + 1.dp, + if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline.copy(alpha = 0.5f), + shape, + ) + .clickable(onClick = item.onClick) + .padding(horizontal = if (collapsed) 2.dp else 11.dp, vertical = if (collapsed) 6.dp else 9.dp) + } else { + base + .clickable(onClick = item.onClick) + .background(if (active) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent) + .padding(horizontal = if (collapsed) 2.dp else 13.dp, vertical = if (collapsed) 7.dp else 11.dp) + } + val iconTint = if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant + val labelColor = if (active) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant + if (collapsed) { + // Icon-only width is unchanged — a TINY label goes UNDER the icon (2 lines max, + // centre-aligned, wrapping/abbreviated) so every button stays identifiable without + // widening the rail. + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = styled, + ) { + RailItemIcon(item, iconTint) + Spacer(Modifier.height(2.dp)) + Text( + collapsedLabel(item.label), + color = labelColor, + fontSize = 7.5.sp, + lineHeight = 8.5.sp, + fontWeight = FontWeight.Medium, + textAlign = TextAlign.Center, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + } + } else { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.Start, + modifier = styled, + ) { + RailItemIcon(item, iconTint) + Spacer(Modifier.width(11.dp)) + Text( + item.label, + color = labelColor, + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 0.3.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + } + } + } + + } // end scrollable section list (its weight fills the gap so the footer stays pinned) + + // ── Optional pinned footer (e.g. the sync summary) ── + if (footer != null) { + HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.25f)) + footer() + } + } +} + +/** + * Portrait counterpart to [CollapsibleRail]: the same navigation [items] laid out as a horizontal + * icon-over-label bar pinned across the top, with an accent underline under the selected one. Mirrors + * the container editor's top tab bar so every editor reads the same — pin this in portrait wherever a + * [CollapsibleRail] is used in landscape. Optional [links] (Help / Reset …) are appended after a + * faint separator, exactly like the rail's links. + * + * (The container editor still carries its own private copy of this bar; new screens should prefer + * this shared one, and the container editor can migrate to it later.) + */ +@Composable +fun RailTopTabs( + items: List, + modifier: Modifier = Modifier, + links: List = emptyList(), +) { + Column(modifier = modifier.fillMaxWidth()) { + Row( + modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 2.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + items.forEach { item -> + TopTabCell( + icon = item.icon, + label = item.label, + selected = item.selected, + onClick = item.onClick, + modifier = Modifier.weight(1f), + ) + } + if (links.isNotEmpty()) { + // Faint separator: everything past here is an action button, not a tab. + Box( + modifier = Modifier + .padding(horizontal = 2.dp) + .width(1.dp) + .height(30.dp) + .background(MaterialTheme.colorScheme.outline.copy(alpha = 0.4f)), + ) + links.forEach { link -> + TopTabCell(link.icon, link.label, selected = false, onClick = link.onClick, modifier = Modifier.weight(1f)) + } + } + } + HorizontalDivider() + } +} + +/** One cell of [RailTopTabs] — icon over a small label, with an accent underline (zero-width when + * unselected, so every cell keeps the same height). Mirrors the container editor's TopCell. */ +@Composable +private fun TopTabCell( + icon: ImageVector, + label: String, + selected: Boolean, + onClick: () -> Unit, + modifier: Modifier = Modifier, +) { + val tint = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = modifier + .clip(RoundedCornerShape(9.dp)) + .background(if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.14f) else Color.Transparent) + .clickable(onClick = onClick) + .padding(vertical = 6.dp, horizontal = 1.dp), + ) { + Icon(icon, contentDescription = label, tint = tint, modifier = Modifier.size(20.dp)) + Spacer(Modifier.height(3.dp)) + Text( + label, + color = tint, + fontSize = 8.5.sp, + fontWeight = FontWeight.Bold, + letterSpacing = 0.2.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + textAlign = TextAlign.Center, + ) + Spacer(Modifier.height(2.dp)) + Box( + modifier = Modifier + .height(2.dp) + .width(if (selected) 16.dp else 0.dp) + .clip(RoundedCornerShape(3.dp)) + .background(if (selected) MaterialTheme.colorScheme.primary else Color.Transparent), + ) + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/FavoritesStore.kt b/app/src/main/java/com/steamdeck/launcher/files/FavoritesStore.kt new file mode 100644 index 0000000000..01b4509a41 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/FavoritesStore.kt @@ -0,0 +1,60 @@ +package com.steamdeck.launcher.files + +import android.content.Context +import org.json.JSONArray + +/** + * Persists the File Manager's favourite / bookmarked directories. + * + * Stores an ordered (insertion-order) list of absolute path strings as a JSON array + * under "file_manager_favorites" in SharedPreferences "file_manager_prefs". Only the + * absolute path is kept — everything shown on a favourite card (drive label, container + * name, display path) is derived live, so a renamed or deleted container resolves + * correctly for free. + */ +object FavoritesStore { + + private const val PREFS_NAME = "file_manager_prefs" + private const val KEY = "file_manager_favorites" + + private fun prefs(context: Context) = + context.applicationContext.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + + /** Ordered list of favourited absolute paths (insertion order). */ + fun list(context: Context): List { + val raw = prefs(context).getString(KEY, null) ?: return emptyList() + return runCatching { + val arr = JSONArray(raw) + buildList { for (i in 0 until arr.length()) add(arr.getString(i)) } + }.getOrDefault(emptyList()) + } + + fun isFavorite(context: Context, path: String): Boolean = list(context).contains(path) + + /** Add [path] if not already present (deduped); keeps insertion order. */ + fun add(context: Context, path: String) { + val current = list(context) + if (current.contains(path)) return + save(context, current + path) + } + + fun remove(context: Context, path: String) { + val current = list(context) + if (!current.contains(path)) return + save(context, current.filterNot { it == path }) + } + + /** Toggle [path]; returns true if it is now a favourite, false if it was removed. */ + fun toggle(context: Context, path: String): Boolean = + if (isFavorite(context, path)) { + remove(context, path); false + } else { + add(context, path); true + } + + private fun save(context: Context, paths: List) { + val arr = JSONArray() + paths.forEach { arr.put(it) } + prefs(context).edit().putString(KEY, arr.toString()).apply() + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/FileManagerActivity.kt b/app/src/main/java/com/steamdeck/launcher/files/FileManagerActivity.kt new file mode 100644 index 0000000000..4804c9ac0e --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/FileManagerActivity.kt @@ -0,0 +1,35 @@ +package com.steamdeck.launcher.files + +import android.Manifest +import android.content.pm.PackageManager +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.ui.Modifier +import com.steamdeck.launcher.ui.SteamDeckTheme + +/** The File Manager as a screen of its own, from the Files tile on the main screen. */ +class FileManagerActivity : ComponentActivity() { + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE), 1) + } + setContent { + SteamDeckTheme { + Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) { + FileManagerScreen() + } + } + } + } + + override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) { + super.onRequestPermissionsResult(requestCode, permissions, grantResults) + if (requestCode == 1 && grantResults.firstOrNull() == PackageManager.PERMISSION_GRANTED) recreate() + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/FileManagerScreen.kt b/app/src/main/java/com/steamdeck/launcher/files/FileManagerScreen.kt new file mode 100644 index 0000000000..12557b7519 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/FileManagerScreen.kt @@ -0,0 +1,2102 @@ +package com.steamdeck.launcher.files + +import android.widget.Toast +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.Image +import android.content.res.Configuration +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.clickable +import androidx.compose.foundation.combinedClickable +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +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.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.ArrowBack +import androidx.compose.material.icons.filled.Bolt +import androidx.compose.material.icons.filled.Checklist +import androidx.compose.material.icons.filled.ContentPaste +import androidx.compose.material.icons.filled.CreateNewFolder +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.FileCopy +import androidx.compose.material.icons.filled.Folder +import androidx.compose.material.icons.filled.GridView +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.InsertDriveFile +import androidx.compose.material.icons.filled.MoreVert +import androidx.compose.material.icons.filled.ContentCut +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material.icons.filled.PlayArrow +import androidx.compose.material.icons.filled.SdStorage +import androidx.compose.material.icons.filled.Search +import androidx.compose.material.icons.filled.Sort +import androidx.compose.material.icons.filled.Star +import androidx.compose.material.icons.filled.Unarchive +import androidx.compose.material.icons.filled.ViewList +import androidx.compose.material.icons.filled.StarBorder +import androidx.compose.material.icons.filled.PushPin +import androidx.compose.material.icons.filled.Storage +import androidx.compose.material.icons.filled.Smartphone +import androidx.compose.material.icons.filled.Download +import androidx.compose.material.icons.filled.Image +import androidx.compose.material.icons.filled.SportsEsports +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.pulltorefresh.PullToRefreshContainer +import androidx.compose.material3.pulltorefresh.rememberPullToRefreshState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.DisposableEffect +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableFloatStateOf +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.ImageBitmap +import androidx.compose.ui.graphics.asImageBitmap +import androidx.compose.ui.graphics.vector.ImageVector +import androidx.compose.ui.input.nestedscroll.nestedScroll +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.graphics.vector.rememberVectorPainter +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalLifecycleOwner +import androidx.compose.ui.res.painterResource +import androidx.lifecycle.Lifecycle +import androidx.lifecycle.LifecycleEventObserver +import coil.compose.AsyncImage +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.steamdeck.launcher.R +import com.steamdeck.launcher.session.SessionPrefs +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/* + * Bannerlator's File Manager (ui/screens/FileManagerScreen.kt), carried over whole: the same + * browsing, grid and list, sorting, search, multi-select, copy/cut/paste with conflicts and + * progress, rename, delete, new folder, properties, favourites and the locations rail, and the + * same pick modes. What this app has no use for is not here: running a file in a Wine container, + * adding it to a container's shortcuts, the Drive C: / Drive Z: locations and the archive + * unpacker that installs into a prefix. Everything else is line for line the same so a fix in + * either app carries to the other. + */ + +/** + * What to do when a pasted item already exists at the destination. + * + * OVERWRITE and MERGE resolve to the same call — `copyWithProgress` recurses into an existing + * directory and truncates existing files — but they mean different things to the user, so both are + * offered and the wording is chosen per item type (files overwrite, folders merge). + */ +enum class ConflictChoice { OVERWRITE, MERGE, KEEP_BOTH, SKIP } + +/** + * Ordering for the file list. Folders always lead regardless of direction — a descending sort that + * buries every folder under the files is never what someone means by "Z to A". + */ +/** + * Shortens a path from the LEFT, keeping whole segments. + * + * Compose's TextOverflow can only ellipsise the tail, which for a path throws away the part that + * matters — `/storage/emulated/0/Winlator/Game…` tells you nothing about where you are. + */ +private fun elidePathStart(path: String, max: Int): String { + if (path.length <= max) return path + val parts = path.split('/').filter { it.isNotEmpty() } + val out = StringBuilder() + for (part in parts.asReversed()) { + if (out.length + part.length + 1 > max - 2) break + out.insert(0, "/$part") + } + return if (out.isEmpty()) "…" + path.takeLast(max - 1) else "…$out" +} + +private fun comparatorFor(sortBy: String, desc: Boolean): Comparator { + val inner: Comparator = when (sortBy) { + "date" -> compareBy { it.lastModified() } + // Directory length() is meaningless, so folders sort by name within the size ordering + // instead of pretending to have one. + "size" -> compareBy { if (it.isDirectory) -1L else it.length() } + else -> compareBy { it.name.lowercase() } + } + val directed = if (desc) inner.reversed() else inner + return compareBy { if (it.isDirectory) 0 else 1 }.then(directed) +} + +private val FileTypeIcon: Map = mapOf( + "folder" to Icons.Filled.Folder, +) + +// Image extensions that get a real thumbnail (via Coil) instead of the generic file icon. +private val IMAGE_THUMB_EXTS = setOf("jpg", "jpeg", "png", "webp", "bmp", "gif") + +// Color-only sweep: the former card-fill / card-stroke / divider / icon-blue / icon-white +// constants were rerouted onto MaterialTheme.colorScheme tokens (surface / outline / primary / +// onSurface) at their use sites so a theme preset/accent recolors them. + +// True when [child] is [ancestor] itself or lives anywhere inside it. +private fun isWithin(child: File, ancestor: File): Boolean { + val c = runCatching { child.canonicalPath }.getOrDefault(child.absolutePath) + val a = runCatching { ancestor.canonicalPath }.getOrDefault(ancestor.absolutePath) + return c == a || c.startsWith(a + File.separator) +} + +// ── DOS file attributes (Read-only / Hidden) ── +// The in-container file manager (wfm.exe) exposes these in its Properties dialog; this mirrors the +// same two toggles for files browsed from the app side. No root — we only touch permission bits the +// app owns (container files) and the Wine DOS-attribute xattr. + +// FILE_ATTRIBUTE_HIDDEN, as Wine encodes it in the user.DOSATTRIB extended attribute. +private const val FILE_ATTRIBUTE_HIDDEN = 0x2 +private const val DOSATTRIB_XATTR = "user.DOSATTRIB" + +// Snapshot of a file's two toggleable attributes. hiddenSupported is false when the underlying +// filesystem can't store the DOSATTRIB xattr (the FUSE /storage volumes) — the Hidden toggle is then +// disabled while Read-only keeps working. +private data class FileAttrState( + val readOnly: Boolean, + val hidden: Boolean, + val hiddenSupported: Boolean, +) + +// Wine (and Samba) store user.DOSATTRIB as an ASCII hex string ("0x22"), sometimes with trailing +// Samba fields after a separator. We only need the leading DOS-attribute hex, so read from the "0x" +// prefix and stop at the first non-hex character. +private fun parseDosAttrib(raw: ByteArray): Int { + val s = String(raw, Charsets.US_ASCII).trim() + val hex = if (s.startsWith("0x") || s.startsWith("0X")) s.substring(2) else s + val digits = hex.takeWhile { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' } + return digits.toIntOrNull(16) ?: 0 +} + +// Read the current read-only + Wine-hidden state. Never throws: an xattr-unsupported filesystem +// comes back hiddenSupported=false (Hidden toggle disabled), Read-only always resolves. +private fun readFileAttrs(file: File): FileAttrState { + val path = file.absolutePath + // Read-only reflects the OWNER write bit — that's what Wine maps to FILE_ATTRIBUTE_READONLY. + val readOnly = runCatching { + (android.system.Os.stat(path).st_mode and android.system.OsConstants.S_IWUSR) == 0 + }.getOrDefault(!file.canWrite()) + + var hidden = false + var supported = true + try { + hidden = (parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) and FILE_ATTRIBUTE_HIDDEN) != 0 + } catch (e: android.system.ErrnoException) { + // ENODATA: xattr namespace works, the attribute just isn't set yet -> still toggleable. + // ENOTSUP/EOPNOTSUPP/anything else: the fs can't store it -> disable the Hidden toggle. + supported = e.errno == android.system.OsConstants.ENODATA + } catch (e: Exception) { + supported = false + } + return FileAttrState(readOnly, hidden, supported) +} + +// Toggle read-only by flipping the write bits, preserving every other permission bit. Setting +// read-only clears owner/group/other write (so Wine sees FILE_ATTRIBUTE_READONLY regardless of which +// write bit it checks); clearing it restores owner write. Falls back to File.setWritable if chmod is +// somehow refused. Returns true on success. +private fun setReadOnly(file: File, readOnly: Boolean): Boolean = runCatching { + val path = file.absolutePath + val mode = android.system.Os.stat(path).st_mode + val writeBits = android.system.OsConstants.S_IWUSR or + android.system.OsConstants.S_IWGRP or android.system.OsConstants.S_IWOTH + val newMode = if (readOnly) mode and writeBits.inv() + else mode or android.system.OsConstants.S_IWUSR + android.system.Os.chmod(path, newMode) + true +}.getOrElse { file.setWritable(!readOnly, true) } + +// Flip Wine's DOS hidden bit in user.DOSATTRIB, preserving the other DOS-attribute bits +// (archive/system/read-only) already encoded there, and synthesizing a minimal value when absent. +// Writes Wine's own "0x%x" format, which Wine reads back natively. Returns false when the fs can't +// store the xattr, so the caller can disable just the Hidden toggle. +private fun setHidden(file: File, hidden: Boolean): Boolean = try { + val path = file.absolutePath + var attr = try { + parseDosAttrib(android.system.Os.getxattr(path, DOSATTRIB_XATTR)) + } catch (e: android.system.ErrnoException) { + if (e.errno == android.system.OsConstants.ENODATA) 0 else throw e + } + attr = if (hidden) attr or FILE_ATTRIBUTE_HIDDEN else attr and FILE_ATTRIBUTE_HIDDEN.inv() + val value = "0x%x".format(attr).toByteArray(Charsets.US_ASCII) + android.system.Os.setxattr(path, DOSATTRIB_XATTR, value, 0) + true +} catch (e: Exception) { + false +} + +// ── Favorites: origin resolution ── + +enum class FavStorage { INTERNAL, SD, OTHER } + +data class FavLocation( + val storage: FavStorage, + val driveLabel: String, // "Internal", "SD card", or "Storage" + val displayPath: String // the unix absolute path +) + +// Resolve where [file] lives (storage source + a friendly label) by prefix-matching its path. +fun describeLocation(file: File): FavLocation { + val abs = file.absolutePath + + val internal = "/storage/emulated/0" + if (abs == internal || abs.startsWith("$internal/")) { + return FavLocation(FavStorage.INTERNAL, "Internal", abs) + } + + if (abs.startsWith("/storage/")) { + val name = abs.removePrefix("/storage/").substringBefore('/') + if (name.isNotEmpty() && name != "emulated" && name != "self") { + return FavLocation(FavStorage.SD, "SD card", abs) + } + } + + return FavLocation(FavStorage.OTHER, "Storage", abs) +} + +// Semantic identity colours for the favourite-card drive badge. Intentionally NOT theme +// accent colours — they identify the storage source at a glance. Returns (background, foreground). +private fun badgeColors(loc: FavLocation): Pair { + val white = Color(0xFFFFFFFF) + return when { + loc.storage == FavStorage.INTERNAL -> Color(0xFF2E5FB0) to white // blue + loc.storage == FavStorage.SD -> Color(0xFF2E7D32) to white // green + else -> Color(0xFF555555) to white // grey + } +} + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun FileManagerScreen( + // Pick mode (issue #73): reuse this File Manager as a themed file picker. When on, editing/run + // features are gated off and tapping a matching file returns it via [onPick]. Defaults keep the + // full-featured File Manager nav destination unchanged. + pickMode: Boolean = false, + // Directory-pick mode (issue #70): only folders are listed, files are hidden, and a + // "Select this folder" action returns the current directory via [onPick]. Implies pickMode. + pickDirMode: Boolean = false, + pickExtensions: List = emptyList(), + initialDir: File? = null, + pickerTitle: String? = null, + onPick: ((File) -> Unit)? = null, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + + // Only matching files are shown in pick mode (directories are always shown). Empty = all files. + val lowerExts = remember(pickExtensions) { pickExtensions.map { it.lowercase() } } + fun matchesPickExt(file: File): Boolean { + if (lowerExts.isEmpty()) return true + val name = file.name.lowercase() + return lowerExts.any { name.endsWith(".$it") } + } + + val pickPrefs = remember { context.getSharedPreferences("file_manager", android.content.Context.MODE_PRIVATE) } + val browsePrefs = pickPrefs + val rootDir = remember { + // Both modes: honour an explicit caller-supplied start dir (e.g. Log Manager's game-log + // folder), else open at the INTERNAL STORAGE ROOT. Selection screens (drive-folder pick, + // local component pick, imports) previously defaulted to Download which — combined with the + // currentRoot floor below — trapped users in Download with no way up (reported bug). + initialDir?.takeIf { it.isDirectory } ?: File("/storage/emulated/0") + } + + var currentDir by remember { mutableStateOf(rootDir) } + // The up/back FLOOR — back + the up-arrow are disabled while currentDir == currentRoot. It MUST be + // the VOLUME ROOT of the start dir (internal /storage/emulated/0, or an SD card /storage/XXXX-XXXX), + // NOT the start dir itself: otherwise opening at any subfolder disables up/back and traps the user + // there. (Mirrors the volume-root logic in favLocationOf above.) + var currentRoot by remember { + val abs = rootDir.absolutePath + val internal = "/storage/emulated/0" + val vol = when { + abs == internal || abs.startsWith("$internal/") -> File(internal) + abs.startsWith("/storage/") -> { + val name = abs.removePrefix("/storage/").substringBefore('/') + if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else rootDir + } + else -> rootDir + } + mutableStateOf(vol) + } + var entries by remember { mutableStateOf(listOf()) } + var selectedEntry by remember { mutableStateOf(null) } + var showMenuFor by remember { mutableStateOf(null) } + // Clipboard holds a LIST so one paste can carry a whole selection. Cut/copy semantics are a + // flag on the batch rather than per item — mixing the two in one clipboard has no sane meaning. + var clipboardFiles by remember { mutableStateOf>(emptyList()) } + var isCutOperation by remember { mutableStateOf(false) } + // Multi-select. Keyed by absolute path rather than File so a directory reload (which builds + // fresh File objects) doesn't silently drop the selection. + var selectionMode by remember { mutableStateOf(false) } + var selectedPaths by remember { mutableStateOf>(emptySet()) } + // Paste conflict resolution, surfaced from the IO coroutine and answered by the dialog. + var pendingConflict by remember { mutableStateOf(null) } + var conflictChoice by remember { mutableStateOf(null) } + var conflictApplyToAll by remember { mutableStateOf(false) } + // Set while a copy/move runs so the progress UI can offer a cancel. + var operationJob by remember { mutableStateOf(null) } + var pendingBulkDelete by remember { mutableStateOf>(emptyList()) } + // Browse controls. Persisted so the list doesn't reset its order every time you open a folder. + var searchQuery by remember { mutableStateOf("") } + var showSearch by remember { mutableStateOf(false) } + var sortBy by remember { mutableStateOf(browsePrefs.getString("fmSortBy", "name") ?: "name") } + var sortDesc by remember { mutableStateOf(browsePrefs.getBoolean("fmSortDesc", false)) } + var showHidden by remember { mutableStateOf(browsePrefs.getBoolean("fmShowHidden", true)) } + var showSortMenu by remember { mutableStateOf(false) } + // View mode: list of cards (default) or a thumbnail grid. Density applies to the list only — + // a grid tile has no second line to compact. + // The grid/list toggle is the SOURCE OF TRUTH in BOTH orientations (it drives the view and its + // choice persists across rotation). Grid is the default — most useful in landscape, and in + // portrait GridCells.Adaptive naturally renders fewer columns (~2). Do NOT force portrait to list: + // that broke the toggle on-device (tapping it did nothing in portrait). + var gridView by remember { mutableStateOf(browsePrefs.getBoolean("fmGridView", true)) } + val showGrid = gridView + var compactRows by remember { mutableStateOf(browsePrefs.getBoolean("fmCompactRows", false)) } + var showNewFolderDialog by remember { mutableStateOf(false) } + var renameTarget by remember { mutableStateOf(null) } + // Properties sheet (basic info + Read-only / Hidden toggles) target; null when closed. + var propertiesTarget by remember { mutableStateOf(null) } + var isOperationRunning by remember { mutableStateOf(false) } + var operationLabel by remember { mutableStateOf("") } + var operationDeterminate by remember { mutableStateOf(false) } + var operationProgress by remember { mutableFloatStateOf(0f) } + val listState = rememberLazyListState() + val pullState = rememberPullToRefreshState() + + // Favorites view: when on, a dedicated bookmarks list replaces the file list. + // favTick is bumped on any add/remove/toggle so the favorites view + per-row star recompute. + var showFavorites by remember { mutableStateOf(false) } + var favTick by remember { mutableIntStateOf(0) } + + // resetScroll: jump to the top of the list (true for navigation; false for in-place reloads + // after delete/paste/rename/refresh so the user keeps their scroll position). + fun loadDirectory(dir: File, resetScroll: Boolean = true) { + currentDir = dir + // Remember the browsed directory so the next pick resumes here. + if (pickMode) pickPrefs.edit().putString("lastFilePickerDir", dir.absolutePath).apply() + scope.launch { + val list = withContext(Dispatchers.IO) { + dir.listFiles()?.toList() + // Dir-pick mode: folders only. File-pick: folders + matching files. Else: all. + ?.filter { if (pickDirMode) it.isDirectory else !pickMode || it.isDirectory || matchesPickExt(it) } + // Dotfiles are noise in a storage root (.aya, .$recycle_bin$) but occasionally + // the thing you came for, so it's a toggle rather than a permanent filter. + ?.filter { showHidden || !it.name.startsWith(".") } + ?.sortedWith(comparatorFor(sortBy, sortDesc)) ?: emptyList() + } + entries = list + if (resetScroll) listState.scrollToItem(0) + } + } + + // Pull-to-refresh: re-list the current directory, keeping scroll position. + if (pullState.isRefreshing) { + LaunchedEffect(true) { + loadDirectory(currentDir, resetScroll = false) + pullState.endRefresh() + } + } + + // Jump to a drive's root; pins the Back boundary so we don't climb above it. + fun openDrive(dir: File) { + currentRoot = dir + loadDirectory(dir) + } + + LaunchedEffect(Unit) { openDrive(rootDir) } + + // System/gesture Back: while the Favorites view is open it closes that first; otherwise + // it goes up one directory. Only at the current drive's root with Favorites closed is it + // disabled, letting Back propagate to close the File Manager. + BackHandler(enabled = showFavorites || currentDir != currentRoot) { + if (showFavorites) { + showFavorites = false + return@BackHandler + } + val parent = currentDir.parentFile + if (parent != null && parent.exists()) loadDirectory(parent) + } + + // Resolve a non-colliding destination in [dir] for [name] (foo.txt -> "foo (1).txt"). + fun uniqueDestination(dir: File, name: String): File { + var candidate = File(dir, name) + if (!candidate.exists()) return candidate + val dot = name.lastIndexOf('.') + val base = if (dot > 0) name.substring(0, dot) else name + val ext = if (dot > 0) name.substring(dot) else "" + var i = 1 + do { + candidate = File(dir, "$base ($i)$ext") + i++ + } while (candidate.exists()) + return candidate + } + + fun performDelete(file: File) { + scope.launch { + isOperationRunning = true + operationLabel = "Deleting..." + val ok = withContext(Dispatchers.IO) { FileOps.delete(file) } + isOperationRunning = false + loadDirectory(currentDir, resetScroll = false) + if (!ok) Toast.makeText(context, "Delete failed", Toast.LENGTH_SHORT).show() + } + } + + /** Waits for the user to answer the conflict dialog for [file]; null if they cancelled it. */ + suspend fun askConflict(file: File): ConflictChoice? { + pendingConflict = file + conflictChoice = null + // Poll rather than plumb a CompletableDeferred through Compose state — the dialog answers + // by setting conflictChoice, and this coroutine is already off the critical path. + while (pendingConflict != null && conflictChoice == null) kotlinx.coroutines.delay(50) + return conflictChoice + } + + fun performPaste() { + val sources = clipboardFiles + if (sources.isEmpty()) return + val dstDir = currentDir + val cut = isCutOperation + + operationJob = scope.launch { + operationProgress = 0f + operationDeterminate = true + operationLabel = if (cut) "Moving..." else "Copying..." + isOperationRunning = true + + var applyToAll: ConflictChoice? = null + var failed = 0 + var skipped = 0 + var done = 0 + + for (src in sources) { + // Pasting a folder into itself or its own subtree would recurse forever. + if (src.isDirectory && isWithin(dstDir, src)) { + failed++ + continue + } + // Moving into the folder it already sits in is a no-op. + if (cut && src.parentFile?.absolutePath == dstDir.absolutePath) { + skipped++ + continue + } + + var dst = File(dstDir, src.name) + if (dst.exists()) { + val choice = applyToAll ?: askConflict(src)?.also { + if (conflictApplyToAll) applyToAll = it + } ?: run { skipped++; null } ?: continue + when (choice) { + // Overwrite and Merge both paste onto the real destination: copyWithProgress + // recurses into an existing directory and truncates existing files, so the + // two differ only in what the user expects, not in what we call. + ConflictChoice.OVERWRITE, ConflictChoice.MERGE -> Unit + ConflictChoice.KEEP_BOTH -> dst = uniqueDestination(dstDir, src.name) + ConflictChoice.SKIP -> { skipped++; continue } + } + } + + // Progress is per item; with a batch the label carries the overall position. + operationLabel = buildString { + append(if (cut) "Moving" else "Copying") + if (sources.size > 1) append(" ${done + 1}/${sources.size}") + append(" — ").append(src.name) + } + var lastPct = -1 + val onProgress = FileOps.ProgressCallback { copied, total -> + val pct = if (total > 0) ((copied * 100) / total).toInt() else 100 + if (pct != lastPct) { + lastPct = pct + operationProgress = pct / 100f + } + } + val target = dst + val ok = withContext(Dispatchers.IO) { + if (cut) FileOps.moveWithProgress(src, target, onProgress) + else FileOps.copyWithProgress(src, target, onProgress) + } + if (ok) done++ else failed++ + } + + isOperationRunning = false + operationDeterminate = false + operationJob = null + clipboardFiles = emptyList() + isCutOperation = false + selectionMode = false + selectedPaths = emptySet() + loadDirectory(currentDir, resetScroll = false) + + val message = when { + failed > 0 -> "$done done, $failed failed" + skipped > 0 -> "$done done, $skipped skipped" + sources.size > 1 -> "$done items ${if (cut) "moved" else "copied"}" + else -> null + } + if (message != null) Toast.makeText(context, message, Toast.LENGTH_SHORT).show() + } + } + + fun performRename(file: File, newName: String) { + val target = File(file.parentFile, newName) + if (target.exists()) { + Toast.makeText(context, "\"$newName\" already exists", Toast.LENGTH_SHORT).show() + return + } + scope.launch { + isOperationRunning = true + operationLabel = "Renaming..." + val ok = withContext(Dispatchers.IO) { file.renameTo(target) } + isOperationRunning = false + loadDirectory(currentDir, resetScroll = false) + if (!ok) Toast.makeText(context, "Rename failed", Toast.LENGTH_SHORT).show() + } + } + + fun createFolder(parent: File, name: String) { + val target = File(parent, name) + if (target.exists()) { + Toast.makeText(context, "\"$name\" already exists", Toast.LENGTH_SHORT).show() + return + } + scope.launch { + isOperationRunning = true + operationLabel = "Creating folder..." + val ok = withContext(Dispatchers.IO) { target.mkdirs() } + isOperationRunning = false + loadDirectory(currentDir, resetScroll = false) + if (!ok) Toast.makeText(context, "Could not create folder", Toast.LENGTH_SHORT).show() + } + } + + var showDriveMenu by remember { mutableStateOf(false) } + // Re-enumerated whenever we come back to the screen: returning from a container can leave this + // process on a stale storage view, and the volume set has to be re-read rather than cached. + var storageTick by remember { mutableIntStateOf(0) } + val lifecycleOwner = LocalLifecycleOwner.current + DisposableEffect(lifecycleOwner) { + val observer = LifecycleEventObserver { _, event -> + if (event == Lifecycle.Event.ON_RESUME) storageTick++ + } + lifecycleOwner.lifecycle.addObserver(observer) + onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } + } + val drives = remember(storageTick) { StorageRoots.list(context) } + + // ── Dialogs ── + + if (showNewFolderDialog) { + var folderName by remember { mutableStateOf("") } + OutlinedAlertDialog( + onDismissRequest = { showNewFolderDialog = false }, + title = { Text("New Folder") }, + text = { + OutlinedTextField( + value = folderName, + onValueChange = { folderName = it }, + label = { Text("Folder name") }, + singleLine = true, + ) + }, + confirmButton = { + TextButton(onClick = { + showNewFolderDialog = false + if (folderName.isNotBlank()) createFolder(currentDir, folderName) + }) { Text("Create") } + }, + dismissButton = { TextButton(onClick = { showNewFolderDialog = false }) { Text("Cancel") } }, + ) + } + + if (renameTarget != null) { + var newName by remember(renameTarget) { mutableStateOf(renameTarget?.name ?: "") } + OutlinedAlertDialog( + onDismissRequest = { renameTarget = null }, + title = { Text("Rename") }, + text = { + OutlinedTextField( + value = newName, + onValueChange = { newName = it }, + label = { Text("New name") }, + singleLine = true, + ) + }, + confirmButton = { + TextButton(onClick = { + val file = renameTarget + renameTarget = null + if (file != null && newName.isNotBlank()) performRename(file, newName) + }) { Text("Rename") } + }, + dismissButton = { TextButton(onClick = { renameTarget = null }) { Text("Cancel") } }, + ) + } + + propertiesTarget?.let { file -> + FilePropertiesDialog( + file = file, + onDismiss = { propertiesTarget = null }, + // Attribute changes affect Hidden/read-only which the listing filters/sorts on, so refresh + // in place (keeping scroll) after any toggle applies. + onChanged = { loadDirectory(currentDir, resetScroll = false) }, + ) + } + + if (selectedEntry != null && selectedEntry != showMenuFor) { + val file = selectedEntry ?: return + OutlinedAlertDialog( + onDismissRequest = { selectedEntry = null }, + title = { Text("Delete?") }, + text = { Text("Delete \"${file.name}\" permanently?") }, + confirmButton = { + TextButton(onClick = { + selectedEntry = null + performDelete(file) + }) { Text("Delete") } + }, + dismissButton = { TextButton(onClick = { selectedEntry = null }) { Text("Cancel") } }, + ) + } + + if (pendingBulkDelete.isNotEmpty()) { + val victims = pendingBulkDelete + OutlinedAlertDialog( + onDismissRequest = { pendingBulkDelete = emptyList() }, + title = { Text("Delete ${victims.size} item${if (victims.size == 1) "" else "s"}?") }, + text = { + Column { + Text("This can't be undone.") + Spacer(Modifier.height(6.dp)) + // Name a few so an accidental Select-All is obvious before it's too late. + victims.take(5).forEach { + Text("• ${it.name}", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp) + } + if (victims.size > 5) { + Text( + "…and ${victims.size - 5} more", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + ) + } + } + }, + confirmButton = { + TextButton(onClick = { + pendingBulkDelete = emptyList() + selectionMode = false + selectedPaths = emptySet() + operationJob = scope.launch { + isOperationRunning = true + var failed = 0 + victims.forEachIndexed { i, f -> + operationLabel = "Deleting ${i + 1}/${victims.size} — ${f.name}" + if (!withContext(Dispatchers.IO) { FileOps.delete(f) }) failed++ + } + isOperationRunning = false + operationJob = null + loadDirectory(currentDir, resetScroll = false) + if (failed > 0) { + Toast.makeText(context, "$failed couldn't be deleted", Toast.LENGTH_SHORT).show() + } + } + }) { Text("Delete", color = MaterialTheme.colorScheme.error) } + }, + dismissButton = { TextButton(onClick = { pendingBulkDelete = emptyList() }) { Text("Cancel") } }, + ) + } + + // Paste conflict — one per colliding item, with "apply to all" for a long batch. + pendingConflict?.let { conflict -> + val isDir = conflict.isDirectory + OutlinedAlertDialog( + onDismissRequest = { pendingConflict = null }, + title = { Text("\"${conflict.name}\" already exists") }, + text = { + Column { + Text( + if (isDir) "Merge adds and replaces files inside the existing folder." + else "Overwrite replaces the existing file.", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + ) + if (clipboardFiles.size > 1) { + Spacer(Modifier.height(8.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + androidx.compose.material3.Checkbox( + checked = conflictApplyToAll, + onCheckedChange = { conflictApplyToAll = it }, + ) + Text("Apply to all conflicts", fontSize = 12.sp) + } + } + Spacer(Modifier.height(4.dp)) + listOf( + (if (isDir) ConflictChoice.MERGE else ConflictChoice.OVERWRITE) to + (if (isDir) "Merge" else "Overwrite"), + ConflictChoice.KEEP_BOTH to "Keep both", + ConflictChoice.SKIP to "Skip", + ).forEach { (choice, label) -> + TextButton( + modifier = Modifier.fillMaxWidth(), + onClick = { conflictChoice = choice; pendingConflict = null }, + ) { Text(label, modifier = Modifier.fillMaxWidth()) } + } + } + }, + confirmButton = {}, + dismissButton = { + TextButton(onClick = { conflictChoice = ConflictChoice.SKIP; pendingConflict = null }) { + Text("Cancel") + } + }, + ) + } + + Column(modifier = Modifier.fillMaxSize()) { + // ── Pick-mode title ── + if (pickMode && !pickerTitle.isNullOrEmpty()) { + Text( + text = pickerTitle, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.surfaceContainer) + .padding(horizontal = 16.dp, vertical = 10.dp), + ) + } + // ── Dir-pick action bar: confirm the currently-browsed folder ── + if (pickDirMode) { + Button( + onClick = { onPick?.invoke(currentDir) }, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + Icon(Icons.Filled.Folder, null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text("Select this folder") + } + } + // ── Path bar ── + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.surfaceContainer) + .padding(horizontal = 8.dp, vertical = 6.dp), + ) { + IconButton(onClick = { + val parent = currentDir.parentFile + // Don't climb above the current drive's root. + if (currentDir != currentRoot && parent != null && parent.exists()) loadDirectory(parent) + }, enabled = currentDir != currentRoot) { + Icon(Icons.Filled.ArrowBack, "Back", tint = MaterialTheme.colorScheme.primary) + } + + val currentDriveLabel = describeLocation(currentDir).driveLabel + // Dim the drive chip while the Favorites list is open (it's not the active context). + val driveChipAlpha = if (showFavorites) 0.45f else 1f + Box { + // The drive/location selector opens the drive dropdown, so give it the same outlined + // look as the "New Folder" button + the rail location items — it reads as a button, not + // plain text. Border uses the theme accent token; behaviour unchanged. + val driveChipShape = RoundedCornerShape(8.dp) + Text( + text = " $currentDriveLabel ▾", + color = MaterialTheme.colorScheme.onBackground.copy(alpha = driveChipAlpha), + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier + .clip(driveChipShape) + .background(MaterialTheme.colorScheme.surfaceContainer) + .border(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f), driveChipShape) + .clickable { showDriveMenu = true } + .padding(horizontal = 10.dp, vertical = 5.dp), + ) + DropdownMenu( + expanded = showDriveMenu, + onDismissRequest = { showDriveMenu = false }, + modifier = Modifier.outlinedMenuCard(), + ) { + drives.forEachIndexed { i, drive -> + if (i > 0) MenuItemDivider() + DropdownMenuItem( + text = { Text(drive.label) }, + leadingIcon = { + Icon( + if (drive.removable) Icons.Filled.SdStorage else Icons.Filled.Storage, + null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(18.dp), + ) + }, + onClick = { + showDriveMenu = false + if (drive.readable) { + openDrive(drive.dir) + } else { + Toast.makeText( + context, + "${drive.label} is mounted but not readable right now", + Toast.LENGTH_SHORT, + ).show() + } + }, + ) + } + } + } + + Spacer(Modifier.width(4.dp)) + + if (showFavorites) { + Text( + text = "★ Favorites", + color = MaterialTheme.colorScheme.primary, + fontSize = 13.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + } else if (LocalConfiguration.current.orientation == Configuration.ORIENTATION_PORTRAIT) { + // PORTRAIT: hide the current-folder name — it's redundant with the path bar directly + // below (which shows the full path). The spacer keeps the action icons right-aligned. + Spacer(Modifier.weight(1f)) + } else { + // LANDSCAPE: the CURRENT FOLDER, not the full path. A path ellipsised on the right + // hides its tail — the only part that says where you are ("…/Winlator/Game…"). The + // full path moves to the line below, where it has room. + Text( + text = currentDir.name.ifBlank { currentDir.absolutePath }, + color = MaterialTheme.colorScheme.onSurface, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + } + + if (!showFavorites) { + // New Folder moved off a bottom bar into the toolbar (next to the grid/list toggle), + // as a compact outlined button, so the file list reclaims that bottom strip. + if (!pickMode) { + OutlinedButton( + onClick = { showNewFolderDialog = true }, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp), + modifier = Modifier.height(32.dp), + ) { + Icon(Icons.Filled.CreateNewFolder, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(5.dp)) + Text("New Folder", color = MaterialTheme.colorScheme.onBackground, fontSize = 12.sp) + } + } + IconButton(onClick = { + gridView = !gridView + browsePrefs.edit().putBoolean("fmGridView", gridView).apply() + }) { + Icon( + if (gridView) Icons.Filled.ViewList else Icons.Filled.GridView, + if (gridView) "List view" else "Grid view", + tint = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + IconButton(onClick = { showSearch = !showSearch; if (!showSearch) searchQuery = "" }) { + Icon(Icons.Filled.Search, "Search", tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + Box { + IconButton(onClick = { showSortMenu = true }) { + Icon(Icons.Filled.Sort, "Sort", tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + DropdownMenu(expanded = showSortMenu, onDismissRequest = { showSortMenu = false }) { + listOf("name" to "Name", "date" to "Date modified", "size" to "Size") + .forEach { (key, label) -> + DropdownMenuItem( + text = { + Text(if (sortBy == key) "$label ${if (sortDesc) "↓" else "↑"}" else label) + }, + onClick = { + // Tapping the active field flips direction; a different + // field switches to it ascending. + if (sortBy == key) sortDesc = !sortDesc else { sortBy = key; sortDesc = false } + browsePrefs.edit().putString("fmSortBy", sortBy) + .putBoolean("fmSortDesc", sortDesc).apply() + showSortMenu = false + loadDirectory(currentDir, resetScroll = false) + }, + ) + } + HorizontalDivider(color = MaterialTheme.colorScheme.outline) + DropdownMenuItem( + text = { Text(if (compactRows) "Comfortable rows" else "Compact rows") }, + onClick = { + compactRows = !compactRows + browsePrefs.edit().putBoolean("fmCompactRows", compactRows).apply() + showSortMenu = false + }, + ) + DropdownMenuItem( + text = { Text(if (showHidden) "Hide hidden files" else "Show hidden files") }, + onClick = { + showHidden = !showHidden + browsePrefs.edit().putBoolean("fmShowHidden", showHidden).apply() + showSortMenu = false + loadDirectory(currentDir, resetScroll = false) + }, + ) + } + } + } + + // Star toggle: open/close the dedicated Favorites list. + IconButton(onClick = { showFavorites = !showFavorites }) { + if (showFavorites) { + Icon(Icons.Filled.Star, "Hide favorites", tint = MaterialTheme.colorScheme.primary) + } else { + Icon(Icons.Filled.StarBorder, "Show favorites", tint = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } + + // ── Search field ── filters the current folder only; it is not a recursive search. + if (showSearch && !showFavorites) { + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + singleLine = true, + placeholder = { Text("Filter this folder", fontSize = 13.sp) }, + modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp), + ) + } + + // Free space on the volume being browsed — worth knowing before starting a 60 GB copy. + val freeSpace = remember(currentDir.absolutePath, entries) { + runCatching { currentDir.usableSpace }.getOrDefault(0L) + } + if (!showFavorites) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 2.dp), + ) { + Text( + // Elided from the LEFT: the deepest part of a path is the informative part, so + // when it doesn't fit we drop the /storage/emulated/0 prefix, not the tail. + text = elidePathStart(currentDir.absolutePath, 52), + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 11.sp, + maxLines = 1, + // fill = true: the path takes all remaining width, so the free-space figure + // is pinned to the right edge instead of sliding around with the path length. + modifier = Modifier.weight(1f), + ) + if (freeSpace > 0) { + Text( + "${FileOps.formatBytes(freeSpace)} free", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 11.sp, + maxLines = 1, + ) + } + } + } + + HorizontalDivider(color = MaterialTheme.colorScheme.outline) + + // ── Selection bar ── replaces the paste banner while picking items. + if (selectionMode) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.primary.copy(alpha = 0.12f)) + .padding(horizontal = 12.dp, vertical = 6.dp), + ) { + Text( + "${selectedPaths.size} selected", + color = MaterialTheme.colorScheme.onBackground, + fontSize = 13.sp, + modifier = Modifier.weight(1f), + ) + // Compact outlined buttons so all five fit one row alongside the count. + val selBarPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp) + OutlinedButton( + onClick = { + selectedPaths = if (selectedPaths.size == entries.size) emptySet() + else entries.map { it.absolutePath }.toSet() + }, + contentPadding = selBarPadding, + ) { Text(if (selectedPaths.size == entries.size) "None" else "All", fontSize = 12.sp) } + Spacer(Modifier.width(4.dp)) + OutlinedButton( + enabled = selectedPaths.isNotEmpty(), + onClick = { + clipboardFiles = entries.filter { it.absolutePath in selectedPaths } + isCutOperation = false + selectionMode = false + selectedPaths = emptySet() + }, + contentPadding = selBarPadding, + ) { Text("Copy", fontSize = 12.sp) } + Spacer(Modifier.width(4.dp)) + OutlinedButton( + enabled = selectedPaths.isNotEmpty(), + onClick = { + clipboardFiles = entries.filter { it.absolutePath in selectedPaths } + isCutOperation = true + selectionMode = false + selectedPaths = emptySet() + }, + contentPadding = selBarPadding, + ) { Text("Cut", fontSize = 12.sp) } + Spacer(Modifier.width(4.dp)) + OutlinedButton( + enabled = selectedPaths.isNotEmpty(), + onClick = { pendingBulkDelete = entries.filter { it.absolutePath in selectedPaths } }, + contentPadding = selBarPadding, + border = BorderStroke(1.dp, MaterialTheme.colorScheme.error), + ) { Text("Delete", color = MaterialTheme.colorScheme.error, fontSize = 12.sp) } + Spacer(Modifier.width(4.dp)) + OutlinedButton( + onClick = { selectionMode = false; selectedPaths = emptySet() }, + contentPadding = selBarPadding, + ) { Text("Done", fontSize = 12.sp) } + } + } + + // ── Paste banner ── + if (clipboardFiles.isNotEmpty()) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.outline.copy(alpha = 0.1f)) + .clickable { performPaste() } + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + Icon(Icons.Filled.ContentPaste, "Paste", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + val what = if (clipboardFiles.size == 1) clipboardFiles.first().name + else "${clipboardFiles.size} items" + Text( + "Paste $what${if (isCutOperation) " (move)" else ""} here", + color = MaterialTheme.colorScheme.onBackground, fontSize = 13.sp, modifier = Modifier.weight(1f), + ) + TextButton(onClick = { clipboardFiles = emptyList(); isCutOperation = false }) { + Text("Cancel", color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp) + } + } + } + + // ── Progress overlay ── + if (isOperationRunning) { + Column( + modifier = Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.surfaceContainer) + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + val pctText = if (operationDeterminate) " ${(operationProgress * 100).toInt()}%" else "" + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + "$operationLabel$pctText", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + // A multi-gigabyte copy onto a slow card is exactly when you discover you + // picked the wrong folder; without this the only way out was killing the app. + if (operationJob != null) { + TextButton(onClick = { + operationJob?.cancel() + operationJob = null + isOperationRunning = false + operationDeterminate = false + loadDirectory(currentDir, resetScroll = false) + }) { Text("Cancel", fontSize = 12.sp) } + } + } + Spacer(Modifier.height(4.dp)) + if (operationDeterminate) { + LinearProgressIndicator( + progress = { operationProgress }, + modifier = Modifier.fillMaxWidth().height(4.dp), + color = MaterialTheme.colorScheme.primary, + trackColor = MaterialTheme.colorScheme.outline, + ) + } else { + LinearProgressIndicator( + modifier = Modifier.fillMaxWidth().height(4.dp), + color = MaterialTheme.colorScheme.primary, + trackColor = MaterialTheme.colorScheme.outline, + ) + } + } + } + + // ── Left locations rail (mockup Option 2) + content ── + // Shared collapsible rail: landscape expanded by default, portrait collapsed icon-only. Not + // shown in pick mode (the themed picker keeps its slim layout). Built each recompose (cheap) + // so it tracks the current drive/favourites without stale click lambdas. + val fmRailState = rememberRailState("filemanager") + fun locItem(label: String, icon: androidx.compose.ui.graphics.vector.ImageVector, dir: File) = + RailItem(label, icon, !showFavorites && currentRoot.absolutePath == dir.absolutePath) { + showFavorites = false; openDrive(dir) + } + val storageItems = buildList { + add(locItem("Internal", Icons.Filled.Smartphone, File("/storage/emulated/0"))) + drives.filter { it.removable }.forEach { d -> + add(RailItem(d.label, Icons.Filled.SdStorage, !showFavorites && currentRoot.absolutePath == d.dir.absolutePath) { + showFavorites = false; if (d.readable) openDrive(d.dir) + }) + } + } + val quickItems = buildList { + File("/storage/emulated/0/Download").takeIf { it.isDirectory }?.let { add(locItem("Downloads", Icons.Filled.Download, it)) } + // The ROMs folder chosen on the main screen: what the session shows as /root/ROMs. + SessionPrefs.romsDir(context).takeIf { it.isNotEmpty() }?.let(::File)?.takeIf { it.isDirectory } + ?.let { add(locItem("ROMs", Icons.Filled.SportsEsports, it)) } + File("/storage/emulated/0/Download/SteamDeck").takeIf { it.isDirectory }?.let { add(locItem("Session logs", Icons.Filled.Description, it)) } + File("/storage/emulated/0/Pictures").takeIf { it.isDirectory }?.let { add(locItem("Pictures", Icons.Filled.Image, it)) } + } + val favItems = remember(favTick) { FavoritesStore.list(context).map(::File).filter { it.exists() } } + .map { d -> RailItem(d.name, Icons.Filled.Star, false) { showFavorites = false; openDrive(d) } } + val locationSections = buildList { + add(RailSection("STORAGE", storageItems)) + if (quickItems.isNotEmpty()) add(RailSection("QUICK", quickItems)) + if (favItems.isNotEmpty()) add(RailSection("★ FAVORITES", favItems)) + } + + Row(modifier = Modifier.weight(1f).fillMaxWidth()) { + // The slim picker keeps its layout: no rail. + if (!pickMode) { + CollapsibleRail(state = fmRailState, title = "Files", sections = locationSections, outlinedItems = true) + } + Box(modifier = Modifier.weight(1f).fillMaxSize()) { + // ── Favorites list OR file list ── + if (showFavorites) { + FavoritesList( + currentDir = currentDir, + favTick = favTick, + onPinCurrent = { + FavoritesStore.add(context, currentDir.absolutePath) + favTick++ + Toast.makeText(context, "Added \"${currentDir.name}\" to Favorites", Toast.LENGTH_SHORT).show() + }, + onJump = { dir -> + showFavorites = false + openDrive(dir) + }, + onUnpin = { dir -> + FavoritesStore.remove(context, dir.absolutePath) + favTick++ + Toast.makeText(context, "Removed \"${dir.name}\" from Favorites", Toast.LENGTH_SHORT).show() + }, + modifier = Modifier.fillMaxSize(), + ) + } else { + // ── File list (pull down to refresh) ── + Box( + modifier = Modifier + .fillMaxSize() + .nestedScroll(pullState.nestedScrollConnection), + ) { + val shownEntries = if (searchQuery.isBlank()) entries + else entries.filter { it.name.contains(searchQuery, ignoreCase = true) } + + if (showGrid && entries.isNotEmpty()) { + LazyVerticalGrid( + columns = GridCells.Adaptive(minSize = 104.dp), + modifier = Modifier.fillMaxSize(), + contentPadding = PaddingValues(8.dp), + ) { + items(shownEntries, key = { it.absolutePath }) { file -> + val isFav = remember(file.absolutePath, favTick) { + FavoritesStore.isFavorite(context, file.absolutePath) + } + FileGridTile( + file = file, + selectionMode = selectionMode, + selected = file.absolutePath in selectedPaths, + onLongPress = { + if (!pickMode) { + // In selection mode a long-press toggles; otherwise it opens the + // same context menu the list rows show (the tile has no ⋮ button). + if (selectionMode) { + selectedPaths = if (file.absolutePath in selectedPaths) + selectedPaths - file.absolutePath + else selectedPaths + file.absolutePath + } else { + showMenuFor = file + } + } + }, + onToggleSelect = { + selectedPaths = if (file.absolutePath in selectedPaths) + selectedPaths - file.absolutePath + else selectedPaths + file.absolutePath + }, + onTap = { + if (file.isDirectory) loadDirectory(file) + else if (pickMode) { + if (matchesPickExt(file)) { + pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() + onPick?.invoke(file) + } + } + }, + onMenu = { showMenuFor = file }, + menuExpanded = showMenuFor == file, + onDismissMenu = { showMenuFor = null }, + isFavorite = isFav, + onSelect = { + selectionMode = true + selectedPaths = selectedPaths + file.absolutePath + showMenuFor = null + }, + onRename = { renameTarget = file; showMenuFor = null }, + onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, + onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, + onDelete = { selectedEntry = file; showMenuFor = null }, + onToggleFavorite = { + val nowFav = FavoritesStore.toggle(context, file.absolutePath) + favTick++ + showMenuFor = null + Toast.makeText( + context, + if (nowFav) "Added \"${file.name}\" to Favorites" + else "Removed \"${file.name}\" from Favorites", + Toast.LENGTH_SHORT, + ).show() + }, + onProperties = { propertiesTarget = file; showMenuFor = null }, + ) + } + } + } else + LazyColumn(state = listState, modifier = Modifier.fillMaxSize()) { + if (entries.isEmpty()) { + item { + Box( + modifier = Modifier.fillParentMaxSize(), + contentAlignment = Alignment.Center, + ) { + Text("Empty directory", color = MaterialTheme.colorScheme.onSurfaceVariant) + } + } + } else { + val shown = shownEntries + items(shown, key = { it.absolutePath }) { file -> + val isFav = remember(file.absolutePath, favTick) { + FavoritesStore.isFavorite(context, file.absolutePath) + } + FileItemRow( + file = file, + showActions = !pickMode, + compact = compactRows, + selectionMode = selectionMode, + selected = file.absolutePath in selectedPaths, + onLongPress = { + // In selection mode a long-press toggles; otherwise it opens the + // per-item context menu (matching the grid tiles). + if (!pickMode) { + if (selectionMode) { + selectedPaths = if (file.absolutePath in selectedPaths) + selectedPaths - file.absolutePath + else selectedPaths + file.absolutePath + } else { + showMenuFor = file + } + } + }, + onToggleSelect = { + selectedPaths = if (file.absolutePath in selectedPaths) + selectedPaths - file.absolutePath + else selectedPaths + file.absolutePath + }, + onTap = { + if (file.isDirectory) loadDirectory(file) + else if (pickMode) { + if (matchesPickExt(file)) { + pickPrefs.edit().putString("lastFilePickerDir", currentDir.absolutePath).apply() + onPick?.invoke(file) + } + } + }, + onMenu = { showMenuFor = file }, + menuExpanded = showMenuFor == file, + onDismissMenu = { showMenuFor = null }, + onSelect = { + selectionMode = true + selectedPaths = selectedPaths + file.absolutePath + showMenuFor = null + }, + onCopy = { clipboardFiles = listOf(file); isCutOperation = false; showMenuFor = null }, + onCut = { clipboardFiles = listOf(file); isCutOperation = true; showMenuFor = null }, + onDelete = { selectedEntry = file; showMenuFor = null }, + onRename = { renameTarget = file; showMenuFor = null }, + isFavorite = isFav, + onToggleFavorite = { + val nowFav = FavoritesStore.toggle(context, file.absolutePath) + favTick++ + showMenuFor = null + Toast.makeText( + context, + if (nowFav) "Added \"${file.name}\" to Favorites" + else "Removed \"${file.name}\" from Favorites", + Toast.LENGTH_SHORT, + ).show() + }, + onProperties = { propertiesTarget = file; showMenuFor = null }, + ) + } + } + } + // material3 1.2.0's PullToRefreshContainer draws its indicator even at rest; + // only show it while the user is actively pulling or a refresh is running. + if (pullState.verticalOffset > 0.5f || pullState.isRefreshing) { + PullToRefreshContainer( + state = pullState, + modifier = Modifier.align(Alignment.TopCenter), + ) + } + } + } + } // end content Box (beside the rail) + } // end rail + content Row + // (New Folder moved into the top toolbar; the bottom bar was removed to reclaim its strip.) + } +} + +// The context-menu item list shared by the list rows (FileItemRow) and the grid tiles +// (FileGridTile), so both open the identical menu. Gating (isDir/canRun/isInno/looksLikeArchive) is +// recomputed from [file] here — one source of truth for what each item shows. Every item dismisses +// the menu first, then runs its action. +@Composable +private fun FileContextMenuItems( + file: File, + isFavorite: Boolean, + onSelect: () -> Unit, + onRename: () -> Unit, + onCopy: () -> Unit, + onCut: () -> Unit, + onDelete: () -> Unit, + onToggleFavorite: () -> Unit, + onProperties: () -> Unit, + onDismissMenu: () -> Unit, +) { + val isDir = file.isDirectory + // Enter multi-select on this item (replaces the old long-press-only entry point). + DropdownMenuItem( + text = { Text("Select") }, + leadingIcon = { Icon(Icons.Filled.Checklist, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onSelect() }, + ) + MenuItemDivider() + // Properties: basic info + Read-only / Hidden toggles, for ANY file or folder (handy for config + // files like .txt/.cfg/.ini). Kept near the top since it's a common reason to open this menu. + DropdownMenuItem( + text = { Text("Properties") }, + leadingIcon = { Icon(Icons.Filled.Info, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onProperties() }, + ) + MenuItemDivider() + // Favorites are directories — only folders get the pin toggle. + if (isDir) { + DropdownMenuItem( + text = { Text(if (isFavorite) "Remove from Favorites" else "Add to Favorites") }, + leadingIcon = { + Icon( + if (isFavorite) Icons.Filled.Star else Icons.Filled.StarBorder, + null, + tint = MaterialTheme.colorScheme.primary, + ) + }, + onClick = { onToggleFavorite() }, + ) + MenuItemDivider() + } + DropdownMenuItem( + text = { Text("Rename") }, + leadingIcon = { Icon(Icons.Filled.Edit, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onRename() }, + ) + MenuItemDivider() + DropdownMenuItem( + text = { Text("Copy") }, + leadingIcon = { Icon(Icons.Filled.FileCopy, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onCopy() }, + ) + MenuItemDivider() + DropdownMenuItem( + text = { Text("Cut") }, + leadingIcon = { Icon(Icons.Filled.ContentCut, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onCut() }, + ) + MenuItemDivider() + DropdownMenuItem( + text = { Text("Delete") }, + leadingIcon = { Icon(Icons.Filled.Delete, null, tint = MaterialTheme.colorScheme.primary) }, + onClick = { onDismissMenu(); onDelete() }, + ) +} + +@Composable +@OptIn(ExperimentalFoundationApi::class) +private fun FileItemRow( + file: File, + showActions: Boolean = true, + compact: Boolean = false, + selectionMode: Boolean = false, + selected: Boolean = false, + onLongPress: () -> Unit = {}, + onToggleSelect: () -> Unit = {}, + onTap: () -> Unit, + onMenu: () -> Unit, + menuExpanded: Boolean, + onDismissMenu: () -> Unit, + onSelect: () -> Unit = {}, + onCopy: () -> Unit, + onCut: () -> Unit, + onDelete: () -> Unit, + onRename: () -> Unit, + isFavorite: Boolean = false, + onToggleFavorite: () -> Unit = {}, + onProperties: () -> Unit = {}, +) { + val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) } + val isDir = file.isDirectory + val isExe = !isDir && file.name.lowercase().let { it.endsWith(".exe") || it.endsWith(".bat") || it.endsWith(".msi") || it.endsWith(".sh") } + // Image files show a real thumbnail instead of the generic file icon (handy when picking a + // wallpaper/icon). Coil sizes the decode to the 36dp slot and caches it, so scrolling stays smooth. + val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS + + // For real PE executables, try to pull out the embedded application icon (async, off the main thread). + var exeIcon by remember(file.absolutePath) { mutableStateOf(null) } + if (!isDir && file.name.lowercase().endsWith(".exe")) { + LaunchedEffect(file.absolutePath) { + val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) } + if (bmp != null) exeIcon = bmp.asImageBitmap() + } + } + + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 3.dp) + .combinedClickable( + // In selection mode a tap toggles instead of opening, so you can rattle through a + // folder without long-pressing every single row. + onClick = { if (selectionMode) onToggleSelect() else onTap() }, + onLongClick = onLongPress, + ), + shape = RoundedCornerShape(10.dp), + colors = CardDefaults.cardColors( + containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f) + else MaterialTheme.colorScheme.surfaceContainer, + ), + border = BorderStroke( + 1.dp, + if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline, + ), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(horizontal = 12.dp, vertical = if (compact) 3.dp else 8.dp), + ) { + if (selectionMode) { + androidx.compose.material3.Checkbox(checked = selected, onCheckedChange = { onToggleSelect() }) + Spacer(Modifier.width(4.dp)) + } + when { + // Show the executable's own embedded icon when we managed to extract one. + exeIcon != null -> Image( + bitmap = exeIcon!!, + contentDescription = null, + modifier = Modifier.size(if (compact) 24.dp else 36.dp), + ) + isExe -> Icon( + painter = painterResource(R.drawable.icon_menu_container), + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(if (compact) 24.dp else 36.dp), + ) + isDir -> Icon( + imageVector = Icons.Filled.Folder, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(if (compact) 24.dp else 36.dp), + ) + // Real image preview. Falls back to the generic file icon while loading or on decode failure. + isImage -> AsyncImage( + model = file, + contentDescription = null, + contentScale = ContentScale.Crop, + placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile), + error = rememberVectorPainter(Icons.Filled.InsertDriveFile), + modifier = Modifier + .size(36.dp) + .clip(RoundedCornerShape(6.dp)), + ) + else -> Icon( + imageVector = Icons.Filled.InsertDriveFile, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.size(if (compact) 24.dp else 36.dp), + ) + } + Spacer(Modifier.width(10.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = file.name, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Text( + text = buildString { + if (!isDir) append(FileOps.formatBytes(file.length())).append(" \u2022 ") + append(dateFormat.format(Date(file.lastModified()))) + }, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 11.sp, + ) + } + if (showActions) Box { + IconButton(onClick = onMenu) { + Icon(Icons.Filled.MoreVert, "Actions", tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(20.dp)) + } + DropdownMenu( + expanded = menuExpanded, + onDismissRequest = onDismissMenu, + modifier = Modifier.outlinedMenuCard(), + ) { + FileContextMenuItems( + file = file, + isFavorite = isFavorite, + onSelect = onSelect, + onRename = onRename, + onCopy = onCopy, + onCut = onCut, + onDelete = onDelete, + onToggleFavorite = onToggleFavorite, + onProperties = onProperties, + onDismissMenu = onDismissMenu, + ) + } + } + } + } +} + +// Dedicated Favorites list that replaces the file list while the star toggle is on. +// Reads the store keyed on [favTick] so it recomposes after any pin/unpin. +@Composable +private fun FavoritesList( + currentDir: File, + favTick: Int, + onPinCurrent: () -> Unit, + onJump: (File) -> Unit, + onUnpin: (File) -> Unit, + modifier: Modifier = Modifier, +) { + val context = LocalContext.current + val favorites = remember(favTick) { + FavoritesStore.list(context).map(::File).filter { it.exists() } + } + val currentAlreadyPinned = remember(favTick, currentDir.absolutePath) { + FavoritesStore.isFavorite(context, currentDir.absolutePath) + } + + LazyColumn(modifier = modifier) { + item { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), + ) { + Text( + text = "Favorites", + color = MaterialTheme.colorScheme.onBackground, + fontSize = 15.sp, + fontWeight = FontWeight.SemiBold, + modifier = Modifier.weight(1f), + ) + TextButton( + onClick = onPinCurrent, + enabled = !currentAlreadyPinned, + ) { + Icon(Icons.Filled.PushPin, null, tint = MaterialTheme.colorScheme.primary, modifier = Modifier.size(16.dp)) + Spacer(Modifier.width(6.dp)) + Text( + text = "Pin current folder", + color = MaterialTheme.colorScheme.primary, + fontSize = 13.sp, + ) + } + } + } + + if (favorites.isEmpty()) { + item { + Box( + modifier = Modifier.fillParentMaxSize(), + contentAlignment = Alignment.Center, + ) { + Text( + text = "No favorites yet — pin a folder with its ⋮ menu to jump back here fast.", + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 13.sp, + modifier = Modifier.padding(horizontal = 32.dp), + ) + } + } + } else { + items(favorites, key = { it.absolutePath }) { file -> + val loc = remember(file.absolutePath) { describeLocation(file) } + FavoriteCard( + file = file, + loc = loc, + onJump = { onJump(file) }, + onUnpin = { onUnpin(file) }, + ) + } + } + } +} + +// A single favourite — matches the FileItemRow card style (surfaceContainer + outline + +// RoundedCornerShape(10.dp)). Shows the folder name, a coloured drive badge + origin text, +// and the full display path; tapping jumps into it, the filled star unpins. +@Composable +private fun FavoriteCard( + file: File, + loc: FavLocation, + onJump: () -> Unit, + onUnpin: () -> Unit, +) { + val (badgeBg, badgeFg) = badgeColors(loc) + Card( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 12.dp, vertical = 3.dp) + .clickable(onClick = onJump), + shape = RoundedCornerShape(10.dp), + colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outline), + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp), + ) { + Icon( + imageVector = Icons.Filled.Folder, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(36.dp), + ) + Spacer(Modifier.width(10.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = file.name, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.height(2.dp)) + // Origin line: coloured drive badge + source description. + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = loc.driveLabel, + color = badgeFg, + fontSize = 9.sp, + fontWeight = FontWeight.Bold, + modifier = Modifier + .clip(RoundedCornerShape(4.dp)) + .background(badgeBg) + .padding(horizontal = 6.dp, vertical = 2.dp), + ) + Spacer(Modifier.width(6.dp)) + Text( + text = when (loc.storage) { + FavStorage.INTERNAL -> "Internal storage" + FavStorage.SD -> "SD card" + FavStorage.OTHER -> "Storage" + }, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 11.sp, + ) + } + Spacer(Modifier.height(2.dp)) + Text( + text = loc.displayPath, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 11.sp, + fontFamily = FontFamily.Monospace, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + ) + } + IconButton(onClick = onUnpin) { + Icon( + Icons.Filled.Star, + contentDescription = "Remove from favorites", + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(22.dp), + ) + } + } + } +} + +/** + * One entry in the File Manager's grid view: a big thumbnail with the name under it. + * + * Deliberately drops size and date — at this width they truncate to noise. The grid is for + * recognising things by sight (screenshots, covers, game folders); the list stays the view for + * reading details. + */ +@OptIn(ExperimentalFoundationApi::class) +@Composable +private fun FileGridTile( + file: File, + selectionMode: Boolean, + selected: Boolean, + onLongPress: () -> Unit, + onToggleSelect: () -> Unit, + onTap: () -> Unit, + onMenu: () -> Unit, + menuExpanded: Boolean = false, + onDismissMenu: () -> Unit = {}, + isFavorite: Boolean = false, + onSelect: () -> Unit = {}, + onRename: () -> Unit = {}, + onCopy: () -> Unit = {}, + onCut: () -> Unit = {}, + onDelete: () -> Unit = {}, + onToggleFavorite: () -> Unit = {}, + onProperties: () -> Unit = {}, +) { + val isDir = file.isDirectory + val isImage = !isDir && file.extension.lowercase() in IMAGE_THUMB_EXTS + var exeIcon by remember(file.absolutePath) { mutableStateOf(null) } + if (!isDir && file.name.lowercase().endsWith(".exe")) { + LaunchedEffect(file.absolutePath) { + val bmp = withContext(Dispatchers.IO) { PeIconExtractor.extract(file) } + if (bmp != null) exeIcon = bmp.asImageBitmap() + } + } + // The tile has no ⋮ button — long-press opens this menu, anchored to the Box around the Card. + Box { + Card( + modifier = Modifier + .padding(4.dp) + .combinedClickable( + onClick = { if (selectionMode) onToggleSelect() else onTap() }, + onLongClick = onLongPress, + ), + shape = RoundedCornerShape(10.dp), + colors = CardDefaults.cardColors( + containerColor = if (selected) MaterialTheme.colorScheme.primary.copy(alpha = 0.18f) + else MaterialTheme.colorScheme.surfaceContainer, + ), + border = BorderStroke( + 1.dp, + if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outline, + ), + ) { + Column( + horizontalAlignment = Alignment.CenterHorizontally, + modifier = Modifier.fillMaxWidth().padding(8.dp), + ) { + Box(modifier = Modifier.size(56.dp), contentAlignment = Alignment.Center) { + when { + exeIcon != null -> Image(bitmap = exeIcon!!, contentDescription = null, modifier = Modifier.size(48.dp)) + isDir -> Icon( + Icons.Filled.Folder, null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(48.dp), + ) + isImage -> AsyncImage( + model = file, + contentDescription = null, + contentScale = ContentScale.Crop, + placeholder = rememberVectorPainter(Icons.Filled.InsertDriveFile), + error = rememberVectorPainter(Icons.Filled.InsertDriveFile), + modifier = Modifier.size(56.dp).clip(RoundedCornerShape(6.dp)), + ) + else -> Icon( + Icons.Filled.InsertDriveFile, null, + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(44.dp), + ) + } + if (selectionMode) { + androidx.compose.material3.Checkbox( + checked = selected, + onCheckedChange = { onToggleSelect() }, + modifier = Modifier.align(Alignment.TopStart), + ) + } + } + Spacer(Modifier.height(4.dp)) + // Always reserve two lines (issue #475): a one-line name used to make its card shorter than + // its neighbours, so grid rows had ragged heights. Fixed min/max keeps every tile the same size. + Text( + file.name, + color = MaterialTheme.colorScheme.onSurface, + fontSize = 11.sp, + minLines = 2, + maxLines = 2, + textAlign = androidx.compose.ui.text.style.TextAlign.Center, + overflow = TextOverflow.Ellipsis, + ) + } + } + DropdownMenu( + expanded = menuExpanded, + onDismissRequest = onDismissMenu, + modifier = Modifier.outlinedMenuCard(), + ) { + FileContextMenuItems( + file = file, + isFavorite = isFavorite, + onSelect = onSelect, + onRename = onRename, + onCopy = onCopy, + onCut = onCut, + onDelete = onDelete, + onToggleFavorite = onToggleFavorite, + onProperties = onProperties, + onDismissMenu = onDismissMenu, + ) + } + } +} + +/** + * Properties sheet for a single file or folder: basic info plus the two Windows/Wine file attributes + * the in-container file manager (wfm.exe) also exposes — Read-only and Hidden. Each toggle applies + * immediately (off the main thread) and refreshes the listing via [onChanged]. + * + * State is keyed on the file so it always reflects the entry it was opened for. On a filesystem that + * can't store Wine's DOSATTRIB xattr (the FUSE /storage volumes) only the Hidden toggle is disabled; + * Read-only keeps working everywhere. + */ +@Composable +private fun FilePropertiesDialog( + file: File, + onDismiss: () -> Unit, + onChanged: () -> Unit, +) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val dateFormat = remember { SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()) } + var attrs by remember(file.absolutePath) { mutableStateOf(null) } + // Guards against a second toggle landing while the first is still being applied off-thread. + var busy by remember(file.absolutePath) { mutableStateOf(false) } + LaunchedEffect(file.absolutePath) { + attrs = withContext(Dispatchers.IO) { readFileAttrs(file) } + } + + OutlinedAlertDialog( + onDismissRequest = onDismiss, + title = { Text("Properties") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState())) { + // ── Basic info ── + Text( + text = file.name, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 14.sp, + fontWeight = FontWeight.SemiBold, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + ) + Spacer(Modifier.height(6.dp)) + PropertyLine("Location", file.parent ?: "—") + PropertyLine( + "Type", + if (file.isDirectory) "Folder" + else file.extension.uppercase().let { if (it.isBlank()) "File" else "$it file" }, + ) + if (!file.isDirectory) PropertyLine("Size", FileOps.formatBytes(file.length())) + PropertyLine("Modified", dateFormat.format(Date(file.lastModified()))) + + Spacer(Modifier.height(10.dp)) + HorizontalDivider(color = MaterialTheme.colorScheme.outline) + Spacer(Modifier.height(6.dp)) + + val state = attrs + // ── Read-only ── checked when the owner can't write (Wine's FILE_ATTRIBUTE_READONLY). + AttributeToggleRow( + label = "Read-only", + description = "Stops games (and Wine) from overwriting or deleting this file.", + checked = state?.readOnly == true, + enabled = state != null && !busy, + onToggle = { want -> + busy = true + scope.launch { + val ok = withContext(Dispatchers.IO) { setReadOnly(file, want) } + busy = false + if (ok) { + attrs = attrs?.copy(readOnly = want) + onChanged() + } else { + Toast.makeText(context, "Couldn't change Read-only", Toast.LENGTH_SHORT).show() + } + } + }, + ) + Spacer(Modifier.height(2.dp)) + // ── Hidden ── Wine's DOS hidden bit in the user.DOSATTRIB xattr. + val hiddenSupported = state?.hiddenSupported == true + AttributeToggleRow( + label = "Hidden", + description = if (state != null && !hiddenSupported) + "This storage can't store the hidden flag." + else "Marks the file hidden in Windows (Wine's hidden attribute).", + checked = state?.hidden == true, + enabled = state != null && hiddenSupported && !busy, + onToggle = { want -> + busy = true + scope.launch { + val ok = withContext(Dispatchers.IO) { setHidden(file, want) } + busy = false + if (ok) { + attrs = attrs?.copy(hidden = want) + onChanged() + } else { + // The write failed after all — disable the toggle rather than lie. + attrs = attrs?.copy(hiddenSupported = false) + Toast.makeText(context, "Couldn't change Hidden on this storage", Toast.LENGTH_SHORT).show() + } + } + }, + ) + } + }, + confirmButton = { TextButton(onClick = onDismiss) { Text("Done") } }, + ) +} + +// One "label: value" line in the Properties info block. +@Composable +private fun PropertyLine(label: String, value: String) { + Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) { + Text( + text = label, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 12.sp, + modifier = Modifier.width(76.dp), + ) + Text( + text = value, + color = MaterialTheme.colorScheme.onSurface, + fontSize = 12.sp, + maxLines = 2, + overflow = TextOverflow.Ellipsis, + modifier = Modifier.weight(1f), + ) + } +} + +// A labelled attribute switch with a one-line description, used by the Properties sheet. +@Composable +private fun AttributeToggleRow( + label: String, + description: String, + checked: Boolean, + enabled: Boolean, + onToggle: (Boolean) -> Unit, +) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = label, + color = MaterialTheme.colorScheme.onBackground, + fontSize = 14.sp, + fontWeight = FontWeight.Medium, + ) + Text( + text = description, + color = MaterialTheme.colorScheme.onSurfaceVariant, + fontSize = 11.sp, + ) + } + Spacer(Modifier.width(8.dp)) + androidx.compose.material3.Switch( + checked = checked, + enabled = enabled, + onCheckedChange = onToggle, + ) + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/FileOps.kt b/app/src/main/java/com/steamdeck/launcher/files/FileOps.kt new file mode 100644 index 0000000000..8ddfb1f8df --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/FileOps.kt @@ -0,0 +1,130 @@ +package com.steamdeck.launcher.files + +import android.util.Log +import java.io.File +import java.io.FileInputStream +import java.io.FileOutputStream +import java.io.IOException +import java.nio.file.Files +import java.util.Locale + +/** + * The file operations the File Manager needs, as Bannerlator's FileUtils has them: a delete that + * says whether it worked, a copy and a move that report bytes as they go, and the size format + * the rows use. Kept apart from core/FileUtils, whose callers want a quiet delete. + */ +object FileOps { + private const val TAG = "FileOps" + + /** Byte-accurate copy progress (copied/total bytes), reported as the copy proceeds. */ + fun interface ProgressCallback { fun onProgress(copiedBytes: Long, totalBytes: Long) } + + fun formatBytes(bytes: Long): String { + if (bytes <= 0) return "0 bytes" + val units = arrayOf("bytes", "KB", "MB", "GB", "TB") + val group = (Math.log10(bytes.toDouble()) / Math.log10(1024.0)).toInt().coerceIn(0, units.lastIndex) + return String.format(Locale.ENGLISH, "%.2f", bytes / Math.pow(1024.0, group.toDouble())) + " " + units[group] + } + + fun isSymlink(file: File): Boolean = try { Files.isSymbolicLink(file.toPath()) } catch (e: Exception) { false } + + /** Recursive delete that never follows a symlink; true when everything went. */ + fun delete(target: File?): Boolean { + if (target == null) return false + if (target.isDirectory && !isSymlink(target)) { + if (!clear(target)) return false + } + return target.delete() + } + + fun clear(dir: File): Boolean { + val children = dir.listFiles() ?: return true + var ok = true + for (child in children) if (!delete(child)) ok = false + return ok + } + + /** Recursive total size in bytes of files under [f] (skips symlinks). Used to size a progress bar. */ + fun totalSize(f: File?): Long { + if (f == null || !f.exists() || isSymlink(f)) return 0 + if (f.isDirectory) return f.listFiles()?.sumOf { totalSize(it) } ?: 0 + return f.length() + } + + /** + * Moves [src] to [dst], relinking instead of copying whenever possible. A rename is instant + * regardless of size but only works within one filesystem; renameTo returning false is the + * signal that a boundary was crossed, so it doubles as the check, and the fallback is + * copy-then-delete. Only attempted when the destination does not exist: renaming onto an + * existing directory does not merge. + */ + fun moveWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean { + if (sameFile(src, dst)) return true + if (!dst.exists() && src.renameTo(dst)) { + progress?.onProgress(1, 1) + return true + } + if (!copyWithProgress(src, dst, progress)) return false + return delete(src) + } + + /** A copy that reports byte progress, smooth even within one large file. */ + fun copyWithProgress(src: File, dst: File, progress: ProgressCallback?): Boolean { + val total = maxOf(totalSize(src), 1L) + return copyWithProgress(src, dst, longArrayOf(0), total, progress) + } + + private fun copyWithProgress(src: File, dst: File, done: LongArray, total: Long, progress: ProgressCallback?): Boolean { + if (isSymlink(src)) return true + if (sameFile(src, dst)) return true + if (src.isDirectory && isWithin(dst, src)) { + Log.e(TAG, "Refusing to copy directory into itself: $src -> $dst") + return false + } + if (src.isDirectory) { + if (!dst.exists() && !dst.mkdirs()) return false + var allOk = true + src.list()?.forEach { name -> + if (!copyWithProgress(File(src, name), File(dst, name), done, total, progress)) { + Log.e(TAG, "Failed to copy: ${File(src, name)}") + allOk = false + } + } + return allOk + } + val parent = dst.parentFile + if (!src.exists() || (parent != null && !parent.exists() && !parent.mkdirs())) return false + val chunk = 4L * 1024 * 1024 // report progress every 4 MiB + try { + FileInputStream(src).channel.use { input -> + FileOutputStream(dst).channel.use { output -> + val size = input.size() + var position = 0L + while (position < size) { + val transferred = input.transferTo(position, minOf(chunk, size - position), output) + if (transferred <= 0) break + position += transferred + done[0] += transferred + progress?.onProgress(done[0], total) + } + if (position < size) throw IOException("Incomplete copy: $position/$size bytes") + } + } + return true + } catch (e: IOException) { + Log.e(TAG, "Failed to copy file: $src to $dst", e) + dst.delete() + return false + } + } + + private fun sameFile(a: File, b: File): Boolean = + try { a.canonicalPath == b.canonicalPath } catch (e: IOException) { a.absolutePath == b.absolutePath } + + /** True when [child] is [ancestor] itself or lives anywhere inside it. */ + private fun isWithin(child: File, ancestor: File): Boolean { + val c = try { child.canonicalPath } catch (e: IOException) { child.absolutePath } + val a = try { ancestor.canonicalPath } catch (e: IOException) { ancestor.absolutePath } + return c == a || c.startsWith(a + File.separator) + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/FilePickerActivity.kt b/app/src/main/java/com/steamdeck/launcher/files/FilePickerActivity.kt index 28ac499416..dd05f10fa4 100644 --- a/app/src/main/java/com/steamdeck/launcher/files/FilePickerActivity.kt +++ b/app/src/main/java/com/steamdeck/launcher/files/FilePickerActivity.kt @@ -8,6 +8,7 @@ import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.systemBarsPadding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.ui.Modifier @@ -15,7 +16,7 @@ import com.steamdeck.launcher.ui.SteamDeckTheme import java.io.File /** - * Themed host for [FilePickerScreen]. Launched through [InAppFilePicker] and answers with the + * Themed host for [FileManagerScreen] in pick mode. Launched through [InAppFilePicker] and answers with the * picked path in [EXTRA_SELECTED_FILE] on RESULT_OK. * * Extras: @@ -36,25 +37,24 @@ class FilePickerActivity : ComponentActivity() { val extensions = intent.getStringArrayExtra(EXTRA_EXTENSIONS)?.toList() ?: emptyList() val pickDir = intent.getBooleanExtra(EXTRA_PICK_DIRECTORY, false) val title = intent.getStringExtra(EXTRA_PICKER_TITLE) - val prefs = getSharedPreferences("picker", MODE_PRIVATE) - val initialDir = (intent.getStringExtra(EXTRA_INITIAL_DIRECTORY) ?: prefs.getString("lastDir", null)) + // The screen remembers the folder it last picked from; an explicit start wins over it. + val prefs = getSharedPreferences("file_manager", MODE_PRIVATE) + val initialDir = (intent.getStringExtra(EXTRA_INITIAL_DIRECTORY) ?: prefs.getString("lastFilePickerDir", null)) ?.let { File(it) }?.takeIf { it.isDirectory } setContent { SteamDeckTheme { - Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) { - FilePickerScreen( + Surface(modifier = Modifier.fillMaxSize().systemBarsPadding(), color = MaterialTheme.colorScheme.background) { + FileManagerScreen( + pickMode = true, pickDirMode = pickDir, pickExtensions = extensions, initialDir = initialDir, - title = title ?: if (pickDir) "Choose a folder" else "Choose a file", + pickerTitle = title ?: if (pickDir) "Choose a folder" else "Choose a file", onPick = { file -> - val remembered = if (file.isDirectory) file else file.parentFile - remembered?.let { prefs.edit().putString("lastDir", it.absolutePath).apply() } setResult(Activity.RESULT_OK, Intent().putExtra(EXTRA_SELECTED_FILE, file.absolutePath)) finish() }, - onCancel = { setResult(Activity.RESULT_CANCELED); finish() }, ) } } diff --git a/app/src/main/java/com/steamdeck/launcher/files/FilePickerScreen.kt b/app/src/main/java/com/steamdeck/launcher/files/FilePickerScreen.kt deleted file mode 100644 index f09c2ddc1c..0000000000 --- a/app/src/main/java/com/steamdeck/launcher/files/FilePickerScreen.kt +++ /dev/null @@ -1,283 +0,0 @@ -package com.steamdeck.launcher.files - -import androidx.activity.compose.BackHandler -import androidx.compose.foundation.Canvas -import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxSize -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.systemBarsPadding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.ArrowBack -import androidx.compose.material.icons.filled.ArrowDropDown -import androidx.compose.material.icons.filled.KeyboardArrowUp -import androidx.compose.material.icons.filled.Refresh -import androidx.compose.material3.Button -import androidx.compose.material3.DropdownMenu -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.geometry.CornerRadius -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.geometry.Size -import androidx.compose.ui.graphics.Color -import androidx.compose.ui.graphics.drawscope.Stroke -import androidx.compose.ui.platform.LocalContext -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import androidx.compose.ui.unit.sp -import com.steamdeck.launcher.core.FileUtils -import java.io.File -import java.text.SimpleDateFormat -import java.util.Date -import java.util.Locale - -/** - * The file picker, as Bannerlator's File Manager behaves in pick mode: a drive menu with every - * mounted volume ([StorageRoots]), the path with an up-arrow that stops at the drive's root so - * nobody is trapped in a subfolder, folders first, and either a tap on a matching file or "Use - * this folder". Nothing here edits, runs or copies anything; that is a file manager's job and - * this app does not have one. - */ -@Composable -fun FilePickerScreen( - pickDirMode: Boolean, - pickExtensions: List, - initialDir: File?, - title: String, - onPick: (File) -> Unit, - onCancel: () -> Unit, -) { - val context = LocalContext.current - val colors = MaterialTheme.colorScheme - val lowerExts = remember(pickExtensions) { pickExtensions.map { it.lowercase() } } - - val start = remember { initialDir?.takeIf { it.isDirectory } ?: File(INTERNAL) } - var currentDir by remember { mutableStateOf(start) } - // The floor for up/back: the volume the folder is on, never the folder itself. - var currentRoot by remember { mutableStateOf(volumeRootOf(start)) } - var entries by remember { mutableStateOf?>(null) } - var storageTick by remember { mutableStateOf(0) } - val drives = remember(storageTick) { StorageRoots.list(context) } - var showDrives by remember { mutableStateOf(false) } - - fun matches(file: File): Boolean { - if (file.isDirectory) return true - if (pickDirMode) return false - if (lowerExts.isEmpty()) return true - val name = file.name.lowercase() - return lowerExts.any { name.endsWith(".$it") } - } - - fun reload() { - entries = currentDir.listFiles() - ?.filter { !it.name.startsWith(".") && matches(it) } - ?.sortedWith(compareBy { !it.isDirectory }.thenBy { it.name.lowercase() }) - } - - fun open(dir: File) { - currentDir = dir - reload() - } - - fun openDrive(root: File) { - currentRoot = root - open(root) - } - - fun goUp() { - val parent = currentDir.parentFile ?: return - if (currentDir.absolutePath == currentRoot.absolutePath) return - open(parent) - } - - val atRoot = currentDir.absolutePath == currentRoot.absolutePath - LaunchedEffect(Unit) { reload() } - BackHandler { if (atRoot) onCancel() else goUp() } - - Column(modifier = Modifier.fillMaxSize().systemBarsPadding()) { - // Header: back, title, drive menu, refresh. - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().padding(start = 4.dp, end = 4.dp, top = 4.dp), - ) { - IconButton(onClick = onCancel) { Icon(Icons.Filled.ArrowBack, contentDescription = "Cancel") } - Text( - title, fontSize = 17.sp, fontWeight = FontWeight.Medium, color = colors.onBackground, - maxLines = 1, overflow = TextOverflow.Ellipsis, modifier = Modifier.weight(1f), - ) - Box { - val driveLabel = drives.firstOrNull { currentRoot.absolutePath == it.dir.absolutePath }?.label - ?: currentRoot.name.ifEmpty { "/" } - OutlinedButton(onClick = { showDrives = true }) { - Text(driveLabel, fontSize = 12.sp, maxLines = 1) - Icon(Icons.Filled.ArrowDropDown, contentDescription = null, modifier = Modifier.size(18.dp)) - } - DropdownMenu(expanded = showDrives, onDismissRequest = { showDrives = false }) { - drives.forEach { drive -> - DropdownMenuItem( - text = { - Column { - Text(drive.label + if (drive.removable) " · SD" else "") - Text( - if (drive.readable) drive.dir.absolutePath else "mounted, not readable right now", - fontSize = 11.sp, color = colors.onSurfaceVariant, - ) - } - }, - enabled = drive.readable, - onClick = { showDrives = false; openDrive(drive.dir) }, - ) - } - } - } - IconButton(onClick = { storageTick++; reload() }) { - Icon(Icons.Filled.Refresh, contentDescription = "Refresh") - } - } - // The path, with up. - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp), - ) { - IconButton(onClick = { goUp() }, enabled = !atRoot) { - Icon(Icons.Filled.KeyboardArrowUp, contentDescription = "Up") - } - Text( - elideStart(currentDir.absolutePath, 60), fontSize = 12.sp, color = colors.onSurfaceVariant, - maxLines = 1, overflow = TextOverflow.Ellipsis, - ) - } - HorizontalDivider(color = colors.surfaceVariant) - - val list = entries - when { - list == null -> Message( - if (currentDir.canRead()) "Nothing to list here" else "Not readable — allow storage access for SteamDeck and try again", - Modifier.weight(1f), - ) - list.isEmpty() -> Message( - when { - pickDirMode -> "No folders here — use this one, or go up" - lowerExts.isNotEmpty() -> "No ${lowerExts.joinToString(" / ") { ".$it" }} files here" - else -> "Empty folder" - }, - Modifier.weight(1f), - ) - else -> LazyColumn(modifier = Modifier.weight(1f).fillMaxWidth()) { - items(list, key = { it.absolutePath }) { file -> - EntryRow(file) { if (file.isDirectory) open(file) else onPick(file) } - } - } - } - - if (pickDirMode) { - HorizontalDivider(color = colors.surfaceVariant) - Row( - horizontalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxWidth().padding(12.dp), - ) { - OutlinedButton(onClick = onCancel, modifier = Modifier.weight(1f)) { Text("Cancel") } - Button(onClick = { onPick(currentDir) }, modifier = Modifier.weight(2f)) { - Text("Use this folder", maxLines = 1, overflow = TextOverflow.Ellipsis) - } - } - } - } -} - -@Composable -private fun Message(text: String, modifier: Modifier) { - Box(modifier = modifier.fillMaxWidth().padding(24.dp), contentAlignment = Alignment.Center) { - Text(text, color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 13.sp) - } -} - -@Composable -private fun EntryRow(file: File, onTap: () -> Unit) { - val colors = MaterialTheme.colorScheme - val isDir = file.isDirectory - val detail = remember(file.absolutePath) { - val stamp = SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault()).format(Date(file.lastModified())) - if (isDir) stamp else "${FileUtils.sizeToString(file.length())} · $stamp" - } - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.fillMaxWidth().clickable(onClick = onTap).padding(horizontal = 16.dp, vertical = 9.dp), - ) { - Glyph(isDir, if (isDir) colors.primary else colors.onSurfaceVariant) - Spacer(Modifier.width(14.dp)) - Column(modifier = Modifier.weight(1f)) { - Text(file.name, fontSize = 14.sp, color = colors.onBackground, maxLines = 1, overflow = TextOverflow.Ellipsis) - Text(detail, fontSize = 11.sp, color = colors.onSurfaceVariant, maxLines = 1) - } - } - HorizontalDivider(color = colors.surfaceVariant, modifier = Modifier.padding(start = 56.dp)) -} - -/** A folder or a page, drawn: the app ships no icon set beyond the few in Material's core. */ -@Composable -private fun Glyph(folder: Boolean, tint: Color) { - Canvas(modifier = Modifier.size(26.dp)) { - val w = size.width - val h = size.height - if (folder) { - // Tab, then body. - drawRoundRect(tint, Offset(0f, h * 0.18f), Size(w * 0.42f, h * 0.2f), CornerRadius(w * 0.06f)) - drawRoundRect(tint, Offset(0f, h * 0.28f), Size(w, h * 0.58f), CornerRadius(w * 0.08f)) - } else { - val left = w * 0.15f - val top = h * 0.06f - drawRoundRect( - tint, Offset(left, top), Size(w * 0.7f, h * 0.88f), CornerRadius(w * 0.06f), - style = Stroke(width = w * 0.07f), - ) - // Three lines of "text". - for (i in 0..2) { - val y = h * (0.38f + 0.17f * i) - drawLine(tint, Offset(w * 0.3f, y), Offset(w * 0.7f, y), strokeWidth = w * 0.06f) - } - } - } -} - -private const val INTERNAL = "/storage/emulated/0" - -/** `/storage/emulated/0/Download/x` -> `/storage/emulated/0`; `/storage/ABCD-1234/y` -> the card. */ -private fun volumeRootOf(dir: File): File { - val abs = dir.absolutePath - return when { - abs == INTERNAL || abs.startsWith("$INTERNAL/") -> File(INTERNAL) - abs.startsWith("/storage/") -> { - val name = abs.removePrefix("/storage/").substringBefore('/') - if (name.isNotEmpty() && name != "emulated" && name != "self") File("/storage/$name") else dir - } - else -> dir - } -} - -private fun elideStart(path: String, max: Int): String = - if (path.length <= max) path else "…" + path.takeLast(max - 1) diff --git a/app/src/main/java/com/steamdeck/launcher/files/MenuStyle.kt b/app/src/main/java/com/steamdeck/launcher/files/MenuStyle.kt new file mode 100644 index 0000000000..0a0590b7e9 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/MenuStyle.kt @@ -0,0 +1,30 @@ +package com.steamdeck.launcher.files + +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.unit.dp + +// Shared outlined-card look for the app's popup menus, matching the FileManager / CommunityCard +// idiom (surfaceContainer fill, 1dp outline, rounded 10dp). Applied to a DropdownMenu's modifier so +// the popup reads as an outlined card. Keep all three menu call-sites on this so they stay identical. +@Composable +internal fun Modifier.outlinedMenuCard(): Modifier { + val cs = MaterialTheme.colorScheme + val shape = RoundedCornerShape(10.dp) + return this + .clip(shape) + .background(cs.surfaceContainer) + .border(1.dp, cs.outline, shape) +} + +// The thin low-alpha separator that sits between items inside an outlined menu card. +@Composable +internal fun MenuItemDivider() { + HorizontalDivider(color = MaterialTheme.colorScheme.outline.copy(alpha = 0.5f)) +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/OutlinedAlertDialog.kt b/app/src/main/java/com/steamdeck/launcher/files/OutlinedAlertDialog.kt new file mode 100644 index 0000000000..e554d54b2f --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/OutlinedAlertDialog.kt @@ -0,0 +1,54 @@ +package com.steamdeck.launcher.files + +import androidx.compose.foundation.border +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.AlertDialogDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.Shape +import androidx.compose.ui.unit.Dp +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.DialogProperties + +// Single source of truth for the app's AlertDialogs: a drop-in wrapper around the Material3 +// slot-based AlertDialog that adds a 1dp outline around the whole popup box — matching the +// outline that Modifier.outlinedMenuCard() (MenuStyle.kt) puts on the app's menus. Signature +// mirrors androidx.compose.material3.AlertDialog exactly (compose-bom 2024.02.00 → material3 +// 1.2.0), so every call site can swap AlertDialog( → OutlinedAlertDialog( unchanged. The +// border shares the dialog's shape so its corner radius follows the rounded dialog. +@Composable +internal fun OutlinedAlertDialog( + onDismissRequest: () -> Unit, + confirmButton: @Composable () -> Unit, + modifier: Modifier = Modifier, + dismissButton: (@Composable () -> Unit)? = null, + icon: (@Composable () -> Unit)? = null, + title: (@Composable () -> Unit)? = null, + text: (@Composable () -> Unit)? = null, + shape: Shape = AlertDialogDefaults.shape, + containerColor: Color = AlertDialogDefaults.containerColor, + iconContentColor: Color = AlertDialogDefaults.iconContentColor, + titleContentColor: Color = AlertDialogDefaults.titleContentColor, + textContentColor: Color = AlertDialogDefaults.textContentColor, + tonalElevation: Dp = AlertDialogDefaults.TonalElevation, + properties: DialogProperties = DialogProperties() +) { + AlertDialog( + onDismissRequest = onDismissRequest, + confirmButton = confirmButton, + modifier = modifier.border(1.dp, MaterialTheme.colorScheme.outline, shape), + dismissButton = dismissButton, + icon = icon, + title = title, + text = text, + shape = shape, + containerColor = containerColor, + iconContentColor = iconContentColor, + titleContentColor = titleContentColor, + textContentColor = textContentColor, + tonalElevation = tonalElevation, + properties = properties + ) +} diff --git a/app/src/main/java/com/steamdeck/launcher/files/PeIconExtractor.kt b/app/src/main/java/com/steamdeck/launcher/files/PeIconExtractor.kt new file mode 100644 index 0000000000..12edba5042 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/files/PeIconExtractor.kt @@ -0,0 +1,277 @@ +package com.steamdeck.launcher.files + +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import java.io.File +import java.io.RandomAccessFile +import kotlin.math.max + +/** + * Extracts the embedded application icon from a Windows PE executable (.exe). + * + * Walks the PE resource directory to the first RT_GROUP_ICON, picks the largest / + * deepest-colour entry it references, then decodes that RT_ICON image. Icon images + * are either PNG (Vista+) — decoded directly — or a classic DIB (BITMAPINFOHEADER + + * XOR pixels + 1-bpp AND mask) — decoded by hand here. + * + * Everything is best-effort: any malformed/oversized/unsupported input returns null. + */ +object PeIconExtractor { + + private const val RT_ICON = 3 + private const val RT_GROUP_ICON = 14 + private const val MAX_RES_SECTION = 64 * 1024 * 1024 // don't slurp absurd resource sections + private const val MAX_ICON_DIM = 1024 + + fun extract(file: File): Bitmap? = try { + RandomAccessFile(file, "r").use { parse(it) } + } catch (_: Throwable) { + null + } + + private fun parse(raf: RandomAccessFile): Bitmap? { + val dos = read(raf, 0, 0x40) ?: return null + if (u8(dos, 0) != 0x4D || u8(dos, 1) != 0x5A) return null // "MZ" + val peOff = u32(dos, 0x3C).toInt() + + val coff = read(raf, peOff.toLong(), 24) ?: return null + if (u8(coff, 0) != 0x50 || u8(coff, 1) != 0x45 || u8(coff, 2) != 0 || u8(coff, 3) != 0) return null // "PE\0\0" + val numSections = u16(coff, 6) + val sizeOpt = u16(coff, 20) + if (numSections <= 0 || numSections > 96 || sizeOpt <= 0) return null + + val optOff = peOff + 24L + val opt = read(raf, optOff, sizeOpt) ?: return null + val magic = u16(opt, 0) + val ddOff = if (magic == 0x20B) 112 else 96 // PE32+ vs PE32 data-directory offset + val resDirEntry = ddOff + 2 * 8 // data directory index 2 = resource table + if (resDirEntry + 8 > opt.size) return null + val resRVA = u32(opt, resDirEntry).toInt() + val resSize = u32(opt, resDirEntry + 4).toInt() + if (resRVA == 0 || resSize == 0) return null + + val secTabOff = optOff + sizeOpt + val secTab = read(raf, secTabOff, numSections * 40) ?: return null + + var secVA = 0 + var secPtr = 0L + var secRaw = 0 + var found = false + for (i in 0 until numSections) { + val o = i * 40 + if (o + 40 > secTab.size) break + val va = u32(secTab, o + 12).toInt() + val vSize = u32(secTab, o + 8).toInt() + val raw = u32(secTab, o + 16).toInt() + val pRaw = u32(secTab, o + 20) + val span = max(vSize, raw) + if (resRVA >= va && resRVA < va + span) { + secVA = va; secPtr = pRaw; secRaw = raw; found = true; break + } + } + if (!found || secRaw <= 0 || secRaw > MAX_RES_SECTION) return null + + val res = read(raf, secPtr, secRaw) ?: return null + val resDirStart = resRVA - secVA + if (resDirStart < 0 || resDirStart + 16 > res.size) return null + + // RT_GROUP_ICON -> first group's data entry -> GRPICONDIR + val grpTypeDir = findIdSubdir(res, resDirStart, RT_GROUP_ICON, resDirStart) ?: return null + val grpData = firstDataEntry(res, grpTypeDir, resDirStart) ?: return null + val grp = dataEntryBytes(res, grpData, secVA) ?: return null + if (grp.size < 6) return null + + val count = u16(grp, 4) + if (count <= 0) return null + var bestId = -1 + var bestScore = -1L + for (i in 0 until count) { + val e = 6 + i * 14 + if (e + 14 > grp.size) break + var w = u8(grp, e); if (w == 0) w = 256 + var h = u8(grp, e + 1); if (h == 0) h = 256 + val bits = u16(grp, e + 6) + val id = u16(grp, e + 12) + val score = w.toLong() * h * 1000 + bits + if (score > bestScore) { bestScore = score; bestId = id } + } + if (bestId < 0) return null + + // RT_ICON with the chosen id -> image bytes + val iconTypeDir = findIdSubdir(res, resDirStart, RT_ICON, resDirStart) ?: return null + val iconIdDir = findIdSubdir(res, iconTypeDir, bestId, resDirStart) ?: return null + val iconData = firstDataEntry(res, iconIdDir, resDirStart) ?: return null + val img = dataEntryBytes(res, iconData, secVA) ?: return null + + return decodeIcon(img) + } + + // ── resource-directory navigation ── + + /** Resolve the sub-directory under [dirIdx] whose id matches [wantId]; null if absent or not a directory. */ + private fun findIdSubdir(res: ByteArray, dirIdx: Int, wantId: Int, resDirStart: Int): Int? { + if (dirIdx + 16 > res.size) return null + val total = u16(res, dirIdx + 12) + u16(res, dirIdx + 14) + val start = dirIdx + 16 + for (i in 0 until total) { + val e = start + i * 8 + if (e + 8 > res.size) break + val id = u32(res, e) + val off = u32(res, e + 4) + if (id and 0x80000000L == 0L && id.toInt() == wantId) { + if (off and 0x80000000L != 0L) return resDirStart + (off and 0x7FFFFFFFL).toInt() + return null + } + } + return null + } + + /** Descend the first entry of each level until an IMAGE_RESOURCE_DATA_ENTRY; returns its index. */ + private fun firstDataEntry(res: ByteArray, dirIdx: Int, resDirStart: Int): Int? { + if (dirIdx + 16 > res.size) return null + if (u16(res, dirIdx + 12) + u16(res, dirIdx + 14) == 0) return null + val e = dirIdx + 16 + if (e + 8 > res.size) return null + val off = u32(res, e + 4) + return if (off and 0x80000000L != 0L) { + firstDataEntry(res, resDirStart + (off and 0x7FFFFFFFL).toInt(), resDirStart) + } else { + resDirStart + off.toInt() + } + } + + /** Read the bytes an IMAGE_RESOURCE_DATA_ENTRY points at (its OffsetToData is an RVA). */ + private fun dataEntryBytes(res: ByteArray, entryIdx: Int, secVA: Int): ByteArray? { + if (entryIdx < 0 || entryIdx + 8 > res.size) return null + val rva = u32(res, entryIdx).toInt() + val size = u32(res, entryIdx + 4).toInt() + val start = rva - secVA + if (size <= 0 || start < 0 || start + size > res.size) return null + return res.copyOfRange(start, start + size) + } + + // ── icon image decoding ── + + private fun decodeIcon(b: ByteArray): Bitmap? { + if (b.size >= 8 && u8(b, 0) == 0x89 && u8(b, 1) == 0x50 && u8(b, 2) == 0x4E && u8(b, 3) == 0x47) { + return runCatching { BitmapFactory.decodeByteArray(b, 0, b.size) }.getOrNull() + } + return runCatching { decodeDib(b) }.getOrNull() + } + + private fun decodeDib(b: ByteArray): Bitmap? { + if (b.size < 40) return null + val headerSize = u32(b, 0).toInt() + val width = s32(b, 4) + val heightFull = s32(b, 8) + val height = heightFull / 2 // DIB icon height counts XOR + AND mask + val bitCount = u16(b, 14) + if (width <= 0 || height <= 0 || width > MAX_ICON_DIM || height > MAX_ICON_DIM) return null + + val clrUsed = u32(b, 32).toInt() + val numColors = if (bitCount <= 8) (if (clrUsed != 0) clrUsed else 1 shl bitCount) else 0 + val paletteOff = headerSize + val palette = IntArray(numColors) + for (i in 0 until numColors) { + val o = paletteOff + i * 4 + if (o + 4 > b.size) break + palette[i] = (0xFF shl 24) or (u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o) + } + + val xorStart = paletteOff + numColors * 4 + val rowSize = ((bitCount * width + 31) / 32) * 4 + val andRowSize = ((width + 31) / 32) * 4 + val andStart = xorStart + rowSize * height + + // 32-bit icons sometimes ship an all-zero alpha channel; fall back to the AND mask then. + var hasAlpha = false + if (bitCount == 32) { + var y = 0 + loop@ while (y < height && !hasAlpha) { + var x = 0 + while (x < width) { + val o = xorStart + y * rowSize + x * 4 + 3 + if (o < b.size && b[o].toInt() != 0) { hasAlpha = true; break@loop } + x++ + } + y++ + } + } + + val pixels = IntArray(width * height) + for (y in 0 until height) { + val srcRow = height - 1 - y + for (x in 0 until width) { + val argb: Int = when (bitCount) { + 32 -> { + val o = xorStart + srcRow * rowSize + x * 4 + if (o + 4 > b.size) 0 else { + val color = (u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o) + if (hasAlpha) (u8(b, o + 3) shl 24) or color + else maskAlpha(b, andStart, andRowSize, srcRow, x) or color + } + } + 24 -> { + val o = xorStart + srcRow * rowSize + x * 3 + if (o + 3 > b.size) 0 else + maskAlpha(b, andStart, andRowSize, srcRow, x) or + (u8(b, o + 2) shl 16) or (u8(b, o + 1) shl 8) or u8(b, o) + } + 8 -> { + val o = xorStart + srcRow * rowSize + x + val idx = if (o < b.size) u8(b, o) else 0 + val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF + maskAlpha(b, andStart, andRowSize, srcRow, x) or col + } + 4 -> { + val o = xorStart + srcRow * rowSize + x / 2 + val byte = if (o < b.size) u8(b, o) else 0 + val idx = if (x % 2 == 0) byte shr 4 else byte and 0x0F + val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF + maskAlpha(b, andStart, andRowSize, srcRow, x) or col + } + 1 -> { + val o = xorStart + srcRow * rowSize + x / 8 + val byte = if (o < b.size) u8(b, o) else 0 + val idx = (byte shr (7 - x % 8)) and 1 + val col = palette.getOrElse(idx) { 0 } and 0x00FFFFFF + maskAlpha(b, andStart, andRowSize, srcRow, x) or col + } + else -> return null + } + pixels[y * width + x] = argb + } + } + return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888) + } + + /** AND-mask alpha for a pixel: returns 0xFF000000 (opaque) or 0 (transparent), shifted into place. */ + private fun maskAlpha(b: ByteArray, andStart: Int, andRowSize: Int, srcRow: Int, x: Int): Int { + val o = andStart + srcRow * andRowSize + x / 8 + if (o >= b.size) return 0xFF shl 24 + val bit = (b[o].toInt() shr (7 - x % 8)) and 1 + return if (bit == 1) 0 else (0xFF shl 24) + } + + // ── little-endian readers ── + + private fun u8(b: ByteArray, off: Int): Int = b[off].toInt() and 0xFF + private fun u16(b: ByteArray, off: Int): Int = u8(b, off) or (u8(b, off + 1) shl 8) + private fun u32(b: ByteArray, off: Int): Long = + u8(b, off).toLong() or (u8(b, off + 1).toLong() shl 8) or + (u8(b, off + 2).toLong() shl 16) or (u8(b, off + 3).toLong() shl 24) + + private fun s32(b: ByteArray, off: Int): Int = u32(b, off).toInt() + + private fun read(raf: RandomAccessFile, pos: Long, len: Int): ByteArray? { + if (len <= 0 || pos < 0) return null + val fileLen = raf.length() + if (pos >= fileLen) return null + val n = minOf(len.toLong(), fileLen - pos).toInt() + if (n <= 0) return null + val buf = ByteArray(n) + raf.seek(pos) + raf.readFully(buf) + return buf + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/session/CrashHandler.kt b/app/src/main/java/com/steamdeck/launcher/session/CrashHandler.kt index bd85ad345d..96c2377e2a 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/CrashHandler.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/CrashHandler.kt @@ -34,6 +34,8 @@ object CrashHandler { worker.start() worker.join(8000) } + // The session's tree would outlive us otherwise, and block the next launch. + OrphanReaper.reap("app crash") } catch (e: Throwable) { // Nothing more to do for a crash inside the crash handler. } finally { diff --git a/app/src/main/java/com/steamdeck/launcher/session/OrphanReaper.kt b/app/src/main/java/com/steamdeck/launcher/session/OrphanReaper.kt new file mode 100644 index 0000000000..c66f7b2413 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/session/OrphanReaper.kt @@ -0,0 +1,51 @@ +package com.steamdeck.launcher.session + +import android.util.Log +import java.io.File + +/** + * Kills every process of this app's uid other than the app itself. + * + * A session is a tree of processes under proot, and proot dies with the app only when the app's + * own teardown runs. When the app is killed or crashes instead, the tree stays: proot holding the + * rootfs, gamescope holding the GPU, Steam holding its lock file - and the next session never + * comes up, or comes up beside a client that is already running. A user on a Thor Pro had to + * force-stop the app before every launch. Everything of ours that should be alive between + * sessions is inside the app process, so at session start anything else under our uid is a + * leftover, and this sweeps it. Each pid is checked by uid at kill time, never by name. + */ +object OrphanReaper { + private const val TAG = "OrphanReaper" + + fun reap(reason: String): Int { + val me = android.os.Process.myPid() + val uid = android.os.Process.myUid() + var killed = 0 + File("/proc").listFiles()?.forEach { entry -> + val pid = entry.name.toIntOrNull() ?: return@forEach + if (pid == me || pid <= 1) return@forEach + if (uidOf(pid) != uid) return@forEach + val name = try { File(entry, "cmdline").readText().substringBefore('\u0000') } catch (e: Exception) { "?" } + try { + android.os.Process.killProcess(pid) + killed++ + Log.i(TAG, "killed leftover $pid ($name) - $reason") + } catch (e: Exception) { + Log.w(TAG, "could not kill $pid ($name)", e) + } + } + if (killed > 0) Log.i(TAG, "$killed leftover process(es) from an earlier session - $reason") + return killed + } + + private fun uidOf(pid: Int): Int { + return try { + File("/proc/$pid/status").useLines { lines -> + lines.firstOrNull { it.startsWith("Uid:") } + ?.substringAfter("Uid:")?.trim()?.split(Regex("\\s+"))?.firstOrNull()?.toIntOrNull() ?: -1 + } + } catch (e: Exception) { + -1 + } + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt index 0d7f205a9d..3148994311 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionPrefs.kt @@ -181,4 +181,40 @@ object SessionPrefs { fun setLogsEnabled(context: Context, on: Boolean) { prefs(context).edit().putBoolean("logs", on).apply() } + + // ── Per-mode display ──────────────────────────────────────────────────────────────────── + + /** + * The tallest the session's display may be, in pixels, for MODE_STEAM / MODE_DESKTOP: + * 0 = the panel's own height, otherwise a cap. 1080 is the default the app always had - the + * client's CEF is the heaviest thing in a session and above 1080p it costs frames for nothing + * a handheld panel can show. Read once, when the session's display is sized. + */ + fun resolutionCap(context: Context, mode: String): Int = prefs(context).getInt("resolutionCap.$mode", 1080) + + fun setResolutionCap(context: Context, mode: String, cap: Int) { + prefs(context).edit().putInt("resolutionCap.$mode", cap).apply() + } + + /** + * What the desktop shell composites with: pixman (software, the default - the Adreno stand-in + * is not a DRM render node, so labwc's gbm allocator cannot use it), or gles2 / vulkan for a + * device that has a real node. `Download/steamdeck-wlr-renderer` still overrides it. + */ + fun desktopRenderer(context: Context): String = prefs(context).getString("desktopRenderer", "pixman") ?: "pixman" + + fun setDesktopRenderer(context: Context, renderer: String) { + prefs(context).edit().putString("desktopRenderer", renderer).apply() + } + + /** + * HDR10 output for MODE_STEAM / MODE_DESKTOP. Off by default. Honoured only when the panel + * lists HDR10 (HdrSupport), and decided when the compositor starts, which is once per app + * process: a change applies after the app is fully closed and opened again. + */ + fun hdr(context: Context, mode: String): Boolean = prefs(context).getBoolean("hdr.$mode", false) + + fun setHdr(context: Context, mode: String, on: Boolean) { + prefs(context).edit().putBoolean("hdr.$mode", on).apply() + } } diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt index ad4efb8589..2742cde1ab 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionService.kt @@ -72,7 +72,13 @@ class SessionService : Service() { SessionState.running = true SessionState.firstFrameSeen = false acquireLocks() - Thread({ runSession() }, "session-start").start() + Thread({ + // A tree the last session left behind (the app was killed or crashed, so its teardown + // never ran) would hold the rootfs, the GPU and Steam's lock: nothing of ours should + // be alive between sessions outside this process. + OrphanReaper.reap("session starting") + runSession() + }, "session-start").start() // The activity or the notification stops us; the system must not resurrect a session whose // guest processes are long gone. return START_NOT_STICKY @@ -238,6 +244,13 @@ class SessionService : Service() { guest.add("BL_WIDTH=" + size.first) guest.add("BL_HEIGHT=" + size.second) + if (SessionState.hdr) { + // The activity opened the compositor's HDR gate: gamescope offers HDR to its clients + // and DXVK takes the HDR10 swapchain when a game asks for one. + guest.add("BL_HDR=1") + guest.add("DXVK_HDR=1") + Log.i(TAG, "hdr: gamescope --hdr-enabled, DXVK_HDR=1") + } guest.add("BL_FPS=0") guest.add("BL_REFRESH=" + Math.round(SessionState.refreshHz)) guest.add("BL_LOG=" + sessionLog.path) @@ -272,7 +285,7 @@ class SessionService : Service() { if (SessionState.mode == MODE_DESKTOP) { val override = File(Environment.getExternalStorageDirectory(), "Download/steamdeck-wlr-renderer") .takeIf { it.isFile }?.let { FileUtils.readString(it)?.trim() } - guest.add("BL_WLR_RENDERER=" + (override?.takeIf { it.isNotEmpty() } ?: "pixman")) + guest.add("BL_WLR_RENDERER=" + (override?.takeIf { it.isNotEmpty() } ?: SessionPrefs.desktopRenderer(this))) } guest.add(LinuxRuntime.SESSION_SCRIPT) guest.add(SessionState.mode) diff --git a/app/src/main/java/com/steamdeck/launcher/session/SessionState.kt b/app/src/main/java/com/steamdeck/launcher/session/SessionState.kt index 1ca21c5d02..ada1de4b1c 100644 --- a/app/src/main/java/com/steamdeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/steamdeck/launcher/session/SessionState.kt @@ -10,6 +10,9 @@ import java.io.File object SessionState { @Volatile var running = false + /** HDR10 was asked for and the panel can show it: the compositor was told, and the session + * gets DXVK_HDR=1 and gamescope --hdr-enabled. Decided by the activity before the compositor starts. */ + @JvmStatic var hdr = false /** Which session this is: SessionService.MODE_STEAM or MODE_DESKTOP. */ @Volatile diff --git a/app/src/main/java/com/steamdeck/launcher/ui/AudioDialog.kt b/app/src/main/java/com/steamdeck/launcher/ui/AudioDialog.kt deleted file mode 100644 index c2a6d13259..0000000000 --- a/app/src/main/java/com/steamdeck/launcher/ui/AudioDialog.kt +++ /dev/null @@ -1,69 +0,0 @@ -package com.steamdeck.launcher.ui - -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Switch -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.unit.dp - -/** - * The two audio opt-ins. The client always has PulseAudio; these change what the games get and - * whether anything can record. Both apply at the next session start. - */ -@Composable -fun AudioDialog( - directAudio: Boolean, - mic: Boolean, - onDirectAudio: (Boolean) -> Unit, - onMic: (Boolean) -> Unit, - onDismiss: () -> Unit, -) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Audio") }, - text = { - Column { - Text( - "The Steam client itself always plays through PulseAudio. These two change what happens around it, at the next session start.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(12.dp)) - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - Column(modifier = Modifier.weight(1f)) { - Text("DirectAudio for games", style = MaterialTheme.typography.bodyMedium) - Text( - "Replaces Wine's audio driver inside the games the client launches with one that talks straight to Android — lower latency, no PulseAudio in between. Wine 11 Protons only (Valve's ARM64, GE, cachyos); on anything else it stays off rather than play silence. A game's first launch after turning this on still uses Proton's own audio; the second uses this.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Switch(checked = directAudio, onCheckedChange = onDirectAudio) - } - Spacer(Modifier.height(8.dp)) - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) { - Column(modifier = Modifier.weight(1f)) { - Text("Microphone", style = MaterialTheme.typography.bodyMedium) - Text( - "Gives the session Android's microphone: the Steam client shows an input device named DirectAudioMic, for voice chat. Asks for the recording permission; with it off, nothing in the session can record and Android's indicator stays off.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - Switch(checked = mic, onCheckedChange = onMic) - } - } - }, - confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } }, - ) -} diff --git a/app/src/main/java/com/steamdeck/launcher/ui/DriverDialog.kt b/app/src/main/java/com/steamdeck/launcher/ui/DriverDialog.kt deleted file mode 100644 index 78ae3bc55c..0000000000 --- a/app/src/main/java/com/steamdeck/launcher/ui/DriverDialog.kt +++ /dev/null @@ -1,140 +0,0 @@ -package com.steamdeck.launcher.ui - -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.Row -import androidx.compose.foundation.layout.Spacer -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.layout.width -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll -import androidx.compose.material3.AlertDialog -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.RadioButton -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.unit.dp -import com.steamdeck.launcher.session.SessionService - -/** One driver as the dialog shows it. [removable] is false for the runtime's own and the bundled builds. */ -class DriverRow(val id: String, val name: String, val detail: String, val removable: Boolean) - -/** - * The two driver choices a session has, each its own list, because a zip for one cannot serve the - * other: the glibc Turnip the runtime draws with (chosen per mode — Steam and the desktop can - * differ), and the bionic Turnip the app's compositor puts the frame on the panel with. Imports - * are validated where they land, so a "-Linux" zip dropped in the Android list is refused with - * the reason rather than becoming a black session. - */ -@Composable -fun DriverDialog( - linuxRows: List, - linuxSteam: String, - linuxDesktop: String, - androidRows: List, - androidSelected: String, - onSelectLinux: (mode: String, id: String) -> Unit, - onImportLinux: () -> Unit, - onRemoveLinux: (String) -> Unit, - onSelectAndroid: (String) -> Unit, - onImportAndroid: () -> Unit, - onRemoveAndroid: (String) -> Unit, - onDismiss: () -> Unit, -) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Graphics drivers") }, - text = { - Column(modifier = Modifier.verticalScroll(rememberScrollState())) { - Text("Linux runtime driver", style = MaterialTheme.typography.titleSmall) - Text( - "What the Steam client, its games and the desktop's programs render on, inside the runtime. " + - "\"-Linux\" Turnip zips only — these are Linux processes and cannot load an Android driver. " + - "Applies at the next session start.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(6.dp)) - Row(modifier = Modifier.fillMaxWidth()) { - Spacer(Modifier.weight(1f)) - Text("Steam", style = MaterialTheme.typography.labelSmall, modifier = Modifier.width(52.dp), fontWeight = FontWeight.Bold) - Text("Desktop", style = MaterialTheme.typography.labelSmall, modifier = Modifier.width(60.dp), fontWeight = FontWeight.Bold) - } - for (row in linuxRows) { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) { - Column(modifier = Modifier.weight(1f)) { - Text(row.name, style = MaterialTheme.typography.bodyMedium) - if (row.detail.isNotEmpty()) Text( - row.detail, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (row.removable) TextButton( - onClick = { onRemoveLinux(row.id) }, - contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp), - ) { Text("Remove", style = MaterialTheme.typography.labelSmall) } - } - RadioButton( - selected = row.id == linuxSteam, - onClick = { onSelectLinux(SessionService.MODE_STEAM, row.id) }, - modifier = Modifier.width(52.dp), - ) - RadioButton( - selected = row.id == linuxDesktop, - onClick = { onSelectLinux(SessionService.MODE_DESKTOP, row.id) }, - modifier = Modifier.width(60.dp), - ) - } - } - OutlinedButton(onClick = onImportLinux, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) { - Text("Import \"-Linux\" Turnip zip…") - } - - Spacer(Modifier.height(14.dp)) - HorizontalDivider() - Spacer(Modifier.height(10.dp)) - - Text("Display driver (Android)", style = MaterialTheme.typography.titleSmall) - Text( - "What the app's compositor puts frames on the screen with — the last step of every session. " + - "AdrenoTools zips only. The compositor loads its driver once per app process, so a change " + - "applies after the app is fully closed and opened again.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - Spacer(Modifier.height(6.dp)) - for (row in androidRows) { - Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) { - Column(modifier = Modifier.weight(1f)) { - Text(row.name, style = MaterialTheme.typography.bodyMedium) - if (row.detail.isNotEmpty()) Text( - row.detail, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (row.removable) TextButton( - onClick = { onRemoveAndroid(row.id) }, - contentPadding = androidx.compose.foundation.layout.PaddingValues(0.dp), - ) { Text("Remove", style = MaterialTheme.typography.labelSmall) } - } - RadioButton( - selected = row.id == androidSelected, - onClick = { onSelectAndroid(row.id) }, - ) - } - } - OutlinedButton(onClick = onImportAndroid, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) { - Text("Import AdrenoTools zip…") - } - } - }, - confirmButton = { TextButton(onClick = onDismiss) { Text("OK") } }, - ) -} diff --git a/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt b/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt index dadf0ec49e..bd22862ff2 100644 --- a/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt +++ b/app/src/main/java/com/steamdeck/launcher/ui/MainScreen.kt @@ -15,7 +15,11 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.systemBarsPadding +import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Icon import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.AlertDialog @@ -77,11 +81,12 @@ fun MainScreen( onRuntime: () -> Unit, onFrameGen: () -> Unit, onProtons: () -> Unit, - onDrivers: () -> Unit, - onAudio: () -> Unit, + onSteamSettings: () -> Unit, + onDesktopSettings: () -> Unit, onPerformance: () -> Unit, onOffline: () -> Unit, onRoms: () -> Unit, + onFiles: () -> Unit, onLogs: () -> Unit, onCredits: () -> Unit, ) { @@ -148,14 +153,36 @@ fun MainScreen( Spacer(Modifier.height(14.dp * k)) val buttonHeight = 40.dp * k - Button( - onClick = onPlay, enabled = state.ready && !state.busy, - modifier = Modifier.fillMaxWidth().height(buttonHeight), - ) { Text("Play", fontSize = 14.sp * k) } + // Each launch button has its own cog: what only matters for that mode lives there. + Row(horizontalArrangement = Arrangement.spacedBy(6.dp * k), modifier = Modifier.fillMaxWidth()) { + Button( + onClick = onPlay, enabled = state.ready && !state.busy, + modifier = Modifier.weight(1f).height(buttonHeight), + ) { Text("Play", fontSize = 14.sp * k) } + CogButton(k, onSteamSettings) + } + Row(horizontalArrangement = Arrangement.spacedBy(6.dp * k), modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k)) { + OutlinedButton( + onClick = onDesktop, enabled = state.ready && !state.busy && state.desktopInstalled, + modifier = Modifier.weight(1f).height(buttonHeight), + ) { Text(if (state.desktopInstalled) "Desktop" else "Desktop — install it under Desktop & apps", fontSize = 13.sp * k, maxLines = 1, overflow = TextOverflow.Ellipsis) } + CogButton(k, onDesktopSettings) + } + // Offline is read while the client starts, so it is decided here rather than in the + // session's drawer, and it needs credentials from an earlier sign-in to be possible. OutlinedButton( - onClick = onDesktop, enabled = state.ready && !state.busy && state.desktopInstalled, + onClick = onOffline, enabled = state.offlineAccount != null, modifier = Modifier.fillMaxWidth().padding(top = 5.dp * k).height(buttonHeight), - ) { Text(if (state.desktopInstalled) "Desktop" else "Desktop — install it under Desktop & apps", fontSize = 13.sp * k) } + ) { + Text( + when { + state.offlineAccount == null -> "Start offline — sign in once first" + state.offline -> "Start offline: on · ${state.offlineAccount}" + else -> "Start offline: off" + }, + fontSize = 13.sp * k, + ) + } Spacer(Modifier.height(8.dp * k)) val runtimeLabel = when { @@ -175,11 +202,6 @@ fun MainScreen( MenuTile("Compatibility tools", null, k, Modifier.weight(1f), onClick = onProtons) } Spacer(Modifier.height(6.dp * k)) - Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) { - MenuTile("Graphics drivers", null, k, Modifier.weight(1f), onClick = onDrivers) - MenuTile("Audio", null, k, Modifier.weight(1f), onClick = onAudio) - } - Spacer(Modifier.height(6.dp * k)) Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) { MenuTile("Performance", null, k, Modifier.weight(1f), onClick = onPerformance) // The folder's own name is the value; the whole path is in the dialog. @@ -190,17 +212,7 @@ fun MainScreen( } Spacer(Modifier.height(6.dp * k)) Row(horizontalArrangement = tileGap, modifier = Modifier.fillMaxWidth()) { - // Offline is read while the client starts, so it is decided here rather than in the - // session's drawer, and it needs credentials from an earlier sign-in to be possible. - MenuTile( - "Start offline", - when { - state.offlineAccount == null -> "sign in once first" - state.offline -> "on · ${state.offlineAccount}" - else -> "off" - }, - k, Modifier.weight(1f), enabled = state.offlineAccount != null, onClick = onOffline, - ) + MenuTile("Files", null, k, Modifier.weight(1f), onClick = onFiles) MenuTile( "Session logs", if (state.logsEnabled) "on · Download/SteamDeck" else "off", k, Modifier.weight(1f), onClick = onLogs, @@ -216,6 +228,16 @@ fun MainScreen( } } +/** The cog beside a launch button. */ +@Composable +private fun CogButton(k: Float, onClick: () -> Unit) { + OutlinedButton( + onClick = onClick, + modifier = Modifier.width(44.dp * k).height(40.dp * k), + contentPadding = PaddingValues(0.dp), + ) { Icon(Icons.Filled.Settings, contentDescription = "Settings", modifier = Modifier.size(18.dp * k)) } +} + /** One tile of the two-column menu: what it is, and under it what it is set to. */ @Composable private fun MenuTile( diff --git a/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt new file mode 100644 index 0000000000..9be5905b5b --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/ui/ModeSettingsDialog.kt @@ -0,0 +1,214 @@ +package com.steamdeck.launcher.ui + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.unit.dp +import com.steamdeck.launcher.session.SessionService + +/** One driver as the dialog shows it. [removable] is false for the runtime's own and the bundled builds. */ +class DriverRow(val id: String, val name: String, val detail: String, val removable: Boolean) + +/** Everything one mode's settings dialog shows; the activity owns the values. */ +class ModeSettings( + val mode: String, + val resolutionCap: Int, + val shapeMode: String, + val hdr: Boolean, + /** Why HDR cannot be offered on this display, or null when it can. */ + val hdrReason: String?, + val linuxRows: List, + val linuxSelected: String, + val androidRows: List, + val androidSelected: String, + val touchMode: String, + /** Steam only. */ + val oscMode: String?, + val directAudio: Boolean?, + val mic: Boolean?, + /** Desktop only. */ + val renderer: String?, +) + +class ModeSettingsActions( + val onResolution: (Int) -> Unit, + val onShape: (String) -> Unit, + val onHdr: (Boolean) -> Unit, + val onSelectLinux: (String) -> Unit, + val onImportLinux: () -> Unit, + val onRemoveLinux: (String) -> Unit, + val onSelectAndroid: (String) -> Unit, + val onImportAndroid: () -> Unit, + val onRemoveAndroid: (String) -> Unit, + val onTouch: (String) -> Unit, + val onOsc: (String) -> Unit, + val onDirectAudio: (Boolean) -> Unit, + val onMic: (Boolean) -> Unit, + val onRenderer: (String) -> Unit, + val onDismiss: () -> Unit, +) + +/** + * The cog beside Play / Desktop: what only matters for that one mode, in one place - the display + * the session is sized to, HDR, the driver inside the runtime, the display driver, and the input + * and audio choices - so the main screen is left with what applies to both. + */ +@Composable +fun ModeSettingsDialog(s: ModeSettings, a: ModeSettingsActions) { + val steam = s.mode == SessionService.MODE_STEAM + AlertDialog( + onDismissRequest = a.onDismiss, + title = { Text(if (steam) "Steam session" else "Desktop session") }, + text = { + Column(modifier = Modifier.verticalScroll(rememberScrollState())) { + Section("Display", "Takes effect at the next session: gamescope sizes its display once, when it starts.") + Text("Resolution", style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 4.dp)) + listOf( + 1080 to "Up to 1080p — the default", + 900 to "Up to 900p", + 720 to "Up to 720p — lighter on the GPU", + 0 to "The panel's own — above 1080p costs frames for nothing a handheld can show", + ).forEach { (cap, label) -> + Choice(label, s.resolutionCap == cap) { a.onResolution(cap) } + } + Text("Shape", style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 6.dp)) + Choice("The panel's shape (never narrower than 16:9)", s.shapeMode == "auto") { a.onShape("auto") } + Choice("16:9 — for a foldable, with bars on either panel", s.shapeMode == "16:9") { a.onShape("16:9") } + + Spacer(Modifier.height(6.dp)) + SwitchRow( + "HDR10 output", + s.hdrReason ?: (if (steam) "The compositor offers games HDR10 and gamescope passes it on; a game that renders HDR shows as HDR. Applies after the app is closed and opened again." + else "Offered to the desktop's programs; labwc itself composites in SDR, so only a program that presents HDR directly shows it. Applies after the app is closed and opened again."), + checked = s.hdr && s.hdrReason == null, enabled = s.hdrReason == null, onChange = a.onHdr, + ) + + Divider() + Section( + "Linux runtime driver", + "What " + (if (steam) "the Steam client and its games" else "the desktop's programs") + + " render on, inside the runtime. \"-Linux\" Turnip zips only. Applies at the next session start.", + ) + for (row in s.linuxRows) DriverChoice(row, row.id == s.linuxSelected, { a.onSelectLinux(row.id) }, { a.onRemoveLinux(row.id) }) + OutlinedButton(onClick = a.onImportLinux, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) { + Text("Import \"-Linux\" Turnip zip…") + } + + Divider() + Section( + "Display driver (Android)", + "What the app's compositor puts frames on the screen with, the last step of every session; shared by both modes. " + + "AdrenoTools zips only. Applies after the app is fully closed and opened again.", + ) + for (row in s.androidRows) DriverChoice(row, row.id == s.androidSelected, { a.onSelectAndroid(row.id) }, { a.onRemoveAndroid(row.id) }) + OutlinedButton(onClick = a.onImportAndroid, modifier = Modifier.fillMaxWidth().padding(top = 4.dp)) { + Text("Import AdrenoTools zip…") + } + + Divider() + Section("Touch", "How a finger drives the pointer. Also in the session's drawer.") + Choice("Auto — touchpad on the desktop, direct in Steam", s.touchMode == "auto") { a.onTouch("auto") } + Choice("Touchpad — drag moves the pointer, tap clicks", s.touchMode == "touchpad") { a.onTouch("touchpad") } + Choice("Direct — the pointer jumps under the finger", s.touchMode == "direct") { a.onTouch("direct") } + + if (steam && s.oscMode != null) { + Spacer(Modifier.height(6.dp)) + Text("On-screen controls", style = MaterialTheme.typography.labelLarge) + Choice("Auto — shown when no controller is attached", s.oscMode == "auto") { a.onOsc("auto") } + Choice("Always", s.oscMode == "always") { a.onOsc("always") } + Choice("Never", s.oscMode == "never") { a.onOsc("never") } + } + + if (steam && s.directAudio != null && s.mic != null) { + Divider() + Section("Audio", null) + SwitchRow( + "DirectAudio for games", + "Games play straight to the device, bypassing PulseAudio: lower latency. Off = PulseAudio for everything.", + s.directAudio, true, a.onDirectAudio, + ) + SwitchRow( + "Microphone", + "The device's microphone for voice chat, as the client's input device. Asks for the permission once.", + s.mic, true, a.onMic, + ) + } + + if (!steam && s.renderer != null) { + Divider() + Section( + "Desktop renderer", + "How labwc composites the desktop. pixman is software and works everywhere; gles2 / vulkan need a real DRM render node, which the Adreno stand-in is not on most devices.", + ) + Choice("pixman — software, the default", s.renderer == "pixman") { a.onRenderer("pixman") } + Choice("gles2", s.renderer == "gles2") { a.onRenderer("gles2") } + Choice("vulkan", s.renderer == "vulkan") { a.onRenderer("vulkan") } + } + } + }, + confirmButton = { TextButton(onClick = a.onDismiss) { Text("Done") } }, + ) +} + +@Composable +private fun Section(title: String, detail: String?) { + Text(title, style = MaterialTheme.typography.titleSmall) + if (detail != null) Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) +} + +@Composable +private fun Divider() { + Spacer(Modifier.height(12.dp)) + HorizontalDivider() + Spacer(Modifier.height(10.dp)) +} + +@Composable +private fun Choice(label: String, selected: Boolean, onClick: () -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth()) { + RadioButton(selected = selected, onClick = onClick) + Text(label, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.weight(1f)) + } +} + +@Composable +private fun SwitchRow(label: String, detail: String, checked: Boolean, enabled: Boolean, onChange: (Boolean) -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp)) { + Column(modifier = Modifier.weight(1f)) { + Text(label, style = MaterialTheme.typography.bodyMedium) + Text(detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + } + Switch(checked = checked, enabled = enabled, onCheckedChange = onChange) + } +} + +@Composable +private fun DriverChoice(row: DriverRow, selected: Boolean, onSelect: () -> Unit, onRemove: () -> Unit) { + Row(verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) { + RadioButton(selected = selected, onClick = onSelect) + Column(modifier = Modifier.weight(1f)) { + Text(row.name, style = MaterialTheme.typography.bodyMedium) + if (row.detail.isNotEmpty()) Text(row.detail, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) + if (row.removable) TextButton(onClick = onRemove, contentPadding = PaddingValues(0.dp)) { + Text("Remove", style = MaterialTheme.typography.labelSmall) + } + } + } +} diff --git a/app/src/main/java/com/steamdeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/steamdeck/launcher/ui/SessionOverlay.kt index 2eccc35e1f..226248c4f6 100644 --- a/app/src/main/java/com/steamdeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/steamdeck/launcher/ui/SessionOverlay.kt @@ -94,6 +94,8 @@ class DrawerActions( val onHud: (Boolean) -> Unit, val onFrameGen: () -> Unit, val onKeyboard: () -> Unit, + /** Sends the Guide button (the client's menu); null on the desktop, where there is none. */ + val onSteamMenu: (() -> Unit)?, val onProtons: () -> Unit, val onOsc: () -> Unit, val onTouch: () -> Unit, @@ -136,6 +138,9 @@ fun SessionDrawer(a: DrawerActions) { OutlinedButton(onClick = a.onKeyboard, modifier = Modifier.fillMaxWidth().padding(top = 8.dp)) { Text("Keyboard", fontSize = 13.sp) } + if (a.onSteamMenu != null) OutlinedButton(onClick = a.onSteamMenu, modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) { + Text("Steam menu ◉", fontSize = 13.sp) + } OutlinedButton(onClick = a.onFrameGen, modifier = Modifier.fillMaxWidth().padding(top = 6.dp)) { Text("Frame generation: ${a.frameGenLabel}", fontSize = 13.sp) } diff --git a/app/src/main/java/com/steamdeck/launcher/wayland/HdrSupport.kt b/app/src/main/java/com/steamdeck/launcher/wayland/HdrSupport.kt new file mode 100644 index 0000000000..b3e2a54d62 --- /dev/null +++ b/app/src/main/java/com/steamdeck/launcher/wayland/HdrSupport.kt @@ -0,0 +1,67 @@ +package com.steamdeck.launcher.wayland + +import android.content.Context +import android.os.Build +import android.view.Display +import android.view.WindowManager + +/** + * What the panel says about HDR, read from android.view.Display: the gate the compositor's HDR10 + * output sits behind (banner_color.h). A property of the display, not the device - and the + * settings screen greys the HDR switch out with the reason when it is not there, rather than + * offering a switch that a session would then silently ignore. + */ +class HdrProbe( + val hdr10: Boolean, + val formats: String, + val maxLuminance: Float, + val maxAverageLuminance: Float, + val minLuminance: Float, + val ratioAvailable: Boolean, + val ratio: Float, + val displayId: Int, + val name: String, +) { + /** Why HDR cannot be offered, or null when it can. */ + val reason: String? = when { + Build.VERSION.SDK_INT < 29 -> "needs Android 10 or newer (display layers with a colour space)" + !hdr10 -> if (formats.isEmpty()) "this display reports no HDR support" else "this display supports $formats, not HDR10" + else -> null + } +} + +object HdrSupport { + fun probe(context: Context): HdrProbe { + val display: Display? = if (Build.VERSION.SDK_INT >= 30) { + try { context.display } catch (e: Exception) { null } + } else { + @Suppress("DEPRECATION") + (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager).defaultDisplay + } + if (display == null) return HdrProbe(false, "", 0f, 0f, 0f, false, -1f, -1, "none") + val caps = try { display.hdrCapabilities } catch (e: Exception) { null } + val types = caps?.supportedHdrTypes ?: IntArray(0) + val formats = types.joinToString(", ") { typeName(it) } + val ratioAvailable = Build.VERSION.SDK_INT >= 34 && try { display.isHdrSdrRatioAvailable } catch (e: Exception) { false } + val ratio = if (ratioAvailable) try { display.hdrSdrRatio } catch (e: Exception) { -1f } else -1f + return HdrProbe( + hdr10 = types.contains(Display.HdrCapabilities.HDR_TYPE_HDR10), + formats = formats, + maxLuminance = caps?.desiredMaxLuminance ?: 0f, + maxAverageLuminance = caps?.desiredMaxAverageLuminance ?: 0f, + minLuminance = caps?.desiredMinLuminance ?: 0f, + ratioAvailable = ratioAvailable, + ratio = ratio, + displayId = display.displayId, + name = display.name ?: "display", + ) + } + + private fun typeName(t: Int): String = when (t) { + Display.HdrCapabilities.HDR_TYPE_DOLBY_VISION -> "Dolby Vision" + Display.HdrCapabilities.HDR_TYPE_HDR10 -> "HDR10" + Display.HdrCapabilities.HDR_TYPE_HLG -> "HLG" + Display.HdrCapabilities.HDR_TYPE_HDR10_PLUS -> "HDR10+" + else -> "HDR" + } +} diff --git a/app/src/main/res/drawable/icon_menu_container.xml b/app/src/main/res/drawable/icon_menu_container.xml new file mode 100644 index 0000000000..c75cafd2b2 --- /dev/null +++ b/app/src/main/res/drawable/icon_menu_container.xml @@ -0,0 +1,5 @@ + + + + diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session index 538d2050be..c44efcbb41 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-session +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-session @@ -101,6 +101,9 @@ if [ -z "${BL_INSIDE:-}" ]; then args+=(-r "$BL_REFRESH") fi [ "$mode" = steam ] && args+=(-e) + # HDR10: the app opened its compositor's colour-management gate for this session (BL_HDR=1); + # gamescope then offers HDR to its clients through the same wp_color_manager_v1 it binds on ours. + [ "${BL_HDR:-0}" = 1 ] && args+=(--hdr-enabled) export BL_INSIDE=1 exec gamescope "${args[@]}" -- "$0" "$mode" "$@" fi