diff --git a/flexera/AndroidManifest.xml b/flexera/AndroidManifest.xml index 92628a082f..e40b4fc25d 100644 --- a/flexera/AndroidManifest.xml +++ b/flexera/AndroidManifest.xml @@ -3,9 +3,10 @@ Flexera Launcher manifest overrides. Attached to the debug and release build types in build.gradle, which outrank Lawnchair's flavor manifests and every library manifest during the merge. - Network access: the INTERNET permission comes from Lawnchair's manifest and is kept for one purpose, - the app's own update check (app.flexera.update.FlexeraUpdater). Lawnchair's online features stay - switched off in code; see app.flexera.FlexeraNetwork. + Network access: the INTERNET permission comes from Lawnchair's manifest and is kept for the + launcher's own features: the update check (app.flexera.update.FlexeraUpdater), and what the owner + sets up (the clock's weather, the RSS reader, the car widget's Traccar server and map). + Lawnchair's online features stay switched off in code; see app.flexera.FlexeraNetwork. --> @@ -16,7 +17,8 @@ @@ -58,6 +60,27 @@ android:exported="false" android:theme="@style/Theme.Transparent" /> + + + + + + + + + + + + + + + + + + + diff --git a/flexera/res/drawable/ic_flexera_car.xml b/flexera/res/drawable/ic_flexera_car.xml new file mode 100644 index 0000000000..725264a7ff --- /dev/null +++ b/flexera/res/drawable/ic_flexera_car.xml @@ -0,0 +1,14 @@ + + + + + diff --git a/flexera/res/layout/flexera_car_widget_placeholder.xml b/flexera/res/layout/flexera_car_widget_placeholder.xml new file mode 100644 index 0000000000..ae5f036918 --- /dev/null +++ b/flexera/res/layout/flexera_car_widget_placeholder.xml @@ -0,0 +1,16 @@ + + + + + + diff --git a/flexera/res/values/flexera_dimens.xml b/flexera/res/values/flexera_dimens.xml index afeb2ee3a5..3b18b5b4cd 100644 --- a/flexera/res/values/flexera_dimens.xml +++ b/flexera/res/values/flexera_dimens.xml @@ -75,6 +75,10 @@ 13sp 10dp + + 15sp + 12sp + 34dp 4dp 12sp diff --git a/flexera/res/values/flexera_strings.xml b/flexera/res/values/flexera_strings.xml index 9e8298846a..1b855f4ede 100644 --- a/flexera/res/values/flexera_strings.xml +++ b/flexera/res/values/flexera_strings.xml @@ -84,7 +84,7 @@ QR code that downloads the latest version Privacy What goes online - Flexera Launcher goes online for two things. It asks its release page whether a newer version exists, about once a day, and downloads that version when you ask. And if you pick a place for the weather on a clock widget, it asks Open-Meteo, a weather service, for the weather there. Looking a place up sends the name you type and your phone\'s language; asking for its weather sends the place, to about a kilometre, and whether you use Celsius or Fahrenheit. Nothing else about you, your apps or your phone leaves it. + Flexera Launcher goes online only for these things. It asks its release page whether a newer version exists, about once a day, and downloads that version when you ask. If you pick a place for the weather on a clock widget, it asks Open-Meteo, a weather service, for the weather there. Looking a place up sends the name you type and your phone\'s language; asking for its weather sends the place, to about a kilometre, and whether you use Celsius or Fahrenheit. The RSS reader fetches the feeds you add, and the articles you open, from their own sites. A car widget asks your own Traccar server where the car is, while the widget is on screen, and fetches the map around the car from OpenStreetMap, which so sees which streets are shown; when Traccar gives no street name, your phone\'s own address lookup is asked for it. Nothing else about you, your apps or your phone leaves it. Search apps and more @@ -225,6 +225,74 @@ Picture %1$d of %2$d None of the chosen pictures could be read + + + Car + Where your car is parked, on a map, from your Traccar server + + Your car + Tap to set up + Tap to sign in to Traccar again + Tap to allow local network access + Looking for the car… + Traccar has no position for it yet + Can\'t reach Traccar + Parked + + Parked for %1$s + + Parked since %1$s + Parked for over a week + Driving + + Driving, %1$s + + updated %1$s + + © OpenStreetMap + + Show the way to %1$s + Open the car widget\'s options + Ask Traccar again + No app here can show the way + + + Traccar server + Server address + traccar.example.com + Token + Show + Hide + Leave empty to keep the token you gave before + Make a token in Traccar, in your account\'s settings. Safest is a Traccar user of its own for this, one that can see only your car: the token can do no more than that user can. + + Connect + Cancel + + Connected to %1$s + Change + Car + Online + Offline + This Traccar user can\'t see any devices. + + %1$s isn\'t in this list any more. Pick a car above. + Done + Try again + Allow local network access + That isn\'t a web address. + Enter the token from Traccar. + Traccar didn\'t accept the token. It may be wrong or expired, or its user disabled. + Something answered at that address, but not Traccar. + The address has to start with https. The token isn\'t sent over a connection that isn\'t encrypted. + Android doesn\'t trust the server\'s certificate. + The server is on the network your phone is on, and Android keeps the launcher off that network until you allow it. + Couldn\'t reach the server. Check the address and your connection. + Traccar answered with an error. + The token couldn\'t be stored safely on this phone, so it wasn\'t kept. + While a car widget is on screen, the launcher asks your Traccar server where the car is: every two minutes at most while it\'s parked, more often while it drives. The map comes from OpenStreetMap, which sees which streets are shown. When Traccar gives no street name, your phone\'s own address lookup is asked for it. The token is kept encrypted on this phone, and not in backups. + Updates diff --git a/flexera/res/xml/flexera_car_widget_info.xml b/flexera/res/xml/flexera_car_widget_info.xml new file mode 100644 index 0000000000..6f48f9d80a --- /dev/null +++ b/flexera/res/xml/flexera_car_widget_info.xml @@ -0,0 +1,23 @@ + + + diff --git a/flexera/src/app/flexera/widget/CarLocation.kt b/flexera/src/app/flexera/widget/CarLocation.kt new file mode 100644 index 0000000000..f99cc3c9ad --- /dev/null +++ b/flexera/src/app/flexera/widget/CarLocation.kt @@ -0,0 +1,359 @@ +package app.flexera.widget + +import android.content.Context +import android.location.Address +import android.location.Geocoder +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.util.Log +import androidx.annotation.WorkerThread +import com.android.launcher3.util.Executors +import java.io.IOException +import java.util.Locale +import java.util.concurrent.CopyOnWriteArraySet +import kotlin.math.atan2 +import kotlin.math.cos +import kotlin.math.sin +import kotlin.math.sqrt +import org.json.JSONException +import org.json.JSONObject + +/** + * Where each car of the car widgets is: its last position from the owner's Traccar server + * ([Traccar]), the street it stands in, and since when it has stood there. + * + * The server is asked only while a car widget is in view, at most every [FRESH_PARKED_MS] while + * the car stands still and every [FRESH_MOVING_MS] while it drives; after a request that failed, + * at intervals that grow from [RETRY_MS] to [RETRY_MAX_MS]. The last answer is kept, so that the + * car is on the map at once and stays there through a spell offline: a parked car's place does + * not go out of date. + * + * The street comes from the server when it looks addresses up itself, else from the phone's own + * address lookup ([Geocoder]), asked once for each place the car stops at. Since when the car + * stands still comes from Traccar's stops report, asked once when the car stops and again now and + * then ([STOP_RECHECK_MS]). + */ +internal object CarLocation { + + /** What is known of a car. */ + data class Reading( + val latitude: Double, + val longitude: Double, + /** When the tracker took the position, in milliseconds since 1970. */ + val fixTime: Long, + val moving: Boolean, + val speedKnots: Double, + /** The street, as short as it can be said ("Ilica 42"); null when none is known. */ + val street: String?, + /** Since when the car stands where it is; 0 while that is not known, or while it drives. */ + val parkedSince: Long, + /** True when it already stood there at the start of the stops report ([STOP_WINDOW_MS]). */ + val parkedLonger: Boolean, + /** When the server last answered, in milliseconds since 1970. */ + val readAt: Long, + /** When the stops report was last asked; 0 for never. */ + val stopsAskedAt: Long, + /** Where the [street] was found, so that it is not looked up again while the car stays. */ + val streetLatitude: Double, + val streetLongitude: Double, + ) + + /** How a car stands, for the widget: a reading, nothing yet, or a problem in the way. */ + class State(val reading: Reading?, val problem: Traccar.Problem?, val noPosition: Boolean, val asking: Boolean) + + /** Told, on the main thread, that something new is known about a car. */ + fun interface Listener { + fun onCarLocationChanged(deviceId: Long) + } + + private const val TAG = "CarLocation" + private const val FILE = "flexera_car_location" + + /** How old a reading may be before the server is asked again, while the car stands and while it drives. */ + private const val FRESH_PARKED_MS = 2 * 60 * 1000L + private const val FRESH_MOVING_MS = 20 * 1000L + + /** The first wait after a failed request, doubled for each failure in a row up to [RETRY_MAX_MS]. */ + private const val RETRY_MS = 60 * 1000L + private const val RETRY_MAX_MS = 15 * 60 * 1000L + + /** How far back the stops report looks. A car parked longer than this is "parked for over a week". */ + const val STOP_WINDOW_MS = 7 * 24 * 60 * 60 * 1000L + + /** + * How often the stops report is asked again while the car stands still: when the start of the + * stop is not known yet (Traccar counts a stop only after some minutes), and when it is, in + * case the car went and came back between two looks. + */ + private const val STOP_RETRY_MS = 4 * 60 * 1000L + private const val STOP_RECHECK_MS = 30 * 60 * 1000L + + /** How near the car must be to a stop of the report for it to be the stop it is in now. */ + private const val STOP_RADIUS_M = 150.0 + + /** How much earlier than the car's last position the stop may end and still be the one going on. */ + private const val STOP_END_SLACK_MS = 10 * 60 * 1000L + + /** How near the start of the report a stop must start to have started before it. */ + private const val STOP_CLIPPED_MS = 60 * 1000L + + /** How far the car may be from where its street was found for the street to stay. */ + private const val STREET_RADIUS_M = 40.0 + + private class Failure(val at: Long, val inARow: Int, val problem: Traccar.Problem) + + private val listeners = CopyOnWriteArraySet() + private val main = Handler(Looper.getMainLooper()) + + // Guarded by [asking]: which devices are being asked for, the last failure of each, and + // those for which Traccar had no position, with when it said so (elapsedRealtime). + private val asking = HashSet() + private val failures = HashMap() + private val empty = HashMap() + + fun addListener(listener: Listener) { + listeners.add(listener) + } + + fun removeListener(listener: Listener) { + listeners.remove(listener) + } + + /** What is known of a car now, for the widget. */ + fun state(context: Context, deviceId: Long): State = synchronized(asking) { + State( + reading = reading(context, deviceId), + problem = failures[deviceId]?.problem, + noPosition = deviceId in empty.keys, + asking = deviceId in asking, + ) + } + + /** The last reading of a car from the account signed in now; null when there is none. */ + fun reading(context: Context, deviceId: Long): Reading? { + val account = CarWidgetStore.account(context) ?: return null + val stored = prefs(context).getString(key(deviceId), null) ?: return null + return try { + val json = JSONObject(stored) + if (json.optString("server") != account.server) return null + Reading( + latitude = json.getDouble("lat"), + longitude = json.getDouble("lon"), + fixTime = json.optLong("fix"), + moving = json.optBoolean("moving"), + speedKnots = json.optDouble("speed", 0.0), + street = if (json.isNull("street")) null else json.optString("street").ifEmpty { null }, + parkedSince = json.optLong("since"), + parkedLonger = json.optBoolean("longer"), + readAt = json.optLong("read"), + stopsAskedAt = json.optLong("stops"), + streetLatitude = json.optDouble("streetLat", Double.NaN), + streetLongitude = json.optDouble("streetLon", Double.NaN), + ) + } catch (e: JSONException) { + null + } + } + + /** + * Asks the server for a car's position in the background, unless the last answer is fresh, a + * request is on its way, or the last one failed too recently to try again. [now] asks even + * when the last answer is fresh, as for a tap on a widget waiting for its first one. + */ + fun refreshIfStale(context: Context, deviceId: Long, now: Boolean = false) { + val app = context.applicationContext + val account = CarWidgetStore.account(app) ?: return + val last = reading(app, deviceId) + val fresh = if (last?.moving == true) FRESH_MOVING_MS else FRESH_PARKED_MS + if (!now && last != null && System.currentTimeMillis() - last.readAt in 0 until fresh) return + synchronized(asking) { + // "No position yet" is an answer too, as fresh as a position would be. + val emptyAt = empty[deviceId] + if (!now && emptyAt != null && SystemClock.elapsedRealtime() - emptyAt < FRESH_PARKED_MS) return + val failure = failures[deviceId] + if (failure != null) { + // A token Traccar refused is not tried again until the owner signs in anew. + if (failure.problem == Traccar.Problem.TOKEN) return + if (SystemClock.elapsedRealtime() - failure.at < retryAfter(failure.inARow)) return + } + if (!asking.add(deviceId)) return + } + tell(deviceId) + Executors.THREAD_POOL_EXECUTOR.execute { + try { + val position = Traccar.latestPosition(app, account, deviceId) + synchronized(asking) { + failures.remove(deviceId) + if (position == null) empty[deviceId] = SystemClock.elapsedRealtime() else empty.remove(deviceId) + } + if (position != null) store(app, account, deviceId, read(app, account, deviceId, position, last)) + } catch (e: Traccar.TraccarException) { + synchronized(asking) { + failures[deviceId] = Failure(SystemClock.elapsedRealtime(), (failures[deviceId]?.inARow ?: 0) + 1, e.problem) + } + } catch (e: RuntimeException) { + Log.w(TAG, "No position this time", e) + synchronized(asking) { + failures[deviceId] = Failure(SystemClock.elapsedRealtime(), (failures[deviceId]?.inARow ?: 0) + 1, Traccar.Problem.SERVER) + } + } finally { + synchronized(asking) { asking.remove(deviceId) } + tell(deviceId) + } + } + } + + /** + * Forgets every car's reading and failures, as when the owner signs in to another server or + * with another token: that one may see other cars, or none. + */ + fun forget(context: Context) { + prefs(context).edit().clear().apply() + forgetFailures() + } + + /** Forgets the failures, so that every car is asked for at once: the owner has just signed in. */ + fun forgetFailures() { + synchronized(asking) { + failures.clear() + empty.clear() + } + } + + /** A new reading from [position], with what [last] knew that still holds. */ + @WorkerThread + private fun read(context: Context, account: Traccar.Account, deviceId: Long, position: Traccar.Position, last: Reading?): Reading { + val now = System.currentTimeMillis() + + // The street: the server's, or the last one found while the car is still near where it + // was found, or the phone's lookup. + var streetLatitude = position.latitude + var streetLongitude = position.longitude + val street = position.address?.let(::streetOf) + ?: last?.takeIf { + it.street != null && distance(it.streetLatitude, it.streetLongitude, position.latitude, position.longitude) <= STREET_RADIUS_M + }?.let { + streetLatitude = it.streetLatitude + streetLongitude = it.streetLongitude + it.street + } + ?: lookUpStreet(context, position.latitude, position.longitude) + + // Since when it stands here. + var since = 0L + var longer = false + var stopsAskedAt = last?.stopsAskedAt ?: 0L + if (!position.moving) { + // Standing where it stood at the last look: what was known of the stop holds. + val samePlace = last != null && !last.moving && + distance(last.latitude, last.longitude, position.latitude, position.longitude) <= STOP_RADIUS_M + val stillThere = samePlace && last.parkedSince > 0 + if (stillThere) { + since = last.parkedSince + longer = last.parkedLonger + } + val due = if (stillThere) STOP_RECHECK_MS else STOP_RETRY_MS + if (!samePlace || now - stopsAskedAt !in 0 until due) { + stopsAskedAt = now + try { + val from = now - STOP_WINDOW_MS + val stop = Traccar.lastStop(context, account, deviceId, from, now) + val current = stop != null && + stop.end >= position.fixTime - STOP_END_SLACK_MS && + distance(stop.latitude, stop.longitude, position.latitude, position.longitude) <= STOP_RADIUS_M + if (current) { + since = stop.start + longer = stop.start - from < STOP_CLIPPED_MS + } else if (!stillThere) { + since = 0L + } + } catch (e: Traccar.TraccarException) { + // The report may be switched off for this user; the car is shown without it. + Log.w(TAG, "No stops report: ${e.problem}") + } + } + } + return Reading( + latitude = position.latitude, + longitude = position.longitude, + fixTime = position.fixTime, + moving = position.moving, + speedKnots = position.speedKnots, + street = street, + parkedSince = since, + parkedLonger = longer, + readAt = now, + stopsAskedAt = stopsAskedAt, + streetLatitude = if (street == null) Double.NaN else streetLatitude, + streetLongitude = if (street == null) Double.NaN else streetLongitude, + ) + } + + private fun store(context: Context, account: Traccar.Account, deviceId: Long, reading: Reading) { + val json = JSONObject() + .put("server", account.server) + .put("lat", reading.latitude) + .put("lon", reading.longitude) + .put("fix", reading.fixTime) + .put("moving", reading.moving) + .put("speed", reading.speedKnots) + .put("street", reading.street ?: JSONObject.NULL) + .put("since", reading.parkedSince) + .put("longer", reading.parkedLonger) + .put("read", reading.readAt) + .put("stops", reading.stopsAskedAt) + if (reading.streetLatitude.isFinite() && reading.streetLongitude.isFinite()) { + json.put("streetLat", reading.streetLatitude).put("streetLon", reading.streetLongitude) + } + prefs(context).edit().putString(key(deviceId), json.toString()).apply() + } + + /** The first part of an address, where the street and the house number are: "Ilica 42". */ + private fun streetOf(address: String): String? = address.substringBefore(',').trim().ifEmpty { null } + + /** + * The street at a place, from the phone's own address lookup; null when the phone has none, + * is offline, or knows no address there. + */ + @WorkerThread + @Suppress("DEPRECATION") + private fun lookUpStreet(context: Context, latitude: Double, longitude: Double): String? { + if (!Geocoder.isPresent()) return null + return try { + val found: Address = Geocoder(context, Locale.getDefault()) + .getFromLocation(latitude, longitude, 1)?.firstOrNull() ?: return null + found.getAddressLine(0)?.let(::streetOf) ?: found.thoroughfare + } catch (e: IOException) { + Log.w(TAG, "No street from the phone's address lookup: ${e.message}") + null + } catch (e: IllegalArgumentException) { + null + } + } + + /** The distance between two places in metres, along the earth's surface. */ + internal fun distance(lat1: Double, lon1: Double, lat2: Double, lon2: Double): Double { + if (!lat1.isFinite() || !lon1.isFinite() || !lat2.isFinite() || !lon2.isFinite()) return Double.MAX_VALUE + val p1 = Math.toRadians(lat1) + val p2 = Math.toRadians(lat2) + val dp = p2 - p1 + val dl = Math.toRadians(lon2 - lon1) + val a = sin(dp / 2) * sin(dp / 2) + cos(p1) * cos(p2) * sin(dl / 2) * sin(dl / 2) + return EARTH_RADIUS_M * 2 * atan2(sqrt(a), sqrt(1 - a)) + } + + private const val EARTH_RADIUS_M = 6_371_000.0 + + private fun retryAfter(inARow: Int): Long = + (RETRY_MS shl (inARow - 1).coerceIn(0, 8)).coerceAtMost(RETRY_MAX_MS) + + private fun tell(deviceId: Long) { + main.post { listeners.forEach { it.onCarLocationChanged(deviceId) } } + } + + private fun key(deviceId: Long) = "car_$deviceId" + + private fun prefs(context: Context) = + context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE) +} diff --git a/flexera/src/app/flexera/widget/CarWidgetConfigActivity.kt b/flexera/src/app/flexera/widget/CarWidgetConfigActivity.kt new file mode 100644 index 0000000000..80689ca2cb --- /dev/null +++ b/flexera/src/app/flexera/widget/CarWidgetConfigActivity.kt @@ -0,0 +1,455 @@ +package app.flexera.widget + +import android.appwidget.AppWidgetManager +import android.content.Intent +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.activity.result.contract.ActivityResultContracts +import androidx.annotation.StringRes +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.heightIn +import androidx.compose.foundation.layout.imePadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.selection.selectable +import androidx.compose.foundation.selection.selectableGroup +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.key +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.platform.LocalFocusManager +import androidx.compose.ui.platform.LocalSoftwareKeyboardController +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.LiveRegionMode +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.input.VisualTransformation +import androidx.compose.ui.unit.dp +import app.flexera.update.FlexeraUpdater +import app.lawnchair.ui.theme.EdgeToEdge +import app.lawnchair.ui.theme.LawnchairTheme +import com.android.launcher3.R +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.withContext + +/** + * The car widget's options: the Traccar server and the token the launcher signs in with, once for + * all car widgets, and the car this widget follows, picked from the devices Traccar lists. A sheet + * over the home screen, as the clock's options are. + * + * Android opens it when the widget is put on the home screen, and the widget's edit button opens + * it again; the widget opens it itself when it is not set up, when Traccar refuses the token, and + * when Android 17 keeps the launcher off the home network the server is on. A widget being added + * stays on the home screen only once it has a car. + */ +class CarWidgetConfigActivity : ComponentActivity() { + + private var widget = AppWidgetManager.INVALID_APPWIDGET_ID + + @OptIn(ExperimentalMaterial3Api::class) + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + enableEdgeToEdge() + widget = intent?.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) + ?: AppWidgetManager.INVALID_APPWIDGET_ID + if (widget == AppWidgetManager.INVALID_APPWIDGET_ID) { + setResult(RESULT_CANCELED) + finish() + return + } + updateResult() + + setContent { + LawnchairTheme { + EdgeToEdge() + ModalBottomSheet( + onDismissRequest = { finish() }, + sheetState = rememberModalBottomSheetState(skipPartiallyExpanded = true), + containerColor = MaterialTheme.colorScheme.surface, + // No dimming: what shows of the home screen above the sheet stays as it is. + scrimColor = Color.Transparent, + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + .imePadding() + .padding(start = 24.dp, end = 24.dp, bottom = 32.dp), + ) { + Text( + text = stringResource(id = R.string.flexera_car_widget), + style = MaterialTheme.typography.titleLarge, + ) + Spacer(modifier = Modifier.height(20.dp)) + CarOptions(widget = widget, onChanged = ::updateResult, onDone = ::finish) + } + } + } + } + } + + /** Leaving says yes once the widget has an account and a car; a widget being added without them is dropped. */ + private fun updateResult() { + val ready = CarWidgetStore.account(this) != null && CarWidgetStore.car(this, widget) != null + setResult(if (ready) RESULT_OK else RESULT_CANCELED, Intent().putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, widget)) + } +} + +/** How signing in went. */ +private sealed interface SignIn { + data object Idle : SignIn + data object Running : SignIn + + /** [message] says what went wrong; [problem] is Traccar's, when it came that far. */ + data class Failed(@StringRes val message: Int, val problem: Traccar.Problem? = null) : SignIn +} + +@Composable +private fun CarOptions(widget: Int, onChanged: () -> Unit, onDone: () -> Unit) { + val context = LocalContext.current + val scope = rememberCoroutineScope() + val keyboard = LocalSoftwareKeyboardController.current + val focus = LocalFocusManager.current + + var account by remember { mutableStateOf(CarWidgetStore.account(context)) } + var editing by rememberSaveable { mutableStateOf(account == null) } + var server by rememberSaveable { mutableStateOf(account?.server?.removePrefix("https://").orEmpty()) } + // Not kept with the screen's saved state, so that the token is not written out with it. + var token by remember { mutableStateOf("") } + var tokenShown by remember { mutableStateOf(false) } + var signIn by remember { mutableStateOf(SignIn.Idle) } + var attempts by remember { mutableIntStateOf(0) } + + var devices by remember { mutableStateOf?>(null) } + var listing by remember { mutableStateOf(false) } + var listProblem by remember { mutableStateOf(null) } + var chosen by remember { mutableStateOf(CarWidgetStore.car(context, widget)) } + + val choose = { device: Traccar.Device -> + val car = CarWidgetStore.Car(device.id, device.name) + CarWidgetStore.setCar(context, widget, car) + chosen = car + onChanged() + } + + val list = { signedIn: Traccar.Account -> + listing = true + listProblem = null + scope.launch { + val result = withContext(Dispatchers.IO) { runCatching { Traccar.devices(context, signedIn) } } + listing = false + result.onSuccess { found -> + devices = found + if (chosen == null && found.size == 1) choose(found.first()) + } + result.onFailure { error -> + val problem = (error as? Traccar.TraccarException)?.problem ?: Traccar.Problem.SERVER + if (problem == Traccar.Problem.TOKEN) { + // The token no longer works: sign in again, here. + editing = true + signIn = SignIn.Failed(R.string.flexera_car_config_problem_token, problem) + } else { + listProblem = problem + } + } + } + Unit + } + + val connect = connect@{ + if (signIn == SignIn.Running) return@connect + val address = Traccar.normalize(server) + if (address == null) { + signIn = SignIn.Failed(R.string.flexera_car_config_problem_address) + return@connect + } + // An empty token field keeps the token given before, for the same server. + val key = token.trim().ifEmpty { account?.takeIf { it.server == address }?.token.orEmpty() } + if (key.isEmpty()) { + signIn = SignIn.Failed(R.string.flexera_car_config_problem_no_token) + return@connect + } + if (!address.startsWith("https://")) { + signIn = SignIn.Failed(problemText(Traccar.Problem.NOT_SECURE), Traccar.Problem.NOT_SECURE) + return@connect + } + keyboard?.hide() + focus.clearFocus() + signIn = SignIn.Running + attempts++ + val candidate = Traccar.Account(address, key) + scope.launch { + val result = withContext(Dispatchers.IO) { runCatching { Traccar.devices(context, candidate) } } + result.onSuccess { found -> + CarWidgetStore.setAccount(context, candidate) + val kept = CarWidgetStore.account(context) + if (kept == null) { + signIn = SignIn.Failed(R.string.flexera_car_config_problem_keystore) + return@onSuccess + } + account = kept + server = kept.server.removePrefix("https://") + token = "" + tokenShown = false + editing = false + signIn = SignIn.Idle + listProblem = null + devices = found + if (chosen == null && found.size == 1) choose(found.first()) + onChanged() + } + result.onFailure { error -> + val problem = (error as? Traccar.TraccarException)?.problem ?: Traccar.Problem.SERVER + signIn = SignIn.Failed(problemText(problem), problem) + } + } + Unit + } + + // Android 17 asks before an app may reach a device on the phone's own network. + val allowLocalNetwork = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + if (!granted) return@rememberLauncherForActivityResult + if (editing) connect() else account?.let(list) + } + + LaunchedEffect(Unit) { + account?.let(list) + } + + Heading(R.string.flexera_car_config_server_heading) + if (editing) { + OutlinedTextField( + value = server, + onValueChange = { server = it }, + label = { Text(text = stringResource(id = R.string.flexera_car_config_server)) }, + placeholder = { Text(text = stringResource(id = R.string.flexera_car_config_server_hint)) }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri, imeAction = ImeAction.Next), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(modifier = Modifier.height(12.dp)) + OutlinedTextField( + value = token, + onValueChange = { token = it }, + label = { Text(text = stringResource(id = R.string.flexera_car_config_token)) }, + singleLine = true, + visualTransformation = if (tokenShown) VisualTransformation.None else PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = ImeAction.Done), + keyboardActions = KeyboardActions(onDone = { connect() }), + trailingIcon = { + TextButton(onClick = { tokenShown = !tokenShown }) { + Text( + text = stringResource( + id = if (tokenShown) R.string.flexera_car_config_token_hide else R.string.flexera_car_config_token_show, + ), + ) + } + }, + supportingText = if (account != null) { + { Text(text = stringResource(id = R.string.flexera_car_config_token_keep)) } + } else { + null + }, + modifier = Modifier.fillMaxWidth(), + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = stringResource(id = R.string.flexera_car_config_token_help), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(modifier = Modifier.height(16.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Button(onClick = { connect() }, enabled = signIn != SignIn.Running) { + Text(text = stringResource(id = R.string.flexera_car_config_connect)) + } + if (account != null) { + Spacer(modifier = Modifier.width(8.dp)) + TextButton( + onClick = { + editing = false + signIn = SignIn.Idle + token = "" + }, + ) { + Text(text = stringResource(id = R.string.flexera_car_config_cancel)) + } + } + } + // Each try gets a new note, which TalkBack reads out, also when it says what the last one did. + key(attempts) { + when (val state = signIn) { + SignIn.Running -> LinearProgressIndicator( + modifier = Modifier + .fillMaxWidth() + .padding(top = 16.dp), + ) + + is SignIn.Failed -> { + Note(stringResource(id = state.message)) + if (state.problem == Traccar.Problem.LOCAL_NETWORK) { + TextButton(onClick = { allowLocalNetwork.launch(FlexeraUpdater.LOCAL_NETWORK_PERMISSION) }) { + Text(text = stringResource(id = R.string.flexera_car_config_allow_local_network)) + } + } + } + + SignIn.Idle -> Unit + } + } + } else { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = stringResource(id = R.string.flexera_car_config_connected, account?.host.orEmpty()), + style = MaterialTheme.typography.bodyLarge, + modifier = Modifier.weight(1f), + ) + TextButton( + onClick = { + editing = true + signIn = SignIn.Idle + }, + ) { + Text(text = stringResource(id = R.string.flexera_car_config_change)) + } + } + + Spacer(modifier = Modifier.height(20.dp)) + Heading(R.string.flexera_car_config_car_heading) + val found = devices + when { + listing && found == null -> LinearProgressIndicator(modifier = Modifier.fillMaxWidth()) + + listProblem != null -> { + val problem = listProblem!! + Note(stringResource(id = problemText(problem))) + Row { + if (problem == Traccar.Problem.LOCAL_NETWORK) { + TextButton(onClick = { allowLocalNetwork.launch(FlexeraUpdater.LOCAL_NETWORK_PERMISSION) }) { + Text(text = stringResource(id = R.string.flexera_car_config_allow_local_network)) + } + } + TextButton(onClick = { account?.let(list) }) { + Text(text = stringResource(id = R.string.flexera_car_config_try_again)) + } + } + } + + found != null && found.isEmpty() -> Note(stringResource(id = R.string.flexera_car_config_no_devices)) + + found != null -> Column(modifier = Modifier.selectableGroup()) { + found.forEach { device -> + val selected = device.id == chosen?.deviceId + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier + .fillMaxWidth() + .heightIn(min = 56.dp) + .selectable(selected = selected, onClick = { choose(device) }, role = Role.RadioButton), + ) { + RadioButton(selected = selected, onClick = null) + Spacer(modifier = Modifier.width(12.dp)) + Column { + Text(text = device.name, style = MaterialTheme.typography.bodyLarge) + Text( + text = stringResource( + id = if (device.online) R.string.flexera_car_config_online else R.string.flexera_car_config_offline, + ), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } + } + val picked = chosen + if (picked != null && found.none { it.id == picked.deviceId }) { + Note(stringResource(id = R.string.flexera_car_config_car_missing, picked.name)) + } + } + } + + if (chosen != null) { + Spacer(modifier = Modifier.height(20.dp)) + Button(onClick = onDone, modifier = Modifier.fillMaxWidth()) { + Text(text = stringResource(id = R.string.flexera_car_config_done)) + } + } + } + + Spacer(modifier = Modifier.height(24.dp)) + Text( + text = stringResource(id = R.string.flexera_car_config_privacy), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +@StringRes +private fun problemText(problem: Traccar.Problem): Int = when (problem) { + Traccar.Problem.TOKEN -> R.string.flexera_car_config_problem_token + Traccar.Problem.NOT_TRACCAR -> R.string.flexera_car_config_problem_not_traccar + Traccar.Problem.NOT_SECURE -> R.string.flexera_car_config_problem_https + Traccar.Problem.CERTIFICATE -> R.string.flexera_car_config_problem_certificate + Traccar.Problem.LOCAL_NETWORK -> R.string.flexera_car_config_problem_local_network + Traccar.Problem.OFFLINE -> R.string.flexera_car_config_problem_offline + Traccar.Problem.SERVER -> R.string.flexera_car_config_problem_server +} + +@Composable +private fun Heading(@StringRes text: Int) { + Text( + text = stringResource(id = text), + style = MaterialTheme.typography.labelLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(modifier = Modifier.height(8.dp)) +} + +/** What a try did. TalkBack reads it out as it appears: nothing else would say that it is there. */ +@Composable +private fun Note(text: String) { + Text( + text = text, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier + .padding(top = 12.dp) + .semantics { liveRegion = LiveRegionMode.Polite }, + ) +} diff --git a/flexera/src/app/flexera/widget/CarWidgetProvider.kt b/flexera/src/app/flexera/widget/CarWidgetProvider.kt new file mode 100644 index 0000000000..18d3a993f4 --- /dev/null +++ b/flexera/src/app/flexera/widget/CarWidgetProvider.kt @@ -0,0 +1,67 @@ +package app.flexera.widget + +import android.appwidget.AppWidgetProvider +import android.content.ComponentName +import android.content.Context +import android.util.Log +import com.android.launcher3.BuildConfig +import com.android.launcher3.model.data.LauncherAppWidgetInfo + +/** + * The launcher's own car widget: where the owner's car is, on a map, from their Traccar server. + * Android knows it as an ordinary app widget; the launcher draws it itself with a + * [CarWidgetView]. Setting it up means signing in to Traccar once and picking the car + * ([CarWidgetConfigActivity]); which car a widget follows is kept in [CarWidgetStore], under the + * widget's id, and goes with the widget when a restore gives it a new one. See [FlexeraWidgets]. + */ +class CarWidgetProvider : AppWidgetProvider() { + + override fun onDeleted(context: Context, appWidgetIds: IntArray) { + appWidgetIds.forEach { CarWidgetStore.delete(context, it) } + } + + /** After Android's own restore. */ + override fun onRestored(context: Context, oldWidgetIds: IntArray, newWidgetIds: IntArray) { + CarWidgetStore.move(context, oldWidgetIds, newWidgetIds) + } + + companion object { + private const val TAG = "CarWidgetProvider" + + @JvmField + val componentName = ComponentName(BuildConfig.APPLICATION_ID, CarWidgetProvider::class.java.name) + + /** + * Told by Launcher3 (WidgetInflater) that a widget of the home screen got a new id + * because the one it had is no longer valid, as after a restore of the launcher's + * backup; [oldAppWidgetId] is the id it had. As for the clock (ClockWidgetProvider), the + * car goes to the new id before Launcher3 deletes the old one. + */ + @JvmStatic + fun onNewAppWidgetId(context: Context, item: LauncherAppWidgetInfo, oldAppWidgetId: Int) { + val newId = item.appWidgetId + if (item.providerName != componentName || oldAppWidgetId <= 0 || newId <= 0) return + try { + CarWidgetStore.move(context, intArrayOf(oldAppWidgetId), intArrayOf(newId)) + } catch (e: RuntimeException) { + // Never in the way of loading the home screens. + Log.w(TAG, "Car not handed to widget $newId", e) + } + } + + /** + * Told by Launcher3 (LauncherWidgetHolder) that it deleted a widget id, of any widget. + * Android calls onDeleted only for an id that was bound; a car widget removed while it + * waited for "tap to set up" may have its car under one that was not. + */ + @JvmStatic + fun onAppWidgetIdDeleted(context: Context, appWidgetId: Int) { + if (appWidgetId <= 0) return + try { + CarWidgetStore.delete(context, appWidgetId) + } catch (e: RuntimeException) { + Log.w(TAG, "Car of widget $appWidgetId not removed", e) + } + } + } +} diff --git a/flexera/src/app/flexera/widget/CarWidgetStore.kt b/flexera/src/app/flexera/widget/CarWidgetStore.kt new file mode 100644 index 0000000000..1f4832f54d --- /dev/null +++ b/flexera/src/app/flexera/widget/CarWidgetStore.kt @@ -0,0 +1,217 @@ +package app.flexera.widget + +import android.content.Context +import android.content.SharedPreferences +import android.os.Handler +import android.os.Looper +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import android.util.Log +import java.security.KeyStore +import java.util.concurrent.CopyOnWriteArraySet +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +/** + * What the car widget ([CarWidgetProvider]) keeps: the Traccar server it reads from and the token + * it signs in with, once for all car widgets, and for each widget the device it follows. + * + * The token is kept encrypted with a key that lives in Android's keystore and never leaves it. + * None of this is in a backup (the launcher's backup rules name other files), and a copy of the + * file on another phone could not be read without that key: after a restore the owner signs in + * again. + */ +object CarWidgetStore { + + /** The device a widget follows, with its name as it was when picked. */ + data class Car(val deviceId: Long, val name: String) + + /** + * Told, on the main thread, that a widget's car changed ([appWidgetId]), or that the account + * did ([ALL]). + */ + fun interface Listener { + fun onCarWidgetChanged(appWidgetId: Int) + } + + /** The [Listener] id for a change that concerns every car widget. */ + const val ALL = 0 + + private const val TAG = "CarWidgetStore" + private const val FILE = "flexera_car_widget" + private const val SERVER = "server" + private const val TOKEN = "token" + private const val DEVICE = "device_" + private const val NAME = "name_" + private val KEYS = listOf(DEVICE, NAME) + + private val listeners = CopyOnWriteArraySet() + private val main = Handler(Looper.getMainLooper()) + + /** The account as last read or written, so that the keystore is asked once per run. */ + @Volatile + private var cached: Pair? = null + + fun addListener(listener: Listener) { + listeners.add(listener) + } + + fun removeListener(listener: Listener) { + listeners.remove(listener) + } + + /** The Traccar server and token, or null when the owner has not signed in, or the token can no longer be read. */ + internal fun account(context: Context): Traccar.Account? { + val prefs = prefs(context) + val server = prefs.getString(SERVER, null) ?: return null + val sealed = prefs.getString(TOKEN, null) ?: return null + cached?.let { (key, account) -> if (key == "$server|$sealed") return account } + val account = TokenVault.open(sealed)?.let { Traccar.Account(server, it) } + cached = "$server|$sealed" to account + return account + } + + /** + * Signs the car widgets in to [account], or out with null. The positions known from another + * account are forgotten. + */ + internal fun setAccount(context: Context, account: Traccar.Account?) { + val before = account(context) + val edit = prefs(context).edit() + if (account == null) { + edit.remove(SERVER).remove(TOKEN) + cached = null + } else { + val sealed = TokenVault.seal(account.token) + if (sealed == null) { + // Without the keystore the token is not kept at all, rather than kept readable. + Log.w(TAG, "The token could not be encrypted; not kept") + edit.remove(SERVER).remove(TOKEN) + cached = null + } else { + edit.putString(SERVER, account.server).putString(TOKEN, sealed) + cached = "${account.server}|$sealed" to account + } + } + edit.apply() + if (before != account) { + CarLocation.forget(context) + } else { + // The same sign-in again, as after Traccar refused it and the owner put it right there. + CarLocation.forgetFailures() + } + tell(ALL) + } + + /** The car a widget follows; null for a widget not set up. */ + fun car(context: Context, appWidgetId: Int): Car? { + val prefs = prefs(context) + val id = prefs.getString(DEVICE + appWidgetId, null)?.toLongOrNull() ?: return null + return Car(id, prefs.getString(NAME + appWidgetId, null).orEmpty()) + } + + fun setCar(context: Context, appWidgetId: Int, car: Car) { + prefs(context).edit() + .putString(DEVICE + appWidgetId, car.deviceId.toString()) + .putString(NAME + appWidgetId, car.name) + .apply() + tell(appWidgetId) + } + + /** Forgets the car of a widget that left the home screen. The account stays for the others. */ + fun delete(context: Context, appWidgetId: Int) { + val edit = prefs(context).edit() + for (key in KEYS) edit.remove(key + appWidgetId) + edit.apply() + } + + /** + * Hands the car of each widget in [from] to the widget at the same place in [to]: the ids that + * a restore gave the widgets in place of the ones they had. May be called on any thread. + */ + fun move(context: Context, from: IntArray, to: IntArray) { + val prefs = prefs(context) + val before = prefs.all + val edit = prefs.edit() + // All old ids are cleared first, in one change, so that an id that is one widget's old id + // and another's new one ends up with the right car. + for (oldId in from) { + for (key in KEYS) edit.remove(key + oldId) + } + val moved = ArrayList() + for (i in from.indices) { + val newId = to.getOrNull(i) ?: continue + for (key in KEYS) { + val value = before[key + from[i]] as? String + if (value == null) edit.remove(key + newId) else edit.putString(key + newId, value) + } + moved.add(newId) + } + edit.apply() + moved.forEach(::tell) + } + + private fun tell(appWidgetId: Int) { + main.post { listeners.forEach { it.onCarWidgetChanged(appWidgetId) } } + } + + private fun prefs(context: Context): SharedPreferences = + context.applicationContext.getSharedPreferences(FILE, Context.MODE_PRIVATE) + + /** + * Encrypts the token with AES-GCM under a key of Android's keystore. What is kept is the + * nonce followed by the sealed token, in Base64. + */ + private object TokenVault { + private const val STORE = "AndroidKeyStore" + private const val ALIAS = "flexera_traccar_token" + private const val TRANSFORMATION = "AES/GCM/NoPadding" + private const val NONCE_BYTES = 12 + private const val TAG_BITS = 128 + + fun seal(token: String): String? = try { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.ENCRYPT_MODE, key(create = true)) + val nonce = cipher.iv + check(nonce.size == NONCE_BYTES) { "Unexpected nonce size ${nonce.size}" } + Base64.encodeToString(nonce + cipher.doFinal(token.toByteArray(Charsets.UTF_8)), Base64.NO_WRAP) + } catch (e: Exception) { + // The keystore can fail in many ways, some of them unchecked (ProviderException). + Log.w(TAG, "Could not encrypt the token", e) + null + } + + fun open(sealed: String): String? = try { + val bytes = Base64.decode(sealed, Base64.NO_WRAP) + val key = key(create = false) + if (key == null || bytes.size <= NONCE_BYTES) { + null + } else { + val cipher = Cipher.getInstance(TRANSFORMATION) + cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(TAG_BITS, bytes, 0, NONCE_BYTES)) + String(cipher.doFinal(bytes, NONCE_BYTES, bytes.size - NONCE_BYTES), Charsets.UTF_8) + } + } catch (e: Exception) { + Log.w(TAG, "Could not read the token", e) + null + } + + private fun key(create: Boolean): SecretKey? { + val store = KeyStore.getInstance(STORE).apply { load(null) } + (store.getKey(ALIAS, null) as? SecretKey)?.let { return it } + if (!create) return null + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, STORE) + generator.init( + KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(256) + .build(), + ) + return generator.generateKey() + } + } +} diff --git a/flexera/src/app/flexera/widget/CarWidgetView.kt b/flexera/src/app/flexera/widget/CarWidgetView.kt new file mode 100644 index 0000000000..e913f63e7e --- /dev/null +++ b/flexera/src/app/flexera/widget/CarWidgetView.kt @@ -0,0 +1,1042 @@ +package app.flexera.widget + +import android.animation.ValueAnimator +import android.app.Activity +import android.app.ActivityOptions +import android.appwidget.AppWidgetManager +import android.content.ActivityNotFoundException +import android.content.Context +import android.content.ContextWrapper +import android.content.Intent +import android.content.res.Configuration +import android.graphics.Bitmap +import android.graphics.BitmapShader +import android.graphics.Canvas +import android.graphics.Color +import android.graphics.ColorMatrix +import android.graphics.ColorMatrixColorFilter +import android.graphics.LinearGradient +import android.graphics.Matrix +import android.graphics.Paint +import android.graphics.Path +import android.graphics.Rect +import android.graphics.RectF +import android.graphics.Shader +import android.graphics.Typeface +import android.graphics.drawable.Drawable +import android.icu.text.MeasureFormat +import android.icu.util.LocaleData +import android.icu.util.Measure +import android.icu.util.MeasureUnit +import android.icu.util.ULocale +import android.net.Uri +import android.text.TextPaint +import android.text.TextUtils +import android.text.format.DateFormat +import android.util.AttributeSet +import android.util.Log +import android.util.TypedValue +import android.view.ViewConfiguration +import android.widget.FrameLayout +import android.widget.Toast +import android.window.SplashScreen +import androidx.core.content.ContextCompat +import androidx.core.graphics.ColorUtils +import androidx.core.view.ViewCompat +import androidx.core.view.accessibility.AccessibilityNodeInfoCompat.AccessibilityActionCompat +import app.lawnchair.icons.shape.CornerShapeCompat +import app.lawnchair.icons.shape.IconShape +import app.lawnchair.preferences2.PreferenceManager2 +import app.lawnchair.preferences2.firstCached +import com.android.launcher3.R +import com.android.launcher3.Utilities +import com.android.launcher3.util.Themes +import java.util.Calendar +import java.util.Locale +import kotlin.math.PI +import kotlin.math.cos +import kotlin.math.floor +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.min +import kotlin.math.roundToInt +import kotlin.math.tan + +/** + * What the car widget ([CarWidgetProvider]) looks like: a map of the streets around the car, with + * the car in the middle, and under it the street and how long the car has stood there, or how + * fast it drives. + * + * Like the picture widget it is shaped like a large icon: its edges are those of the icons in + * its cells ([IconFrame]) and its corners those of the icon shape, with the icons' soft shadow. + * The map is OpenStreetMap's ([MapTiles]), toned down a little, and turned dark with the dark + * theme; the car's place comes from the owner's Traccar server ([CarLocation]). + * + * A tap shows the way to the car on foot in Google Maps, or in another map app. While the widget + * is not set up, or Traccar has to be signed in to again or allowed on the local network, a tap + * opens its options ([CarWidgetConfigActivity]) instead. + * + * In the list of widgets the same view shows a drawn sample map. + */ +class CarWidgetView @JvmOverloads constructor( + context: Context, + attrs: AttributeSet? = null, +) : FrameLayout(context, attrs), + CarWidgetStore.Listener, + CarLocation.Listener, + MapTiles.Listener { + + /** What a tap does. */ + private enum class Tap { NOTHING, DIRECTIONS, OPTIONS, ASK_AGAIN } + + private var appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID + + /** True while this is only a sample of the widget, in the list of widgets. */ + private var sample = true + private var car: CarWidgetStore.Car? = null + private var signedIn = false + private var state: CarLocation.State? = null + private var onScreen = false + private var tap = Tap.NOTHING + + // Where the widget is drawn, and its outline: worked out in updateFrame(). + private val frame = RectF() + private val shape = Path() + private var corner = 0f + private var iconSize = 0f + + // Where the parts go: worked out in arrange(). + private var showText = false + private var textBeside = false + private var textX = 0f + private var textWidth = 0f + private var titleBaseline = 0f + private var detailBaseline = 0f + private var scrimFrom = 0f + private var pinX = 0f + private var pinY = 0f + private var pinRadius = 0f + + // The two lines, as written and as they fit. + private var title = "" + private var detail = "" + /** The detail without the car's name, for a widget too narrow for all of it; empty when there is none. */ + private var shortDetail = "" + private var shownTitle: CharSequence = "" + private var shownDetail: CharSequence = "" + + // The map, drawn into a picture of the frame's size whenever it changes, then drawn in the + // widget's shape with its edges smoothed. + private var map: Bitmap? = null + private var mapShader: BitmapShader? = null + private val mapMatrix = Matrix() + private var mapDirty = true + + /** True when every tile the map needs was there the last time it was drawn. */ + private var mapComplete = false + private var night = false + private val tileTarget = Rect() + + private val mapPaint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG) + private val tilePaint = Paint(Paint.FILTER_BITMAP_FLAG) + private val samplePaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val platePaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val pressPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.BLACK } + private val pinPaint = Paint(Paint.ANTI_ALIAS_FLAG) + /** The car on the badge: white on a deep accent, a deep shade of it on a light one (the dark theme's). */ + private var glyphColor = Color.WHITE + private val ringPaint = Paint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE } + private val pillPaint = Paint(Paint.ANTI_ALIAS_FLAG) + private val creditPaint = TextPaint(Paint.ANTI_ALIAS_FLAG) + private val titlePaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = Color.WHITE } + private val detailPaint = TextPaint(Paint.ANTI_ALIAS_FLAG).apply { color = DETAIL_COLOR } + private val credit: String = resources.getString(R.string.flexera_car_widget_attribution) + private val creditPill = RectF() + private var creditX = 0f + private var creditBaseline = 0f + + private val carGlyph: Drawable? = ContextCompat.getDrawable(context, R.drawable.ic_flexera_car)?.mutate() + + /** How far the widget has dimmed under the finger, from 0 to 1. */ + private var pressed = 0f + private var pressAnimator: ValueAnimator? = null + private val longPressed = Runnable { dimTo(0f) } + + /** + * Looks again now and then while the widget is on the screen: the time it has stood there + * moves on. Out of sight, as on another home screen page, which Launcher3 leaves shown, it + * only checks every little while whether it is in sight again, and then looks at once. + */ + private val tick = object : Runnable { + override fun run() { + removeCallbacks(this) + if (!onScreen || sample) return + if (!WidgetSight.isSeen(this@CarWidgetView, onScreen)) { + postDelayed(this, SEEN_CHECK_MS) + return + } + look() + postDelayed(this, TICK_MS) + } + } + + // The icon shape, as corners that can be put on a rectangle of any size. Null for the few + // shapes that are one fixed outline; those get plain round corners. + private val cornerShape: IconShape.CornerBased? by lazy(LazyThreadSafetyMode.NONE) { + when (val iconShape = currentIconShape()) { + is IconShape.SystemBased -> iconShape.findNearestShape() + is IconShape.CornerBased -> iconShape + else -> null + } + } + + init { + setWillNotDraw(false) + // Says to Launcher3 that this widget shapes itself (see RoundedCornerEnforcement). + id = android.R.id.background + clipToOutline = true + setUpPaints() + } + + /** Tells the view which widget it shows. Ids that Android never hands out mean a sample. */ + fun bind(appWidgetId: Int) { + this.appWidgetId = appWidgetId + sample = appWidgetId <= 0 + if (sample) { + // In the list of widgets a tap belongs to the list. + setOnClickListener(null) + isClickable = false + } else { + setOnClickListener { onTap() } + } + frame.setEmpty() + if (isLaidOut) updateFrame() + // Android may have said the widget is on the screen before it was told which one it is. + look() + } + + override fun onAttachedToWindow() { + super.onAttachedToWindow() + CarWidgetStore.addListener(this) + CarLocation.addListener(this) + MapTiles.addListener(this) + readState() + } + + override fun onDetachedFromWindow() { + CarWidgetStore.removeListener(this) + CarLocation.removeListener(this) + MapTiles.removeListener(this) + removeCallbacks(tick) + undim() + super.onDetachedFromWindow() + } + + override fun onVisibilityAggregated(isVisible: Boolean) { + super.onVisibilityAggregated(isVisible) + onScreen = isVisible + if (isVisible) { + tick.run() + } else { + removeCallbacks(tick) + undim() + } + } + + override fun onCarWidgetChanged(appWidgetId: Int) { + if (sample) return + // A car just picked, or a new sign-in, is asked for at once: the options sheet is closed + // over the home screen without the widget leaving the screen. + if (appWidgetId == CarWidgetStore.ALL || appWidgetId == this.appWidgetId) look() + } + + override fun onCarLocationChanged(deviceId: Long) { + if (!sample && deviceId == car?.deviceId) readState() + } + + override fun onTileArrived() { + if (!mapComplete && hasMap()) { + mapDirty = true + invalidate() + } + } + + override fun onConfigurationChanged(newConfig: Configuration) { + super.onConfigurationChanged(newConfig) + // The dark theme turns the map dark; the Bold text setting makes the lines heavier. + setUpPaints() + mapDirty = true + arrange() + invalidate() + } + + override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { + super.onLayout(changed, left, top, right, bottom) + updateFrame() + } + + /** Looks at the car again: asks the server if that is due, and shows what is known. */ + private fun look() { + // The state first: the car may have just been changed in the options. + readState() + if (!sample && WidgetSight.isSeen(this, onScreen)) car?.let { CarLocation.refreshIfStale(context, it.deviceId) } + } + + /** Takes what is known of this widget's car, and shows it. */ + private fun readState() { + val oldReading = state?.reading + if (sample) { + car = null + signedIn = false + state = null + } else { + car = CarWidgetStore.car(context, appWidgetId) + signedIn = CarWidgetStore.account(context) != null + state = car?.let { CarLocation.state(context, it.deviceId) } + } + val reading = state?.reading + if (reading?.latitude != oldReading?.latitude || reading?.longitude != oldReading?.longitude) mapDirty = true + write() + arrange() + invalidate() + } + + /** What the two lines say, and what a tap does. */ + private fun write() { + val car = car + val state = state + val reading = state?.reading + val problem = state?.problem + val name = car?.name.orEmpty() + shortDetail = "" + // What a screen reader says, where the lines are too terse to be read out ("2h 15m"). + var spoken = "" + when { + sample -> { + title = resources.getString(R.string.flexera_car_widget_sample_name) + detail = resources.getString(R.string.flexera_car_widget_parked_for, duration(SAMPLE_PARKED_MS)) + spoken = title + ", " + + resources.getString(R.string.flexera_car_widget_parked_for, duration(SAMPLE_PARKED_MS, aloud = true)) + tap = Tap.NOTHING + } + + car == null || !signedIn -> { + title = resources.getString(R.string.flexera_car_widget_set_up) + detail = "" + tap = Tap.OPTIONS + } + + problem == Traccar.Problem.TOKEN || problem == Traccar.Problem.LOCAL_NETWORK -> { + title = reading?.street ?: name.ifEmpty { resources.getString(R.string.flexera_car_widget_sample_name) } + detail = resources.getString( + if (problem == Traccar.Problem.TOKEN) { + R.string.flexera_car_widget_sign_in + } else { + R.string.flexera_car_widget_local_network + }, + ) + tap = Tap.OPTIONS + } + + reading == null -> { + title = name.ifEmpty { resources.getString(R.string.flexera_car_widget_sample_name) } + when { + problem != null -> { + detail = resources.getString(R.string.flexera_car_widget_unreachable) + tap = Tap.OPTIONS + } + + state?.noPosition == true -> { + detail = resources.getString(R.string.flexera_car_widget_no_position) + tap = Tap.ASK_AGAIN + } + + else -> { + detail = resources.getString(R.string.flexera_car_widget_looking) + tap = Tap.ASK_AGAIN + } + } + } + + else -> { + val status = status(reading) + val parts = ArrayList() + if (reading.street != null) { + title = reading.street + if (name.isNotEmpty()) parts.add(name) + parts.add(status) + } else if (name.isNotEmpty()) { + title = name + parts.add(status) + } else { + title = status + } + if (System.currentTimeMillis() - reading.readAt > STALE_MS) { + parts.add(resources.getString(R.string.flexera_car_widget_updated, moment(reading.readAt))) + } + detail = parts.joinToString(SEPARATOR) + if (reading.street != null && name.isNotEmpty()) shortDetail = parts.drop(1).joinToString(SEPARATOR) + val aloud = status(reading, aloud = true) + spoken = (listOf(title) + parts).map { if (it === status) aloud else it }.joinToString(", ") + tap = Tap.DIRECTIONS + } + } + contentDescription = spoken.ifEmpty { listOf(title, detail).filter { it.isNotEmpty() }.joinToString(", ") } + if (!sample) { + val label = when (tap) { + Tap.DIRECTIONS -> resources.getString( + R.string.flexera_car_widget_directions, + name.ifEmpty { resources.getString(R.string.flexera_car_widget_sample_name) }, + ) + Tap.OPTIONS -> resources.getString(R.string.flexera_car_widget_open_options) + Tap.ASK_AGAIN, Tap.NOTHING -> resources.getString(R.string.flexera_car_widget_ask_again) + } + ViewCompat.replaceAccessibilityAction(this, AccessibilityActionCompat.ACTION_CLICK, label, null) + } + } + + /** + * How the car stands: "Parked for 2h", "Parked since Mon 14:20", "Driving, 54 km/h"; with + * [aloud], in words a screen reader can say ("Parked for 2 hours"). + */ + private fun status(reading: CarLocation.Reading, aloud: Boolean = false): String { + if (reading.moving) { + val kmh = reading.speedKnots * KMH_PER_KNOT + return if (kmh >= 1.0) { + resources.getString(R.string.flexera_car_widget_driving_speed, speed(reading.speedKnots)) + } else { + resources.getString(R.string.flexera_car_widget_driving) + } + } + val since = reading.parkedSince + if (since <= 0L) return resources.getString(R.string.flexera_car_widget_parked) + if (reading.parkedLonger) return resources.getString(R.string.flexera_car_widget_parked_over_week) + val stood = System.currentTimeMillis() - since + return if (stood < DAY_MS) { + resources.getString(R.string.flexera_car_widget_parked_for, duration(stood, aloud)) + } else { + resources.getString(R.string.flexera_car_widget_parked_since, moment(since)) + } + } + + /** + * A stretch of time as the phone's language writes it narrowest, to fit a small widget: "12m", + * "2h 15m", "9h"; with [aloud], in full words. + */ + private fun duration(milliseconds: Long, aloud: Boolean = false): String { + val width = if (aloud) MeasureFormat.FormatWidth.WIDE else MeasureFormat.FormatWidth.NARROW + val format = MeasureFormat.getInstance(Locale.getDefault(), width) + val minutes = max(1L, milliseconds / MINUTE_MS) + if (minutes < 60) return format.format(Measure(minutes, MeasureUnit.MINUTE)) + val hours = minutes / 60 + val rest = minutes % 60 + // The minutes matter for the first hours; after that the hour is enough. + return if (hours < 6 && rest > 0) { + format.formatMeasures(Measure(hours, MeasureUnit.HOUR), Measure(rest, MeasureUnit.MINUTE)) + } else { + format.format(Measure(hours, MeasureUnit.HOUR)) + } + } + + /** A moment: its time today, its day and time this week, else its date. */ + private fun moment(time: Long): String { + val locale = Locale.getDefault() + val then = Calendar.getInstance().apply { timeInMillis = time } + val now = Calendar.getInstance() + val hours = if (DateFormat.is24HourFormat(context)) "Hm" else "hma" + val skeleton = when { + now[Calendar.YEAR] == then[Calendar.YEAR] && now[Calendar.DAY_OF_YEAR] == then[Calendar.DAY_OF_YEAR] -> hours + now.timeInMillis - time < 6 * DAY_MS -> "EEE$hours" + else -> "dMMM" + } + return DateFormat.format(DateFormat.getBestDateTimePattern(locale, skeleton), then).toString() + } + + /** A speed in the unit of the phone's region: miles an hour in the United States and Britain. */ + private fun speed(knots: Double): String { + val locale = Locale.getDefault() + val system = LocaleData.getMeasurementSystem(ULocale.forLocale(locale)) + val miles = system == LocaleData.MeasurementSystem.US || system == LocaleData.MeasurementSystem.UK + val value = if (miles) knots * MPH_PER_KNOT else knots * KMH_PER_KNOT + val unit = if (miles) MeasureUnit.MILE_PER_HOUR else MeasureUnit.KILOMETER_PER_HOUR + return MeasureFormat.getInstance(locale, MeasureFormat.FormatWidth.SHORT).format(Measure(value.roundToInt(), unit)) + } + + /** True when the map shows real streets, which come with OpenStreetMap's credit. */ + private fun hasMap(): Boolean = !sample && state?.reading != null + + private fun setUpPaints() { + night = (resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES + tilePaint.colorFilter = ColorMatrixColorFilter(if (night) darkMap() else lightMap()) + val density = resources.displayMetrics.density + val shadow = SHADOW_RADIUS_DP * density + titlePaint.typeface = ClockFonts.typeface(context, Typeface.DEFAULT, TITLE_WEIGHT) + titlePaint.textSize = resources.getDimension(R.dimen.flexera_car_widget_title_size) + titlePaint.setShadowLayer(shadow, 0f, SHADOW_DROP_DP * density, TEXT_SHADOW_COLOR) + detailPaint.typeface = ClockFonts.typeface(context, Typeface.DEFAULT, DETAIL_WEIGHT) + detailPaint.textSize = resources.getDimension(R.dimen.flexera_car_widget_detail_size) + detailPaint.setShadowLayer(shadow, 0f, SHADOW_DROP_DP * density, TEXT_SHADOW_COLOR) + creditPaint.typeface = ClockFonts.typeface(context, Typeface.DEFAULT, DETAIL_WEIGHT) + creditPaint.color = if (night) CREDIT_TEXT_NIGHT else CREDIT_TEXT_DAY + pillPaint.color = if (night) CREDIT_PILL_NIGHT else CREDIT_PILL_DAY + pinPaint.color = Themes.getColorAccent(context) + glyphColor = if (ColorUtils.calculateLuminance(pinPaint.color) > LIGHT_ACCENT_LUMINANCE) { + ColorUtils.blendARGB(pinPaint.color, Color.BLACK, DARK_GLYPH_SHADE) + } else { + Color.WHITE + } + ringPaint.setShadowLayer(shadow, 0f, SHADOW_DROP_DP * density, PIN_SHADOW_COLOR) + } + + /** + * Works out where the widget is drawn inside this view. On the home screen that is the box + * around the icons of the cells the widget covers; anywhere else it is the whole view. + */ + private fun updateFrame() { + var left = 0f + var top = 0f + var right = width.toFloat() + var bottom = height.toFloat() + var round = min(width, height) * LOOSE_CORNER_SHARE + var icon = min(width, height) * LOOSE_ICON_SHARE + + val aligned = IconFrame.of(this) + if (aligned != null) { + left = aligned.left + top = aligned.top + right = aligned.right + bottom = aligned.bottom + round = aligned.visibleIconSize / 2f + icon = aligned.iconSize + } + round = min(round, min(right - left, bottom - top) / 2f) + if (left == frame.left && top == frame.top && right == frame.right && bottom == frame.bottom) return + frame.set(left, top, right, bottom) + corner = round + iconSize = icon + + shape.reset() + val corners = cornerShape + if (corners != null) { + CornerShapeCompat.addToPath(corners, shape, left, top, right, bottom, size = round) + } else { + val radius = round * currentIconShape().windowTransitionRadius + shape.addRoundRect(frame, radius, radius, Path.Direction.CW) + } + shape.close() + + // The same soft shadow an icon has (ShadowGenerator), so the map sits on the wallpaper + // the way the icons do. + platePaint.setShadowLayer(icon * SHADOW_BLUR_SHARE, 0f, icon * SHADOW_DROP_SHARE, PLATE_SHADOW_COLOR) + mapDirty = true + arrange() + invalidate() + } + + /** Where the lines, the car and the credit go in the frame, and the lines cut to fit. */ + private fun arrange() { + if (frame.isEmpty) return + val density = resources.displayMetrics.density + val rtl = layoutDirection == LAYOUT_DIRECTION_RTL + val wasX = pinX + val wasY = pinY + val pad = max(TEXT_PAD_DP * density, corner * TEXT_PAD_IN_CORNER) + pinRadius = (iconSize * PIN_IN_ICON).coerceIn(PIN_MIN_DP * density, PIN_MAX_DP * density) + pinRadius = min(pinRadius, min(frame.width(), frame.height()) * PIN_MAX_SHARE) + + val tm = titlePaint.fontMetrics + val dm = detailPaint.fontMetrics + val gap = LINE_GAP_DP * density + val titleHeight = tm.descent - tm.ascent + val bothHeight = titleHeight + gap + (dm.descent - dm.ascent) + + // Short and wide, like four cells by one: the lines beside the car. Otherwise under it. + // Where both lines do not fit, the first goes alone; where it does not either, none. + textBeside = frame.width() >= frame.height() * BESIDE_MIN_RATIO && + frame.height() < bothHeight + 2 * pad + 2 * pinRadius + val keep = if (textBeside) pad else 2 * pad + val lineWidth = if (textBeside) frame.width() * BESIDE_TEXT_SHARE - pad else frame.width() - 2 * pad + val hasDetail = detail.isNotEmpty() && frame.height() >= bothHeight + keep + val block = if (hasDetail) bothHeight else titleHeight + showText = lineWidth >= MIN_TEXT_WIDTH_DP * density && frame.height() >= block + keep + if (textBeside) { + textWidth = lineWidth + textX = if (rtl) frame.right - pad else frame.left + pad + val top = frame.centerY() - block / 2f + titleBaseline = top - tm.ascent + detailBaseline = titleBaseline + tm.descent + gap - dm.ascent + pinX = if (rtl) frame.left + frame.width() * (1f - BESIDE_PIN_SHARE) else frame.left + frame.width() * BESIDE_PIN_SHARE + pinY = frame.centerY() + scrimFrom = frame.width() * BESIDE_SCRIM_SHARE + } else if (showText) { + textWidth = lineWidth + textX = if (rtl) frame.right - pad else frame.left + pad + detailBaseline = frame.bottom - pad - dm.descent + titleBaseline = if (hasDetail) detailBaseline + dm.ascent - gap - tm.descent else frame.bottom - pad - tm.descent + val textTop = titleBaseline + tm.ascent + scrimFrom = textTop - pad * SCRIM_ABOVE_TEXT - frame.top + pinX = frame.centerX() + pinY = (frame.top + (textTop - frame.top) / 2f).coerceAtLeast(frame.top + pinRadius + pad / 2f) + } else { + pinX = frame.centerX() + pinY = frame.centerY() + } + titlePaint.textAlign = if (rtl) Paint.Align.RIGHT else Paint.Align.LEFT + detailPaint.textAlign = titlePaint.textAlign + shownTitle = if (showText) TextUtils.ellipsize(title, titlePaint, max(0f, textWidth), TextUtils.TruncateAt.END) else "" + // Where the whole detail does not fit, the car's name goes first: how it stands matters more. + val line = if (shortDetail.isNotEmpty() && detailPaint.measureText(detail) > textWidth) shortDetail else detail + shownDetail = if (showText && hasDetail) TextUtils.ellipsize(line, detailPaint, max(0f, textWidth), TextUtils.TruncateAt.END) else "" + + // The credit, small, in the top corner on the side the lines end; smaller still where it would not fit. + val inset = max(CREDIT_INSET_DP * density, corner * CREDIT_INSET_IN_CORNER) + val padX = CREDIT_PAD_X_DP * density + val padY = CREDIT_PAD_Y_DP * density + var size = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, CREDIT_SP, resources.displayMetrics) + creditPaint.textSize = size + val room = frame.width() - 2 * inset - 2 * padX + val wide = creditPaint.measureText(credit) + if (wide > room && room > 0f) { + size = max(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, CREDIT_MIN_SP, resources.displayMetrics), size * room / wide) + creditPaint.textSize = size + } + val cm = creditPaint.fontMetrics + val pillWidth = creditPaint.measureText(credit) + 2 * padX + val pillHeight = (cm.descent - cm.ascent) + 2 * padY + val pillLeft = if (rtl) frame.left + inset else frame.right - inset - pillWidth + creditPill.set(pillLeft, frame.top + inset, pillLeft + pillWidth, frame.top + inset + pillHeight) + creditX = creditPill.left + padX + creditBaseline = creditPill.top + padY - cm.ascent + + if (hasMap()) keepCarClearOfCredit(rtl, density) + // The map is drawn around the car, so it moves with it. + if (pinX != wasX || pinY != wasY) mapDirty = true + } + + /** + * Moves the car from under the credit. Beside the lines it goes toward them, as far as they + * leave room; otherwise down, halfway between the credit and the lines or the bottom edge. + * In a widget too small for either it stays where it is. + */ + private fun keepCarClearOfCredit(rtl: Boolean, density: Float) { + val clear = pinRadius + CREDIT_GAP_DP * density + if (!creditCovers(pinX, pinY, clear)) return + if (textBeside) { + val lines = if (showText) { + max( + titlePaint.measureText(shownTitle, 0, shownTitle.length), + detailPaint.measureText(shownDetail, 0, shownDetail.length), + ) + } else { + 0f + } + val x = if (rtl) creditPill.right + clear else creditPill.left - clear + val room = if (rtl) x <= textX - lines - clear else x >= textX + lines + clear + if (room) { + pinX = x + return + } + } + val floor = if (showText && !textBeside) titleBaseline + titlePaint.fontMetrics.ascent else frame.bottom + val y = (creditPill.bottom + floor) / 2f + if (y - clear >= creditPill.bottom && y + clear <= floor) pinY = y + } + + /** True when a circle of [radius] around ([x], [y]) reaches the credit. */ + private fun creditCovers(x: Float, y: Float, radius: Float): Boolean { + val dx = x - x.coerceIn(creditPill.left, creditPill.right) + val dy = y - y.coerceIn(creditPill.top, creditPill.bottom) + return dx * dx + dy * dy < radius * radius + } + + override fun onDraw(canvas: Canvas) { + super.onDraw(canvas) + if (frame.isEmpty) return + if (mapDirty || map == null) drawMap() + val shader = mapShader ?: return + + canvas.drawPath(shape, platePaint) + mapPaint.shader = shader + canvas.drawPath(shape, mapPaint) + mapPaint.shader = null + + drawCar(canvas) + if (showText) { + canvas.drawText(shownTitle, 0, shownTitle.length, textX, titleBaseline, titlePaint) + if (shownDetail.isNotEmpty()) canvas.drawText(shownDetail, 0, shownDetail.length, textX, detailBaseline, detailPaint) + } + if (hasMap()) { + val radius = creditPill.height() / 2f + canvas.drawRoundRect(creditPill, radius, radius, pillPaint) + canvas.drawText(credit, creditX, creditBaseline, creditPaint) + } + if (pressed > 0f) { + pressPaint.alpha = (pressed * PRESSED_ALPHA).roundToInt() + canvas.drawPath(shape, pressPaint) + } + } + + /** The car's mark: a round badge in the accent colour with a car in it, ringed in white. */ + private fun drawCar(canvas: Canvas) { + val faded = !sample && state?.reading == null + val layer = if (faded) canvas.saveLayerAlpha(null, FADED_PIN_ALPHA) else -1 + canvas.drawCircle(pinX, pinY, pinRadius, ringPaint) + canvas.drawCircle(pinX, pinY, pinRadius * (1f - PIN_RING_SHARE), pinPaint) + carGlyph?.let { glyph -> + val half = pinRadius * GLYPH_IN_PIN / 2f + glyph.setBounds((pinX - half).roundToInt(), (pinY - half).roundToInt(), (pinX + half).roundToInt(), (pinY + half).roundToInt()) + glyph.setTint(glyphColor) + glyph.draw(canvas) + } + if (layer >= 0) canvas.restoreToCount(layer) + } + + /** Draws the map, and the shade under the lines, into the picture the widget shows. */ + private fun drawMap() { + val width = frame.width().roundToInt() + val height = frame.height().roundToInt() + if (width <= 0 || height <= 0) return + val picture = map?.takeIf { it.width == width && it.height == height } + ?: try { + Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888) + } catch (e: OutOfMemoryError) { + Log.w(TAG, "No memory for the map") + return + }.also { + map = it + mapShader = BitmapShader(it, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP) + } + val canvas = Canvas(picture) + canvas.drawColor(if (night) LAND_NIGHT else LAND_DAY) + val reading = state?.reading + mapComplete = if (!sample && reading != null) { + drawTiles(canvas, reading.latitude, reading.longitude, pinX - frame.left, pinY - frame.top, width, height) + } else { + drawSample(canvas, width.toFloat(), height.toFloat()) + true + } + if (showText) drawScrim(canvas, width.toFloat(), height.toFloat()) + mapMatrix.setTranslate(frame.left, frame.top) + mapShader?.setLocalMatrix(mapMatrix) + mapDirty = false + } + + /** + * Draws the tiles around a place so that the place is at [anchorX], [anchorY] of the + * picture. Returns false when some were not there yet; they are asked for, and the map is + * drawn again as they come in ([onTileArrived]). + */ + private fun drawTiles(canvas: Canvas, latitude: Double, longitude: Double, anchorX: Float, anchorY: Float, width: Int, height: Int): Boolean { + val density = resources.displayMetrics.density + // Tiles are made for screens of one pixel per point; drawn at that size the street names + // would be too small to read on a phone. They are scaled up, less than the screen's + // density, which keeps more of the streets in the frame. + val tile = MapTiles.TILE_PX * max(1f, density * TILE_SCALE_IN_DENSITY).toDouble() + val across = MapTiles.tilesAcross(ZOOM) + val latitudeRadians = Math.toRadians(latitude.coerceIn(-MAX_LATITUDE, MAX_LATITUDE)) + val worldX = (longitude + 180.0) / 360.0 * across * tile + val worldY = (1.0 - ln(tan(latitudeRadians) + 1.0 / cos(latitudeRadians)) / PI) / 2.0 * across * tile + val originX = worldX - anchorX + val originY = worldY - anchorY + var complete = true + for (y in floor(originY / tile).toInt()..floor((originY + height) / tile).toInt()) { + if (y !in 0 until across) continue + for (x in floor(originX / tile).toInt()..floor((originX + width) / tile).toInt()) { + val bitmap = MapTiles.get(context, ZOOM, x, y) + if (bitmap == null) { + complete = false + continue + } + // Rounded the same way at each edge, so that neighbouring tiles meet without a seam. + tileTarget.set( + (x * tile - originX).roundToInt(), + (y * tile - originY).roundToInt(), + ((x + 1) * tile - originX).roundToInt(), + ((y + 1) * tile - originY).roundToInt(), + ) + canvas.drawBitmap(bitmap, null, tileTarget, tilePaint) + } + } + return complete + } + + /** A made-up neighbourhood for the sample and for a widget without a position: a park, a river and some streets. */ + private fun drawSample(canvas: Canvas, width: Float, height: Float) { + val unit = min(width, height) + samplePaint.style = Paint.Style.FILL + samplePaint.color = if (night) PARK_NIGHT else PARK_DAY + canvas.drawRoundRect(width * 0.62f, height * 0.06f, width * 1.1f, height * 0.40f, unit * 0.06f, unit * 0.06f, samplePaint) + samplePaint.color = if (night) WATER_NIGHT else WATER_DAY + canvas.drawPath( + Path().apply { + moveTo(-unit * 0.1f, height * 0.78f) + cubicTo(width * 0.25f, height * 0.70f, width * 0.45f, height * 0.98f, width * 0.75f, height * 0.92f) + lineTo(width * 0.75f, height * 1.1f) + lineTo(-unit * 0.1f, height * 1.1f) + close() + }, + samplePaint, + ) + samplePaint.style = Paint.Style.STROKE + samplePaint.strokeCap = Paint.Cap.ROUND + samplePaint.color = if (night) ROAD_NIGHT else ROAD_DAY + samplePaint.strokeWidth = unit * 0.035f + canvas.drawLine(width * 0.18f, -unit * 0.1f, width * 0.30f, height * 1.1f, samplePaint) + canvas.drawLine(width * 0.52f, -unit * 0.1f, width * 0.58f, height * 1.1f, samplePaint) + canvas.drawLine(-unit * 0.1f, height * 0.30f, width * 1.1f, height * 0.22f, samplePaint) + samplePaint.strokeWidth = unit * 0.07f + canvas.drawLine(-unit * 0.1f, height * 0.58f, width * 1.1f, height * 0.46f, samplePaint) + canvas.drawLine(width * 0.80f, -unit * 0.1f, width * 0.86f, height * 1.1f, samplePaint) + samplePaint.style = Paint.Style.FILL + } + + /** The shade under the lines, so that white text reads on light streets and parks. */ + private fun drawScrim(canvas: Canvas, width: Float, height: Float) { + val rtl = layoutDirection == LAYOUT_DIRECTION_RTL + val gradient = if (textBeside) { + val from = if (rtl) width else 0f + val to = if (rtl) width - scrimFrom else scrimFrom + LinearGradient(from, 0f, to, 0f, SCRIM_COLORS_STRONG_FIRST, SCRIM_STOPS, Shader.TileMode.CLAMP) + } else { + LinearGradient(0f, height, 0f, scrimFrom.coerceIn(0f, height), SCRIM_COLORS_STRONG_FIRST, SCRIM_STOPS, Shader.TileMode.CLAMP) + } + samplePaint.shader = gradient + canvas.drawRect(0f, 0f, width, height, samplePaint) + samplePaint.shader = null + } + + private fun onTap() { + when (tap) { + Tap.DIRECTIONS -> state?.reading?.let(::openDirections) + Tap.OPTIONS -> openOptions() + Tap.ASK_AGAIN -> car?.let { CarLocation.refreshIfStale(context, it.deviceId, now = true) } + Tap.NOTHING -> Unit + } + } + + /** + * Shows the way to the car on foot: in Google Maps when it is there, else in any map app (a + * geo: link), else on Google Maps' web page. + */ + private fun openDirections(reading: CarLocation.Reading) { + val reveal = Rect() + frame.roundOut(reveal) + if (!reveal.intersect(0, 0, width, height)) reveal.set(0, 0, width, height) + val launch = ActivityOptions.makeClipRevealAnimation(this, reveal.left, reveal.top, reveal.width(), reveal.height()) + if (Utilities.ATLEAST_T) launch.splashScreenStyle = SplashScreen.SPLASH_SCREEN_STYLE_ICON + val onScreen = IntArray(2) + getLocationOnScreen(onScreen) + val bounds = Rect(reveal).apply { offset(onScreen[0], onScreen[1]) } + + val latitude = String.format(Locale.ROOT, "%.6f", reading.latitude) + val longitude = String.format(Locale.ROOT, "%.6f", reading.longitude) + val label = car?.name?.ifEmpty { null } ?: resources.getString(R.string.flexera_car_widget_sample_name) + val web = Uri.parse("https://www.google.com/maps/dir/?api=1&destination=$latitude,$longitude&travelmode=walking") + val ways = listOf( + Intent(Intent.ACTION_VIEW, web).setPackage(GOOGLE_MAPS), + Intent(Intent.ACTION_VIEW, Uri.parse("geo:$latitude,$longitude?q=$latitude,$longitude(${Uri.encode(label)})")), + Intent(Intent.ACTION_VIEW, web), + ) + for (intent in ways) { + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).sourceBounds = bounds + try { + context.startActivity(intent, launch.toBundle()) + return + } catch (e: ActivityNotFoundException) { + // The next way. + } catch (e: SecurityException) { + Log.w(TAG, "Not allowed to open $intent", e) + } + } + Toast.makeText(context, R.string.flexera_car_widget_no_map_app, Toast.LENGTH_SHORT).show() + } + + private fun openOptions() { + val intent = Intent(context, CarWidgetConfigActivity::class.java) + .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId) + var activity: Context? = context + while (activity != null && activity !is Activity) { + activity = (activity as? ContextWrapper)?.baseContext + } + try { + if (activity != null) { + activity.startActivity(intent) + } else { + context.startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) + } + } catch (e: RuntimeException) { + Log.w(TAG, "The car widget's options could not be opened", e) + } + } + + override fun setPressed(pressed: Boolean) { + val was = isPressed + super.setPressed(pressed) + if (pressed == was || sample) return + removeCallbacks(longPressed) + // A press held this long is the launcher's, to pick the widget up. + if (pressed) postDelayed(longPressed, ViewConfiguration.getLongPressTimeout().toLong()) + dimTo(if (pressed) 1f else 0f) + } + + private fun dimTo(target: Float) { + pressAnimator?.cancel() + if (pressed == target) return + pressAnimator = ValueAnimator.ofFloat(pressed, target).apply { + duration = if (target > pressed) PRESS_MS else RELEASE_MS + addUpdateListener { + pressed = it.animatedValue as Float + invalidate() + } + start() + } + } + + private fun undim() { + removeCallbacks(longPressed) + pressAnimator?.cancel() + if (pressed != 0f) { + pressed = 0f + invalidate() + } + } + + private fun currentIconShape(): IconShape = PreferenceManager2.getInstance(context).iconShape.firstCached() + + private companion object { + const val TAG = "CarWidgetView" + + /** Street level: a widget of two cells by two shows a few hundred metres around the car. */ + const val ZOOM = 16 + + /** How much the tiles are scaled up, as a share of the screen's density. */ + const val TILE_SCALE_IN_DENSITY = 0.85f + + /** Where the map's projection ends, north and south. */ + const val MAX_LATITUDE = 85.05112878 + + const val TICK_MS = 30 * 1000L + const val SEEN_CHECK_MS = 2_000L + + /** An answer older than this gets "updated 14:20" after it. */ + const val STALE_MS = 20 * 60 * 1000L + const val MINUTE_MS = 60 * 1000L + const val DAY_MS = 24 * 60 * 60 * 1000L + const val SAMPLE_PARKED_MS = 2 * 60 * MINUTE_MS + + const val KMH_PER_KNOT = 1.852 + const val MPH_PER_KNOT = 1.150779 + + const val GOOGLE_MAPS = "com.google.android.apps.maps" + const val SEPARATOR = " · " + + const val TITLE_WEIGHT = 600 + const val DETAIL_WEIGHT = 400 + const val LINE_GAP_DP = 2f + const val TEXT_PAD_DP = 12f + const val TEXT_PAD_IN_CORNER = 0.45f + const val MIN_TEXT_WIDTH_DP = 72f + + /** The lines go beside the car when the widget is at least this many times as wide as it is tall, and too low for them under it. */ + const val BESIDE_MIN_RATIO = 2f + const val BESIDE_TEXT_SHARE = 0.62f + const val BESIDE_PIN_SHARE = 0.80f + const val BESIDE_SCRIM_SHARE = 0.85f + + /** How far above the lines their shade begins, in text paddings. */ + const val SCRIM_ABOVE_TEXT = 1.6f + val SCRIM_COLORS_STRONG_FIRST = intArrayOf(0xB3000000.toInt(), 0x59000000, 0x00000000) + val SCRIM_STOPS = floatArrayOf(0f, 0.55f, 1f) + + /** The car's mark: its radius as a share of the icon size, its limits, and its white ring. */ + const val PIN_IN_ICON = 0.24f + const val PIN_MIN_DP = 12f + const val PIN_MAX_DP = 20f + const val PIN_MAX_SHARE = 0.22f + const val PIN_RING_SHARE = 0.14f + const val LIGHT_ACCENT_LUMINANCE = 0.4 + const val DARK_GLYPH_SHADE = 0.72f + const val GLYPH_IN_PIN = 1.05f + + /** How faint the car's mark is while there is no position to put it at. */ + const val FADED_PIN_ALPHA = 140 + + const val CREDIT_SP = 9f + const val CREDIT_MIN_SP = 6f + const val CREDIT_INSET_DP = 6f + const val CREDIT_INSET_IN_CORNER = 0.36f + const val CREDIT_PAD_X_DP = 5f + const val CREDIT_PAD_Y_DP = 1.5f + const val CREDIT_GAP_DP = 4f + const val CREDIT_TEXT_DAY = 0xFF3C4043.toInt() + const val CREDIT_PILL_DAY = 0xCCFFFFFF.toInt() + const val CREDIT_TEXT_NIGHT = 0xFFDADCE0.toInt() + const val CREDIT_PILL_NIGHT = 0xB3000000.toInt() + + /** Corner radius and icon size, as shares of the shorter side, where there are no icons to match. */ + const val LOOSE_CORNER_SHARE = 0.18f + const val LOOSE_ICON_SHARE = 0.45f + + // An icon's shadow as Launcher3 draws it (ShadowGenerator.BLUR_FACTOR and + // KEY_SHADOW_DISTANCE), as shares of the icon size; as on the picture widget. + const val SHADOW_BLUR_SHARE = 1.68f / 48f + const val SHADOW_DROP_SHARE = 1f / 48f + const val PLATE_SHADOW_COLOR = 0x26000000 + + const val SHADOW_RADIUS_DP = 3f + const val SHADOW_DROP_DP = 1f + const val TEXT_SHADOW_COLOR = 0x59000000 + const val PIN_SHADOW_COLOR = 0x4D000000 + const val DETAIL_COLOR = 0xE6FFFFFF.toInt() + + // The drawn sample's colours, by day and by night. + const val LAND_DAY = 0xFFEEF0F3.toInt() + const val LAND_NIGHT = 0xFF23262C.toInt() + const val PARK_DAY = 0xFFCDE8CF.toInt() + const val PARK_NIGHT = 0xFF20352A.toInt() + const val WATER_DAY = 0xFFB9D5F2.toInt() + const val WATER_NIGHT = 0xFF1B2F44.toInt() + const val ROAD_DAY = 0xFFFFFFFF.toInt() + const val ROAD_NIGHT = 0xFF3B3F47.toInt() + + /** How dark the widget gets under the finger, out of 255. */ + const val PRESSED_ALPHA = 46f + const val PRESS_MS = 90L + const val RELEASE_MS = 220L + + /** OpenStreetMap's colours, a little calmer, to sit among the icons. */ + fun lightMap(): ColorMatrix = ColorMatrix().apply { setSaturation(0.8f) } + + /** + * OpenStreetMap's map for the dark theme: light and dark turned around with the colours + * kept (inverted, then turned half way round the colour wheel), calmer and a little dimmer. + */ + fun darkMap(): ColorMatrix { + val invert = ColorMatrix( + floatArrayOf( + -1f, 0f, 0f, 0f, 255f, + 0f, -1f, 0f, 0f, 255f, + 0f, 0f, -1f, 0f, 255f, + 0f, 0f, 0f, 1f, 0f, + ), + ) + // The hue turned by 180°, as CSS's hue-rotate does it. + val halfTurn = ColorMatrix( + floatArrayOf( + -0.574f, 1.430f, 0.144f, 0f, 0f, + 0.426f, 0.430f, 0.144f, 0f, 0f, + 0.426f, 1.430f, -0.856f, 0f, 0f, + 0f, 0f, 0f, 1f, 0f, + ), + ) + val calmer = ColorMatrix().apply { setSaturation(0.7f) } + val dimmer = ColorMatrix().apply { setScale(0.88f, 0.88f, 0.92f, 1f) } + return ColorMatrix().apply { + postConcat(invert) + postConcat(halfTurn) + postConcat(calmer) + postConcat(dimmer) + } + } + } +} diff --git a/flexera/src/app/flexera/widget/FlexeraWidgets.kt b/flexera/src/app/flexera/widget/FlexeraWidgets.kt index 420c052563..cc5e775430 100644 --- a/flexera/src/app/flexera/widget/FlexeraWidgets.kt +++ b/flexera/src/app/flexera/widget/FlexeraWidgets.kt @@ -14,8 +14,8 @@ import kotlin.math.max import kotlin.math.roundToInt /** - * The widgets that come with the launcher: Pictures ([PictureWidgetProvider]) and Clock - * ([ClockWidgetProvider]). + * The widgets that come with the launcher: Pictures ([PictureWidgetProvider]), Clock + * ([ClockWidgetProvider]) and Car ([CarWidgetProvider]). * * Android knows each as an ordinary app widget, so they are added, moved, resized and removed * like any other. What they show is not sent through Android, though: the launcher draws them @@ -28,7 +28,9 @@ object FlexeraWidgets { private val noInset = Rect() private fun isOwn(provider: ComponentName?): Boolean = - provider == PictureWidgetProvider.componentName || provider == ClockWidgetProvider.componentName + provider == PictureWidgetProvider.componentName || + provider == ClockWidgetProvider.componentName || + provider == CarWidgetProvider.componentName /** * The room a widget's cells keep free around it, on each side; one cell is [cellWidth] by @@ -105,16 +107,23 @@ object FlexeraWidgets { if (!isOwn(provider)) return null // A widget that still waits to be set up draws its own "tap to set up". if (host is PendingAppWidgetHostView) return null - val pictures = provider == PictureWidgetProvider.componentName + val kind = when (provider) { + PictureWidgetProvider.componentName -> PictureWidgetView::class.java + CarWidgetProvider.componentName -> CarWidgetView::class.java + else -> ClockWidgetView::class.java + } var view: View? = null for (i in host.childCount - 1 downTo 0) { val child = host.getChildAt(i) - val wanted = if (pictures) child is PictureWidgetView else child is ClockWidgetView - if (wanted && view == null) view = child else host.removeViewAt(i) + if (kind.isInstance(child) && view == null) view = child else host.removeViewAt(i) } if (view == null) { - view = if (pictures) PictureWidgetView(host.context) else ClockWidgetView(host.context) + view = when (kind) { + PictureWidgetView::class.java -> PictureWidgetView(host.context) + CarWidgetView::class.java -> CarWidgetView(host.context) + else -> ClockWidgetView(host.context) + } host.addView( view, FrameLayout.LayoutParams( @@ -126,6 +135,7 @@ object FlexeraWidgets { when (view) { is PictureWidgetView -> view.bind(appWidgetId) is ClockWidgetView -> view.bind(appWidgetId) + is CarWidgetView -> view.bind(appWidgetId) } return view } diff --git a/flexera/src/app/flexera/widget/MapTiles.kt b/flexera/src/app/flexera/widget/MapTiles.kt new file mode 100644 index 0000000000..2e2536ca14 --- /dev/null +++ b/flexera/src/app/flexera/widget/MapTiles.kt @@ -0,0 +1,286 @@ +package app.flexera.widget + +import android.content.Context +import android.graphics.Bitmap +import android.graphics.BitmapFactory +import android.os.Handler +import android.os.Looper +import android.os.SystemClock +import android.util.Log +import android.util.LruCache +import androidx.annotation.MainThread +import androidx.annotation.WorkerThread +import com.android.launcher3.BuildConfig +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL +import java.util.concurrent.CopyOnWriteArraySet +import java.util.concurrent.LinkedBlockingQueue +import java.util.concurrent.ThreadPoolExecutor +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger + +/** + * The map under the car widget: tiles of OpenStreetMap's standard map, 256 pixels square. + * + * They are asked of OpenStreetMap's own tile server, under its tile usage policy + * (operations.osmfoundation.org/policies/tiles): only the tiles a widget shows, never ahead of + * time, at most [CONNECTIONS] at once, with a User-Agent that names the app, and each kept on the + * phone for at least [KEEP_MS] or as long as the server says, whichever is longer, then asked + * again only if it has changed (by its ETag). The widget shows "© OpenStreetMap" on the map. + * + * Tiles live in the app's cache folder, which Android may empty when it needs room, and up to + * [MAX_FILES] of them; the ones in use are kept in memory as well. + */ +internal object MapTiles { + + /** Told, on the main thread, that a tile asked for with [get] has arrived. */ + fun interface Listener { + fun onTileArrived() + } + + const val TILE_PX = 256 + + private const val TAG = "MapTiles" + private const val SERVER = "https://tile.openstreetmap.org" + private const val FOLDER = "flexera_map_tiles" + private const val CONNECT_TIMEOUT_MS = 10_000 + private const val READ_TIMEOUT_MS = 15_000 + + /** The policy asks for at most two connections at a time. */ + private const val CONNECTIONS = 2 + + /** The least time a tile is kept before it is asked for again, as the policy asks. */ + private const val KEEP_MS = 7 * 24 * 60 * 60 * 1000L + + /** How long a tile that failed waits before it is asked for again. */ + private const val RETRY_MS = 60 * 1000L + + private const val MAX_FILES = 400 + private const val MAX_TILE_BYTES = 1024 * 1024 + + /** About forty tiles in memory: two widgets' worth at the largest, at two bytes a pixel. */ + private const val MEMORY_BYTES = 6 * 1024 * 1024 + + private val USER_AGENT = "FlexeraLauncher/${BuildConfig.VERSION_NAME} (Android; car widget)" + + private val listeners = CopyOnWriteArraySet() + private val main = Handler(Looper.getMainLooper()) + + private val memory = object : LruCache(MEMORY_BYTES) { + override fun sizeOf(key: String, value: Bitmap): Int = value.byteCount + } + + // Used on the main thread only: the tiles on their way, and when each failed tile may be asked again. + private val loading = HashSet() + private val failedAt = HashMap() + + /** Tiles written since the launcher started, by both fetching threads. */ + private val writes = AtomicInteger() + + private val executor = ThreadPoolExecutor( + CONNECTIONS, + CONNECTIONS, + 30, + TimeUnit.SECONDS, + LinkedBlockingQueue(), + ) { runnable -> + Thread(runnable, "FlexeraMapTiles").apply { + isDaemon = true + priority = Thread.MIN_PRIORITY + } + }.apply { allowCoreThreadTimeOut(true) } + + fun addListener(listener: Listener) { + listeners.add(listener) + } + + fun removeListener(listener: Listener) { + listeners.remove(listener) + } + + /** How many tiles there are along each side of the world at [zoom]. */ + fun tilesAcross(zoom: Int): Int = 1 shl zoom + + /** + * The tile at [zoom], [x], [y], if it is in memory. Otherwise null, and the tile is read from + * the phone or fetched; listeners are told when it is there. + */ + @MainThread + fun get(context: Context, zoom: Int, x: Int, y: Int): Bitmap? { + val across = tilesAcross(zoom) + if (y !in 0 until across) return null + val wrappedX = Math.floorMod(x, across) + val key = "$zoom/$wrappedX/$y" + memory.get(key)?.let { return it } + if (key in loading) return null + val failed = failedAt[key] + if (failed != null && SystemClock.elapsedRealtime() - failed < RETRY_MS) return null + loading.add(key) + val app = context.applicationContext + executor.execute { + val bitmap = try { + load(app, zoom, wrappedX, y) + } catch (e: Exception) { + Log.w(TAG, "Tile $key: ${e.javaClass.simpleName}: ${e.message}") + null + } catch (e: OutOfMemoryError) { + Log.w(TAG, "Tile $key did not fit in memory") + null + } + main.post { + loading.remove(key) + if (bitmap == null) { + failedAt[key] = SystemClock.elapsedRealtime() + } else { + failedAt.remove(key) + memory.put(key, bitmap) + listeners.forEach { it.onTileArrived() } + } + } + } + return null + } + + /** The tile from the phone when it is fresh, else from the server; a stale copy when the server cannot be reached. */ + @WorkerThread + private fun load(context: Context, zoom: Int, x: Int, y: Int): Bitmap? { + val file = File(folder(context), "$zoom/$x/$y.png") + val meta = File(file.path + ".meta") + val kept = if (file.isFile) readMeta(meta) else null + val now = System.currentTimeMillis() + if (kept != null && now < kept.expires) decode(file)?.let { return it } + + val connection = URL("$SERVER/$zoom/$x/$y.png").openConnection() as HttpURLConnection + try { + connection.connectTimeout = CONNECT_TIMEOUT_MS + connection.readTimeout = READ_TIMEOUT_MS + connection.setRequestProperty("User-Agent", USER_AGENT) + if (kept != null) { + kept.etag?.let { connection.setRequestProperty("If-None-Match", it) } + kept.lastModified?.let { connection.setRequestProperty("If-Modified-Since", it) } + } + val code = try { + connection.responseCode + } catch (e: IOException) { + // Offline: a tile kept past its time is better than a hole in the map. + return if (file.isFile) decode(file) else throw e + } + when (code) { + HttpURLConnection.HTTP_NOT_MODIFIED -> { + writeMeta(meta, expiry(connection, now), kept?.etag, kept?.lastModified) + return decode(file) + } + + HttpURLConnection.HTTP_OK -> { + val bytes = connection.inputStream.use { input -> + val out = ByteArrayOutputStream() + val buffer = ByteArray(16 * 1024) + while (true) { + val read = input.read(buffer) + if (read < 0) break + out.write(buffer, 0, read) + if (out.size() > MAX_TILE_BYTES) throw IOException("Too large for a tile") + } + out.toByteArray() + } + val bitmap = decode(bytes) ?: throw IOException("Not a picture") + save(file, bytes) + writeMeta( + meta, + expiry(connection, now), + connection.getHeaderField("ETag"), + connection.getHeaderField("Last-Modified"), + ) + prune(context) + return bitmap + } + + else -> { + Log.w(TAG, "Tile $zoom/$x/$y: HTTP $code") + return if (file.isFile) decode(file) else null + } + } + } finally { + connection.disconnect() + } + } + + /** When a tile fetched at [now] is due to be asked for again: what the server says, but no sooner than [KEEP_MS]. */ + private fun expiry(connection: HttpURLConnection, now: Long): Long { + val maxAge = connection.getHeaderField("Cache-Control") + ?.split(',') + ?.map { it.trim() } + ?.firstOrNull { it.startsWith("max-age=", ignoreCase = true) } + ?.substringAfter('=') + ?.toLongOrNull() + val byServer = when { + maxAge != null -> now + maxAge * 1000 + connection.expiration > 0 -> connection.expiration + else -> 0L + } + return maxOf(now + KEEP_MS, byServer) + } + + private class Meta(val expires: Long, val etag: String?, val lastModified: String?) + + private fun readMeta(meta: File): Meta? = try { + val lines = meta.readLines() + Meta( + expires = lines.getOrNull(0)?.toLongOrNull() ?: 0L, + etag = lines.getOrNull(1)?.ifEmpty { null }, + lastModified = lines.getOrNull(2)?.ifEmpty { null }, + ) + } catch (e: IOException) { + null + } + + private fun writeMeta(meta: File, expires: Long, etag: String?, lastModified: String?) { + try { + meta.parentFile?.mkdirs() + // Header values never hold a line break; one that did would only spoil this tile's record. + meta.writeText("$expires\n${etag.orEmpty().lines().first()}\n${lastModified.orEmpty().lines().first()}\n") + } catch (e: IOException) { + Log.w(TAG, "Could not keep a tile's record", e) + } + } + + private fun save(file: File, bytes: ByteArray) { + try { + file.parentFile?.mkdirs() + val partial = File(file.path + ".part") + partial.writeBytes(bytes) + if (!partial.renameTo(file)) { + partial.delete() + } + } catch (e: IOException) { + Log.w(TAG, "Could not keep a tile", e) + } + } + + /** Keeps the folder to [MAX_FILES] tiles, dropping those used least recently. Now and then, not at every write. */ + private fun prune(context: Context) { + if (writes.incrementAndGet() % 25 != 0) return + val tiles = folder(context).walkTopDown().filter { it.isFile && it.name.endsWith(".png") }.toList() + if (tiles.size <= MAX_FILES) return + tiles.sortedBy { it.lastModified() }.take(tiles.size - MAX_FILES).forEach { tile -> + tile.delete() + File(tile.path + ".meta").delete() + } + } + + private fun decode(file: File): Bitmap? { + // Marks the tile as used, for prune(). + file.setLastModified(System.currentTimeMillis()) + return BitmapFactory.decodeFile(file.path, decodeOptions()) + } + + private fun decode(bytes: ByteArray): Bitmap? = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, decodeOptions()) + + /** The tiles have no see-through parts: two bytes a pixel are enough. */ + private fun decodeOptions() = BitmapFactory.Options().apply { inPreferredConfig = Bitmap.Config.RGB_565 } + + private fun folder(context: Context): File = File(context.cacheDir, FOLDER) +} diff --git a/flexera/src/app/flexera/widget/PictureWidgetView.kt b/flexera/src/app/flexera/widget/PictureWidgetView.kt index f289215ba9..7a750a175f 100644 --- a/flexera/src/app/flexera/widget/PictureWidgetView.kt +++ b/flexera/src/app/flexera/widget/PictureWidgetView.kt @@ -26,20 +26,13 @@ import android.text.StaticLayout import android.text.TextPaint import android.util.AttributeSet import android.util.Log -import android.view.View import android.view.animation.LinearInterpolator import android.widget.FrameLayout import app.lawnchair.icons.shape.CornerShapeCompat import app.lawnchair.icons.shape.IconShape import app.lawnchair.preferences2.PreferenceManager2 import app.lawnchair.preferences2.firstCached -import com.android.launcher3.CellLayout -import com.android.launcher3.Launcher -import com.android.launcher3.LauncherState import com.android.launcher3.R -import com.android.launcher3.ShortcutAndWidgetContainer -import com.android.launcher3.Workspace -import com.android.launcher3.folder.Folder import com.android.launcher3.util.Executors import java.io.File import java.text.BreakIterator @@ -389,38 +382,8 @@ class PictureWidgetView @JvmOverloads constructor( scheduleNext() } - /** - * True while the widget can really be seen. Its window being on the screen is not enough: - * Launcher3 leaves every home screen page shown, and covers them with the app drawer, Recents - * or a folder without hiding them. - */ - private fun isSeen(): Boolean { - if (!onScreen || !isShown) return false - val launcher = launcher() ?: return true - if (!launcher.isInState(LauncherState.NORMAL) && - !launcher.isInState(LauncherState.SPRING_LOADED) && - !launcher.isInState(LauncherState.EDIT_MODE) - ) { - return false - } - if (Folder.getOpen(launcher) != null) return false - // On the home screen: the page the widget is on has to be one of those on the screen, - // and not faded out. - val cells = (parent as? View)?.parent as? ShortcutAndWidgetContainer ?: return true - if (cells.alpha <= 0f) return false - val page = cells.parent as? CellLayout ?: return true - val pages = page.parent as? Workspace<*> ?: return true - return pages.isVisible(page) - } - - private fun launcher(): Launcher? { - var current: Context? = context - while (current != null) { - if (current is Launcher) return current - current = (current as? ContextWrapper)?.baseContext - } - return null - } + /** True while the widget can really be seen ([WidgetSight]). */ + private fun isSeen(): Boolean = WidgetSight.isSeen(this, onScreen) private fun onTap() { when { diff --git a/flexera/src/app/flexera/widget/Traccar.kt b/flexera/src/app/flexera/widget/Traccar.kt new file mode 100644 index 0000000000..dc2f944729 --- /dev/null +++ b/flexera/src/app/flexera/widget/Traccar.kt @@ -0,0 +1,299 @@ +package app.flexera.widget + +import android.content.Context +import android.util.Log +import androidx.annotation.WorkerThread +import app.flexera.update.FlexeraUpdater +import com.android.launcher3.BuildConfig +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.io.InputStream +import java.net.ConnectException +import java.net.HttpURLConnection +import java.net.MalformedURLException +import java.net.NoRouteToHostException +import java.net.SocketTimeoutException +import java.net.URL +import java.net.URLEncoder +import java.net.UnknownServiceException +import java.time.Instant +import java.time.OffsetDateTime +import java.time.format.DateTimeParseException +import java.time.temporal.ChronoUnit +import java.util.Locale +import javax.net.ssl.SSLException +import javax.net.ssl.SSLHandshakeException +import javax.net.ssl.SSLPeerUnverifiedException +import org.json.JSONArray +import org.json.JSONException +import org.json.JSONObject + +/** + * The car widget's side of a Traccar server (traccar.org), the GPS tracking server the owner + * runs: the devices a Traccar user can see, the last position of one, and since when it has + * stood still. Read through Traccar's own REST API, signed in with a token the owner made in + * Traccar for this purpose. + * + * Only over https: the token goes along with every request, and a connection that is not + * encrypted would show it to anyone on the way. Redirects are not followed, for the same reason. + */ +internal object Traccar { + + /** + * A Traccar server, as an address without a trailing slash (`https://traccar.example.com`, + * or with a path when Traccar sits under one), and the token of the user the launcher signs + * in as. + */ + data class Account(val server: String, val token: String) { + /** The server's name, as the options show it. */ + val host: String get() = runCatching { URL(server).host }.getOrNull() ?: server + + override fun toString(): String = "Account($server)" + } + + /** A device the Traccar user can see: a tracker, usually in a car. */ + data class Device(val id: Long, val name: String, val online: Boolean) + + /** Where a device last was, as Traccar knows it. */ + data class Position( + val latitude: Double, + val longitude: Double, + /** When the tracker took this position, in milliseconds since 1970. */ + val fixTime: Long, + /** Traccar's own judgement, from the speed or the ignition. */ + val moving: Boolean, + /** In knots, as Traccar keeps it. */ + val speedKnots: Double, + /** The address, when the server looks addresses up itself; null when it does not. */ + val address: String?, + ) + + /** A stop from Traccar's stops report: where the device stood, from when to when. */ + data class Stop(val latitude: Double, val longitude: Double, val start: Long, val end: Long) + + /** What went wrong, in words the options and the widget can say. */ + enum class Problem { + /** Traccar said no to the token: wrong, expired, or of a user that is disabled. */ + TOKEN, + + /** Something answered, but not Traccar's API. */ + NOT_TRACCAR, + + /** The address is not https. */ + NOT_SECURE, + + /** The server's certificate is not one Android trusts. */ + CERTIFICATE, + + /** Android 17 keeps the launcher from the phone's own network, where the server is. */ + LOCAL_NETWORK, + + /** No answer: offline, a wrong name, or the server is down. */ + OFFLINE, + + /** Traccar answered with an error of its own. */ + SERVER, + } + + class TraccarException(val problem: Problem, message: String, cause: Throwable? = null) : + IOException(message, cause) + + private const val TAG = "Traccar" + private const val CONNECT_TIMEOUT_MS = 10_000 + private const val READ_TIMEOUT_MS = 15_000 + + /** No answer the widget asks for is larger than this; a larger one is something else. */ + private const val MAX_BYTES = 4 * 1024 * 1024 + + // Android's own User-Agent would tell the server the phone's model and its exact Android + // build. This one names only the app. + private val USER_AGENT = "FlexeraLauncher/${BuildConfig.VERSION_NAME}" + + /** + * The server address the owner typed, made into the form [Account] keeps: https when no + * scheme is given, no trailing slash, and without "/api" when the address of the API itself + * was pasted. Null when it is not a web address. + */ + fun normalize(input: String): String? { + var text = input.trim() + if (text.isEmpty()) return null + if (!text.contains("://")) text = "https://$text" + val url = try { + URL(text) + } catch (e: MalformedURLException) { + return null + } + val scheme = url.protocol.lowercase(Locale.ROOT) + if (scheme != "https" && scheme != "http") return null + val host = url.host?.lowercase(Locale.ROOT) + if (host.isNullOrEmpty()) return null + var path = url.path.orEmpty().trimEnd('/') + if (path.endsWith("/api")) path = path.removeSuffix("/api") + val port = if (url.port == -1 || url.port == url.defaultPort) "" else ":${url.port}" + return "$scheme://$host$port$path" + } + + /** The devices the account's user can see, by name. Throws [TraccarException] when it cannot ask. */ + @WorkerThread + @Throws(TraccarException::class) + fun devices(context: Context, account: Account): List { + val answer = array(get(context, account, "/api/devices")) + return (0 until answer.length()) + .mapNotNull { answer.optJSONObject(it) } + .filterNot { it.optBoolean("disabled", false) } + .map { device -> + Device( + id = device.optLong("id"), + name = text(device, "name") ?: text(device, "uniqueId").orEmpty(), + online = device.optString("status") == "online", + ) + } + .filter { it.id > 0 } + .sortedWith(compareBy(String.CASE_INSENSITIVE_ORDER) { it.name }) + } + + /** The last position of a device, or null when Traccar has none yet. */ + @WorkerThread + @Throws(TraccarException::class) + fun latestPosition(context: Context, account: Account, deviceId: Long): Position? { + // With a device and no time span Traccar answers with that device's latest position only. + val answer = array(get(context, account, "/api/positions?deviceId=$deviceId")) + val position = answer.optJSONObject(0) ?: return null + if (!position.has("latitude") || !position.has("longitude")) return null + val attributes = position.optJSONObject("attributes") + return Position( + latitude = position.optDouble("latitude"), + longitude = position.optDouble("longitude"), + fixTime = time(text(position, "fixTime")) ?: time(text(position, "deviceTime")) ?: 0L, + moving = attributes?.optBoolean("motion", false) ?: false, + speedKnots = position.optDouble("speed", 0.0).takeIf { it.isFinite() } ?: 0.0, + address = text(position, "address"), + ).takeIf { it.latitude.isFinite() && it.longitude.isFinite() } + } + + /** + * The last stop of a device between [from] and [to] (milliseconds since 1970), from Traccar's + * stops report. The report includes a stop that is still going on at [to]; its end is then the + * device's last position. Null when the report has no stop in that time. + */ + @WorkerThread + @Throws(TraccarException::class) + fun lastStop(context: Context, account: Account, deviceId: Long, from: Long, to: Long): Stop? { + val span = "from=${query(from)}&to=${query(to)}" + val answer = array(get(context, account, "/api/reports/stops?deviceId=$deviceId&$span")) + return (0 until answer.length()) + .mapNotNull { answer.optJSONObject(it) } + .mapNotNull { stop -> + Stop( + latitude = stop.optDouble("latitude"), + longitude = stop.optDouble("longitude"), + start = time(text(stop, "startTime")) ?: return@mapNotNull null, + end = time(text(stop, "endTime")) ?: return@mapNotNull null, + ).takeIf { it.latitude.isFinite() && it.longitude.isFinite() } + } + .maxByOrNull { it.start } + } + + /** A time as Traccar's API takes it: ISO 8601 in UTC, to the second. */ + private fun query(time: Long): String = + URLEncoder.encode(Instant.ofEpochMilli(time).truncatedTo(ChronoUnit.SECONDS).toString(), "UTF-8") + + /** + * A time as Traccar's API gives it, such as "2026-11-28T10:11:12.000+00:00", in milliseconds + * since 1970; null when there is none or it cannot be read. + */ + internal fun time(text: String?): Long? { + if (text.isNullOrEmpty()) return null + return try { + OffsetDateTime.parse(text).toInstant().toEpochMilli() + } catch (e: DateTimeParseException) { + // An offset written without its colon ("+0000"), as some Java date formats write it. + val fixed = OFFSET_WITHOUT_COLON.replace(text) { "${it.groupValues[1]}:${it.groupValues[2]}" } + runCatching { OffsetDateTime.parse(fixed).toInstant().toEpochMilli() }.getOrNull() + } + } + + private val OFFSET_WITHOUT_COLON = Regex("""([+-]\d{2})(\d{2})$""") + + /** A string field, or null when it is missing, null or empty. Android's optString says "null" for null. */ + private fun text(json: JSONObject, name: String): String? = + if (json.isNull(name)) null else json.optString(name).trim().takeIf { it.isNotEmpty() } + + private fun array(answer: String): JSONArray = try { + JSONArray(answer) + } catch (e: JSONException) { + throw TraccarException(Problem.NOT_TRACCAR, "The answer is not a list", e) + } + + private fun get(context: Context, account: Account, path: String): String { + if (!account.server.startsWith("https://")) { + throw TraccarException(Problem.NOT_SECURE, "Not an https address") + } + val address = account.server + path + val connection = try { + URL(address).openConnection() as HttpURLConnection + } catch (e: IOException) { + throw problemOf(context, address, e) + } + try { + connection.connectTimeout = CONNECT_TIMEOUT_MS + connection.readTimeout = READ_TIMEOUT_MS + // A redirect could take the token to another server. + connection.instanceFollowRedirects = false + connection.useCaches = false + connection.setRequestProperty("Accept", "application/json") + connection.setRequestProperty("Authorization", "Bearer ${account.token}") + connection.setRequestProperty("User-Agent", USER_AGENT) + val code = connection.responseCode + when { + code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN -> + throw TraccarException(Problem.TOKEN, "HTTP $code for $path") + + code == HttpURLConnection.HTTP_NOT_FOUND || code in 300..399 -> + throw TraccarException(Problem.NOT_TRACCAR, "HTTP $code for $path") + + code != HttpURLConnection.HTTP_OK -> + throw TraccarException(Problem.SERVER, "HTTP $code for $path") + } + val type = connection.contentType.orEmpty() + if (!type.contains("json", ignoreCase = true)) { + throw TraccarException(Problem.NOT_TRACCAR, "Answered with \"$type\" for $path") + } + return readCapped(connection.inputStream).toString(Charsets.UTF_8) + } catch (e: TraccarException) { + Log.w(TAG, "${account.host}: ${e.problem} (${e.message})") + throw e + } catch (e: IOException) { + throw problemOf(context, address, e) + } finally { + connection.disconnect() + } + } + + private fun readCapped(input: InputStream): ByteArray = input.use { + val out = ByteArrayOutputStream() + val buffer = ByteArray(16 * 1024) + while (true) { + val read = it.read(buffer) + if (read < 0) break + out.write(buffer, 0, read) + if (out.size() > MAX_BYTES) throw TraccarException(Problem.NOT_TRACCAR, "Too large an answer") + } + out.toByteArray() + } + + private fun problemOf(context: Context, address: String, e: IOException): TraccarException { + val host = runCatching { URL(address).host }.getOrNull() + val problem = when { + (e is SocketTimeoutException || e is ConnectException || e is NoRouteToHostException) && + host != null && FlexeraUpdater.blocksLocalNetwork(context, host) -> Problem.LOCAL_NETWORK + e is SSLHandshakeException || e is SSLPeerUnverifiedException -> Problem.CERTIFICATE + e is SSLException -> Problem.CERTIFICATE + // Android refuses a connection that is not encrypted with this. + e is UnknownServiceException -> Problem.NOT_SECURE + else -> Problem.OFFLINE + } + Log.w(TAG, "$host: $problem (${e.javaClass.simpleName}: ${e.message})") + return TraccarException(problem, e.message.orEmpty(), e) + } +} diff --git a/flexera/src/app/flexera/widget/WidgetSight.kt b/flexera/src/app/flexera/widget/WidgetSight.kt new file mode 100644 index 0000000000..e279fb97f0 --- /dev/null +++ b/flexera/src/app/flexera/widget/WidgetSight.kt @@ -0,0 +1,49 @@ +package app.flexera.widget + +import android.content.Context +import android.content.ContextWrapper +import android.view.View +import com.android.launcher3.CellLayout +import com.android.launcher3.Launcher +import com.android.launcher3.LauncherState +import com.android.launcher3.ShortcutAndWidgetContainer +import com.android.launcher3.Workspace +import com.android.launcher3.folder.Folder + +/** Whether one of the launcher's own widgets can really be seen. */ +internal object WidgetSight { + + /** + * True while [view], the view inside a widget's host view, can be seen; [onScreen] is what + * Android last told it (onVisibilityAggregated). That is not enough by itself: Launcher3 leaves + * every home screen page shown, and covers them with the app drawer, Recents or a folder + * without hiding them. + */ + fun isSeen(view: View, onScreen: Boolean): Boolean { + if (!onScreen || !view.isShown) return false + val launcher = launcher(view.context) ?: return true + if (!launcher.isInState(LauncherState.NORMAL) && + !launcher.isInState(LauncherState.SPRING_LOADED) && + !launcher.isInState(LauncherState.EDIT_MODE) + ) { + return false + } + if (Folder.getOpen(launcher) != null) return false + // On the home screen: the page the widget is on has to be one of those on the screen, + // and not faded out. + val cells = (view.parent as? View)?.parent as? ShortcutAndWidgetContainer ?: return true + if (cells.alpha <= 0f) return false + val page = cells.parent as? CellLayout ?: return true + val pages = page.parent as? Workspace<*> ?: return true + return pages.isVisible(page) + } + + fun launcher(context: Context): Launcher? { + var current: Context? = context + while (current != null) { + if (current is Launcher) return current + current = (current as? ContextWrapper)?.baseContext + } + return null + } +} diff --git a/src/com/android/launcher3/widget/LauncherWidgetHolder.java b/src/com/android/launcher3/widget/LauncherWidgetHolder.java index 2311d651aa..8d6117426c 100644 --- a/src/com/android/launcher3/widget/LauncherWidgetHolder.java +++ b/src/com/android/launcher3/widget/LauncherWidgetHolder.java @@ -199,6 +199,7 @@ public class LauncherWidgetHolder { // not, and the launcher's own widgets may already keep pictures or options under it. app.flexera.widget.PictureWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId); app.flexera.widget.ClockWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId); + app.flexera.widget.CarWidgetProvider.onAppWidgetIdDeleted(mContext, appWidgetId); } /** diff --git a/src/com/android/launcher3/widget/WidgetInflater.kt b/src/com/android/launcher3/widget/WidgetInflater.kt index 83fe08d772..94b99e1fd2 100644 --- a/src/com/android/launcher3/widget/WidgetInflater.kt +++ b/src/com/android/launcher3/widget/WidgetInflater.kt @@ -133,6 +133,7 @@ constructor( // loaded, which would delete those too, so they go to the new id first. app.flexera.widget.PictureWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId) app.flexera.widget.ClockWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId) + app.flexera.widget.CarWidgetProvider.onNewAppWidgetId(context, item, oldAppWidgetId) item.restoreStatus = item.restoreStatus or LauncherAppWidgetInfo.FLAG_ID_ALLOCATED