app/src/main/java/dev/equwal/inkdim/Toggle.kt (1981 bytes)
1 // SPDX-License-Identifier: GPL-3.0-or-later 2 // Copyright (c) 2026 equwal 3 package dev.equwal.inkdim 4 5 import android.content.Context 6 7 /** 8 * The one action of this app, for the icon, the tile and the intent actions. 9 * 10 * It reads the light node first, so the state is what the light really does, 11 * not only what this app last did. Then it writes, and remembers the result. 12 */ 13 object Toggle { 14 15 private const val PREFS = "inkdim" 16 private const val K_ON = "on" 17 18 fun remembered(c: Context): Boolean = 19 c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getBoolean(K_ON, false) 20 21 private fun remember(c: Context, on: Boolean) { 22 c.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putBoolean(K_ON, on).apply() 23 } 24 25 /** 26 * Does [action]. [done] gets the new state, or null when the app could not 27 * do it: no shell access, or no light node on this device. 28 */ 29 fun run(c: Context, action: Dim.Action, done: (Boolean?) -> Unit = {}) { 30 Shell.run(Dim.readCommand(Dim.nodes)) { read -> 31 val value = Dim.parseRead(read.output) 32 if (!read.ok && value == null) return@run done(null) 33 val on = Dim.next(value, remembered(c), action) 34 remember(c, on) 35 val command = if (on) Dim.writeCommand(Dim.nodes, Dim.ON_VALUE) else Dim.restoreCommand() 36 Shell.run(command) { done(if (it.ok) on else null) } 37 } 38 } 39 40 /** The state the light is in now. It also corrects what the app remembers. */ 41 fun live(c: Context, done: (Boolean) -> Unit) { 42 Shell.run(Dim.readCommand(Dim.nodes)) { read -> 43 val on = Dim.isOn(Dim.parseRead(read.output), remembered(c)) 44 remember(c, on) 45 done(on) 46 } 47 } 48 49 /** True when this device has a light node that the app knows. */ 50 fun hasNode(done: (Boolean) -> Unit) { 51 Shell.run(Dim.readCommand(Dim.nodes)) { done(it.ok && Dim.parseRead(it.output) != null) } 52 } 53 }