diff --git a/app/src/main/java/dev/alvin/smbexplorer/ImageViewer.kt b/app/src/main/java/dev/alvin/smbexplorer/ImageViewer.kt index 448abdd..9fda2de 100644 --- a/app/src/main/java/dev/alvin/smbexplorer/ImageViewer.kt +++ b/app/src/main/java/dev/alvin/smbexplorer/ImageViewer.kt @@ -30,11 +30,19 @@ import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.AndroidView import kotlinx.coroutines.CancellationException import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.launch import kotlinx.coroutines.withContext +import kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock import java.nio.ByteBuffer @Composable fun ImageViewer(saved: SavedShare, folder: String, images: List, initial: RemoteEntry, onClose: () -> Unit) { + val loader = remember(saved.id, folder) { ImageLoader(saved.target, folder) } + DisposableEffect(loader) { onDispose { loader.close() } } var index by remember(folder, initial.name) { mutableStateOf(images.indexOfFirst { it.name == initial.name }.coerceAtLeast(0)) } val entry = images[index] var drawable by remember { mutableStateOf(null) } @@ -47,8 +55,8 @@ fun ImageViewer(saved: SavedShare, folder: String, images: List, in error = null loading = true try { - val path = if (folder.isEmpty()) entry.name else "$folder\\${entry.name}" - val bytes = withContext(Dispatchers.IO) { SmbProbe().use { it.readImage(saved.target, path) } } + val bytes = loader.load(entry.name) + images.getOrNull(index + 1)?.let { loader.prefetch(it.name) } drawable = withContext(Dispatchers.Default) { ImageDecoder.decodeDrawable(ImageDecoder.createSource(ByteBuffer.wrap(bytes))) { decoder, info, _ -> val largestSide = maxOf(info.size.width, info.size.height) @@ -100,3 +108,40 @@ fun ImageViewer(saved: SavedShare, folder: String, images: List, in } } } + +private class ImageLoader(private val target: SmbTarget, private val folder: String) { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val mutex = Mutex() + private var session: SmbImageSession? = null + private val cache = LinkedHashMap(4, .75f, true) + private var cacheBytes = 0L + + suspend fun load(name: String): ByteArray = withContext(Dispatchers.IO) { + mutex.withLock { + cache[name]?.let { return@withLock it } + val path = if (folder.isEmpty()) name else "$folder\\$name" + val bytes = (session ?: SmbImageSession(target).also { session = it }).read(path) + if (bytes.size <= 24 * 1024 * 1024) { + while (cacheBytes + bytes.size > 24L * 1024 * 1024) { + val oldest = cache.entries.first() + cacheBytes -= oldest.value.size + cache.remove(oldest.key) + } + cache[name] = bytes + cacheBytes += bytes.size + } + bytes + } + } + + fun prefetch(name: String) { + scope.launch { runCatching { load(name) } } + } + + fun close() { + scope.launch { + mutex.withLock { session?.close(); session = null; cache.clear() } + scope.cancel() + } + } +} diff --git a/app/src/main/java/dev/alvin/smbexplorer/SmbProbe.kt b/app/src/main/java/dev/alvin/smbexplorer/SmbProbe.kt index 48fc320..3c79cec 100644 --- a/app/src/main/java/dev/alvin/smbexplorer/SmbProbe.kt +++ b/app/src/main/java/dev/alvin/smbexplorer/SmbProbe.kt @@ -15,6 +15,8 @@ import java.io.Closeable import java.security.MessageDigest import java.util.EnumSet import java.io.ByteArrayOutputStream +import com.hierynomus.smbj.connection.Connection +import com.hierynomus.smbj.session.Session data class SmbTarget( val host: String, @@ -69,34 +71,6 @@ class SmbProbe : Closeable { } } - fun readImage(target: SmbTarget, path: String, maxBytes: Long = 64L * 1024 * 1024): ByteArray { - val connection = client.connect(target.host.trim(), target.port) - try { - val session = connection.authenticate(AuthenticationContext(target.username, target.password.toCharArray(), target.domain)) - try { - val share = session.connectShare(target.share.trim()) as DiskShare - try { - val file = share.openFile(normalize(path), EnumSet.of(AccessMask.GENERIC_READ), - EnumSet.noneOf(FileAttributes::class.java), EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ), - SMB2CreateDisposition.FILE_OPEN, EnumSet.noneOf(SMB2CreateOptions::class.java)) - try { - require(file.length in 0..maxBytes) { "Image exceeds the 64 MB viewer limit" } - val output = ByteArrayOutputStream() - val buffer = ByteArray(64 * 1024) - var offset = 0L - while (offset < file.length) { - val count = file.read(buffer, offset) - require(count > 0) { "Image ended before all bytes were read" } - output.write(buffer, 0, count) - offset += count - } - return output.toByteArray() - } finally { file.close() } - } finally { share.close() } - } finally { session.close() } - } finally { connection.close() } - } - private fun readRanges(share: DiskShare, path: String): List { val file: File = share.openFile( path, @@ -123,6 +97,41 @@ class SmbProbe : Closeable { override fun close() = client.close() } +/** Keeps the SMB session open while the viewer is visible. Call from one IO coroutine at a time. */ +class SmbImageSession(target: SmbTarget) : Closeable { + private val client = SMBClient() + private val connection: Connection = client.connect(target.host.trim(), target.port) + private val session: Session = connection.authenticate( + AuthenticationContext(target.username, target.password.toCharArray(), target.domain)) + private val share: DiskShare = session.connectShare(target.share.trim()) as DiskShare + + fun read(path: String, maxBytes: Long = 64L * 1024 * 1024): ByteArray { + val file = share.openFile(normalize(path), EnumSet.of(AccessMask.GENERIC_READ), + EnumSet.noneOf(FileAttributes::class.java), EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ), + SMB2CreateDisposition.FILE_OPEN, EnumSet.noneOf(SMB2CreateOptions::class.java)) + try { + require(file.length in 0..maxBytes) { "Image exceeds the 64 MB viewer limit" } + val output = ByteArrayOutputStream(file.length.toInt()) + val buffer = ByteArray(256 * 1024) + var offset = 0L + while (offset < file.length) { + val count = file.read(buffer, offset) + require(count > 0) { "Image ended before all bytes were read" } + output.write(buffer, 0, count) + offset += count + } + return output.toByteArray() + } finally { file.close() } + } + + override fun close() { + share.close() + session.close() + connection.close() + client.close() + } +} + private fun FileIdBothDirectoryInformation.toEntry() = RemoteEntry( fileName, fileAttributes.toInt() and 0x10 != 0,