diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 9dc4e7494..2fc01d8a3 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -123,6 +123,7 @@ import com.droiddeck.launcher.ui.SecondScreenPresentation import com.droiddeck.launcher.ui.BottomDashboard import com.droiddeck.launcher.ui.BottomPage import com.droiddeck.launcher.ui.sessionBottomPages +import com.droiddeck.launcher.ui.BottomPageActions import com.droiddeck.launcher.ui.DroidDeckTheme import com.droiddeck.launcher.wayland.CompositorHost import com.droiddeck.launcher.wayland.WaylandCompositor @@ -3133,7 +3134,40 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { ) /** Pages for the bottom-screen dashboard; the dashboard is offered only while at least one exists. */ - private fun bottomPages(): List = sessionBottomPages() + private fun bottomPages(): List = sessionBottomPages(BottomPageActions(takeScreenshot = ::captureScreenshot)) + + /** Copies the game frame (no overlay) at the size it is shown and saves it to Pictures/DroidDeck. */ + private fun captureScreenshot(onDone: (Boolean) -> Unit) { + val width = if (::surfaceView.isInitialized) surfaceView.width else 0 + val height = if (::surfaceView.isInitialized) surfaceView.height else 0 + if (width <= 0 || height <= 0 || surfaceView.holder.surface?.isValid != true) { + onDone(false) + return + } + val bitmap = try { + android.graphics.Bitmap.createBitmap(width, height, android.graphics.Bitmap.Config.ARGB_8888) + } catch (_: OutOfMemoryError) { + onDone(false) + return + } + try { + android.view.PixelCopy.request(surfaceView, bitmap, { result -> + if (result != android.view.PixelCopy.SUCCESS) { + bitmap.recycle() + onDone(false) + return@request + } + Thread { + val saved = com.droiddeck.launcher.session.BottomScreenshots.save(applicationContext, bitmap) + bitmap.recycle() + runOnUiThread { onDone(saved) } + }.start() + }, uiHandler) + } catch (_: IllegalArgumentException) { + bitmap.recycle() + onDone(false) + } + } private fun tapSteamButton() { if (SessionState.mode == SessionService.MODE_STEAM) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/BottomScreenshots.kt b/app/src/main/java/com/droiddeck/launcher/session/BottomScreenshots.kt new file mode 100644 index 000000000..c79bb62ab --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/session/BottomScreenshots.kt @@ -0,0 +1,97 @@ +package com.droiddeck.launcher.session + +import android.content.ContentValues +import android.content.Context +import android.graphics.Bitmap +import android.net.Uri +import android.os.Build +import android.os.Environment +import android.provider.MediaStore +import java.io.File +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale + +/** A screenshot for the bottom-screen gallery: one DroidDeck took (a MediaStore [uri]) or one Steam saved (a [file]). */ +data class BottomShot(val uri: Uri?, val file: File?, val takenAt: Long, val steam: Boolean) { + val model: Any get() = uri ?: file!! +} + +/** Game frames DroidDeck saves to Pictures/DroidDeck, plus the screenshots Steam keeps under userdata. */ +object BottomScreenshots { + private const val FOLDER = "DroidDeck" + private const val QUALITY = 95 + private const val LIMIT = 120 + + internal fun fileName(at: Long): String = + "DroidDeck_" + SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(Date(at)) + ".jpg" + + fun save(context: Context, bitmap: Bitmap, at: Long = System.currentTimeMillis()): Boolean = runCatching { + val name = fileName(at) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { + val resolver = context.contentResolver + val values = ContentValues().apply { + put(MediaStore.Images.Media.DISPLAY_NAME, name) + put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg") + put(MediaStore.Images.Media.DATE_TAKEN, at) + put(MediaStore.Images.Media.RELATIVE_PATH, "${Environment.DIRECTORY_PICTURES}/$FOLDER") + put(MediaStore.Images.Media.IS_PENDING, 1) + } + val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values) ?: return false + val written = runCatching { + resolver.openOutputStream(uri)?.use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) } == true + }.getOrDefault(false) + if (!written) { + resolver.delete(uri, null, null) + return false + } + resolver.update(uri, ContentValues().apply { put(MediaStore.Images.Media.IS_PENDING, 0) }, null, null) + true + } else { + @Suppress("DEPRECATION") + val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER) + if (!dir.isDirectory && !dir.mkdirs()) return false + val file = File(dir, name) + file.outputStream().use { bitmap.compress(Bitmap.CompressFormat.JPEG, QUALITY, it) } + android.media.MediaScannerConnection.scanFile(context, arrayOf(file.path), arrayOf("image/jpeg"), null) + true + } + }.getOrDefault(false) + + /** Newest first, at most [LIMIT]. */ + fun list(context: Context, runtimeRoot: File): List = + (own(context) + steam(runtimeRoot)).sortedByDescending { it.takenAt }.take(LIMIT) + + private fun own(context: Context): List = runCatching { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) { + @Suppress("DEPRECATION") + val dir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), FOLDER) + return dir.listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty() + .map { BottomShot(null, it, it.lastModified(), steam = false) } + } + val shots = ArrayList() + context.contentResolver.query( + MediaStore.Images.Media.EXTERNAL_CONTENT_URI, + arrayOf(MediaStore.Images.Media._ID, MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DATE_ADDED), + "${MediaStore.Images.Media.RELATIVE_PATH} = ?", arrayOf("${Environment.DIRECTORY_PICTURES}/$FOLDER/"), + "${MediaStore.Images.Media.DATE_ADDED} DESC", + )?.use { c -> + while (c.moveToNext() && shots.size < LIMIT) { + val taken = c.getLong(1).takeIf { it > 0L } ?: (c.getLong(2) * 1000L) + shots += BottomShot(android.content.ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, c.getLong(0)), + null, taken, steam = false) + } + } + shots + }.getOrDefault(emptyList()) + + /** userdata//760/remote//screenshots/*.jpg in each Steam home; the thumbnails folder is skipped. */ + internal fun steam(runtimeRoot: File): List = + SteamDownloadMonitor.STEAM_HOMES.flatMap { home -> + File(runtimeRoot, "$home/userdata").listFiles { f -> f.isDirectory }.orEmpty().flatMap { account -> + File(account, "760/remote").listFiles { f -> f.isDirectory }.orEmpty().flatMap { app -> + File(app, "screenshots").listFiles { f -> f.isFile && f.name.endsWith(".jpg", true) }.orEmpty().toList() + } + } + }.map { BottomShot(null, it, it.lastModified(), steam = true) } +} diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt index 85e33d52e..0373bbab5 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomPages.kt @@ -3,10 +3,17 @@ package com.droiddeck.launcher.ui import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Download import androidx.compose.material.icons.outlined.Notifications +import androidx.compose.material.icons.outlined.PhotoLibrary import com.droiddeck.launcher.R +/** What the bottom-screen pages can ask the running session to do. */ +class BottomPageActions( + val takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)? = null, +) + /** The pages the bottom-screen dashboard offers during a session, in tab order. */ -fun sessionBottomPages(): List = listOf( +fun sessionBottomPages(actions: BottomPageActions): List = listOf( BottomPage("downloads", R.string.bottom_page_downloads, Icons.Outlined.Download) { BottomDownloadsPage() }, BottomPage("notifications", R.string.bottom_page_notifications, Icons.Outlined.Notifications) { BottomNotificationsPage() }, + BottomPage("screenshots", R.string.bottom_page_screenshots, Icons.Outlined.PhotoLibrary) { BottomScreenshotsPage(actions.takeScreenshot) }, ) diff --git a/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenshotsPage.kt b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenshotsPage.kt new file mode 100644 index 000000000..e854016fb --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/ui/BottomScreenshotsPage.kt @@ -0,0 +1,110 @@ +package com.droiddeck.launcher.ui + +import androidx.compose.foundation.background +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.aspectRatio +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableIntStateOf +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.draw.clip +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import coil.compose.AsyncImage +import coil.request.ImageRequest +import com.droiddeck.launcher.R +import com.droiddeck.launcher.runtime.LinuxRuntime +import com.droiddeck.launcher.session.BottomScreenshots +import com.droiddeck.launcher.session.BottomShot +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext + +private const val SHOTS_POLL_MS = 5_000L + +@Composable +fun BottomScreenshotsPage(takeScreenshot: ((onDone: (Boolean) -> Unit) -> Unit)?) { + val context = LocalContext.current + val colors = MaterialTheme.colorScheme + var shots by remember { mutableStateOf>(emptyList()) } + var refresh by remember { mutableIntStateOf(0) } + var open by remember { mutableStateOf(null) } + var status by remember { mutableStateOf(null) } + var busy by remember { mutableStateOf(false) } + LaunchedEffect(refresh) { + while (true) { + shots = withContext(Dispatchers.IO) { BottomScreenshots.list(context, LinuxRuntime.rootDir(context)) } + delay(SHOTS_POLL_MS) + } + } + LaunchedEffect(status) { + if (status != null) { + delay(3_000L) + status = null + } + } + open?.let { shot -> + Box(Modifier.fillMaxSize().clip(RoundedCornerShape(14.dp)).background(androidx.compose.ui.graphics.Color.Black) + .clickable(role = Role.Button) { open = null }.testTag("bottom-shot-full")) { + AsyncImage(ImageRequest.Builder(context).data(shot.model).build(), contentDescription = null, + contentScale = ContentScale.Fit, modifier = Modifier.fillMaxSize()) + } + return + } + Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) { + Text(status?.let { stringResource(it) } ?: stringResource(R.string.bottom_shots_where), fontSize = 13.sp, + color = colors.onSurfaceVariant, maxLines = 2, modifier = Modifier.weight(1f).padding(end = 8.dp)) + if (takeScreenshot != null) BottomPillButton(stringResource(R.string.bottom_shots_take), "bottom-shots-take") { + if (!busy) { + busy = true + takeScreenshot { ok -> + busy = false + status = if (ok) R.string.bottom_shots_saved else R.string.bottom_shots_failed + refresh++ + } + } + } + } + if (shots.isEmpty()) { + Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) { + Text(stringResource(R.string.bottom_shots_none), fontSize = 15.sp, color = colors.onSurfaceVariant) + } + } else { + LazyVerticalGrid(GridCells.Adaptive(150.dp), Modifier.weight(1f).fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) { + items(shots, key = { it.model.toString() }) { shot -> + AsyncImage( + ImageRequest.Builder(context).data(shot.model).size(480, 270).build(), contentDescription = null, + contentScale = ContentScale.Crop, + modifier = Modifier.fillMaxWidth().aspectRatio(16f / 9f).clip(RoundedCornerShape(10.dp)) + .background(LocalPalette.current.surface).clickable(role = Role.Button) { open = shot }, + ) + } + } + } + } +} diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ce976356f..6bba5152c 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -1890,6 +1890,12 @@ No notifications. %1$d notifications Clear + Screenshots + Saved to Pictures/DroidDeck. Steam screenshots show here too. + Take screenshot + Screenshot saved. + Could not take a screenshot. + No screenshots yet. Removing Linux runtime diff --git a/app/src/test/java/com/droiddeck/launcher/session/BottomScreenshotsTest.kt b/app/src/test/java/com/droiddeck/launcher/session/BottomScreenshotsTest.kt new file mode 100644 index 000000000..0731f6b90 --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/session/BottomScreenshotsTest.kt @@ -0,0 +1,32 @@ +package com.droiddeck.launcher.session + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder +import java.io.File + +class BottomScreenshotsTest { + @get:Rule val tmp = TemporaryFolder() + + @Test fun fileNamesSortByTime() { + val name = BottomScreenshots.fileName(0L) + assertTrue(name, name.startsWith("DroidDeck_") && name.endsWith(".jpg")) + assertEquals(29, name.length) + } + + @Test fun steamScreenshotsAreFoundAndThumbnailsSkipped() { + val root = tmp.root + val shots = File(root, "root/.local/share/Steam/userdata/2932373/760/remote/220/screenshots") + File(shots, "thumbnails").mkdirs() + File(shots, "20261031010101_1.jpg").writeText("x") + File(shots, "thumbnails/20261031010101_1.jpg").writeText("x") + File(shots, "screenshots.vdf").writeText("x") + val x64 = File(root, "root/.droiddeck-x64/.local/share/Steam/userdata/2932373/760/remote/440/screenshots") + x64.mkdirs() + File(x64, "20261031020202_1.jpg").writeText("x") + val found = BottomScreenshots.steam(root).map { it.file!!.name }.sorted() + assertEquals(listOf("20261031010101_1.jpg", "20261031020202_1.jpg"), found) + } +}