Skip to content

RF Sentinel (RFSentinel): free, open-source police detector app for Android. Spots police body cams, Flock ALPR cameras, AirTag trackers, Remote ID drones, smart glasses and fake cell towers from Bluetooth LE and WiFi. No root.

Release 2.21.0: theme maker, car and arrow map markers, settings backup with themes, device history import, cleaner Settings with info buttons

CIS-C075b8acd74d52
diff --git a/README.md b/README.md
index 79a75be..d711881 100644
--- a/README.md
+++ b/README.md
@@ -174,9 +174,13 @@ headline as you get closer (strong within 50 m, fading out by 500 m). Full refer
- **Check for updates** (menu ⋮): compares with the latest GitHub release, only when you tap it
- **Screen rotation** (Settings → General): normal, auto-rotate **including upside down**, or always upside down with the USB-C port at the top for an antenna or adapter - even on phones like the Pixel that never auto-rotate upside down
- 13 themes, including the **DedSec** (Watch Dogs 2) and **fsociety** (Mr. Robot) fan themes
+- **Theme maker:** build your own theme - an accent colour the whole palette grows from (the way Material You does), light, dark or pure black, a font (or your own .ttf / .otf), a banner picture, the animated home-screen header with your title, and your own map marker. Export a theme as a file; importing one lets you tick which parts to take (colours, font, banner, header, marker), into a new theme or into one of yours
+- **Map marker:** an arrow, chevron or one of 13 cars and bikes in 16 colours and any size, in place of the plain dot
**Data & privacy**
- Everything stays on the phone; export as CSV, JSON, KML, GPX or GeoJSON
+- **Back up and restore settings** (Settings → Data): one file with your settings, watchlist rules, Home / Work / starred places, floating-window positions and custom themes; restore asks which of those to take. API keys and the "I accept the risk" choices are never in the file
+- **Device history export and import** (Device history menu, or Settings → Data): export every remembered device, import a file from another phone or an earlier export - devices already known are merged, not duplicated
- **Report unknown device:** a privacy-safe signature (no full address, serials, location or times) to help add new equipment
- No accounts, no cloud, no analytics
@@ -572,6 +576,8 @@ their default names.
Pick a theme in the setup wizard or under **Settings → Appearance**.
+Your own themes sit under the built-in ones: **Create a custom theme**, long-press one to edit it, or **Import a theme file**.
+
| Theme | Look |
|---|---|
| **DedSec** | Watch Dogs 2-style: black and white with electric blue, a full-width DedSec poster banner, a sliced wordmark and a `[email protected]:~$` terminal typing hacktivist lines |
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index d510373..c219cf1 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -7,8 +7,8 @@ plugins {
}
// Bump both for every release. versionName ends up in the APK file name.
-val appVersionCode = 44
-val appVersionName = "2.20.0"
+val appVersionCode = 45
+val appVersionName = "2.21.0"
// Release signing credentials live in keystore.properties (git-ignored).
// Without that file, release builds are produced unsigned.
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 487e535..4636f04 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -77,6 +77,8 @@
<activity android:name=".probes.ProbeListActivity" android:exported="false" />
<activity android:name=".ui.DetectionLogActivity" android:exported="false" />
<activity android:name=".ui.DeviceHistoryActivity" android:exported="false" />
+ <activity android:name=".ui.ThemeMakerActivity" android:exported="false"
+ android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden|uiMode" />
<activity android:name=".ui.CellTowersActivity" android:exported="false" />
<activity android:name=".ui.GnssActivity" android:exported="false" />
<activity android:name=".ui.WazeStatusActivity" android:exported="false" />
diff --git a/app/src/main/java/com/rfsentinel/app/MainActivity.kt b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
index ee29c33..4426efb 100644
--- a/app/src/main/java/com/rfsentinel/app/MainActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/MainActivity.kt
@@ -210,11 +210,14 @@ class MainActivity : AppCompatActivity() {
/** Styled themes: their own title, animated wordmark and the user's banner image. */
private fun applyThemeHeader() {
val theme = com.rfsentinel.app.ui.ThemeManager.current(this)
- theme.appTitle?.let { title = it }
- val header = theme.header
- binding.themedHeader.visibility = if (header != null) View.VISIBLE else View.GONE
- if (header == null) return
- binding.themeHeader.style = header
+ com.rfsentinel.app.ui.ThemeManager.appTitle(this)?.let { title = it }
+ val header = com.rfsentinel.app.ui.ThemeManager.headerStyle(this)
+ val ownBanner = theme == com.rfsentinel.app.ui.ThemeManager.AppTheme.CUSTOM && com.rfsentinel.app.ui.ThemeManager.hasBanner(this)
+ // A custom theme can have just a banner and no animated header.
+ binding.themedHeader.visibility = if (header != null || ownBanner) View.VISIBLE else View.GONE
+ binding.themeHeader.visibility = if (header != null) View.VISIBLE else View.GONE
+ if (header == null && !ownBanner) return
+ if (header != null) binding.themeHeader.style = header
val file = com.rfsentinel.app.ui.ThemeManager.bannerFile(this)
// Bundled poster art sits beside the animated header (a picked banner replaces it).
val useArt = theme.headerImage != null && !com.rfsentinel.app.ui.ThemeManager.hasBanner(this)
diff --git a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
index 55a321e..3129f80 100644
--- a/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
+++ b/app/src/main/java/com/rfsentinel/app/car/RFSentinelMediaService.kt
@@ -183,8 +183,12 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
playable(ACTION_SCAN, if (running) "Stop scanning" else "Start scanning",
if (running) "Scanning · ${devices.size} nearby · ${devices.count { com.rfsentinel.app.ui.LiveWindow.alerting(it) }} flagged" else "Not scanning",
dot(if (running) CarUi.CLEAR_COLOR else CarUi.WEAK_COLOR)),
- playable(ACTION_MUTE, if (silenced.isEmpty()) "Mute alerts for 30 minutes" else "Turn alert sound back on",
- silenced.ifEmpty { "Alert sound and voice are on" }, dot(if (silenced.isEmpty()) CarUi.CLEAR_COLOR else CarUi.WEAK_COLOR)),
+ playable(ACTION_MUTE, if (silenced.isEmpty()) "Mute detection alerts for 30 minutes" else "Turn detection alerts back on",
+ silenced.ifEmpty { "Detection alert sound and voice are on (directions are separate)" }, dot(if (silenced.isEmpty()) CarUi.CLEAR_COLOR else CarUi.WEAK_COLOR)),
+ // While guided: the directions have their own mute, so silencing them never silences the detection alerts.
+ if (com.rfsentinel.app.nav.Navigator.active) playable(ACTION_NAV_MUTE, if (Prefs.navVoice(this)) "Mute spoken directions" else "Turn spoken directions back on",
+ if (Prefs.navVoice(this)) "Detection alerts keep sounding" else "Directions are muted; detection alerts still sound",
+ dot(if (Prefs.navVoice(this)) CarUi.CLEAR_COLOR else CarUi.WEAK_COLOR)) else null,
CellsScreen.summary()?.let { playable(INFO_CELLS, "Cell towers", it, dot(0xFF7B1FA2.toInt())) },
playable(INFO_HARDWARE, "Hardware", hardwareSummary(), dot(0xFF0B5C63.toInt()))
)
@@ -204,6 +208,7 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
when (mediaId) {
ACTION_SCAN -> toggleScan()
ACTION_MUTE -> toggleMute()
+ ACTION_NAV_MUTE -> toggleDirections()
null -> Unit
else -> select(mediaId)
}
@@ -214,6 +219,7 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
when (action) {
ACTION_SCAN -> toggleScan()
ACTION_MUTE -> toggleMute()
+ ACTION_NAV_MUTE -> toggleDirections()
}
refresh()
}
@@ -262,6 +268,13 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
}
}
+ /** Spoken directions on / off (the same setting as the mute on the phone's navigation screen); detection alerts are not touched. */
+ private fun toggleDirections() {
+ val on = !Prefs.navVoice(this)
+ Prefs.setNavVoice(this, on)
+ message(if (on) "Spoken directions on" else "Spoken directions muted", "Detection alerts still sound")
+ }
+
private fun toggleMute() {
if (CarUi.silencedText(this).isEmpty()) {
AlertActionReceiver.snooze(this)
@@ -364,7 +377,9 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
val running = ScanForegroundService.isRunning
val muted = CarUi.silencedText(this).isNotEmpty()
- val state = running to muted
+ val guided = com.rfsentinel.app.nav.Navigator.active
+ val directions = Prefs.navVoice(this)
+ val state = listOf(running, muted, guided, directions)
if (state != stateKey) {
stateKey = state
session.setPlaybackState(
@@ -377,8 +392,13 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
ACTION_SCAN, if (running) "Stop scanning" else "Start scanning",
if (running) R.drawable.ic_car_stop else R.drawable.ic_car_play).build())
.addCustomAction(PlaybackStateCompat.CustomAction.Builder(
- ACTION_MUTE, if (muted) "Sound on" else "Mute 30 min",
+ ACTION_MUTE, if (muted) "Alerts on" else "Mute alerts 30 min",
if (muted) R.drawable.ic_car_volume else R.drawable.ic_car_snooze).build())
+ .apply {
+ if (guided) addCustomAction(PlaybackStateCompat.CustomAction.Builder(
+ ACTION_NAV_MUTE, if (directions) "Mute directions" else "Directions on",
+ if (directions) R.drawable.ic_car_voice else R.drawable.ic_car_voice_off).build())
+ }
.build()
)
}
@@ -445,6 +465,7 @@ class RFSentinelMediaService : MediaBrowserServiceCompat() {
private const val ALERT = "alert:"
private const val ACTION_SCAN = "act:scan"
private const val ACTION_MUTE = "act:mute"
+ private const val ACTION_NAV_MUTE = "act:navmute"
private const val INFO_CLEAR = "info:clear"
private const val INFO_NO_CAMERAS = "info:nocams"
private const val INFO_NO_ALERTS = "info:noalerts"
diff --git a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
index 7123659..6de799b 100644
--- a/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/settings/SettingsActivity.kt
@@ -6,7 +6,9 @@ import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.RadioButton
+import com.rfsentinel.app.ui.CustomThemes
import com.rfsentinel.app.ui.ThemeManager
+import com.rfsentinel.app.ui.ThemeImport
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
@@ -30,6 +32,16 @@ class SettingsActivity : AppCompatActivity() {
const val SECTION_MAP = "map"
const val SECTION_NAV = "navigation"
const val SECTION_DATA = "data"
+ private const val PRESETS_INFO = "Adds lists of equipment known to be used by police in that region. The built-in detection " +
+ "(body cams, Flock, drones, trackers, glasses) works everywhere.\n\n" +
+ "Global: body cams (Axon, Zepcam, WatchGuard...), Flock, ShotSpotter, traffic cameras, radios.\n" +
+ "Canada: adds Cyberkar in-car systems, Getac body cams, Genetec plate readers.\n" +
+ "France: Motorola VB400 body cams of the Police nationale and Gendarmerie, Zepcam, TETRAPOL radios.\n" +
+ "United Kingdom: Motorola and Axon body cams, Sepura / Motorola Airwave radios, Jenoptik ANPR cameras.\n" +
+ "Portugal: Motorola SIRESP radios of PSP, GNR and INEM.\n" +
+ "Germany: Motorola VB400 body cams, Motorola and Sepura BOS digital radios.\n" +
+ "Spain: Axon body cams of the Policia Nacional, Teltronic radios.\n" +
+ "Italy: Leonardo / Selex police radios, Selea and Elsag plate readers."
const val WAZE_WARNING_SHORT = "Use at your own risk. Reports come from third-party services RF Sentinel doesn't run or endorse " +
"(OpenWeb Ninja with your own key, or Waze itself); your account, your responsibility."
const val WAZE_WARNING = "Waze police reports are read through OpenWeb Ninja's Waze API with your own API key.\n\n" +
@@ -151,7 +163,7 @@ class SettingsActivity : AppCompatActivity() {
/** Known cameras silenced from the map (tap a camera > Ignore alerts). */
private fun updateIgnoredCamerasText() {
val n = com.rfsentinel.app.alpr.IgnoredCameras.count(this)
- binding.ignoredCamerasText.text = "$n camera${if (n == 1) "" else "s"} with alerts turned off (faded on the map)"
+ binding.ignoredCamerasText.text = "$n camera${if (n == 1) "" else "s"} with alerts turned off · faded on the map"
binding.ignoredCamerasText.visibility = if (n > 0) View.VISIBLE else View.GONE
binding.ignoredCamerasButton.visibility = if (n > 0) android.view.View.VISIBLE else android.view.View.GONE
}
@@ -289,10 +301,10 @@ class SettingsActivity : AppCompatActivity() {
val mb = String.format(java.util.Locale.US, "%.1f MB", rec.bytes / 1_048_576.0)
binding.pcapText.text = when {
rec.active -> "● Recording · ${rec.frames} frames · $mb"
- file != null -> "Last recording: ${rec.frames} frames · $mb" + (rec.stoppedBecause?.let { " (stopped: $it)" } ?: "")
+ file != null -> "Last recording: ${rec.frames} frames · $mb" + (rec.stoppedBecause?.let { " · stopped: $it" } ?: "")
else -> "Record what the USB WiFi adapter or V2X board hears, for Wireshark"
}
- binding.pcapButton.text = if (rec.active) "Stop and share" else "Record frames (.pcap)"
+ binding.pcapButton.text = if (rec.active) "Stop and share" else "Record frames"
binding.pcapShareButton.visibility = if (!rec.active && file != null) View.VISIBLE else View.GONE
binding.pcapText.removeCallbacks(pcapTicker)
if (rec.active) binding.pcapText.postDelayed(pcapTicker, 1_000)
@@ -307,7 +319,7 @@ class SettingsActivity : AppCompatActivity() {
val board = Prefs.ouiSpyBoard(this)
binding.ouiSpyText.text = if (board == null) "OUI-SPY over Bluetooth: not paired"
else com.rfsentinel.app.esp.OuiSpyBle.status.ifBlank { "OUI-SPY $board: connects while scanning" }
- binding.ouiSpyButton.text = if (board == null) "Pair OUI-SPY board (Bluetooth)" else "Change or forget OUI-SPY board"
+ binding.ouiSpyButton.text = if (board == null) "Pair OUI-SPY board" else "Change or forget OUI-SPY board"
}
private val ouiSpyConnectPermission = registerForActivityResult(
@@ -363,7 +375,7 @@ class SettingsActivity : AppCompatActivity() {
/** A folded section on screen, for the search: its header row, divider, body and fold state. */
private class SectionUi(
val title: String, val info: String, val row: View, val divider: View?, val body: View,
- val restore: () -> Unit, val expand: () -> Unit
+ val restore: () -> Unit, val expand: () -> Unit, val setOpen: (Boolean) -> Unit
)
private val sectionUi = mutableListOf<SectionUi>()
@@ -485,6 +497,11 @@ class SettingsActivity : AppCompatActivity() {
"is off until you turn it on. Limits are OpenStreetMap's: where none is mapped there is no sign.\n\n" +
"The full screen map has a button that hides the toolbar, the system bars and the bottom bar (the speedometer, " +
"alert cards and, while guiding, the turn banner stay).\n\n" +
+ "Position marker: your position on the map as an arrow or a car seen from above - sedan, hatchback, wagon, SUV, pickup, " +
+ "sports car, racer, convertible, mini, van, truck, taxi or motorcycle - in 16 colours, from small to very large. " +
+ "It turns with your direction of travel.\n\n" +
+ "Recenter: while you drive, the map goes back to following you ten seconds after you last touched it (like Google Maps); " +
+ "parked it stays where you put it. The speedometer's card turns red while you are over the posted limit.\n\n" +
"Default zoom: how close the map follows you. The 3D driving view pulls back from it as you speed up; the " +
"north-up and heading-up views sit half a level wider. 17 is close to Waze.\n\n" +
"Map provider: OpenFreeMap (OpenStreetMap data, free, no account) or Mapbox (Mapbox's own map: 3D buildings, " +
@@ -639,8 +656,144 @@ class SettingsActivity : AppCompatActivity() {
sectionUi += SectionUi(title, s.info, row, dividerView, s.body, restore = { show() }, expand = {
s.body.visibility = View.VISIBLE
s.header.text = "▾ $title"
+ }, setOpen = { want ->
+ open = want
+ ui.edit().putBoolean(s.key, open).apply()
+ show()
+ })
+ }
+ }
+
+ // ---- ⓘ details beside a setting -----------------------------------------------------------
+
+ /** What an ⓘ says (its tag), so the search finds a setting by its details too. */
+ private class InfoText(val text: String)
+
+ /** The ⓘ: tapping it shows [text] under [title] (the setting's own label when not given). */
+ private fun infoIcon(text: String, title: () -> String): View {
+ val dp = resources.displayMetrics.density
+ val ripple = android.util.TypedValue().also { theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, it, true) }.resourceId
+ return android.widget.TextView(this).apply {
+ this.text = "ⓘ"
+ textSize = 18f
+ alpha = 0.7f
+ tag = InfoText(text)
+ setPadding((10 * dp).toInt(), (8 * dp).toInt(), (6 * dp).toInt(), (8 * dp).toInt())
+ setBackgroundResource(ripple)
+ contentDescription = "About ${title()}"
+ setOnClickListener { AlertDialog.Builder(this@SettingsActivity).setTitle(title()).setMessage(text).setPositiveButton("OK", null).show() }
+ }
+ }
+
+ private fun labelOf(view: View) = ((view as? android.widget.TextView)?.text ?: "").toString().removePrefix("▾ ").substringBefore(":").trim()
+
+ /** [view] with its ⓘ at the end of the row (for a view not yet added anywhere). */
+ private fun infoRow(view: View, text: String, title: String? = null): View {
+ val wrap = (view.layoutParams?.width ?: android.view.ViewGroup.LayoutParams.MATCH_PARENT) == android.view.ViewGroup.LayoutParams.WRAP_CONTENT
+ return android.widget.LinearLayout(this).apply {
+ orientation = android.widget.LinearLayout.HORIZONTAL
+ gravity = android.view.Gravity.CENTER_VERTICAL
+ addView(view, if (wrap) android.widget.LinearLayout.LayoutParams(-2, -2)
+ else android.widget.LinearLayout.LayoutParams(0, -2, 1f))
+ addView(infoIcon(text) { title ?: labelOf(view) })
+ // A hidden setting takes its ⓘ with it.
+ if (view.visibility == View.GONE) visibility = View.GONE
+ }
+ }
+
+ /** Puts an ⓘ at the end of [view]'s row, where it already sits. */
+ private fun info(view: View, text: String, title: String? = null) {
+ val parent = view.parent as? android.view.ViewGroup ?: return
+ val at = parent.indexOfChild(view)
+ val lp = view.layoutParams
+ parent.removeViewAt(at)
+ parent.addView(infoRow(view, text, title), at, android.widget.LinearLayout.LayoutParams(
+ android.widget.LinearLayout.LayoutParams.MATCH_PARENT, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT).apply {
+ (lp as? android.view.ViewGroup.MarginLayoutParams)?.let { setMargins(it.leftMargin, it.topMargin, it.rightMargin, it.bottomMargin) }
+ })
+ }
+
+ /** The unit after a number field ("min", "s", "m", "days"), so the label doesn't have to say it. */
+ private fun withUnit(field: android.widget.EditText, unit: String) {
+ val parent = field.parent as? android.view.ViewGroup ?: return
+ val at = parent.indexOfChild(field)
+ val lp = field.layoutParams
+ parent.removeViewAt(at)
+ val row = android.widget.LinearLayout(this).apply {
+ orientation = android.widget.LinearLayout.HORIZONTAL
+ gravity = android.view.Gravity.CENTER_VERTICAL
+ addView(field, android.widget.LinearLayout.LayoutParams(0, -2, 1f))
+ addView(android.widget.TextView(this@SettingsActivity).apply {
+ text = unit; alpha = 0.75f
+ setPadding((8 * resources.displayMetrics.density).toInt(), 0, (8 * resources.displayMetrics.density).toInt(), 0)
})
}
+ parent.addView(row, at, lp)
+ }
+
+ /** "Probable" with a small "recommended" after it. */
+ private fun tagged(main: String, tag: String): CharSequence = android.text.SpannableStringBuilder(main).apply {
+ append(" ")
+ val start = length
+ append(tag)
+ setSpan(android.text.style.RelativeSizeSpan(0.8f), start, length, 0)
+ setSpan(android.text.style.StyleSpan(android.graphics.Typeface.ITALIC), start, length, 0)
+ }
+
+ /** A long title split in the label and its details: "Drone (Remote ID / drone maker)", "Hacking tools: Flipper...". */
+ private fun splitTitle(t: String): Pair<String, String?> {
+ val p = t.indexOf(" (")
+ if (p > 0 && t.endsWith(")")) return t.substring(0, p) to t.substring(p + 2, t.length - 1).replaceFirstChar { it.uppercase() }
+ val c = t.indexOf(": ")
+ if (c > 0) return t.substring(0, c) to t.substring(c + 2).replaceFirstChar { it.uppercase() }
+ return t to null
+ }
+
+ /** The ⓘ of the settings laid out in the layout file, and the units beside their number fields. */
+ private fun addDetails() {
+ info(binding.autoUpdateSwitch, "When RF Sentinel opens, it asks GitHub whether a newer release is out. Off: nothing is sent until you tap Check for updates.")
+ info(binding.discreetSwitch, "Hides what was detected on the lock screen and in notifications.")
+ info(binding.screenLabel, "Always on: the screen never turns off while RF Sentinel is open.\n\nOn while charging: stays on in the car or on a desk (recommended).\n\nNormal: turns off like any other app.")
+ info(binding.rotationLabel, "Normal follows the phone's auto-rotate.\n\nAuto-rotate, upside down too: also turns upside down, which phones like the Pixel never do on their own.\n\nAlways upside down: the USB-C port at the top, for an antenna or adapter plugged in.")
+ info(binding.bannerLabel, "A picture across the header of the styled themes (a logo or artwork you own). Your custom themes have their own banner, set in the theme maker.")
+ info(binding.hideTrustedSwitch, "Devices on your whitelist are left off the list and radar.")
+ info(binding.scanModeLabel, "Maximum finds devices fastest and uses the most battery. Battery saver notices them later.")
+ info(binding.intervalLabel, "How often WiFi is scanned. Android allows an app 4 scans in 2 minutes unless WiFi scan throttling is turned off in Developer options.")
+ withUnit(binding.intervalInput, "s")
+ info(binding.batteryButton, "Opens Android's battery settings: set RF Sentinel to Unrestricted so scanning keeps going with the screen off.")
+ info(binding.carAutoSwitch, "Starts scanning when the phone connects to your car's Bluetooth or Android Auto, and stops when you leave.")
+ info(binding.presetLabel, PRESETS_INFO)
+ info(binding.thresholdLabel, "Weak: every match, more false alarms.\n\nProbable: recommended.\n\nStrong only: the fewest alerts.")
+ binding.thresholdMedium.text = tagged("Probable", "recommended")
+ info(binding.radarBeepSwitch, "Beeps faster as a flagged device gets closer, like a radar detector.")
+ info(binding.detectorSoundSwitch, "Alerts use radar-detector tones (Ka, K and X) and say \"GPS connected\" when the first GPS fix comes in.")
+ info(binding.dedupeLabel, "The same device won't alert again until this many minutes have passed.")
+ withUnit(binding.dedupeInput, "min")
+ info(binding.shortVoiceSwitch, "\"Body cam\", \"Police car\", \"Speed camera, 50\" instead of whole sentences.")
+ info(binding.bubbleSwitch, "A small bubble over other apps (Waze, Google Maps...) showing the threat level. Needs \"Display over other apps\".")
+ info(binding.floatingMapSwitch, "A small map over other apps, centred on you, with the same device dots as RF Sentinel's map. It always uses OpenFreeMap: a window this small has no room for Mapbox's logo and info button.")
+ info(binding.followSwitch, "Warns when a tracker or flagged device keeps moving with you, for at least the time and distance below.")
+ withUnit(binding.followMinutesInput, "min")
+ withUnit(binding.followMetersInput, "m")
+ info(binding.mapProviderLabel, "OpenFreeMap: free and open, OpenStreetMap data.\n\nMapbox: Mapbox's Standard map with 3D buildings and day / night light.\n\nThe floating mini map and the Android Auto map always use OpenStreetMap maps.")
+ info(binding.mapAutoRecenterSwitch, "While you drive, the map goes back to your position a few seconds after you stop touching it.")
+ info(binding.mapSpeedometerSwitch, "Your speed and the posted limit in a corner of the map; your speed turns red over the limit.")
+ info(binding.mapSpeedLimitLiveSwitch, "Shows the posted limit with no destination too, by asking the route server (Valhalla, OpenStreetMap data) about the road you're on. Your position is sent to it.")
+ info(binding.autoCamerasSwitch, "Fetches the known cameras (OpenStreetMap) for the area the map shows, as you move it.")
+ info(binding.mapCctvSwitch, "Surveillance cameras mapped in OpenStreetMap.")
+ info(binding.deflockButton, "Every plate-reader camera in the US and Canada, from DeFlock's OpenStreetMap snapshot. Works offline and refreshes weekly on Wi-Fi.")
+ info(binding.disable2gLabel, "2G doesn't check that a tower is real. Turning it off is the best protection against fake cell towers (IMSI catchers).")
+ info(binding.cellSecurityLabel, "Android 15 and newer can warn you when a network asks for your phone's identity or turns encryption off.")
+ info(binding.ouiSpyRelaySwitch, "Every device the OUI-SPY board hears comes into the list, not just its own matches.")
+ info(binding.rtl5gSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS. Experimental.")
+ info(binding.usbLightSwitch, "For RTL8811AU / RTL8821AU adapters such as the ALFA AWUS036ACS: the light blinks with received traffic.")
+ info(binding.pinpointSwitch, "Works out where a flagged device is from many readings as you move (GPS runs precise every second while one is in range).")
+ info(binding.liveExportSwitch, "Keeps a live copy of matches, devices and radio hits in a folder other apps can read.")
+ info(binding.retentionLabel, "How long device history is kept. 0 keeps it forever.")
+ withUnit(binding.retentionInput, "days")
+ info(binding.exportAllButton, "CSV, JSON, KML, GPX or GeoJSON.")
+ info(binding.forgetHistoryButton, "New / returning status, detect counts and the remembered cell towers start over. Favorites are kept.")
+ info(binding.openWhitelistButton, "Trusted devices: never flagged, and hidden from the list when you choose.")
}
// ---- Search ----------------------------------------------------------------------------
@@ -690,6 +843,36 @@ class SettingsActivity : AppCompatActivity() {
setPadding((16 * dp).toInt(), (4 * dp).toInt(), (4 * dp).toInt(), 0)
addView(searchInput, android.widget.LinearLayout.LayoutParams(0, android.widget.LinearLayout.LayoutParams.WRAP_CONTENT, 1f))
addView(clear)
+ addView(foldAllButton())
+ }
+ }
+
+ /** Folds every section (or, when all are folded, unfolds them all) and goes back to the top. */
+ private fun foldAllButton(): View {
+ val dp = resources.displayMetrics.density
+ val ripple = android.util.TypedValue().also { theme.resolveAttribute(android.R.attr.selectableItemBackgroundBorderless, it, true) }.resourceId
+ return android.widget.TextView(this).apply {
+ text = "Collapse all"
+ textSize = 13f
+ setTypeface(typeface, android.graphics.Typeface.BOLD)
+ setTextColor(com.google.android.material.color.MaterialColors.getColor(this, androidx.appcompat.R.attr.colorPrimary, currentTextColor))
+ setPadding((10 * dp).toInt(), (10 * dp).toInt(), (12 * dp).toInt(), (10 * dp).toInt())
+ setBackgroundResource(ripple)
+ fun label() {
+ val anyOpen = sectionUi.any { it.body.visibility == View.VISIBLE }
+ val want = if (anyOpen) "Collapse all" else "Expand all"
+ if (text.toString() != want) { text = want; contentDescription = want } // only on a change: setting text lays out again
+ }
+ setOnClickListener {
+ if (searchInput.text.isNotEmpty()) searchInput.setText("")
+ val anyOpen = sectionUi.any { it.body.visibility == View.VISIBLE }
+ sectionUi.forEach { it.setOpen(!anyOpen) }
+ binding.root.scrollTo(0, 0)
+ label()
+ }
+ // Section headers toggled by hand change what the button does.
+ post { label() }
+ binding.root.viewTreeObserver.addOnGlobalLayoutListener { label() }
}
}
@@ -741,6 +924,9 @@ class SettingsActivity : AppCompatActivity() {
val c = v.getChildAt(i)
if (c.visibility == View.VISIBLE) collectMatches(c, q, out)
}
+ } else if (v.tag is InfoText) {
+ // An ⓘ that matches: the setting beside it lights up.
+ if ((v.tag as InfoText).text.lowercase().contains(q)) ((v.parent as? android.view.ViewGroup)?.getChildAt(0))?.let { if (it !in out) out += it }
} else if (v is android.widget.TextView) {
val text = v.text?.toString().orEmpty().lowercase()
val hint = v.hint?.toString().orEmpty().lowercase()
@@ -750,6 +936,58 @@ class SettingsActivity : AppCompatActivity() {
// ---- RTL-SDR radio -------------------------------------------------------------------
+ /** Settings > Data > Back up settings: writes the backup where you choose. */
+ private val backupPicker = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.CreateDocument("application/json")) { uri ->
+ if (uri == null) return@registerForActivityResult
+ val ok = runCatching {
+ contentResolver.openOutputStream(uri, "wt")!!.use { it.write(com.rfsentinel.app.util.SettingsBackup.create(this).toByteArray(Charsets.UTF_8)) }
+ }.isSuccess
+ Toast.makeText(this, if (ok) "Settings backed up. API keys and risk acknowledgements are not in the file." else "Couldn't write the file", Toast.LENGTH_LONG).show()
+ }
+
+ /** Settings > Data > Restore settings: reads a backup, asks, applies it and restarts the app. */
+ private val restorePicker = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->
+ if (uri == null) return@registerForActivityResult
+ val backup = com.rfsentinel.app.util.SettingsBackup
+ val text = runCatching { contentResolver.openInputStream(uri)!!.use { backup.read(it) } }.getOrNull()
+ if (text == null) { Toast.makeText(this, "Couldn't read that file (or it is too big for a backup)", Toast.LENGTH_LONG).show(); return@registerForActivityResult }
+ val found = when (val i = backup.inspect(text)) {
+ is com.rfsentinel.app.util.SettingsBackup.Inspect.Bad -> {
+ androidx.appcompat.app.AlertDialog.Builder(this).setTitle("Not restored").setMessage(i.why).setPositiveButton("OK", null).show()
+ return@registerForActivityResult
+ }
+ is com.rfsentinel.app.util.SettingsBackup.Inspect.Ok -> i
+ }
+ // A box per section: what is ticked is replaced by the file's, the rest is left as it is.
+ val chosen = found.sections.toMutableSet()
+ val labels = found.sections.map { s ->
+ if (s == com.rfsentinel.app.util.SettingsBackup.Section.THEMES) "${s.label}: ${found.themes}" else s.label
+ }.toTypedArray()
+ androidx.appcompat.app.AlertDialog.Builder(this)
+ .setTitle("Restore what? Ticked parts are replaced, then RF Sentinel restarts")
+ .setMultiChoiceItems(labels, BooleanArray(labels.size) { true }) { _, which, on ->
+ if (on) chosen += found.sections[which] else chosen -= found.sections[which]
+ }
+ .setPositiveButton("Restore") { _, _ ->
+ if (chosen.isEmpty()) { Toast.makeText(this, "Nothing ticked - nothing restored", Toast.LENGTH_SHORT).show(); return@setPositiveButton }
+ when (val r = backup.restore(this, text, chosen)) {
+ is com.rfsentinel.app.util.SettingsBackup.Result.Refused -> androidx.appcompat.app.AlertDialog.Builder(this)
+ .setTitle("Not restored").setMessage(r.why).setPositiveButton("OK", null).show()
+ is com.rfsentinel.app.util.SettingsBackup.Result.Restored -> {
+ restored = true
+ Toast.makeText(this, "Restored ${r.count} settings - restarting", Toast.LENGTH_LONG).show()
+ // A fresh start picks everything up (themes, filters, services read their settings at start-up).
+ packageManager.getLaunchIntentForPackage(packageName)?.let {
+ startActivity(it.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK or android.content.Intent.FLAG_ACTIVITY_CLEAR_TASK))
+ }
+ Runtime.getRuntime().exit(0)
+ }
+ }
+ }
+ .setNegativeButton("Cancel", null)
+ .show()
+ }
+
private val freqListPicker = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->
if (uri == null) return@registerForActivityResult
lifecycleScope.launch {
@@ -791,8 +1029,8 @@ class SettingsActivity : AppCompatActivity() {
addOnChangeListener { _, v, fromUser -> if (fromUser) { save(v.toInt()); l.text = text(v.toInt()) } }
})
}
- fun lines(title: String, hint: String, value: String, save: (String) -> Unit) {
- label(title)
+ fun lines(title: String, hint: String, value: String, details: String? = null, save: (String) -> Unit) {
+ label(title).also { if (details != null) info(it, details) }
box.addView(android.widget.EditText(this).apply {
setText(value); this.hint = hint
minLines = 2; maxLines = 8; gravity = android.view.Gravity.TOP
@@ -805,19 +1043,20 @@ class SettingsActivity : AppCompatActivity() {
})
})
}
- fun switch(t: String, on: Boolean, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {
+ fun switch(t: String, on: Boolean, info: String? = null, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {
text = t; isChecked = on
setOnCheckedChangeListener { _, v -> save(v) }
- }.also { box.addView(it) }
+ }.also { box.addView(if (info == null) it else infoRow(it, info)) }
- slider(15, 50, Prefs.radioMinSnr(this), { "Sensitivity: report a radio from $it dB above the noise (lower = hears farther, more false alarms)" }) {
+ slider(15, 50, Prefs.radioMinSnr(this), { "Sensitivity: $it dB above the noise" }) {
Prefs.setRadioMinSnr(this, it)
}
+ info(box.getChildAt(box.childCount - 2), "A radio is reported once its signal is this far above the noise. Lower hears farther, with more false alarms.", "Sensitivity")
label("Bands to sweep")
val off = Prefs.radioBandsOff(this).toMutableSet()
for ((key, band) in com.rfsentinel.app.sdr.RadioSettings.BUILT_IN) {
box.addView(android.widget.CheckBox(this).apply {
- text = "%s (%.1f-%.1f MHz)".format(java.util.Locale.US, band.label, band.startHz / 1e6, band.endHz / 1e6)
+ text = "%s · %.1f-%.1f MHz".format(java.util.Locale.US, band.label, band.startHz / 1e6, band.endHz / 1e6)
isChecked = key !in off
setOnCheckedChangeListener { _, on ->
if (on) off -= key else off += key
@@ -825,14 +1064,15 @@ class SettingsActivity : AppCompatActivity() {
}
})
}
- lines("Your own bands (one per line, in MHz)", "380-400 TETRA\n220-222", Prefs.radioCustomBands(this)) { Prefs.setRadioCustomBands(this, it) }
- lines("Never report these ranges", "462-469 business band\n151.8-152.0", Prefs.radioExcluded(this)) { Prefs.setRadioExcluded(this, it) }
- lines("Watch these frequencies (always reported when active)", "154.4300 County fire dispatch\n460.125", Prefs.radioTargets(this)) { Prefs.setRadioTargets(this, it) }
- switch("Say the frequency (and its name) instead of \"Radio transmitting nearby\"", Prefs.radioSpeakFreq(this)) { Prefs.setRadioSpeakFreq(this, it) }
- switch("Also detect cellular transmitters (LTE uplink, experimental)", Prefs.radioCellOn(this)) { Prefs.setRadioCellOn(this, it) }
- label("Watches the phone / modem side of the LTE bands for a transmitter travelling near you (a vehicle modem, a " +
- "Cradlepoint-style router, a camera with a SIM). Energy only, nothing decoded. Adds time to each sweep; " +
- "a phone counts too, so it is a weak sign on its own.", small = true)
+ lines("Your own bands", "380-400 TETRA\n220-222", Prefs.radioCustomBands(this), "One per line, in MHz, with an optional name.") { Prefs.setRadioCustomBands(this, it) }
+ lines("Never report these ranges", "462-469 business band\n151.8-152.0", Prefs.radioExcluded(this), "One per line, in MHz.") { Prefs.setRadioExcluded(this, it) }
+ lines("Watch these frequencies", "154.4300 County fire dispatch\n460.125", Prefs.radioTargets(this),
+ "Always reported when active, whatever the sensitivity. One per line, in MHz, with an optional name.") { Prefs.setRadioTargets(this, it) }
+ switch("Say the frequency", Prefs.radioSpeakFreq(this), "Says the frequency (and its name) instead of \"Radio transmitting nearby\".") { Prefs.setRadioSpeakFreq(this, it) }
+ switch("Detect cellular transmitters", Prefs.radioCellOn(this),
+ "Experimental. Watches the phone / modem side of the LTE bands (uplink) for a transmitter travelling near you: a vehicle modem, a " +
+ "Cradlepoint-style router, a camera with a SIM. Energy only, nothing decoded. Adds time to each sweep; " +
+ "a phone counts too, so it is a weak sign on its own.") { Prefs.setRadioCellOn(this, it) }
slider(0, 20, Prefs.radioTrendDb(this), { if (it == 0) "Closer / moving away: off" else "Say \"getting closer\" / \"moving away\" when the signal changes by $it dB" }) {
Prefs.setRadioTrendDb(this, it)
}
@@ -856,7 +1096,8 @@ class SettingsActivity : AppCompatActivity() {
})
})
- val rrSwitch = switch("Name hits from RadioReference (your own Premium login)", Prefs.radioReferenceOn(this)) {
+ val rrSwitch = switch("Name hits from RadioReference", Prefs.radioReferenceOn(this),
+ "Names a hit from RadioReference's database. Needs your own RadioReference Premium login and developer key, stored encrypted on this phone.") {
Prefs.setRadioReferenceOn(this, it)
}
fun secret(title: String, key: String, password: Boolean) {
@@ -939,31 +1180,31 @@ class SettingsActivity : AppCompatActivity() {
if (small) alpha = 0.75f
setPadding(0, (if (small) 0 else 10 * dp).toInt(), 0, (2 * dp).toInt())
}.also { box.addView(it) }
- fun switch(t: String, on: Boolean, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {
+ fun switch(t: String, on: Boolean, info: String? = null, save: (Boolean) -> Unit) = SwitchMaterial(this).apply {
text = t; isChecked = on
setOnCheckedChangeListener { _, v -> save(v) }
- }.also { box.addView(it) }
+ }.also { box.addView(if (info == null) it else infoRow(it, info)) }
- switch("Spoken directions", Prefs.navVoice(this)) { Prefs.setNavVoice(this, it) }
- switch("Start scanning when a destination is started", Prefs.navStartScan(this)) { Prefs.setNavStartScan(this, it) }
- label("A scan that is already running is left alone, and the scan keeps going after you arrive.", small = true)
+ switch("Spoken directions", Prefs.navVoice(this), "Turn-by-turn directions spoken aloud. Muting them never mutes the detection alerts.") { Prefs.setNavVoice(this, it) }
+ switch("Scan when a route starts", Prefs.navStartScan(this),
+ "Starts scanning when you start a destination. A scan already running is left alone, and the scan keeps going after you arrive.") { Prefs.setNavStartScan(this, it) }
switch("Keep the screen on while guiding", Prefs.navKeepScreenOn(this)) { Prefs.setNavKeepScreenOn(this, it) }
- switch("Night map after sunset while guiding", Prefs.navAutoNight(this)) { Prefs.setNavAutoNight(this, it) }
- label("Worked out on the phone from your position and the time. Pressing the sun / moon button on the map keeps " +
- "the look you chose instead.", small = true)
- label("Routes avoid (ticking one while you plan a route is remembered here for the next one)")
+ switch("Night map after sunset", Prefs.navAutoNight(this),
+ "While guiding, the map turns dark after sunset, worked out on the phone from your position and the time. " +
+ "Pressing the sun / moon button on the map keeps the look you chose instead.") { Prefs.setNavAutoNight(this, it) }
+ box.addView(infoRow(label("Routes avoid").also { box.removeView(it) },
+ "Ticking one while you plan a route is remembered here for the next one.\n\n" +
+ "Speed cameras and plate readers: routes go round the cameras of the camera map (Known cameras) where there is a way round, " +
+ "and each route says what is left on it. The cameras along the route are fetched first if they are not on the phone. " +
+ "A camera right at the start or end, or on the only bridge, can't be avoided. A detour can be longer."))
switch("Tolls", Prefs.navAvoidTolls(this)) { Prefs.setNavAvoidTolls(this, it) }
switch("Highways", Prefs.navAvoidHighways(this)) { Prefs.setNavAvoidHighways(this, it) }
switch("Ferries", Prefs.navAvoidFerries(this)) { Prefs.setNavAvoidFerries(this, it) }
switch("Speed cameras", Prefs.navAvoidSpeedCameras(this)) { Prefs.setNavAvoidSpeedCameras(this, it) }
- switch("Plate readers (ALPR)", Prefs.navAvoidPlateReaders(this)) { Prefs.setNavAvoidPlateReaders(this, it) }
- label("Routes go round the cameras of the camera map (Known cameras) where there is a way round, and each route says " +
- "what is left on it. The cameras along the route are fetched first if they are not on the phone (Known cameras > " +
- "Download automatically). A camera right at the start or end, or on the only bridge, can't be avoided. A detour can be longer.",
- small = true)
-
- label("Distances in")
- val units = listOf("auto" to "Automatic (by the phone's region)", "km" to "Kilometres", "mi" to "Miles")
+ switch("Plate readers", Prefs.navAvoidPlateReaders(this)) { Prefs.setNavAvoidPlateReaders(this, it) }
+
+ box.addView(infoRow(label("Distances in").also { box.removeView(it) }, "Automatic follows the phone's region."))
+ val units = listOf("auto" to "Automatic", "km" to "Kilometres", "mi" to "Miles")
val group = android.widget.RadioGroup(this)
for ((key, text) in units) {
group.addView(android.widget.RadioButton(this).apply {
@@ -1003,8 +1244,14 @@ class SettingsActivity : AppCompatActivity() {
setupMapProvider()
setupMapZoom()
setupMapTilt()
+ binding.mapMarkerButton.text = com.rfsentinel.app.ui.MarkerPicker.summary(this) + " ▾"
+ binding.mapMarkerButton.setOnClickListener {
+ com.rfsentinel.app.ui.MarkerPicker.show(this) { binding.mapMarkerButton.text = com.rfsentinel.app.ui.MarkerPicker.summary(this) + " ▾" }
+ }
binding.mapKnownCamerasSwitch.isChecked = Prefs.showKnownAlpr(this)
binding.mapKnownCamerasSwitch.setOnCheckedChangeListener { _, on -> Prefs.setShowKnownAlpr(this, on) }
+ binding.mapAutoRecenterSwitch.isChecked = Prefs.mapAutoRecenter(this)
+ binding.mapAutoRecenterSwitch.setOnCheckedChangeListener { _, on -> Prefs.setMapAutoRecenter(this, on) }
binding.mapSpeedometerSwitch.isChecked = Prefs.mapSpeedometer(this)
binding.mapSpeedLimitLiveSwitch.isChecked = Prefs.mapSpeedLimitLive(this)
binding.mapSpeedLimitLiveSwitch.isEnabled = binding.mapSpeedometerSwitch.isChecked
@@ -1053,7 +1300,7 @@ class SettingsActivity : AppCompatActivity() {
private fun setupMapTilt() {
fun show(t: Double) {
val what = when { t <= 40 -> "flatter, more overhead"; t <= 55 -> "balanced, like Waze"; else -> "steep: far down the road" }
- binding.map3dTiltText.text = "3D view angle: ${t.toInt()}° ($what)"
+ binding.map3dTiltText.text = "3D view angle: ${t.toInt()}° · $what"
}
val t = Prefs.map3dTilt(this)
binding.map3dTiltSlider.value = t.toFloat(); show(t)
@@ -1073,7 +1320,7 @@ class SettingsActivity : AppCompatActivity() {
z <= 17.25 -> "street level, close to Waze"
else -> "very close: the next intersection"
}
- binding.mapZoomText.text = "Default zoom: ${"%.2f".format(java.util.Locale.US, z).trimEnd('0').trimEnd('.')} ($what)"
+ binding.mapZoomText.text = "Default zoom: ${"%.2f".format(java.util.Locale.US, z).trimEnd('0').trimEnd('.')} · $what"
}
val z = Prefs.mapDefaultZoom(this)
// The slider counts quarter levels (58 = 14.5 ... 74 = 18.5): whole numbers, no rounding errors.
@@ -1164,13 +1411,16 @@ class SettingsActivity : AppCompatActivity() {
}
private fun addLiveWindowSliders() {
+ val texts = mutableListOf<android.widget.TextView>()
fun slider(label: (Int) -> String, from: Int, to: Int, value: Int, save: (Int) -> Unit): com.google.android.material.slider.Slider {
val text = android.widget.TextView(this).apply {
textSize = 13f
setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0)
this.text = label(value)
}
- binding.sectionScanning.addView(text)
+ texts += text
+ binding.sectionScanning.addView(infoRow(text, "How long a device stays in the list and radar after it was last heard. " +
+ "Flagged, favourite and following devices always stay 3 minutes.", "Out of range"))
val s = com.google.android.material.slider.Slider(this).apply {
valueFrom = from.toFloat(); valueTo = to.toFloat(); stepSize = 5f
this.value = (value - value % 5).coerceIn(from, to).toFloat()
@@ -1184,11 +1434,11 @@ class SettingsActivity : AppCompatActivity() {
binding.sectionScanning.addView(s)
return s
}
- slider({ "Remove Bluetooth devices from the list after $it s out of range" }, 5, 180, Prefs.liveBleSec(this)) {
+ slider({ "Bluetooth: off the list after $it s" }, 5, 180, Prefs.liveBleSec(this)) {
Prefs.setLiveBleSec(this, it)
}
// Below 30 s only with Developer options on and a WiFi scan interval under 30 s.
- val wifiLabel = { s: Int -> "Remove WiFi devices from the list after $s s out of range" }
+ val wifiLabel = { s: Int -> "WiFi: off the list after $s s" }
val wifiSlider = slider(wifiLabel, Prefs.minLiveWifiSec(this), 180, Prefs.liveWifiSec(this)) {
Prefs.setLiveWifiSec(this, it)
}
@@ -1203,8 +1453,7 @@ class SettingsActivity : AppCompatActivity() {
if (wifiSlider.value < min) {
wifiSlider.value = min.toFloat()
Prefs.setLiveWifiSec(this@SettingsActivity, min)
- (binding.sectionScanning.getChildAt(binding.sectionScanning.indexOfChild(wifiSlider) - 1)
- as? android.widget.TextView)?.text = wifiLabel(min)
+ texts.last().text = wifiLabel(min)
}
wifiSlider.valueFrom = min.toFloat()
}
@@ -1252,13 +1501,11 @@ class SettingsActivity : AppCompatActivity() {
orientation = android.widget.LinearLayout.VERTICAL
setPadding((24 * dp).toInt(), 0, 0, (8 * dp).toInt())
}
- box.addView(android.widget.TextView(this).apply {
- text = WAZE_WARNING_SHORT
- textSize = 12f
- alpha = 0.75f
- })
- val ninjaBtn = android.widget.RadioButton(this).apply { id = View.generateViewId(); text = "OpenWeb Ninja (your own API key; Waze never sees you)" }
- val directBtn = android.widget.RadioButton(this).apply { id = View.generateViewId(); text = "Waze direct (no key; sends a position rounded to 1 km to Waze)" }
+ box.addView(infoRow(android.widget.TextView(this).apply { text = "Source"; textSize = 12f; alpha = 0.75f },
+ "OpenWeb Ninja: your own API key; Waze never sees you. It doesn't offer traffic jams as alerts.\n\n" +
+ "Waze direct: free and live, no key. Uses an anonymous Waze account on this phone and sends a position rounded to 1 km to Waze."))
+ val ninjaBtn = android.widget.RadioButton(this).apply { id = View.generateViewId(); text = "OpenWeb Ninja" }
+ val directBtn = android.widget.RadioButton(this).apply { id = View.generateViewId(); text = "Waze direct" }
val backendGroup = android.widget.RadioGroup(this).apply { addView(ninjaBtn); addView(directBtn) }
box.addView(backendGroup)
// Two independent ranges (both backends): how close a report must be to alert, and how far the map shows them.
@@ -1336,12 +1583,11 @@ class SettingsActivity : AppCompatActivity() {
box.addView(ninjaInterval)
// Behaviour switches: each has a line under it saying what it does.
fun switchRow(label: String, hint: String, checked: Boolean, save: (Boolean) -> Unit) {
- box.addView(SwitchMaterial(this).apply {
+ box.addView(infoRow(SwitchMaterial(this).apply {
text = label
isChecked = checked
setOnCheckedChangeListener { _, on -> save(on) }
- })
- box.addView(android.widget.TextView(this).apply { text = hint; textSize = 11f; alpha = 0.6f })
+ }, hint))
}
switchRow("Slower when parked, faster on fast roads",
"Parked for 90 s: checks run 4 times less often. Over 80 km/h: twice as often (Waze direct only).",
@@ -1394,15 +1640,6 @@ class SettingsActivity : AppCompatActivity() {
})
box.addView(row)
}
- val jamNote = android.widget.TextView(this).apply {
- text = "OpenWeb Ninja doesn't offer traffic jams as alerts; they only come through Waze direct."
- textSize = 11f; alpha = 0.6f
- }
- box.addView(jamNote)
- val directNote = android.widget.TextView(this).apply {
- text = "Direct: free and live. Uses an anonymous Waze account on this phone."
- textSize = 12f; alpha = 0.75f
- }
val forgetBtn = android.widget.Button(this).apply {
text = "Forget Waze account"
setOnClickListener {
@@ -1412,7 +1649,7 @@ class SettingsActivity : AppCompatActivity() {
}
val directBox = android.widget.LinearLayout(this).apply {
orientation = android.widget.LinearLayout.VERTICAL
- addView(directNote); addView(forgetBtn)
+ addView(forgetBtn)
}
box.addView(directBox)
wazeKeyInput = android.widget.EditText(this).apply {
@@ -1426,7 +1663,6 @@ class SettingsActivity : AppCompatActivity() {
fun showBackend(direct: Boolean) {
wazeKeyInput?.visibility = if (direct) View.GONE else View.VISIBLE
directInterval.visibility = if (direct) View.VISIBLE else View.GONE
- jamNote.visibility = if (direct) View.GONE else View.VISIBLE
ninjaInterval.visibility = if (direct) View.GONE else View.VISIBLE
directBox.visibility = if (direct) View.VISIBLE else View.GONE
}
@@ -1481,7 +1717,80 @@ class SettingsActivity : AppCompatActivity() {
}
private fun updateBannerButtons() {
- binding.bannerClearButton.isEnabled = ThemeManager.hasBanner(this)
+ binding.bannerClearButton.isEnabled = ThemeManager.hasGlobalBanner(this)
+ }
+
+ /** The built-in themes, then your own (long-press one to edit it), then the buttons to make or import one. */
+ private fun buildThemeList() {
+ binding.themeGroup.removeAllViews()
+ val current = ThemeManager.current(this)
+ val custom = ThemeManager.custom(this)
+ ThemeManager.builtIn.forEach { t ->
+ val unavailable = t == ThemeManager.AppTheme.MATERIAL_YOU && !ThemeManager.isDynamicColorAvailable
+ binding.themeGroup.addView(RadioButton(this).apply {
+ id = View.generateViewId()
+ text = t.title
+ isChecked = t == current
+ setOnCheckedChangeListener { _, checked ->
+ if (checked && t != ThemeManager.current(this@SettingsActivity)) {
+ resumeScroll = binding.root.scrollY
+ ThemeManager.set(this@SettingsActivity, t)
+ recreate()
+ }
+ }
+ })
+ }
+ CustomThemes.all(this).forEach { c ->
+ binding.themeGroup.addView(RadioButton(this).apply {
+ id = View.generateViewId()
+ text = c.name
+ isChecked = current == ThemeManager.AppTheme.CUSTOM && custom?.id == c.id
+ setOnCheckedChangeListener { _, checked ->
+ if (checked && !(ThemeManager.current(this@SettingsActivity) == ThemeManager.AppTheme.CUSTOM && ThemeManager.custom(this@SettingsActivity)?.id == c.id)) {
+ resumeScroll = binding.root.scrollY
+ ThemeManager.setCustom(this@SettingsActivity, c.id)
+ recreate()
+ }
+ }
+ setOnLongClickListener { editTheme(c.id); true }
+ })
+ }
+ }
+
+ private fun editTheme(id: String?) {
+ startActivity(Intent(this, com.rfsentinel.app.ui.ThemeMakerActivity::class.java).apply { if (id != null) putExtra(com.rfsentinel.app.ui.ThemeMakerActivity.EXTRA_ID, id) })
+ }
+
+ private val themeFilePicker = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->
+ if (uri == null) return@registerForActivityResult
+ ThemeImport.open(this, uri) { resumeScroll = binding.root.scrollY; recreate() }
+ }
+
+ private fun setupThemeButtons() {
+ val box = binding.sectionAppearance
+ val at = box.indexOfChild(binding.themeGroup) + 1
+ val row = android.widget.LinearLayout(this).apply { orientation = android.widget.LinearLayout.VERTICAL }
+ fun btn(text: String, onClick: () -> Unit) = com.google.android.material.button.MaterialButton(this, null, com.google.android.material.R.attr.materialButtonOutlinedStyle).apply {
+ this.text = text; setOnClickListener { onClick() }
+ }.also { row.addView(it, android.widget.LinearLayout.LayoutParams(-1, -2)) }
+ // The themes' descriptions, in the ⓘ of a "Theme" label above the list.
+ val themesInfo = ThemeManager.builtIn.joinToString("\n\n") { t ->
+ t.title + ": " + t.description +
+ if (t == ThemeManager.AppTheme.MATERIAL_YOU && !ThemeManager.isDynamicColorAvailable) " (this phone: standard Material 3 colours)" else ""
+ } + "\n\nYour own themes are listed after these: long-press one to edit it."
+ box.addView(infoRow(android.widget.TextView(this).apply {
+ text = "Theme"; setPadding(0, (10 * resources.displayMetrics.density).toInt(), 0, 0); textSize = 13f
+ }, themesInfo), at - 1)
+ btn("Create a custom theme...") { editTheme(null) }
+ btn("Edit a theme...") {
+ val all = CustomThemes.all(this)
+ if (all.isEmpty()) Toast.makeText(this, "You have no custom themes yet", Toast.LENGTH_SHORT).show()
+ else AlertDialog.Builder(this).setTitle("Edit which theme?")
+ .setItems(all.map { it.name }.toTypedArray()) { _, i -> editTheme(all[i].id) }.show()
+ }
+ btn("Import a theme file...") { themeFilePicker.launch(arrayOf("application/json", "text/plain", "*/*")) }
+ info(row.getChildAt(0), "Make your own theme: colours, font, banner, header and map marker. Export it as a file to share it.")
+ box.addView(row, at + 1)
}
override fun onDestroy() {
@@ -1513,23 +1822,8 @@ class SettingsActivity : AppCompatActivity() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
// Appearance: applied immediately (the screen restyles itself).
- val current = ThemeManager.current(this)
- ThemeManager.AppTheme.entries.forEach { t ->
- val unavailable = t == ThemeManager.AppTheme.MATERIAL_YOU && !ThemeManager.isDynamicColorAvailable
- binding.themeGroup.addView(RadioButton(this).apply {
- id = View.generateViewId()
- text = t.title + " \u2014 " + t.description +
- if (unavailable) " (this phone: standard Material 3 colours)" else ""
- isChecked = t == current
- setOnCheckedChangeListener { _, checked ->
- if (checked && t != ThemeManager.current(this@SettingsActivity)) {
- resumeScroll = binding.root.scrollY
- ThemeManager.set(this@SettingsActivity, t)
- recreate()
- }
- }
- })
- }
+ buildThemeList()
+ setupThemeButtons()
resumeScroll?.let { y ->
binding.root.post {
@@ -1601,11 +1895,13 @@ class SettingsActivity : AppCompatActivity() {
// Categories
for (c in Category.entries) {
+ val (short, more) = splitTitle(c.title)
val sw = SwitchMaterial(this).apply {
- text = c.title
+ text = short
isChecked = Prefs.categoryEnabled(this@SettingsActivity, c)
}
- binding.categoryContainer.addView(sw)
+ val details = listOfNotNull(more, if (c == Category.POLICE_REPORT) WAZE_WARNING_SHORT else null).joinToString("\n\n")
+ binding.categoryContainer.addView(if (details.isEmpty()) sw else infoRow(sw, details, short))
categorySwitches[c] = sw
if (c == Category.TRACKER) {
airTagSwitch = SwitchMaterial(this).apply {
@@ -1742,6 +2038,7 @@ class SettingsActivity : AppCompatActivity() {
setupNavSection()
setupRadioSection()
setupLiveExport()
+ addDetails()
binding.hideTrustedSwitch.isChecked = Prefs.hideWhitelisted(this)
binding.hideTrustedSwitch.setOnCheckedChangeListener { _, on -> Prefs.setHideWhitelisted(this, on) }
binding.usbLightSwitch.isChecked = Prefs.usbAdapterLight(this)
@@ -1797,6 +2094,12 @@ class SettingsActivity : AppCompatActivity() {
// Data
binding.retentionInput.setText(Prefs.retentionDays(this).toString())
binding.exportAllButton.setOnClickListener { com.rfsentinel.app.util.Exporter.showExportMenu(this) }
+ binding.importHistoryButton.setOnClickListener {
+ startActivity(Intent(this, com.rfsentinel.app.ui.DeviceHistoryActivity::class.java)
+ .putExtra(com.rfsentinel.app.ui.DeviceHistoryActivity.EXTRA_IMPORT, true))
+ }
+ binding.backupSettingsButton.setOnClickListener { backupPicker.launch(com.rfsentinel.app.util.SettingsBackup.fileName()) }
+ binding.restoreSettingsButton.setOnClickListener { restorePicker.launch(arrayOf("application/json", "text/plain", "*/*")) }
// Lists, tools & about (moved here from the main screen's menu).
binding.openWatchlistButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.ouilist.OuiListActivity::class.java)) }
binding.openWhitelistButton.setOnClickListener { startActivity(Intent(this, com.rfsentinel.app.whitelist.WhitelistActivity::class.java)) }
@@ -1832,6 +2135,8 @@ class SettingsActivity : AppCompatActivity() {
override fun onResume() {
super.onResume()
+ // Back from the theme maker: its themes may have changed.
+ if (loaded) buildThemeList()
updatePcap()
// The user may be coming back from Developer options.
updateWifiThrottleHint()
@@ -1900,7 +2205,11 @@ class SettingsActivity : AppCompatActivity() {
}
/** Settings save themselves: whenever this screen is left (back, home, another screen). */
+ /** A restored backup is in place: leaving Settings must not write the old on-screen values over it. */
+ private var restored = false
+
override fun onPause() {
+ if (restored) { super.onPause(); return }
saveSecrets()
// Leaving Settings ends any sound preview (not an intro played by a starting scan).
com.rfsentinel.app.util.AlertPlayer.stopPreview(stopIntro = introTesting)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/CustomColors.kt b/app/src/main/java/com/rfsentinel/app/ui/CustomColors.kt
new file mode 100644
index 0000000..11abee9
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/CustomColors.kt
@@ -0,0 +1,136 @@
+// Material's colour science (the palettes Material You makes) and its colour-resource override are marked internal to the library;
+// they are what DynamicColors itself uses, pinned with the Material version and covered by CustomThemeTest.
+@file:android.annotation.SuppressLint("RestrictedApi")
+
+package com.rfsentinel.app.ui
+
+import android.app.Activity
+import android.content.Context
+import android.content.res.Configuration
+import android.os.Build
+import androidx.annotation.ColorInt
+import com.google.android.material.color.ColorResourcesOverride
+import com.google.android.material.color.MaterialColorUtilitiesHelper
+import com.google.android.material.color.ThemeUtils
+import com.google.android.material.color.utilities.DynamicScheme
+import com.google.android.material.color.utilities.Hct
+import com.google.android.material.color.utilities.SchemeContent
+import com.google.android.material.color.utilities.SchemeExpressive
+import com.google.android.material.color.utilities.SchemeFidelity
+import com.google.android.material.color.utilities.SchemeFruitSalad
+import com.google.android.material.color.utilities.SchemeMonochrome
+import com.google.android.material.color.utilities.SchemeNeutral
+import com.google.android.material.color.utilities.SchemeRainbow
+import com.google.android.material.color.utilities.SchemeTonalSpot
+import com.google.android.material.color.utilities.SchemeVibrant
+
+/**
+ * The colours of a custom theme: Material 3's palette grown from the accent you pick (the same colour science Android's
+ * own Material You uses), light or dark, or pure black for an OLED screen. Applied by overriding the colour resources the
+ * Material 3 dynamic-colour theme overlay reads, which Android can do from version 11; older phones keep the standard
+ * colours (the font, banner, header and marker still apply).
+ */
+object CustomColors {
+
+ enum class Scheme(val key: String, val label: String) {
+ TONAL("tonal", "Balanced"), VIBRANT("vibrant", "Vivid"), NEUTRAL("neutral", "Muted"), EXPRESSIVE("expressive", "Playful"),
+ CONTENT("content", "Match my accent"), FIDELITY("fidelity", "Faithful"), MONOCHROME("monochrome", "Grey"),
+ RAINBOW("rainbow", "Rainbow"), FRUIT("fruit", "Fruit salad");
+
+ companion object { fun of(key: String?) = entries.firstOrNull { it.key == key } ?: TONAL }
+ }
+
+ enum class Mode(val key: String, val label: String) {
+ SYSTEM("system", "Follow the phone"), LIGHT("light", "Light"), DARK("dark", "Dark"), BLACK("black", "Pure black (OLED)");
+
+ companion object { fun of(key: String?) = entries.firstOrNull { it.key == key } ?: SYSTEM }
+ }
+
+ /** Whether this phone can recolour the app (Android 11 or newer). */
+ val available: Boolean get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.R
+
+ /** Dark or light, as this theme's mode says (the phone's own setting for "follow"). */
+ fun isDark(context: Context, t: CustomTheme): Boolean = when (Mode.of(t.mode)) {
+ Mode.LIGHT -> false
+ Mode.DARK, Mode.BLACK -> true
+ Mode.SYSTEM -> (context.resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES
+ }
+
+ fun scheme(t: CustomTheme, dark: Boolean): DynamicScheme {
+ val hct = Hct.fromInt(t.accent)
+ return when (Scheme.of(t.scheme)) {
+ Scheme.TONAL -> SchemeTonalSpot(hct, dark, 0.0)
+ Scheme.VIBRANT -> SchemeVibrant(hct, dark, 0.0)
+ Scheme.NEUTRAL -> SchemeNeutral(hct, dark, 0.0)
+ Scheme.EXPRESSIVE -> SchemeExpressive(hct, dark, 0.0)
+ Scheme.CONTENT -> SchemeContent(hct, dark, 0.0)
+ Scheme.FIDELITY -> SchemeFidelity(hct, dark, 0.0)
+ Scheme.MONOCHROME -> SchemeMonochrome(hct, dark, 0.0)
+ Scheme.RAINBOW -> SchemeRainbow(hct, dark, 0.0)
+ Scheme.FRUIT -> SchemeFruitSalad(hct, dark, 0.0)
+ }
+ }
+
+ /**
+ * The colour resources to override and their new values. With the pure-black mode the dark backgrounds and surfaces
+ * become black (the raised containers a step lighter, so cards still show).
+ */
+ fun overrides(context: Context, t: CustomTheme, dark: Boolean = isDark(context, t)): Map<Int, Int> {
+ val map = HashMap(MaterialColorUtilitiesHelper.createColorResourcesIdsToColorValues(scheme(t, dark)))
+ if (dark && Mode.of(t.mode) == Mode.BLACK) {
+ for (id in map.keys.toList()) {
+ val name = runCatching { context.resources.getResourceEntryName(id) }.getOrNull() ?: continue
+ blackFor(name)?.let { map[id] = it }
+ }
+ }
+ return map
+ }
+
+ /**
+ * The theme's colours by token name ("primary", "surface_container", "on_surface"...), read straight from the palette:
+ * what the maker's preview paints with (Android caches resource colours, so a preview through resources would not change).
+ */
+ fun palette(context: Context, t: CustomTheme, dark: Boolean): Map<String, Int> {
+ val out = HashMap<String, Int>()
+ for ((id, c) in overrides(context, t, dark)) {
+ val name = runCatching { context.resources.getResourceEntryName(id) }.getOrNull() ?: continue
+ if (name.startsWith("material_personalized_color_")) out[name.removePrefix("material_personalized_color_")] = c
+ }
+ return out
+ }
+
+ /** The colour for a background / surface token in the pure-black mode (the overrides are of the dark palette then); null for any other token. */
+ internal fun blackFor(entryName: String): Int? {
+ if (!entryName.startsWith("material_personalized_color_")) return null
+ return when (entryName.removePrefix("material_personalized_color_")) {
+ "background", "surface", "surface_dim", "surface_container_lowest" -> 0xFF000000.toInt()
+ "surface_container_low" -> 0xFF0A0A0A.toInt()
+ "surface_container" -> 0xFF111111.toInt()
+ "surface_container_high" -> 0xFF181818.toInt()
+ "surface_container_highest", "surface_bright", "surface_variant" -> 0xFF202020.toInt()
+ else -> null
+ }
+ }
+
+ private val overlay get() = com.google.android.material.R.style.ThemeOverlay_Material3_DynamicColors_DayNight
+
+ /** Recolours an activity that is being created (before its views exist). False when this phone can't. */
+ fun apply(activity: Activity, t: CustomTheme): Boolean {
+ if (!available) return false
+ ThemeUtils.applyThemeOverlay(activity, overlay)
+ return ColorResourcesOverride.getInstance()?.applyIfPossible(activity, overrides(activity, t)) ?: false
+ }
+
+ /** A context in which views come out in this theme's colours (the maker's preview); [dark] says which way round. */
+ fun preview(base: Context, t: CustomTheme, dark: Boolean): Context {
+ val cfg = Configuration(base.resources.configuration)
+ cfg.uiMode = (cfg.uiMode and Configuration.UI_MODE_NIGHT_MASK.inv()) or (if (dark) Configuration.UI_MODE_NIGHT_YES else Configuration.UI_MODE_NIGHT_NO)
+ var ctx: Context = base.createConfigurationContext(cfg)
+ if (available) ctx = ColorResourcesOverride.getInstance()?.wrapContextIfPossible(ctx, overrides(ctx, t, dark)) ?: ctx
+ return androidx.appcompat.view.ContextThemeWrapper(ctx, com.rfsentinel.app.R.style.Theme_RFSentinel_Custom).also {
+ if (available) it.theme.applyStyle(overlay, true)
+ }
+ }
+
+ @ColorInt fun accentOf(t: CustomTheme): Int = t.accent
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/CustomTheme.kt b/app/src/main/java/com/rfsentinel/app/ui/CustomTheme.kt
new file mode 100644
index 0000000..2725a48
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/CustomTheme.kt
@@ -0,0 +1,284 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.util.Base64
+import androidx.core.content.edit
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.File
+import java.util.Locale
+
+/** The parts of a custom theme that import can replace one at a time. */
+enum class ThemePart(val label: String) {
+ COLORS("Colors (accent, palette, background)"),
+ FONT("Font"),
+ BANNER("Banner image"),
+ HEADER("Header style and title"),
+ MARKER("Position marker")
+}
+
+/**
+ * A theme made in the theme maker: colours grown from one accent, a font, a banner image, the header on the home screen and
+ * the position marker. Only the choices are kept here (the banner and a font file live in the theme's own folder).
+ */
+data class CustomTheme(
+ val id: String,
+ val name: String,
+ val accent: Int = 0xFF1E6FE0.toInt(),
+ /** [CustomColors.Scheme.key]: how the palette is grown from the accent. */
+ val scheme: String = "tonal",
+ /** [CustomColors.Mode.key]: follow the phone, light, dark or pure black. */
+ val mode: String = "system",
+ /** A [FontApplier] family key, or "file" for the theme's own font file. */
+ val font: String = "default",
+ val fontFile: String? = null,
+ val banner: String? = null,
+ /** A [ThemeHeaderView.Style] name, or null for no animated header. */
+ val header: String? = null,
+ val title: String? = null,
+ val markerStyle: String? = null,
+ val markerColor: String? = null,
+ val markerSize: Float? = null
+) {
+ fun toJson(): JSONObject = JSONObject().put("id", id).put("name", name).put("accent", accent).put("scheme", scheme).put("mode", mode)
+ .put("font", font).put("fontFile", fontFile ?: JSONObject.NULL).put("banner", banner ?: JSONObject.NULL)
+ .put("header", header ?: JSONObject.NULL).put("title", title ?: JSONObject.NULL)
+ .put("markerStyle", markerStyle ?: JSONObject.NULL).put("markerColor", markerColor ?: JSONObject.NULL)
+ .put("markerSize", markerSize?.toDouble() ?: JSONObject.NULL)
+
+ /** Which of the five parts of this theme differ from the defaults (what a shared file carries). */
+ val parts: Set<ThemePart> get() = buildSet {
+ add(ThemePart.COLORS)
+ if (font != "default") add(ThemePart.FONT)
+ if (banner != null) add(ThemePart.BANNER)
+ if (header != null || !title.isNullOrBlank()) add(ThemePart.HEADER)
+ if (markerStyle != null) add(ThemePart.MARKER)
+ }
+
+ companion object {
+ private fun JSONObject.str(k: String): String? = if (isNull(k)) null else optString(k).takeIf { it.isNotBlank() }
+
+ /** Reads one theme, cleaning every value (unknown words become the defaults) so a hand-edited file can't break the app. */
+ fun fromJson(o: JSONObject, id: String = o.optString("id")): CustomTheme {
+ val styles = ThemeHeaderView.Style.entries.map { it.name }
+ val markerStyles = MarkerArt.Style.entries.map { it.key }
+ val colors = MarkerArt.colors.map { it.key }
+ val font = o.str("font")?.takeIf { it == "file" || it in FontApplier.keys } ?: "default"
+ val markerStyle = o.str("markerStyle")?.takeIf { it in markerStyles }
+ return CustomTheme(
+ id = id,
+ name = (o.str("name") ?: "My theme").trim().take(40),
+ accent = (o.optLong("accent", 0xFF1E6FE0L).toInt() or 0xFF000000.toInt()),
+ scheme = o.str("scheme")?.takeIf { s -> CustomColors.Scheme.entries.any { it.key == s } } ?: "tonal",
+ mode = o.str("mode")?.takeIf { m -> CustomColors.Mode.entries.any { it.key == m } } ?: "system",
+ font = font,
+ fontFile = o.str("fontFile")?.let { safeName(it) }.takeIf { font == "file" },
+ banner = o.str("banner")?.let { safeName(it) },
+ header = o.str("header")?.takeIf { it in styles },
+ title = o.str("title")?.trim()?.take(40),
+ markerStyle = markerStyle,
+ markerColor = if (markerStyle == null) null else o.str("markerColor")?.takeIf { it in colors } ?: "blue",
+ markerSize = if (markerStyle == null) null else if (o.isNull("markerSize")) 1.0f else o.optDouble("markerSize", 1.0).toFloat().coerceIn(0.6f, 2.0f)
+ )
+ }
+
+ /** A file name that can't point out of the theme's folder. */
+ fun safeName(s: String) = s.substringAfterLast('/').substringAfterLast('\\').filter { it.isLetterOrDigit() || it in "._-" }.take(60)
+ }
+}
+
+/** The custom themes on this phone, and sharing them as files (a theme with its banner and font in one JSON file). */
+object CustomThemes {
+ private const val PREFS = "custom_themes"
+ private const val KEY = "list"
+ const val MAX_THEMES = 30
+ const val MAX_BANNER_BYTES = 4 * 1024 * 1024
+ const val MAX_FONT_BYTES = 6 * 1024 * 1024
+ const val FORMAT = 1
+
+ private fun sp(c: Context) = c.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+
+ fun all(c: Context): List<CustomTheme> = runCatching {
+ val a = JSONArray(sp(c).getString(KEY, "[]"))
+ (0 until a.length()).mapNotNull { i -> a.optJSONObject(i)?.takeIf { it.optString("id").isNotBlank() }?.let { CustomTheme.fromJson(it) } }
+ }.getOrDefault(emptyList())
+
+ fun get(c: Context, id: String?): CustomTheme? = id?.let { all(c).firstOrNull { t -> t.id == it } }
+
+ private fun write(c: Context, list: List<CustomTheme>) {
+ sp(c).edit(commit = true) { putString(KEY, JSONArray().also { a -> list.forEach { a.put(it.toJson()) } }.toString()) }
+ }
+
+ fun save(c: Context, t: CustomTheme) {
+ val list = all(c).toMutableList()
+ val i = list.indexOfFirst { it.id == t.id }
+ if (i >= 0) list[i] = t else list.add(t)
+ write(c, list.takeLast(MAX_THEMES))
+ }
+
+ fun delete(c: Context, id: String) {
+ write(c, all(c).filter { it.id != id })
+ dir(c, id).deleteRecursively()
+ }
+
+ fun newId(): String = "t" + java.util.UUID.randomUUID().toString().replace("-", "").take(10)
+
+ /** A name not used by another theme ("My theme", "My theme 2"...). */
+ fun uniqueName(c: Context, wanted: String, exceptId: String? = null): String {
+ val taken = all(c).filter { it.id != exceptId }.map { it.name.lowercase(Locale.US) }.toSet()
+ val base = wanted.trim().ifEmpty { "My theme" }.take(36)
+ if (base.lowercase(Locale.US) !in taken) return base
+ var n = 2
+ while ("$base $n".lowercase(Locale.US) in taken) n++
+ return "$base $n"
+ }
+
+ fun dir(c: Context, id: String) = File(c.filesDir, "custom_themes/${CustomTheme.safeName(id)}")
+ fun bannerFile(c: Context, t: CustomTheme): File? = t.banner?.let { File(dir(c, t.id), it) }?.takeIf { it.isFile && it.length() > 0 }
+ fun fontFile(c: Context, t: CustomTheme): File? = t.fontFile?.let { File(dir(c, t.id), it) }?.takeIf { it.isFile && it.length() > 0 }
+
+ /** Changes whenever the theme's choices or its files do: what tells an open screen it is out of date. */
+ fun stamp(c: Context, t: CustomTheme): String =
+ t.hashCode().toString() + ":" + (bannerFile(c, t)?.lastModified() ?: 0L) + ":" + (fontFile(c, t)?.lastModified() ?: 0L)
+
+ /** Whether these bytes are a picture of at most 4 MB. */
+ fun isImage(bytes: ByteArray): Boolean {
+ if (bytes.isEmpty() || bytes.size > MAX_BANNER_BYTES) return false
+ val o = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }
+ android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, o)
+ return o.outWidth > 0 && o.outHeight > 0
+ }
+
+ /** Replaces the theme's banner with these image bytes (a picture of at most 4 MB); returns the updated theme, or null when it isn't an image. */
+ fun setBanner(c: Context, t: CustomTheme, bytes: ByteArray): CustomTheme? {
+ if (!isImage(bytes)) return null
+ val d = dir(c, t.id).apply { mkdirs() }
+ t.banner?.let { File(d, it).delete() }
+ val name = "banner"
+ File(d, name).writeBytes(bytes)
+ return t.copy(banner = name)
+ }
+
+ fun clearBanner(c: Context, t: CustomTheme): CustomTheme { t.banner?.let { File(dir(c, t.id), it).delete() }; return t.copy(banner = null) }
+
+ /** Gives the theme its own font file (a .ttf or .otf of at most 6 MB that loads as a font); null when it isn't one. */
+ fun setFont(c: Context, t: CustomTheme, bytes: ByteArray): CustomTheme? {
+ if (bytes.isEmpty() || bytes.size > MAX_FONT_BYTES) return null
+ val d = dir(c, t.id).apply { mkdirs() }
+ val tmp = File(d, "font.tmp"); tmp.writeBytes(bytes)
+ if (loadFont(tmp) == null) { tmp.delete(); return null }
+ t.fontFile?.let { File(d, it).delete() }
+ tmp.renameTo(File(d, "font"))
+ return t.copy(font = "file", fontFile = "font")
+ }
+
+ /** The font in this file, or null when it isn't a TrueType / OpenType font that loads. */
+ fun loadFont(f: File): android.graphics.Typeface? = runCatching {
+ val head = f.inputStream().use { s -> ByteArray(4).also { s.read(it) } }
+ val magic = head[0] == 0.toByte() && head[1] == 1.toByte() || head[0] == 'O'.code.toByte() || head[0] == 't'.code.toByte()
+ if (magic) android.graphics.Typeface.createFromFile(f) else null
+ }.getOrNull()
+
+ /** Takes the theme's own font file away (it goes back to the standard font). */
+ fun clearFont(c: Context, t: CustomTheme): CustomTheme { t.fontFile?.let { File(dir(c, t.id), it).delete() }; return t.copy(font = "default", fontFile = null) }
+
+ /** A copy of the theme with its own files; saved and returned. */
+ fun duplicate(c: Context, t: CustomTheme): CustomTheme {
+ val shared = parseShared(toShareJson(c, t))
+ return import(c, shared, null, ThemePart.entries.toSet(), t.name + " copy")
+ }
+
+ // ---- sharing: one JSON file with the choices and the theme's own files ---------------------------------
+
+ class Shared(val theme: CustomTheme, val banner: ByteArray?, val font: ByteArray?)
+ class BadThemeFile(message: String) : Exception(message)
+
+ private fun shareObject(c: Context, t: CustomTheme): JSONObject {
+ val assets = JSONObject()
+ bannerFile(c, t)?.let { assets.put("banner", Base64.encodeToString(it.readBytes(), Base64.NO_WRAP)) }
+ fontFile(c, t)?.let { assets.put("font", Base64.encodeToString(it.readBytes(), Base64.NO_WRAP)) }
+ return JSONObject().put("app", "RF Sentinel").put("type", "theme").put("format", FORMAT).put("theme", t.toJson()).put("assets", assets)
+ }
+
+ fun toShareJson(c: Context, t: CustomTheme): String = shareObject(c, t).toString(2)
+
+ fun parseShared(text: String): Shared {
+ val root = runCatching { JSONObject(text) }.getOrNull() ?: throw BadThemeFile("That isn't a theme file (not valid JSON)")
+ return parseShared(root)
+ }
+
+ fun parseShared(root: JSONObject): Shared {
+ if (root.optString("app") != "RF Sentinel" || root.optString("type") != "theme") throw BadThemeFile("That isn't an RF Sentinel theme file")
+ if (root.optInt("format", 0) !in 1..FORMAT) throw BadThemeFile("That theme is from a newer version of RF Sentinel - update the app first")
+ val t = root.optJSONObject("theme") ?: throw BadThemeFile("The theme file has no theme in it")
+ val a = root.optJSONObject("assets")
+ fun asset(k: String, max: Int) = a?.optString(k)?.takeIf { it.isNotEmpty() }?.let { s ->
+ runCatching { Base64.decode(s, Base64.DEFAULT) }.getOrNull()?.takeIf { it.size in 1..max }
+ }
+ return Shared(CustomTheme.fromJson(t, id = ""), asset("banner", MAX_BANNER_BYTES)?.takeIf { isImage(it) }, asset("font", MAX_FONT_BYTES))
+ }
+
+ /** Which of the five parts the file really carries (one without a banner offers no banner to take). */
+ fun partsIn(s: Shared): Set<ThemePart> = buildSet {
+ add(ThemePart.COLORS)
+ if (s.theme.font != "default" && (s.theme.font != "file" || s.font != null)) add(ThemePart.FONT)
+ if (s.banner != null) add(ThemePart.BANNER)
+ if (s.theme.header != null || !s.theme.title.isNullOrBlank()) add(ThemePart.HEADER)
+ if (s.theme.markerStyle != null) add(ThemePart.MARKER)
+ }
+
+ /**
+ * Takes the chosen [parts] of the shared theme: into [target] (those parts of it are replaced, the rest stays) or, with no
+ * target, into a new theme (the parts not chosen stay at the defaults). Saves and returns the result.
+ */
+ fun import(c: Context, shared: Shared, target: CustomTheme?, parts: Set<ThemePart>, newName: String? = null): CustomTheme {
+ val base = target ?: CustomTheme(id = newId(), name = uniqueName(c, newName ?: shared.theme.name))
+ val s = shared.theme
+ var t = base
+ if (ThemePart.COLORS in parts) t = t.copy(accent = s.accent, scheme = s.scheme, mode = s.mode)
+ if (ThemePart.HEADER in parts) t = t.copy(header = s.header, title = s.title)
+ if (ThemePart.MARKER in parts) t = t.copy(markerStyle = s.markerStyle, markerColor = s.markerColor, markerSize = s.markerSize)
+ if (ThemePart.FONT in parts) {
+ t = if (s.font == "file" && shared.font != null) (setFont(c, t.copy(font = "default"), shared.font) ?: t.copy(font = "default", fontFile = null))
+ else { t.fontFile?.let { File(dir(c, t.id), it).delete() }; t.copy(font = if (s.font == "file") "default" else s.font, fontFile = null) }
+ }
+ if (ThemePart.BANNER in parts) {
+ t = if (shared.banner != null) (setBanner(c, t, shared.banner) ?: clearBanner(c, t)) else clearBanner(c, t)
+ }
+ save(c, t)
+ return t
+ }
+
+ // ---- the settings backup carries every theme with its files ---------------------------------------------
+
+ fun backup(c: Context): JSONArray = JSONArray().also { a ->
+ for (t in all(c)) a.put(shareObject(c, t).put("id", t.id))
+ }
+
+ /** Reads the backup's themes (throws [BadThemeFile] for a damaged one) without changing anything. */
+ fun parseBackup(a: JSONArray): List<Pair<String, Shared>> {
+ val incoming = ArrayList<Pair<String, Shared>>()
+ for (i in 0 until a.length()) {
+ val o = a.optJSONObject(i) ?: continue
+ val id = CustomTheme.safeName(o.optString("id")).ifEmpty { newId() }
+ incoming += id to parseShared(o)
+ }
+ return incoming
+ }
+
+ /** Puts the backup's themes in place of this phone's; returns how many. */
+ fun restoreBackup(c: Context, a: JSONArray): Int = applyBackup(c, parseBackup(a))
+
+ fun applyBackup(c: Context, incoming: List<Pair<String, Shared>>): Int {
+ for (t in all(c)) dir(c, t.id).deleteRecursively()
+ write(c, emptyList())
+ for ((id, s) in incoming.take(MAX_THEMES)) {
+ val base = s.theme.copy(id = id, banner = null, font = if (s.theme.font == "file") "default" else s.theme.font, fontFile = null)
+ var t = base
+ if (s.banner != null) t = setBanner(c, t, s.banner) ?: t
+ if (s.theme.font == "file" && s.font != null) t = setFont(c, t, s.font) ?: t
+ save(c, t)
+ }
+ return minOf(incoming.size, MAX_THEMES)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt
index 5aecc5d..1eeadd0 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/DeviceHistoryActivity.kt
@@ -60,6 +60,7 @@ class DeviceHistoryActivity : AppCompatActivity() {
binding.filterChips.addView(chip)
}
binding.searchInput.doAfterTextChanged { search(now = false) }
+ if (intent.getBooleanExtra(EXTRA_IMPORT, false) && savedInstanceState == null) binding.root.post { pickFile() }
binding.keptText.setOnClickListener {
startActivity(Intent(this, com.rfsentinel.app.settings.SettingsActivity::class.java)
.putExtra(com.rfsentinel.app.settings.SettingsActivity.EXTRA_SECTION, com.rfsentinel.app.settings.SettingsActivity.SECTION_DATA))
@@ -106,7 +107,63 @@ class DeviceHistoryActivity : AppCompatActivity() {
override fun onSupportNavigateUp(): Boolean { finish(); return true }
- private companion object { const val LIMIT = 500 }
+ override fun onCreateOptionsMenu(menu: android.view.Menu): Boolean {
+ menu.add(0, 1, 0, "Export history...")
+ menu.add(0, 2, 1, "Import history from a file...")
+ return true
+ }
+
+ override fun onOptionsItemSelected(item: android.view.MenuItem): Boolean = when (item.itemId) {
+ 1 -> { com.rfsentinel.app.util.Exporter.showHistoryExport(this); true }
+ 2 -> { pickFile(); true }
+ else -> super.onOptionsItemSelected(item)
+ }
+
+ /** A history file written by Export (JSON or CSV), or the "everything" export, to add to what the phone remembers. */
+ private val importPicker = registerForActivityResult(androidx.activity.result.contract.ActivityResultContracts.OpenDocument()) { uri ->
+ if (uri != null) importFrom(uri)
+ }
+
+ private fun pickFile() = importPicker.launch(arrayOf("application/json", "text/csv", "text/comma-separated-values", "text/plain", "*/*"))
+
+ private fun importFrom(uri: android.net.Uri) {
+ val progress = android.widget.TextView(this).apply { text = "Reading the file..."; setPadding(64, 32, 64, 8) }
+ val dialog = androidx.appcompat.app.AlertDialog.Builder(this).setTitle("Importing device history").setView(progress).setCancelable(false).show()
+ lifecycleScope.launch {
+ val result = runCatching {
+ kotlinx.coroutines.withContext(kotlinx.coroutines.Dispatchers.IO) {
+ val dao = com.rfsentinel.app.data.AppDatabase.getInstance(this@DeviceHistoryActivity).knownDeviceDao()
+ contentResolver.openInputStream(uri)!!.use { raw ->
+ com.rfsentinel.app.util.DeviceHistoryImport.importInto(dao, com.rfsentinel.app.util.DeviceHistoryImport.Limited(raw)) { n ->
+ runOnUiThread { if (!isDestroyed) progress.text = "$n devices read..." }
+ }
+ }
+ }
+ }
+ if (isFinishing || isDestroyed) return@launch
+ dialog.dismiss()
+ val r = result.getOrNull()
+ if (r == null) {
+ val why = (result.exceptionOrNull() as? com.rfsentinel.app.util.DeviceHistoryImport.NotHistory)?.message ?: "Couldn't read that file (${result.exceptionOrNull()?.message ?: "unknown error"})"
+ androidx.appcompat.app.AlertDialog.Builder(this@DeviceHistoryActivity).setTitle("Not imported").setMessage(why).setPositiveButton("OK", null).show()
+ return@launch
+ }
+ com.rfsentinel.app.data.Favorites.load(this@DeviceHistoryActivity)
+ search(now = true)
+ val keep = Prefs.retentionDays(this@DeviceHistoryActivity)
+ androidx.appcompat.app.AlertDialog.Builder(this@DeviceHistoryActivity).setTitle("History imported")
+ .setMessage("${r.added} new devices, ${r.updated} updated, ${r.unchanged} already there" +
+ (if (r.skipped > 0) ", ${r.skipped} entries skipped (not a device)" else "") + "." +
+ (if (keep > 0) "\n\nDevices not seen for more than $keep days are removed again at the next scan unless starred (Settings > Data > Keep history)." else ""))
+ .setPositiveButton("OK", null).show()
+ }
+ }
+
+ companion object {
+ private const val LIMIT = 500
+ /** Open straight on the file picker for an import (Settings > Data). */
+ const val EXTRA_IMPORT = "import"
+ }
/** One device: name (or MAC) and type, then vendor and MAC, then when it was seen. */
private class Rows(private val open: (KnownDeviceEntity) -> Unit) :
diff --git a/app/src/main/java/com/rfsentinel/app/ui/FontApplier.kt b/app/src/main/java/com/rfsentinel/app/ui/FontApplier.kt
new file mode 100644
index 0000000..eb57f73
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/FontApplier.kt
@@ -0,0 +1,78 @@
+package com.rfsentinel.app.ui
+
+import android.app.Activity
+import android.content.Context
+import android.graphics.Typeface
+import android.os.Handler
+import android.os.Looper
+import android.view.View
+import android.view.ViewGroup
+import android.view.ViewTreeObserver
+import android.widget.TextView
+import androidx.core.content.res.ResourcesCompat
+import com.rfsentinel.app.R
+import java.util.WeakHashMap
+
+/**
+ * The font of a custom theme. Android themes can't choose a font from a file at run time, so every text on a screen is set to
+ * it after the screen is laid out (and again when lists and dialogs inside it add new views). Bold and italic are kept.
+ * System dialogs and the keyboard keep the phone's font.
+ */
+object FontApplier {
+
+ /** The built-in choices: the phone's own font families, and the app's bundled Share Tech Mono. */
+ class Family(val key: String, val label: String, val system: String?)
+
+ val families = listOf(
+ Family("default", "Standard", null),
+ Family("medium", "Medium sans", "sans-serif-medium"),
+ Family("light", "Light sans", "sans-serif-light"),
+ Family("condensed", "Condensed", "sans-serif-condensed"),
+ Family("serif", "Serif", "serif"),
+ Family("mono", "Monospace", "monospace"),
+ Family("serif-mono", "Typewriter", "serif-monospace"),
+ Family("casual", "Casual", "casual"),
+ Family("cursive", "Cursive", "cursive"),
+ Family("tech", "Share Tech Mono (the DedSec look)", null)
+ )
+
+ val keys: Set<String> = families.map { it.key }.toSet()
+
+ /** The typeface for a theme, or null for the standard font. */
+ fun typeface(context: Context, t: CustomTheme): Typeface? = when {
+ t.font == "default" -> null
+ t.font == "file" -> CustomThemes.fontFile(context, t)?.let { runCatching { Typeface.createFromFile(it) }.getOrNull() }
+ t.font == "tech" -> runCatching { ResourcesCompat.getFont(context, R.font.share_tech_mono) }.getOrNull()
+ else -> families.firstOrNull { it.key == t.font }?.system?.let { Typeface.create(it, Typeface.NORMAL) }
+ }
+
+ private val main = Handler(Looper.getMainLooper())
+ private val listeners = WeakHashMap<Activity, ViewTreeObserver.OnGlobalLayoutListener>()
+
+ /** Starts keeping [activity]'s texts in [base]; a null [base] stops it (the standard font is back at the next screen). */
+ fun attach(activity: Activity, base: Typeface?) {
+ detach(activity)
+ if (base == null) return
+ val decor = activity.window?.decorView ?: return
+ var pending = false
+ val run = Runnable { pending = false; apply(decor, base) }
+ val l = ViewTreeObserver.OnGlobalLayoutListener { if (!pending) { pending = true; main.postDelayed(run, 120) } }
+ listeners[activity] = l
+ decor.viewTreeObserver.addOnGlobalLayoutListener(l)
+ apply(decor, base)
+ }
+
+ fun detach(activity: Activity) {
+ listeners.remove(activity)?.let { l -> runCatching { activity.window?.decorView?.viewTreeObserver?.removeOnGlobalLayoutListener(l) } }
+ }
+
+ /** Sets the font on every text under [root] (and on [root] itself). */
+ fun apply(root: View, base: Typeface) {
+ if (root is TextView) {
+ val style = root.typeface?.style ?: Typeface.NORMAL
+ val want = Typeface.create(base, style)
+ if (root.typeface != want) root.typeface = want
+ }
+ if (root is ViewGroup) for (i in 0 until root.childCount) apply(root.getChildAt(i), base)
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt
index a7386bd..9cb01d9 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapEngine.kt
@@ -97,6 +97,8 @@ internal interface MapEngine {
// ---- your position ----
/** Shows your arrow (once the style is in); false without location permission. */
+ /** The picture of your position, turned with your heading (null: the engine's own arrow); applied now or when the puck starts. */
+ fun setMarker(bitmap: Bitmap?)
fun startPuck(): Boolean
val puckOn: Boolean
fun pushFix(fix: Location)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
index 8fb8f47..436c07b 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapFragment.kt
@@ -110,6 +110,18 @@ class MapFragment : Fragment() {
else -> base - (kmh - 30f) / 80f * 1.6
}
+ /** After panning or zooming the map, it goes back to following you once this long has passed without a touch. */
+ const val RECENTER_AFTER_MS = 10_000L
+
+ /**
+ * Whether the live map should take you back to your position now: the setting is on, it is not following you, nobody is
+ * looking at a place's card, you are driving (guided, or moving at walking pace or faster) and the map has been left alone
+ * for [afterMs]. Parked and browsing, it stays where you put it.
+ */
+ internal fun shouldRecenter(enabled: Boolean, following: Boolean, live: Boolean, guiding: Boolean, speedMs: Float,
+ placeCardOpen: Boolean, idleMs: Long, afterMs: Long = RECENTER_AFTER_MS): Boolean =
+ enabled && live && !following && !placeCardOpen && idleMs >= afterMs && (guiding || speedMs >= HEADING_MIN_SPEED_MS)
+
/** The flat views (north up / heading up) sit this much wider than the 3D view at the same default. */
internal const val FLAT_ZOOM_OFFSET = 0.5
@@ -320,6 +332,7 @@ class MapFragment : Fragment() {
try {
val e = MapEngine.create(act)
engine = e
+ markerKey = "" // the new engine has not been given the marker yet
binding.map.addView(e.view, 0, ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
binding.osmCredit.text = e.credit
e.onCreate(state)
@@ -368,8 +381,8 @@ class MapFragment : Fragment() {
r.onStaticChanged = { if (alive) { renderLive(); refreshServiceLocation() } }
m.setMinZoom(2.0)
// Two fingers in 3D: a pinch is your zoom now (until the follow button).
- m.onUserGesture = { if (following) userZoom = true }
- m.onFollowDismissed = { if (alive && following) { following = false; styleFollowButton() } }
+ m.onUserGesture = { touchedAt = android.os.SystemClock.elapsedRealtime(); if (following) userZoom = true }
+ m.onFollowDismissed = { touchedAt = android.os.SystemClock.elapsedRealtime(); if (alive && following) { following = false; styleFollowButton() } }
m.onCameraMove = { updateScale() }
m.onIdle = { r.safe("static") { r.maybeRedrawStatic(); updateScale() } }
m.onClick = { x, y -> r.safe("tap") { r.onTap(x, y, myPosition()) } }
@@ -849,8 +862,20 @@ class MapFragment : Fragment() {
// ---- Your position --------------------------------------------------------------------------------
+ private var markerKey = ""
+
+ /** The marker chosen in Settings > Map: given to the map engine whenever the choice has changed. */
+ private fun applyMarker() {
+ val m = map ?: return
+ val key = MarkerPicker.effective(act).key
+ if (key == markerKey) return
+ markerKey = key
+ m.setMarker(MarkerPicker.current(act))
+ }
+
private fun startLocation() {
val m = map ?: return
+ applyMarker()
if (!m.startPuck()) return
(lastFix ?: knownFix())?.let { m.pushFix(steady(it)) }
applyMode(animate = false)
@@ -868,10 +893,15 @@ class MapFragment : Fragment() {
private val gpsListener = LocationListenerCompat { fix -> rf?.safe("fix") { onFix(fix) } ?: onFix(fix) }
+ /** When the map was last touched (panned, pinched...): the auto-recenter counts from it. */
+ private var touchedAt = 0L
+
private fun onFix(fix: Location) {
if (!alive) return
lastFix = fix
gpsFix = fix
+ if (shouldRecenter(Prefs.mapAutoRecenter(act), following, tripId == null, Navigator.active, if (fix.hasSpeed()) fix.speed else 0f,
+ nav?.cardShown == true, android.os.SystemClock.elapsedRealtime() - touchedAt)) setFollow(true, quiet = true)
if (tripId == null && !Navigator.active && Prefs.mapSpeedometer(act) && Prefs.mapSpeedLimitLive(act) && fix.hasSpeed())
com.rfsentinel.app.nav.SpeedLimits.Live.onFix(fix.latitude, fix.longitude, fix.speed)
updateGauge()
@@ -1119,6 +1149,7 @@ class MapFragment : Fragment() {
super.onResume()
engine?.onResume()
swapEngineIfChanged()
+ applyMarker() // back from Settings > Map: a new marker shows at once
startGps()
// Precise GPS while the map is on screen, so devices land where they were heard.
if (tripId == null) ScanForegroundService.mapShown(act)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
index 3299d94..107c7d1 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapLibreEngine.kt
@@ -50,6 +50,8 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
const val DARK_STYLE = "https://tiles.openfreemap.org/styles/fiord"
const val CREDIT = "© OpenFreeMap © OpenMapTiles © OpenStreetMap contributors"
private const val BUILDINGS = "rf-buildings-3d"
+ /** A clear picture, for the puck layers that must show nothing. */
+ private const val BLANK = "rf-puck-blank"
private const val GRASS = "rf-night-grass"
/** Style properties whose value is a plain array, not an expression. */
private val ARRAY_PROPERTIES = setOf("text-font", "text-offset", "icon-offset", "line-dasharray", "text-variable-anchor", "text-translate", "icon-translate", "circle-translate", "fill-translate", "line-translate")
@@ -126,6 +128,7 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
val m = map ?: return
m.setStyle(Style.Builder().fromUri(if (dark) DARK_STYLE else LIGHT_STYLE)) { style ->
if (dark) runCatching { nightTweaks(style) }
+ addMarkerImage(style)
loaded(true)
}
}
@@ -313,6 +316,38 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
override val puckOn get() = component() != null
+ private var marker: Bitmap? = null
+ private var markerName: String? = null
+ private var markerVersion = 0
+
+ private fun puckOptions(name: String?) = LocationComponentOptions.builder(context)
+ .pulseEnabled(false)
+ .accuracyAnimationEnabled(false)
+ .trackingGesturesManagement(true) // a one-finger pan stops following; a pinch keeps it
+ .apply {
+ if (name != null) {
+ // The marker keeps its size at every zoom (it is drawn at the size chosen in Settings).
+ gpsName(name).foregroundName(name).foregroundStaleName(name).bearingName(name)
+ // The engine's own arrow, ring and shadow behind it are replaced by nothing.
+ .backgroundName(BLANK).backgroundStaleName(BLANK).elevation(0f)
+ .minZoomIconScale(1f).maxZoomIconScale(1f)
+ }
+ }.build()
+
+ /** The marker's picture in the current style (a style that loads later needs it again). */
+ private fun addMarkerImage(style: Style) {
+ marker?.let { b -> markerName?.let { style.addImage(it, b); style.addImage(BLANK, Bitmap.createBitmap(2, 2, Bitmap.Config.ARGB_8888)) } }
+ }
+
+ override fun setMarker(bitmap: Bitmap?) {
+ marker = bitmap
+ markerName = bitmap?.let { "rf-puck-${++markerVersion}" }
+ val style = style()
+ if (style != null) addMarkerImage(style)
+ // A running puck changes picture at once (the name is new, so the old one is not reused).
+ component()?.applyStyle(puckOptions(markerName))
+ }
+
@SuppressLint("MissingPermission") // checked first
override fun startPuck(): Boolean {
val m = map ?: return false
@@ -321,11 +356,8 @@ internal class MapLibreEngine(private val context: Context) : MapEngine {
val lc = m.locationComponent
// Light / dark switch: the component moves to the new style by itself.
if (!lc.isLocationComponentActivated) {
- val options = LocationComponentOptions.builder(context)
- .pulseEnabled(false)
- .accuracyAnimationEnabled(false)
- .trackingGesturesManagement(true) // a one-finger pan stops following; a pinch keeps it
- .build()
+ addMarkerImage(style)
+ val options = puckOptions(markerName)
// Fixes come from the screen, so slow ones can keep the last real heading before the map sees them.
lc.activateLocationComponent(LocationComponentActivationOptions.builder(context, style)
.useDefaultLocationEngine(false)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt b/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt
index a2abaca..670c5ca 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapNav.kt
@@ -133,7 +133,7 @@ internal class MapNav(
b.navEnd.setOnClickListener { Navigator.stop() }
b.navMenu.setOnClickListener { menu(it) }
b.navOverview.setOnClickListener { overview() }
- b.navMute.setOnClickListener { Prefs.setNavVoice(act, !Prefs.navVoice(act)); styleMute() }
+ b.navMute.setOnClickListener { toggleDirections() }
if (embedded) {
b.navEtaBox.setOnClickListener { host.navOpenFull(null) }
b.navBanner.setOnClickListener { host.navOpenFull(null) }
@@ -487,7 +487,7 @@ internal class MapNav(
setOnMenuItemClickListener { item ->
val dest = Navigator.destination
when (item.itemId) {
- 1 -> { Prefs.setNavVoice(act, !Prefs.navVoice(act)); styleMute() }
+ 1 -> toggleDirections()
2 -> host.navSearch(com.rfsentinel.app.nav.NavSearchActivity.MODE_STOP)
3 -> Navigator.changeOptions(act, Navigator.options.copy(avoidTolls = !Navigator.options.avoidTolls))
4 -> Navigator.changeOptions(act, Navigator.options.copy(avoidHighways = !Navigator.options.avoidHighways))
@@ -504,6 +504,14 @@ internal class MapNav(
}
}
+ /** Spoken directions on / off; the detection alerts have their own mute and keep sounding. */
+ private fun toggleDirections() {
+ val on = !Prefs.navVoice(act)
+ Prefs.setNavVoice(act, on)
+ styleMute()
+ android.widget.Toast.makeText(act, if (on) "Spoken directions on" else "Directions muted - detection alerts still sound", android.widget.Toast.LENGTH_SHORT).show()
+ }
+
private fun styleMute() {
val on = Prefs.navVoice(act)
b.navMute.setImageResource(if (on) R.drawable.ic_car_volume else R.drawable.ic_car_volume_off)
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt b/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt
index c49b521..f04b49c 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/MapboxEngine.kt
@@ -269,13 +269,27 @@ internal class MapboxEngine(private val context: Context) : MapEngine {
private var puck = false
override val puckOn get() = puck && !destroyed
+ private var marker: Bitmap? = null
+
+ private fun puck(): com.mapbox.maps.plugin.LocationPuck = marker?.let { b ->
+ val image = com.mapbox.maps.ImageHolder.from(b)
+ // The picture is the bearing layer, which turns with your course; no fixed top picture (it would stay
+ // north up behind it), no shadow, no zoom scaling.
+ com.mapbox.maps.plugin.LocationPuck2D(topImage = null, bearingImage = image, shadowImage = null, scaleExpression = """["interpolate",["linear"],["zoom"],0,1.0,22,1.0]""")
+ } ?: createDefault2DPuck(withBearing = true)
+
+ override fun setMarker(bitmap: Bitmap?) {
+ marker = bitmap
+ if (puck && !destroyed) view.location.locationPuck = puck()
+ }
+
override fun startPuck(): Boolean {
if (destroyed) return false
if (!Permissions.granted(context, android.Manifest.permission.ACCESS_FINE_LOCATION)) return false
if (!puck) {
view.location.apply {
setLocationProvider(fixes)
- locationPuck = createDefault2DPuck(withBearing = true)
+ locationPuck = puck()
puckBearing = PuckBearing.COURSE
puckBearingEnabled = true
enabled = true
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MarkerArt.kt b/app/src/main/java/com/rfsentinel/app/ui/MarkerArt.kt
new file mode 100644
index 0000000..e39dde5
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/MarkerArt.kt
@@ -0,0 +1,310 @@
+package com.rfsentinel.app.ui
+
+import android.graphics.Bitmap
+import android.graphics.BlurMaskFilter
+import android.graphics.Canvas
+import android.graphics.LinearGradient
+import android.graphics.Paint
+import android.graphics.Path
+import android.graphics.RectF
+import android.graphics.Shader
+import android.graphics.Color
+
+/**
+ * The position marker on the map (your arrow): an arrow, or a car seen from above, in a colour of your choice.
+ * Everything is drawn here in code on a 100 x 200 unit sheet with the front at the top, so any size is sharp and
+ * any colour works; the map turns it with your direction of travel. Pure drawing: the same function makes the
+ * map's marker and the pictures in Settings.
+ */
+object MarkerArt {
+
+ enum class Style(val key: String, val label: String) {
+ ARROW("arrow", "Arrow"), CHEVRON("chevron", "Chevron"),
+ SEDAN("sedan", "Sedan"), HATCHBACK("hatchback", "Hatchback"), WAGON("wagon", "Wagon"), SUV("suv", "SUV"),
+ PICKUP("pickup", "Pickup"), SPORTS("sports", "Sports car"), RACER("racer", "Racer"), CONVERTIBLE("convertible", "Convertible"),
+ MINI("mini", "Mini"), VAN("van", "Van"), TRUCK("truck", "Truck"), TAXI("taxi", "Taxi"), MOTORCYCLE("motorcycle", "Motorcycle");
+
+ companion object {
+ fun of(key: String?) = entries.firstOrNull { it.key == key } ?: ARROW
+ }
+ }
+
+ class Swatch(val key: String, val label: String, val argb: Int) {
+ override fun toString() = label
+ }
+
+ val colors: List<Swatch> = listOf(
+ Swatch("red", "Red", 0xFFE53935.toInt()),
+ Swatch("orange", "Orange", 0xFFFB8C00.toInt()),
+ Swatch("yellow", "Yellow", 0xFFFDD835.toInt()),
+ Swatch("gold", "Gold", 0xFFC9A227.toInt()),
+ Swatch("lime", "Lime", 0xFF8BC34A.toInt()),
+ Swatch("green", "Green", 0xFF2E9E4F.toInt()),
+ Swatch("teal", "Teal", 0xFF0AA39C.toInt()),
+ Swatch("cyan", "Sky", 0xFF29B6F6.toInt()),
+ Swatch("blue", "Blue", 0xFF1E6FE0.toInt()),
+ Swatch("navy", "Navy", 0xFF1F3A93.toInt()),
+ Swatch("purple", "Purple", 0xFF8E44D6.toInt()),
+ Swatch("pink", "Pink", 0xFFEC5C9B.toInt()),
+ Swatch("white", "White", 0xFFF3F4F6.toInt()),
+ Swatch("silver", "Silver", 0xFFB8C0C8.toInt()),
+ Swatch("grey", "Grey", 0xFF6B7480.toInt()),
+ Swatch("black", "Black", 0xFF23272D.toInt())
+ )
+
+ fun colorOf(key: String?): Swatch = colors.firstOrNull { it.key == key } ?: colors.first { it.key == "blue" }
+
+ /** The marker, [heightPx] tall and half as wide, front up. */
+ fun render(style: Style, color: Int, heightPx: Int): Bitmap {
+ val h = heightPx.coerceAtLeast(16)
+ val bmp = Bitmap.createBitmap(h / 2, h, Bitmap.Config.ARGB_8888)
+ val c = Canvas(bmp)
+ c.scale(h / 200f, h / 200f)
+ when (style) {
+ Style.ARROW -> arrow(c, color, ARROW)
+ Style.CHEVRON -> arrow(c, color, CHEVRON)
+ Style.SEDAN -> car(c, color, SEDAN)
+ Style.HATCHBACK -> car(c, color, HATCHBACK)
+ Style.WAGON -> car(c, color, WAGON)
+ Style.SUV -> car(c, color, SUV)
+ Style.PICKUP -> car(c, color, PICKUP)
+ Style.SPORTS -> car(c, color, SPORTS)
+ Style.RACER -> car(c, color, RACER)
+ Style.CONVERTIBLE -> car(c, color, CONVERTIBLE)
+ Style.MINI -> car(c, color, MINI)
+ Style.VAN -> car(c, color, VAN)
+ Style.TAXI -> car(c, color, TAXI)
+ Style.TRUCK -> truck(c, color)
+ Style.MOTORCYCLE -> motorcycle(c, color)
+ }
+ return bmp
+ }
+
+ // ---- colours ---------------------------------------------------------------------------------------
+
+ private fun shade(c: Int, f: Float) = Color.argb(Color.alpha(c),
+ (Color.red(c) * f).toInt().coerceIn(0, 255), (Color.green(c) * f).toInt().coerceIn(0, 255), (Color.blue(c) * f).toInt().coerceIn(0, 255))
+
+ private fun lighten(c: Int, t: Float) = Color.argb(Color.alpha(c),
+ (Color.red(c) + (255 - Color.red(c)) * t).toInt(), (Color.green(c) + (255 - Color.green(c)) * t).toInt(), (Color.blue(c) + (255 - Color.blue(c)) * t).toInt())
+
+ private const val GLASS = 0xFF1E2B38.toInt()
+ private const val GLASS_HI = 0xFF3E5C78.toInt()
+ private const val DARK = 0xFF14171B.toInt()
+ private const val HEADLIGHT = 0xFFFFF3B0.toInt()
+ private const val TAILLIGHT = 0xFFD32F2F.toInt()
+ private const val CX = 50f
+
+ private fun fill(color: Int) = Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL; this.color = color }
+ private fun line(color: Int, width: Float) = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ style = Paint.Style.STROKE; this.color = color; strokeWidth = width; strokeJoin = Paint.Join.ROUND; strokeCap = Paint.Cap.ROUND
+ }
+
+ /** The paint for a body: the colour, a little darker towards both sides so it reads as round. */
+ private fun bodyPaint(color: Int, left: Float, right: Float) = Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ shader = LinearGradient(left, 0f, right, 0f,
+ intArrayOf(shade(color, 0.74f), color, lighten(color, 0.14f), color, shade(color, 0.74f)),
+ floatArrayOf(0f, 0.22f, 0.5f, 0.78f, 1f), Shader.TileMode.CLAMP)
+ }
+
+ private fun rr(c: Canvas, l: Float, t: Float, r: Float, b: Float, rad: Float, p: Paint) = c.drawRoundRect(RectF(l, t, r, b), rad, rad, p)
+
+ private fun softShadow(c: Canvas, path: Path) {
+ val p = fill(0x66000000).apply { maskFilter = BlurMaskFilter(5f, BlurMaskFilter.Blur.NORMAL) }
+ c.save(); c.translate(2f, 4f); c.drawPath(path, p); c.restore()
+ }
+
+ // ---- arrows ------------------------------------------------------------------------------------------
+
+ private val ARROW = floatArrayOf(50f, 8f, 92f, 184f, 50f, 148f, 8f, 184f)
+ private val CHEVRON = floatArrayOf(50f, 10f, 92f, 182f, 70f, 182f, 50f, 92f, 30f, 182f, 8f, 182f)
+
+ private fun poly(pts: FloatArray) = Path().apply {
+ moveTo(pts[0], pts[1]); var i = 2; while (i < pts.size) { lineTo(pts[i], pts[i + 1]); i += 2 }; close()
+ }
+
+ private fun arrow(c: Canvas, color: Int, pts: FloatArray) {
+ val path = poly(pts)
+ softShadow(c, path)
+ c.drawPath(path, line(0xFFFFFFFF.toInt(), 9f))
+ c.drawPath(path, bodyPaint(color, 8f, 92f))
+ // The left half a little lighter, as a ridge down the middle.
+ val half = Path().apply { moveTo(50f, pts[1]); lineTo(50f, if (pts.size == 8) 150f else 92f); lineTo(pts[pts.size - 2], pts[pts.size - 1]); close() }
+ c.drawPath(half, fill(0x2EFFFFFF))
+ c.drawPath(path, line(shade(color, 0.6f), 1.5f))
+ }
+
+ // ---- cars --------------------------------------------------------------------------------------------
+
+ private enum class Extra { RAILS, BED, SPOILER, STRIPES, ROOF_SIGN, OPEN_TOP, RIBS, LONG_ROOF }
+
+ /** A car from above, in 100 x 200 units: its width, front and rear, how round those are, and where the glass runs. */
+ private class Car(
+ val w: Float, val top: Float, val bottom: Float, val rf: Float, val rr: Float,
+ /** Where the windshield starts, ends (the roof starts), the roof ends (the rear window starts) and the rear window ends. */
+ val hoodEnd: Float, val wsEnd: Float, val roofEnd: Float, val rearEnd: Float,
+ val wheelsY: List<Float>, val extras: Set<Extra> = emptySet()
+ )
+
+ private val SEDAN = Car(64f, 14f, 186f, 20f, 14f, 62f, 86f, 112f, 134f, listOf(42f, 152f))
+ private val HATCHBACK = Car(62f, 20f, 180f, 20f, 12f, 62f, 86f, 126f, 144f, listOf(44f, 148f))
+ private val WAGON = Car(62f, 12f, 188f, 18f, 8f, 58f, 82f, 146f, 162f, listOf(40f, 158f))
+ private val SUV = Car(72f, 14f, 186f, 14f, 10f, 58f, 84f, 146f, 160f, listOf(40f, 158f), setOf(Extra.RAILS))
+ private val PICKUP = Car(70f, 10f, 190f, 14f, 6f, 56f, 78f, 100f, 110f, listOf(38f, 156f), setOf(Extra.BED))
+ private val SPORTS = Car(70f, 8f, 184f, 26f, 16f, 78f, 98f, 118f, 134f, listOf(34f, 150f), setOf(Extra.SPOILER))
+ private val RACER = Car(70f, 8f, 184f, 26f, 16f, 78f, 98f, 118f, 134f, listOf(34f, 150f), setOf(Extra.SPOILER, Extra.STRIPES))
+ private val CONVERTIBLE = Car(66f, 14f, 184f, 22f, 14f, 70f, 84f, 128f, 128f, listOf(40f, 152f), setOf(Extra.OPEN_TOP))
+ private val MINI = Car(60f, 40f, 168f, 22f, 16f, 72f, 90f, 118f, 134f, listOf(62f, 146f))
+ private val VAN = Car(66f, 16f, 188f, 12f, 8f, 44f, 70f, 176f, 186f, listOf(38f, 162f), setOf(Extra.RIBS, Extra.LONG_ROOF))
+ private val TAXI = Car(64f, 14f, 186f, 20f, 14f, 62f, 86f, 112f, 134f, listOf(42f, 152f), setOf(Extra.ROOF_SIGN))
+
+ private fun car(c: Canvas, color: Int, k: Car) {
+ val l = CX - k.w / 2; val r = CX + k.w / 2
+ val body = Path().apply {
+ addRoundRect(RectF(l, k.top, r, k.bottom), floatArrayOf(k.rf, k.rf, k.rf, k.rf, k.rr, k.rr, k.rr, k.rr), Path.Direction.CW)
+ }
+ softShadow(c, body)
+ // Wheels, a little out of the body at both sides.
+ val wheel = fill(DARK)
+ for (y in k.wheelsY) {
+ rr(c, l - 6.5f, y - 13f, l + 7f, y + 13f, 5f, wheel)
+ rr(c, r - 7f, y - 13f, r + 6.5f, y + 13f, 5f, wheel)
+ }
+ c.drawPath(body, line(0xFFFFFFFF.toInt(), 6f))
+ c.drawPath(body, bodyPaint(color, l, r))
+
+ if (Extra.STRIPES in k.extras) {
+ val s = fill(0xE6FFFFFF.toInt())
+ rr(c, CX - 11f, k.top + 5f, CX - 4f, k.bottom - 5f, 2f, s)
+ rr(c, CX + 4f, k.top + 5f, CX + 11f, k.bottom - 5f, 2f, s)
+ }
+ if (Extra.BED in k.extras) {
+ // The load bed: a dark tub with a lighter rim.
+ val tub = RectF(l + 5f, k.rearEnd + 2f, r - 5f, k.bottom - 5f)
+ c.drawRoundRect(tub, 4f, 4f, fill(shade(color, 0.38f)))
+ c.drawRoundRect(tub, 4f, 4f, line(lighten(color, 0.25f), 1.6f))
+ for (y in listOf(0.33f, 0.66f)) c.drawLine(tub.left + 3f, tub.top + tub.height() * y, tub.right - 3f, tub.top + tub.height() * y, line(shade(color, 0.3f), 1.2f))
+ }
+
+ // The windshield and the cabin.
+ val bw = k.w * 0.40f; val tw = k.w * 0.33f
+ if (Extra.OPEN_TOP in k.extras) {
+ val cockpit = RectF(CX - k.w * 0.37f, k.wsEnd, CX + k.w * 0.37f, k.roofEnd)
+ c.drawRoundRect(cockpit, 8f, 8f, fill(0xFF262B32.toInt()))
+ val seat = fill(0xFF55616E.toInt())
+ rr(c, CX - k.w * 0.31f, k.wsEnd + 10f, CX - 3f, k.wsEnd + 34f, 6f, seat)
+ rr(c, CX + 3f, k.wsEnd + 10f, CX + k.w * 0.31f, k.wsEnd + 34f, 6f, seat)
+ windshield(c, bw, tw, k.hoodEnd, k.wsEnd)
+ } else {
+ windshield(c, bw, tw, k.hoodEnd, k.wsEnd)
+ // The roof, a touch lighter than the rest, with its edge.
+ val roof = RectF(CX - tw, k.wsEnd, CX + tw, k.roofEnd)
+ val long = Extra.LONG_ROOF in k.extras
+ c.drawRoundRect(roof, if (long) 5f else 8f, if (long) 5f else 8f, fill(lighten(color, 0.18f)))
+ c.drawRoundRect(roof, if (long) 5f else 8f, if (long) 5f else 8f, line(shade(color, 0.62f), 1.4f))
+ if (Extra.RAILS in k.extras) {
+ val rail = line(0xFF30363D.toInt(), 2.2f)
+ c.drawLine(CX - tw * 0.72f, k.wsEnd + 5f, CX - tw * 0.72f, k.roofEnd - 5f, rail)
+ c.drawLine(CX + tw * 0.72f, k.wsEnd + 5f, CX + tw * 0.72f, k.roofEnd - 5f, rail)
+ }
+ if (Extra.RIBS in k.extras) {
+ val rib = line(shade(color, 0.7f), 1.4f)
+ var y = k.wsEnd + 14f
+ while (y < k.roofEnd - 8f) { c.drawLine(CX - tw + 4f, y, CX + tw - 4f, y, rib); y += 18f }
+ }
+ if (Extra.ROOF_SIGN in k.extras) {
+ val s = RectF(CX - 10f, (k.wsEnd + k.roofEnd) / 2 - 6f, CX + 10f, (k.wsEnd + k.roofEnd) / 2 + 6f)
+ c.drawRoundRect(s, 3f, 3f, fill(0xFFFFE082.toInt()))
+ c.drawRoundRect(s, 3f, 3f, line(0xFF3A3A3A.toInt(), 1.4f))
+ }
+ if (k.rearEnd > k.roofEnd + 2f) {
+ val rear = Path().apply {
+ moveTo(CX - tw, k.roofEnd); lineTo(CX + tw, k.roofEnd)
+ lineTo(CX + k.w * 0.37f, k.rearEnd); lineTo(CX - k.w * 0.37f, k.rearEnd); close()
+ }
+ c.drawPath(rear, Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ shader = LinearGradient(0f, k.roofEnd, 0f, k.rearEnd, GLASS, GLASS_HI, Shader.TileMode.CLAMP)
+ })
+ }
+ }
+ if (Extra.SPOILER in k.extras) {
+ rr(c, l + 1f, k.bottom - 16f, r - 1f, k.bottom - 9f, 3f, fill(0xFF1A1D21.toInt()))
+ }
+ // Mirrors, lights.
+ val mirror = fill(shade(color, 0.72f))
+ c.drawOval(RectF(l - 5f, k.hoodEnd - 8f, l + 2f, k.hoodEnd + 2f), mirror)
+ c.drawOval(RectF(r - 2f, k.hoodEnd - 8f, r + 5f, k.hoodEnd + 2f), mirror)
+ val head = fill(HEADLIGHT); val tail = fill(TAILLIGHT)
+ rr(c, l + 5f, k.top + 3f, l + 17f, k.top + 9f, 3f, head)
+ rr(c, r - 17f, k.top + 3f, r - 5f, k.top + 9f, 3f, head)
+ rr(c, l + 4f, k.bottom - 9f, l + 15f, k.bottom - 3f, 3f, tail)
+ rr(c, r - 15f, k.bottom - 9f, r - 4f, k.bottom - 3f, 3f, tail)
+ }
+
+ private fun windshield(c: Canvas, bw: Float, tw: Float, from: Float, to: Float) {
+ val p = Path().apply { moveTo(CX - bw, from); lineTo(CX + bw, from); lineTo(CX + tw, to); lineTo(CX - tw, to); close() }
+ c.drawPath(p, Paint(Paint.ANTI_ALIAS_FLAG).apply {
+ shader = LinearGradient(0f, from, 0f, to, GLASS_HI, GLASS, Shader.TileMode.CLAMP)
+ })
+ }
+
+ private fun truck(c: Canvas, color: Int) {
+ val cab = RectF(CX - 31f, 12f, CX + 31f, 72f)
+ val box = RectF(CX - 37f, 78f, CX + 37f, 192f)
+ val all = Path().apply {
+ addRoundRect(cab, floatArrayOf(18f, 18f, 18f, 18f, 4f, 4f, 4f, 4f), Path.Direction.CW)
+ addRoundRect(box, 6f, 6f, Path.Direction.CW)
+ }
+ softShadow(c, all)
+ val wheel = fill(DARK)
+ for (y in listOf(34f, 134f, 168f)) {
+ val cabSide = y < 78f
+ val l = if (cabSide) cab.left else box.left; val r = if (cabSide) cab.right else box.right
+ rr(c, l - 6.5f, y - 13f, l + 7f, y + 13f, 5f, wheel)
+ rr(c, r - 7f, y - 13f, r + 6.5f, y + 13f, 5f, wheel)
+ }
+ // The hitch between the cab and the box.
+ rr(c, CX - 14f, 68f, CX + 14f, 82f, 2f, fill(DARK))
+ val cabPath = Path().apply { addRoundRect(cab, floatArrayOf(18f, 18f, 18f, 18f, 4f, 4f, 4f, 4f), Path.Direction.CW) }
+ c.drawPath(cabPath, line(0xFFFFFFFF.toInt(), 6f))
+ c.drawRoundRect(box, 6f, 6f, line(0xFFFFFFFF.toInt(), 6f))
+ c.drawPath(cabPath, bodyPaint(color, cab.left, cab.right))
+ // The box: pale, with the colour showing in its ribs.
+ val boxColor = lighten(color, 0.82f)
+ c.drawRoundRect(box, 6f, 6f, bodyPaint(boxColor, box.left, box.right))
+ c.drawRoundRect(box, 6f, 6f, line(shade(boxColor, 0.7f), 1.4f))
+ val rib = line(shade(color, 0.9f), 2.2f)
+ var y = 94f
+ while (y < 186f) { c.drawLine(box.left + 6f, y, box.right - 6f, y, rib); y += 18f }
+ windshield(c, 26f, 21f, 36f, 52f)
+ rr(c, CX - 22f, 52f, CX + 22f, 66f, 6f, fill(lighten(color, 0.16f)))
+ val head = fill(HEADLIGHT); val tail = fill(TAILLIGHT)
+ rr(c, cab.left + 5f, 15f, cab.left + 17f, 21f, 3f, head)
+ rr(c, cab.right - 17f, 15f, cab.right - 5f, 21f, 3f, head)
+ rr(c, box.left + 4f, box.bottom - 9f, box.left + 15f, box.bottom - 3f, 3f, tail)
+ rr(c, box.right - 15f, box.bottom - 9f, box.right - 4f, box.bottom - 3f, 3f, tail)
+ }
+
+ private fun motorcycle(c: Canvas, color: Int) {
+ val frontWheel = RectF(43f, 14f, 57f, 62f)
+ val rearWheel = RectF(42f, 138f, 58f, 190f)
+ val tank = RectF(36f, 46f, 64f, 150f)
+ val shape = Path().apply { addRoundRect(tank, 14f, 14f, Path.Direction.CW) }
+ softShadow(c, shape)
+ val tyre = fill(DARK)
+ c.drawRoundRect(frontWheel, 6f, 6f, tyre); c.drawRoundRect(rearWheel, 7f, 7f, tyre)
+ c.drawPath(shape, line(0xFFFFFFFF.toInt(), 6f))
+ c.drawPath(shape, bodyPaint(color, tank.left, tank.right))
+ // Seat and the rider: shoulders, helmet, arms to the bars.
+ rr(c, 41f, 104f, 59f, 146f, 8f, fill(0xFF2A2E34.toInt()))
+ val bars = line(DARK, 5f)
+ c.drawLine(22f, 58f, 78f, 58f, bars)
+ c.drawLine(24f, 56f, 36f, 80f, line(0xFF3A3F47.toInt(), 6f)); c.drawLine(76f, 56f, 64f, 80f, line(0xFF3A3F47.toInt(), 6f))
+ c.drawOval(RectF(33f, 78f, 67f, 116f), fill(0xFF3A3F47.toInt()))
+ c.drawCircle(CX, 96f, 10f, fill(lighten(color, 0.55f)))
+ c.drawCircle(CX, 96f, 10f, line(shade(color, 0.6f), 1.5f))
+ c.drawOval(RectF(18f, 52f, 26f, 62f), fill(shade(color, 0.7f))); c.drawOval(RectF(74f, 52f, 82f, 62f), fill(shade(color, 0.7f)))
+ rr(c, 45f, 16f, 55f, 24f, 4f, fill(HEADLIGHT))
+ rr(c, 45f, 178f, 55f, 186f, 3f, fill(TAILLIGHT))
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/MarkerPicker.kt b/app/src/main/java/com/rfsentinel/app/ui/MarkerPicker.kt
new file mode 100644
index 0000000..22d2356
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/MarkerPicker.kt
@@ -0,0 +1,148 @@
+package com.rfsentinel.app.ui
+
+import android.graphics.drawable.BitmapDrawable
+import android.graphics.drawable.GradientDrawable
+import android.view.Gravity
+import android.view.View
+import android.widget.GridLayout
+import android.widget.HorizontalScrollView
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import com.google.android.material.slider.Slider
+import com.rfsentinel.app.util.Prefs
+
+/**
+ * Settings > Map > Position marker: pick the style (an arrow or a car), its colour and its size, with the result
+ * shown on a light and a dark ground as you choose. Each change is saved at once; the map shows it next time it
+ * is on screen.
+ */
+object MarkerPicker {
+
+ /** The marker's height on the map at size 1.0. */
+ const val BASE_DP = 56f
+
+ fun heightPx(context: android.content.Context, size: Float) = (BASE_DP * size * context.resources.displayMetrics.density).toInt()
+
+ /** What the map uses: the custom theme's own marker when it has one, else the choice made in Settings. */
+ class Choice(val style: String, val color: String, val size: Float) {
+ val key get() = "$style|$color|$size"
+ }
+
+ fun effective(context: android.content.Context): Choice {
+ val t = ThemeManager.custom(context)
+ return if (t?.markerStyle != null) Choice(t.markerStyle, t.markerColor ?: "blue", t.markerSize ?: 1.0f)
+ else Choice(Prefs.markerStyle(context), Prefs.markerColor(context), Prefs.markerSize(context))
+ }
+
+ /** The marker the map draws now. */
+ fun current(context: android.content.Context): android.graphics.Bitmap {
+ val c = effective(context)
+ return MarkerArt.render(MarkerArt.Style.of(c.style), MarkerArt.colorOf(c.color).argb, heightPx(context, c.size))
+ }
+
+ /** "Sedan · Blue", for the Settings button. */
+ fun summary(context: android.content.Context) =
+ MarkerArt.Style.of(Prefs.markerStyle(context)).label + " · " + MarkerArt.colorOf(Prefs.markerColor(context)).label
+
+ /** Settings: picks the marker the map uses when no custom theme sets its own. */
+ fun show(activity: AppCompatActivity, onChanged: () -> Unit) =
+ pick(activity, Choice(Prefs.markerStyle(activity), Prefs.markerColor(activity), Prefs.markerSize(activity))) { c ->
+ Prefs.setMarker(activity, c.style, c.color, c.size); onChanged()
+ }
+
+ /** The picker itself: starts from [start], reports every change through [onChanged] (the caller saves it). */
+ fun pick(activity: AppCompatActivity, start: Choice, onChanged: (Choice) -> Unit) {
+ val d = activity.resources.displayMetrics.density
+ fun px(dp: Float) = (dp * d).toInt()
+ var style = MarkerArt.Style.of(start.style)
+ var color = MarkerArt.colorOf(start.color)
+ var size = start.size.coerceIn(0.6f, 2.0f)
+
+ // The marker, as big as it is on the map, on a light and a dark ground.
+ fun ground(argb: Int) = ImageView(activity).apply {
+ background = GradientDrawable().apply { setColor(argb); cornerRadius = px(10f).toFloat() }
+ scaleType = ImageView.ScaleType.CENTER
+ setPadding(px(8f), px(8f), px(8f), px(8f))
+ }
+ val light = ground(0xFFE9EDF1.toInt()); val dark = ground(0xFF2B3446.toInt())
+ val previews = LinearLayout(activity).apply {
+ orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER
+ val lp = { LinearLayout.LayoutParams(0, px(BASE_DP * 2f + 16f), 1f).apply { marginStart = px(4f); marginEnd = px(4f) } }
+ addView(light, lp()); addView(dark, lp())
+ }
+
+ val styleCells = HashMap<MarkerArt.Style, Pair<LinearLayout, ImageView>>()
+ val grid = GridLayout(activity).apply { columnCount = 5 }
+ for (s in MarkerArt.Style.entries) {
+ val img = ImageView(activity).apply { scaleType = ImageView.ScaleType.FIT_CENTER }
+ val name = TextView(activity).apply { text = s.label; textSize = 10f; gravity = Gravity.CENTER; maxLines = 1 }
+ val cell = LinearLayout(activity).apply {
+ orientation = LinearLayout.VERTICAL; gravity = Gravity.CENTER_HORIZONTAL
+ setPadding(px(2f), px(4f), px(2f), px(4f))
+ addView(img, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, px(72f)))
+ addView(name, LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT))
+ contentDescription = s.label
+ }
+ grid.addView(cell, GridLayout.LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1f), GridLayout.spec(GridLayout.UNDEFINED, 1f)).apply { width = 0 })
+ styleCells[s] = cell to img
+ }
+
+ val swatches = LinkedHashMap<String, View>()
+ val colorRow = LinearLayout(activity).apply { orientation = LinearLayout.HORIZONTAL; setPadding(px(2f), px(6f), px(2f), px(6f)) }
+ for (sw in MarkerArt.colors) {
+ val v = View(activity).apply { contentDescription = sw.label }
+ colorRow.addView(v, LinearLayout.LayoutParams(px(36f), px(36f)).apply { marginEnd = px(8f) })
+ swatches[sw.key] = v
+ }
+
+ val sizeText = TextView(activity).apply { textSize = 14f; setPadding(0, px(8f), 0, 0) }
+ // Whole numbers on the slider (6 = 0.6 times ... 20 = 2 times): no rounding errors.
+ val slider = Slider(activity).apply { valueFrom = 6f; valueTo = 20f; stepSize = 1f; value = Math.round(size * 10f).toFloat() }
+
+ fun refresh() {
+ onChanged(Choice(style.key, color.key, size))
+ val real = MarkerArt.render(style, color.argb, heightPx(activity, size))
+ val show = if (real.height > px(BASE_DP * 2f)) MarkerArt.render(style, color.argb, px(BASE_DP * 2f)) else real
+ light.setImageDrawable(BitmapDrawable(activity.resources, show)); dark.setImageDrawable(BitmapDrawable(activity.resources, show))
+ val accent = ChipStyle.accent(activity).first
+ for ((s, pair) in styleCells) {
+ pair.second.setImageDrawable(BitmapDrawable(activity.resources, MarkerArt.render(s, color.argb, px(72f))))
+ pair.first.background = if (s == style) GradientDrawable().apply { setStroke(px(2f), accent); cornerRadius = px(8f).toFloat() } else null
+ }
+ for ((key, v) in swatches) {
+ val sw = MarkerArt.colorOf(key)
+ v.background = GradientDrawable().apply {
+ shape = GradientDrawable.OVAL; setColor(sw.argb)
+ setStroke(if (key == color.key) px(3f) else px(1f), if (key == color.key) accent else 0x55000000)
+ }
+ }
+ sizeText.text = "Size: " + "%.1f".format(java.util.Locale.US, size) + "x" + if (size == 1.0f) " (standard)" else ""
+ }
+ for ((s, pair) in styleCells) pair.first.setOnClickListener { style = s; refresh() }
+ for ((key, v) in swatches) v.setOnClickListener { color = MarkerArt.colorOf(key); refresh() }
+ slider.addOnChangeListener { _, v, fromUser -> if (fromUser) { size = v / 10f; refresh() } }
+
+ val root = LinearLayout(activity).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(px(16f), px(8f), px(16f), px(4f))
+ addView(previews)
+ addView(TextView(activity).apply { text = "Style"; textSize = 14f; setPadding(0, px(12f), 0, px(2f)) })
+ addView(grid)
+ addView(TextView(activity).apply { text = "Colour"; textSize = 14f; setPadding(0, px(8f), 0, 0) })
+ addView(HorizontalScrollView(activity).apply { isHorizontalScrollBarEnabled = false; addView(colorRow) })
+ addView(sizeText)
+ addView(slider)
+ }
+ refresh()
+ AlertDialog.Builder(activity)
+ .setTitle("Position marker")
+ .setView(ScrollView(activity).apply { addView(root) })
+ .setPositiveButton("Done", null)
+ .setNeutralButton("Reset") { _, _ -> onChanged(Choice("arrow", "blue", 1.0f)) }
+ .show()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
index d2c16b0..bcb8e5e 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SetupActivity.kt
@@ -47,6 +47,8 @@ class SetupActivity : AppCompatActivity() {
private var startAfter = true
private var prefetchOnFinish = true
private var stopObservingPrefetch: (() -> Unit)? = null
+ /** Set when the theme maker was opened from here: the list shows a new theme when we come back. */
+ private var madeTheme = false
private val permissionLauncher = registerForActivityResult(
ActivityResultContracts.RequestMultiplePermissions()
@@ -87,6 +89,11 @@ class SetupActivity : AppCompatActivity() {
}
}
+ override fun onResume() {
+ super.onResume()
+ if (madeTheme) { madeTheme = false; render() }
+ }
+
override fun onDestroy() {
stopObservingPrefetch?.invoke()
super.onDestroy()
@@ -135,7 +142,8 @@ class SetupActivity : AppCompatActivity() {
header("Pick a look", "Tap a theme to preview it right away. Pick one to continue.")
val chosen = ThemeManager.isChosen(this)
val current = ThemeManager.current(this)
- ThemeManager.AppTheme.entries.forEach { t ->
+ val custom = ThemeManager.custom(this)
+ ThemeManager.builtIn.forEach { t ->
val note = if (t == ThemeManager.AppTheme.MATERIAL_YOU && !ThemeManager.isDynamicColorAvailable)
" (this phone: standard Material 3 colours)" else ""
card(t.title, t.description + note, selected = chosen && t == current) {
@@ -150,6 +158,28 @@ class SetupActivity : AppCompatActivity() {
}
}
}
+ CustomThemes.all(this).forEach { c ->
+ card(c.name, "Your own theme", selected = chosen && current == ThemeManager.AppTheme.CUSTOM && custom?.id == c.id) {
+ if (!(ThemeManager.current(this) == ThemeManager.AppTheme.CUSTOM && ThemeManager.custom(this)?.id == c.id) || !ThemeManager.isChosen(this)) {
+ ThemeManager.setCustom(this, c.id)
+ resumeStep = step
+ resumeScroll = binding.pageScroll.scrollY
+ recreate()
+ }
+ }
+ }
+ button("Make your own theme (colours, font, banner...)") {
+ resumeStep = step
+ resumeScroll = binding.pageScroll.scrollY
+ madeTheme = true
+ startActivity(android.content.Intent(this, ThemeMakerActivity::class.java))
+ }
+ button("Import a theme file...") { themeFilePicker.launch(arrayOf("application/json", "text/plain", "*/*")) }
+ }
+
+ private val themeFilePicker = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
+ if (uri == null) return@registerForActivityResult
+ ThemeImport.open(this, uri) { resumeStep = step; resumeScroll = binding.pageScroll.scrollY; recreate() }
}
private fun region() {
diff --git a/app/src/main/java/com/rfsentinel/app/ui/SpeedGaugeView.kt b/app/src/main/java/com/rfsentinel/app/ui/SpeedGaugeView.kt
index fed424a..6ad13ff 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/SpeedGaugeView.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/SpeedGaugeView.kt
@@ -57,21 +57,22 @@ class SpeedGaugeView @JvmOverloads constructor(context: Context, attrs: Attribut
override fun onDraw(c: Canvas) {
val s = speed ?: return
val u = unit()
- val ink = if (dark) 0xFFFFFFFF.toInt() else 0xFF1B1F27.toInt()
- val bg = if (dark) 0xF0222A3A.toInt() else 0xF2FFFFFF.toInt()
val red = 0xFFD32F2F.toInt()
+ // Over the limit the whole card turns red with white writing, as in Google Maps.
+ val ink = if (over || dark) 0xFFFFFFFF.toInt() else 0xFF1B1F27.toInt()
+ val bg = if (over) red else if (dark) 0xF0222A3A.toInt() else 0xF2FFFFFF.toInt()
// The speed: a rounded card, the number big and the unit small under it.
box.set(0f, 0f, u, u)
paint.style = Paint.Style.FILL; paint.color = bg
c.drawRoundRect(box, u * 0.22f, u * 0.22f, paint)
- paint.style = Paint.Style.STROKE; paint.strokeWidth = (if (over) 3f else 1.5f) * d
- paint.color = if (over) red else if (dark) 0x55FFFFFF else 0x33000000
+ paint.style = Paint.Style.STROKE; paint.strokeWidth = (if (over) 2.5f else 1.5f) * d
+ paint.color = if (over) 0xFFFFFFFF.toInt() else if (dark) 0x55FFFFFF else 0x33000000
c.drawRoundRect(box, u * 0.22f, u * 0.22f, paint)
paint.style = Paint.Style.FILL
paint.typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
paint.textAlign = Paint.Align.CENTER
- paint.color = if (over) red else ink
+ paint.color = ink
paint.textSize = u * (if (s >= 100) 0.40f else 0.48f)
c.drawText(s.toString(), u / 2, u * 0.56f, paint)
paint.typeface = Typeface.DEFAULT
diff --git a/app/src/main/java/com/rfsentinel/app/ui/ThemeImport.kt b/app/src/main/java/com/rfsentinel/app/ui/ThemeImport.kt
new file mode 100644
index 0000000..236ff96
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/ThemeImport.kt
@@ -0,0 +1,129 @@
+package com.rfsentinel.app.ui
+
+import android.net.Uri
+import android.text.InputType
+import android.view.View
+import android.widget.ArrayAdapter
+import android.widget.CheckBox
+import android.widget.EditText
+import android.widget.LinearLayout
+import android.widget.RadioButton
+import android.widget.RadioGroup
+import android.widget.ScrollView
+import android.widget.Spinner
+import android.widget.TextView
+import android.widget.Toast
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import com.google.android.material.materialswitch.MaterialSwitch
+
+/**
+ * Importing a theme file: a box per part of the theme (colours, font, banner, header, marker) says what to take, and the
+ * choice is either a new theme or an existing one of yours whose ticked parts get replaced (the rest of it stays).
+ */
+object ThemeImport {
+
+ /** About 14 MB of text is a 4 MB picture and a 6 MB font; more than this is not a theme. */
+ private const val MAX_FILE = 16 * 1024 * 1024
+
+ /** Reads the picked file and opens the dialog; [done] is called after a theme was imported. */
+ fun open(activity: AppCompatActivity, uri: Uri, done: () -> Unit) {
+ val text = runCatching {
+ activity.contentResolver.openInputStream(uri)!!.use { s ->
+ val out = java.io.ByteArrayOutputStream(); val buf = ByteArray(64 * 1024)
+ while (true) { val n = s.read(buf); if (n < 0) break; out.write(buf, 0, n); if (out.size() > MAX_FILE) return@use null }
+ out.toString(Charsets.UTF_8.name())
+ }
+ }.getOrNull()
+ if (text == null) { Toast.makeText(activity, "Couldn't read that file (or it is too big to be a theme)", Toast.LENGTH_LONG).show(); return }
+ val shared = try { CustomThemes.parseShared(text) } catch (e: CustomThemes.BadThemeFile) {
+ AlertDialog.Builder(activity).setTitle("Not imported").setMessage(e.message).setPositiveButton("OK", null).show(); return
+ }
+ show(activity, shared, done)
+ }
+
+ fun show(activity: AppCompatActivity, shared: CustomThemes.Shared, done: () -> Unit) {
+ val dp = activity.resources.displayMetrics.density
+ fun px(v: Float) = (v * dp).toInt()
+ val mine = CustomThemes.all(activity)
+ val have = CustomThemes.partsIn(shared)
+
+ val box = LinearLayout(activity).apply { orientation = LinearLayout.VERTICAL; setPadding(px(20f), px(8f), px(20f), px(4f)) }
+ box.addView(TextView(activity).apply { text = "\"${shared.theme.name}\""; textSize = 17f; setTypeface(typeface, android.graphics.Typeface.BOLD) })
+
+ // Where it goes
+ val where = RadioGroup(activity)
+ val asNew = RadioButton(activity).apply { id = View.generateViewId(); text = "Make it a new theme"; isChecked = true }
+ val asOld = RadioButton(activity).apply { id = View.generateViewId(); text = "Change one of my themes"; isEnabled = mine.isNotEmpty() }
+ where.addView(asNew); where.addView(asOld)
+ box.addView(where, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(10f) })
+ val name = EditText(activity).apply {
+ hint = "Name of the new theme"; setText(CustomThemes.uniqueName(activity, shared.theme.name)); maxLines = 1
+ inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
+ filters = arrayOf(android.text.InputFilter.LengthFilter(40))
+ }
+ box.addView(name)
+ val which = Spinner(activity).apply {
+ adapter = ArrayAdapter(activity, android.R.layout.simple_spinner_dropdown_item, mine.map { it.name })
+ visibility = View.GONE
+ // Start with the theme in use, when it is one of mine.
+ ThemeManager.custom(activity)?.let { c -> mine.indexOfFirst { it.id == c.id }.takeIf { it >= 0 }?.let(::setSelection) }
+ }
+ box.addView(which)
+
+ // What to take
+ box.addView(TextView(activity).apply {
+ text = "What to take from the file:"; setTypeface(typeface, android.graphics.Typeface.BOLD); setPadding(0, px(14f), 0, px(2f))
+ })
+ val boxes = LinkedHashMap<ThemePart, CheckBox>()
+ var positive: android.widget.Button? = null
+ fun refreshOk() { positive?.isEnabled = boxes.values.any { it.isChecked && it.isEnabled } }
+ for (p in ThemePart.entries) {
+ val has = p in have
+ boxes[p] = CheckBox(activity).apply {
+ text = p.label + if (has) "" else " - not in this file"
+ isEnabled = has; isChecked = has
+ setOnCheckedChangeListener { _, _ -> refreshOk() }
+ }
+ box.addView(boxes.getValue(p))
+ }
+ val note = TextView(activity).apply { textSize = 12.5f; alpha = 0.75f; setPadding(0, px(6f), 0, px(6f)) }
+ box.addView(note)
+ val useNow = MaterialSwitch(activity).apply { showText = false; text = "Use it right away"; isChecked = true }
+ box.addView(useNow)
+
+ fun update() {
+ val old = asOld.isChecked
+ name.visibility = if (old) View.GONE else View.VISIBLE
+ which.visibility = if (old) View.VISIBLE else View.GONE
+ note.text = if (old) "Ticked parts replace the same parts of that theme; the others stay as they are."
+ else "Parts you don't tick stay at the standard look in the new theme."
+ }
+ where.setOnCheckedChangeListener { _, _ -> update() }
+ update()
+
+ val dialog = AlertDialog.Builder(activity).setTitle("Import theme")
+ .setView(ScrollView(activity).apply { addView(box) })
+ .setPositiveButton("Import", null)
+ .setNegativeButton("Cancel", null).create()
+ dialog.setOnShowListener {
+ val ok = dialog.getButton(AlertDialog.BUTTON_POSITIVE)
+ positive = ok
+ refreshOk()
+ ok.setOnClickListener {
+ val parts = boxes.filter { it.value.isChecked && it.value.isEnabled }.keys
+ val target = if (asOld.isChecked) mine.getOrNull(which.selectedItemPosition) else null
+ if (target == null && CustomThemes.all(activity).size >= CustomThemes.MAX_THEMES) {
+ Toast.makeText(activity, "That's ${CustomThemes.MAX_THEMES} themes - delete one first", Toast.LENGTH_LONG).show(); return@setOnClickListener
+ }
+ val result = CustomThemes.import(activity, shared, target, parts, name.text.toString())
+ dialog.dismiss()
+ if (useNow.isChecked) ThemeManager.setCustom(activity, result.id)
+ else if (ThemeManager.custom(activity)?.id == result.id) ThemeManager.refresh(activity)
+ Toast.makeText(activity, "\"${result.name}\" imported (${parts.size} of ${ThemePart.entries.size} parts)", Toast.LENGTH_LONG).show()
+ done()
+ }
+ }
+ dialog.show()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/ThemeMakerActivity.kt b/app/src/main/java/com/rfsentinel/app/ui/ThemeMakerActivity.kt
new file mode 100644
index 0000000..b3ea638
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/ui/ThemeMakerActivity.kt
@@ -0,0 +1,548 @@
+package com.rfsentinel.app.ui
+
+import android.graphics.Bitmap
+import android.graphics.BitmapFactory
+import android.graphics.Color
+import android.graphics.Typeface
+import android.os.Bundle
+import android.text.InputType
+import android.view.View
+import android.widget.ArrayAdapter
+import android.widget.EditText
+import android.widget.HorizontalScrollView
+import android.widget.ImageView
+import android.widget.LinearLayout
+import android.widget.RadioButton
+import android.widget.RadioGroup
+import android.widget.ScrollView
+import android.widget.SeekBar
+import android.widget.Spinner
+import android.widget.TextView
+import android.widget.Toast
+import androidx.activity.OnBackPressedCallback
+import androidx.activity.result.contract.ActivityResultContracts
+import androidx.appcompat.app.AlertDialog
+import androidx.appcompat.app.AppCompatActivity
+import androidx.core.widget.doAfterTextChanged
+import com.google.android.material.button.MaterialButton
+import com.google.android.material.card.MaterialCardView
+import com.google.android.material.color.MaterialColors
+import com.google.android.material.materialswitch.MaterialSwitch
+import com.rfsentinel.app.util.applySystemBarInsets
+import java.io.File
+import java.io.InputStream
+
+/**
+ * The theme maker: pick an accent colour (and how the palette grows from it), light / dark / pure black, a font (the phone's
+ * families, the DedSec Share Tech Mono, or a font file of your own), a banner picture, the animated header and title on the
+ * home screen and the position marker. Light and dark previews update as you go; nothing is saved until you save.
+ * A theme can be exported as a file, duplicated, or deleted here.
+ */
+class ThemeMakerActivity : AppCompatActivity() {
+
+ companion object {
+ /** The id of the custom theme to edit; none starts a new one. */
+ const val EXTRA_ID = "id"
+ private const val STATE = "theme"
+ private const val STATE_NEW = "new"
+
+ val accents = listOf(
+ 0xFF1E6FE0, 0xFF29B6F6, 0xFF0AA39C, 0xFF2E9E4F, 0xFF8BC34A, 0xFFFDD835, 0xFFFB8C00, 0xFFE53935,
+ 0xFFEC5C9B, 0xFF8E44D6, 0xFF3F51B5, 0xFF795548, 0xFF607D8B, 0xFFF3F4F6
+ ).map { it.toInt() }
+
+ fun headerLabel(s: ThemeHeaderView.Style) = when (s) {
+ ThemeHeaderView.Style.NIGHT_VISION -> "Night vision"
+ ThemeHeaderView.Style.FSOCIETY -> "Fsociety"
+ ThemeHeaderView.Style.HUD -> "HUD"
+ ThemeHeaderView.Style.CRT -> "CRT"
+ else -> s.name.lowercase().replaceFirstChar { it.uppercase() }
+ }
+ }
+
+ private val dp get() = resources.displayMetrics.density
+ private fun px(v: Float) = (v * dp).toInt()
+
+ /** The theme as edited now; the banner and font picked here wait in memory until it is saved. */
+ private lateinit var t: CustomTheme
+ private var isNew = false
+ private var newBanner: ByteArray? = null
+ private var newFont: ByteArray? = null
+ private var fontPreview: Typeface? = null
+ private lateinit var startJson: String
+
+ private lateinit var page: LinearLayout
+ private lateinit var previewRow: LinearLayout
+ private lateinit var bannerThumb: ImageView
+ private lateinit var bannerRemove: MaterialButton
+ private lateinit var fontGroup: RadioGroup
+ private lateinit var markerSwitch: MaterialSwitch
+ private lateinit var markerImage: ImageView
+ private lateinit var markerButton: MaterialButton
+ private lateinit var swatchRow: LinearLayout
+
+ private val bannerPicker = registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
+ if (uri == null) return@registerForActivityResult
+ val bytes = runCatching { contentResolver.openInputStream(uri)!!.use { readLimited(it, CustomThemes.MAX_BANNER_BYTES) } }.getOrNull()
+ if (bytes == null || !CustomThemes.isImage(bytes)) {
+ Toast.makeText(this, "That isn't a picture (up to 4 MB)", Toast.LENGTH_LONG).show(); return@registerForActivityResult
+ }
+ newBanner = bytes; t = t.copy(banner = "banner")
+ updateBanner(); updatePreview()
+ }
+
+ private val fontPicker = registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri ->
+ if (uri == null) { syncFontRadios(); return@registerForActivityResult }
+ val bytes = runCatching { contentResolver.openInputStream(uri)!!.use { readLimited(it, CustomThemes.MAX_FONT_BYTES) } }.getOrNull()
+ val tmp = File(cacheDir, "maker_font")
+ val face = bytes?.let { runCatching { tmp.writeBytes(it); CustomThemes.loadFont(tmp) }.getOrNull() }
+ if (bytes == null || face == null) {
+ Toast.makeText(this, "That isn't a TrueType / OpenType font (.ttf or .otf, up to 6 MB)", Toast.LENGTH_LONG).show()
+ syncFontRadios(); return@registerForActivityResult
+ }
+ newFont = bytes; fontPreview = face; t = t.copy(font = "file", fontFile = "font")
+ syncFontRadios(); updatePreview()
+ }
+
+ private val exporter = registerForActivityResult(ActivityResultContracts.CreateDocument("application/json")) { uri ->
+ if (uri == null) return@registerForActivityResult
+ val ok = runCatching {
+ val saved = CustomThemes.get(this, t.id) ?: error("not saved")
+ contentResolver.openOutputStream(uri, "wt")!!.use { it.write(CustomThemes.toShareJson(this, saved).toByteArray(Charsets.UTF_8)) }
+ }.isSuccess
+ Toast.makeText(this, if (ok) "Theme file saved - share it, others can import it" else "Couldn't write the file", Toast.LENGTH_LONG).show()
+ }
+
+ private fun readLimited(s: InputStream, max: Int): ByteArray? {
+ val out = java.io.ByteArrayOutputStream()
+ val buf = ByteArray(32 * 1024)
+ while (true) {
+ val n = s.read(buf); if (n < 0) break
+ out.write(buf, 0, n); if (out.size() > max) return null
+ }
+ return out.toByteArray()
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ val id = intent.getStringExtra(EXTRA_ID)
+ val restored = savedInstanceState?.getString(STATE)?.let { runCatching { CustomTheme.fromJson(org.json.JSONObject(it)) }.getOrNull() }
+ val existing = CustomThemes.get(this, id)
+ isNew = savedInstanceState?.getBoolean(STATE_NEW) ?: (existing == null)
+ t = restored ?: existing ?: CustomTheme(id = CustomThemes.newId(), name = CustomThemes.uniqueName(this, "My theme"))
+ startJson = (existing ?: t).toJson().toString()
+ fontPreview = FontApplier.typeface(this, t)
+
+ title = if (isNew) "New theme" else "Edit theme"
+ supportActionBar?.setDisplayHomeAsUpEnabled(true)
+ val scroll = ScrollView(this).apply { isFillViewport = true }
+ page = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL; setPadding(px(16f), px(8f), px(16f), px(24f)) }
+ scroll.addView(page)
+ setContentView(scroll)
+ scroll.applySystemBarInsets()
+ build()
+ updatePreview()
+
+ onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
+ override fun handleOnBackPressed() = leave()
+ })
+ }
+
+ override fun onSupportNavigateUp(): Boolean { leave(); return true }
+
+ override fun onSaveInstanceState(outState: Bundle) {
+ super.onSaveInstanceState(outState)
+ outState.putString(STATE, t.toJson().toString()); outState.putBoolean(STATE_NEW, isNew)
+ }
+
+ private fun dirty() = newBanner != null || newFont != null || t.toJson().toString() != startJson
+
+ private fun leave() {
+ if (!dirty()) { finish(); return }
+ AlertDialog.Builder(this).setTitle("Keep your changes?")
+ .setPositiveButton("Save") { _, _ -> if (save() != null) finish() }
+ .setNegativeButton("Discard") { _, _ -> finish() }
+ .setNeutralButton("Keep editing", null).show()
+ }
+
+ // ---- building the screen ---------------------------------------------------------------------
+
+ private fun section(title: String, hint: String? = null) {
+ page.addView(TextView(this).apply {
+ text = title; textSize = 18f; setTypeface(typeface, Typeface.BOLD)
+ setPadding(0, px(22f), 0, px(2f))
+ })
+ if (hint != null) page.addView(note(hint))
+ }
+
+ private fun note(text: String) = TextView(this).apply { this.text = text; textSize = 12.5f; alpha = 0.75f; setPadding(0, 0, 0, px(6f)) }
+
+ private fun button(text: String, onClick: () -> Unit) = MaterialButton(this, null, com.google.android.material.R.attr.materialButtonOutlinedStyle).apply {
+ this.text = text; setOnClickListener { onClick() }
+ }
+
+ private fun build() {
+ // Name
+ val name = EditText(this).apply {
+ hint = "Theme name"; setText(t.name); inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_CAP_SENTENCES
+ maxLines = 1; filters = arrayOf(android.text.InputFilter.LengthFilter(40))
+ doAfterTextChanged { t = t.copy(name = it?.toString().orEmpty()) }
+ }
+ page.addView(name, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(8f) })
+
+ // Previews
+ previewRow = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; weightSum = 2f }
+ page.addView(previewRow, LinearLayout.LayoutParams(-1, -2).apply { topMargin = px(12f) })
+ if (!CustomColors.available) page.addView(note("This phone is older than Android 11, which can't recolour apps: the colours stay standard here. The font, banner, header and marker still apply."))
+
+ // Colours
+ section("Colours", "Pick the main colour; the whole palette (buttons, cards, switches, backgrounds) grows from it, the way Android's Material You does.")
+ swatchRow = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ page.addView(HorizontalScrollView(this).apply { isHorizontalScrollBarEnabled = false; addView(swatchRow) })
+ updateSwatches()
+ page.addView(button("Custom colour...") { pickColor() }, LinearLayout.LayoutParams(-2, -2).apply { topMargin = px(6f) })
+
+ page.addView(TextView(this).apply { text = "How the palette grows"; setPadding(0, px(12f), 0, 0) })
+ page.addView(Spinner(this).apply {
+ adapter = ArrayAdapter(this@ThemeMakerActivity, android.R.layout.simple_spinner_dropdown_item, CustomColors.Scheme.entries.map { it.label })
+ setSelection(CustomColors.Scheme.entries.indexOfFirst { it.key == t.scheme }.coerceAtLeast(0))
+ onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(p: android.widget.AdapterView<*>?, v: View?, pos: Int, id: Long) {
+ val k = CustomColors.Scheme.entries[pos].key
+ if (k != t.scheme) { t = t.copy(scheme = k); updatePreview() }
+ }
+ override fun onNothingSelected(p: android.widget.AdapterView<*>?) {}
+ }
+ })
+
+ page.addView(TextView(this).apply { text = "Background"; setPadding(0, px(12f), 0, 0) })
+ val modes = RadioGroup(this)
+ CustomColors.Mode.entries.forEach { m ->
+ modes.addView(RadioButton(this).apply {
+ id = View.generateViewId(); text = m.label; isChecked = m.key == t.mode
+ setOnCheckedChangeListener { _, on -> if (on && t.mode != m.key) { t = t.copy(mode = m.key); updatePreview() } }
+ })
+ }
+ page.addView(modes)
+ page.addView(note("\"Follow the phone\" switches with Android's light / dark setting. Pure black saves battery on OLED screens."))
+
+ // Font
+ section("Font", "Used for the app's texts. System dialogs and the keyboard keep the phone's font.")
+ fontGroup = RadioGroup(this)
+ page.addView(fontGroup)
+ buildFontRadios()
+ page.addView(button("Choose a font file (.ttf / .otf)...") { fontPicker.launch(arrayOf("font/*", "application/x-font-ttf", "application/x-font-otf", "application/octet-stream", "*/*")) },
+ LinearLayout.LayoutParams(-2, -2).apply { topMargin = px(4f) })
+
+ // Banner
+ section("Banner", "A picture across the top of the home screen (a logo or artwork you own; up to 4 MB). It stays on this phone and goes into a theme file you export.")
+ bannerThumb = ImageView(this).apply { scaleType = ImageView.ScaleType.CENTER_CROP; adjustViewBounds = true; visibility = View.GONE }
+ page.addView(bannerThumb, LinearLayout.LayoutParams(-1, px(96f)))
+ val bRow = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
+ bRow.addView(button("Choose a picture...") { bannerPicker.launch("image/*") })
+ bannerRemove = button("Remove") {
+ newBanner = null; t = t.copy(banner = null); updateBanner(); updatePreview()
+ }
+ bRow.addView(bannerRemove, LinearLayout.LayoutParams(-2, -2).apply { marginStart = px(8f) })
+ page.addView(bRow)
+ updateBanner()
+
+ // Header
+ section("Home screen header", "The animated header at the top of the home screen, and its title.")
+ val styles = listOf<ThemeHeaderView.Style?>(null) + ThemeHeaderView.Style.entries
+ page.addView(Spinner(this).apply {
+ adapter = ArrayAdapter(this@ThemeMakerActivity, android.R.layout.simple_spinner_dropdown_item, styles.map { it?.let(::headerLabel) ?: "None (just the banner)" })
+ setSelection(styles.indexOfFirst { it?.name == t.header }.coerceAtLeast(0))
+ onItemSelectedListener = object : android.widget.AdapterView.OnItemSelectedListener {
+ override fun onItemSelected(p: android.widget.AdapterView<*>?, v: View?, pos: Int, id: Long) {
+ val n = styles[pos]?.name
+ if (n != t.header) { t = t.copy(header = n); updatePreview() }
+ }
+ override fun onNothingSelected(p: android.widget.AdapterView<*>?) {}
+ }
+ })
+ page.addView(EditText(this).apply {
+ hint = "Title (leave empty for \"RF Sentinel\")"; setText(t.title.orEmpty()); maxLines = 1
+ filters = arrayOf(android.text.InputFilter.LengthFilter(40))
+ doAfterTextChanged { t = t.copy(title = it?.toString()?.takeIf { s -> s.isNotBlank() }); updatePreview() }
+ })
+
+ // Marker
+ section("Position marker", "The arrow or car on the map. Off: the map uses the marker chosen in Settings.")
+ markerSwitch = MaterialSwitch(this).apply { showText = false;
+ text = "This theme has its own marker"; isChecked = t.markerStyle != null
+ setOnCheckedChangeListener { _, on ->
+ t = if (on) t.copy(markerStyle = t.markerStyle ?: "arrow", markerColor = t.markerColor ?: "blue", markerSize = t.markerSize ?: 1.0f)
+ else t.copy(markerStyle = null, markerColor = null, markerSize = null)
+ updateMarker()
+ }
+ }
+ page.addView(markerSwitch)
+ val mRow = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL }
+ markerImage = ImageView(this)
+ mRow.addView(markerImage, LinearLayout.LayoutParams(px(48f), px(72f)))
+ markerButton = button("Choose the marker...") {
+ val start = MarkerPicker.Choice(t.markerStyle ?: "arrow", t.markerColor ?: "blue", t.markerSize ?: 1.0f)
+ MarkerPicker.pick(this, start) { c -> t = t.copy(markerStyle = c.style, markerColor = c.color, markerSize = c.size); updateMarker() }
+ }
+ mRow.addView(markerButton, LinearLayout.LayoutParams(-2, -2).apply { marginStart = px(12f) })
+ page.addView(mRow)
+ updateMarker()
+
+ // Actions
+ section("Save")
+ page.addView(MaterialButton(this).apply { text = "Save and use this theme"; setOnClickListener { useIt() } }, LinearLayout.LayoutParams(-1, -2))
+ page.addView(button("Save") { if (save() != null) Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show() }, LinearLayout.LayoutParams(-1, -2))
+ page.addView(button("Save and export as a file...") {
+ val s = save() ?: return@button
+ exporter.launch("rf-sentinel-theme-" + s.name.lowercase().replace(Regex("[^a-z0-9]+"), "-").trim('-').ifEmpty { "theme" } + ".json")
+ }, LinearLayout.LayoutParams(-1, -2))
+ page.addView(button("Duplicate") { duplicate() }, LinearLayout.LayoutParams(-1, -2))
+ if (!isNew) page.addView(button("Delete this theme") { confirmDelete() }, LinearLayout.LayoutParams(-1, -2))
+ }
+
+ private fun buildFontRadios() {
+ fontGroup.removeAllViews()
+ for (f in FontApplier.families) {
+ fontGroup.addView(RadioButton(this).apply {
+ id = View.generateViewId(); tag = f.key; text = f.label; textSize = 16f
+ typeface = FontApplier.typeface(this@ThemeMakerActivity, CustomTheme("p", "p", font = f.key))
+ isChecked = t.font == f.key
+ setOnCheckedChangeListener { _, on -> if (on && t.font != f.key) { t = t.copy(font = f.key, fontFile = null); fontPreview = FontApplier.typeface(this@ThemeMakerActivity, t); updatePreview() } }
+ })
+ }
+ fontGroup.addView(RadioButton(this).apply {
+ id = View.generateViewId(); tag = "file"; text = if (newFont != null || t.fontFile != null) "My own font file" else "My own font file (none chosen yet)"; textSize = 16f
+ fontPreview?.takeIf { t.font == "file" }?.let { typeface = it }
+ isChecked = t.font == "file"
+ setOnCheckedChangeListener { _, on ->
+ if (on && t.font != "file") {
+ if (newFont != null || t.fontFile != null) { t = t.copy(font = "file"); updatePreview() }
+ else fontPicker.launch(arrayOf("*/*"))
+ }
+ }
+ })
+ }
+
+ /** After a font file was chosen (or the choice was cancelled): the radios show the real choice. */
+ private fun syncFontRadios() = buildFontRadios()
+
+ private fun updateSwatches() {
+ swatchRow.removeAllViews()
+ val all = accents + if (t.accent in accents) emptyList() else listOf(t.accent)
+ for (c in all) {
+ val on = c == t.accent
+ swatchRow.addView(View(this).apply {
+ background = android.graphics.drawable.GradientDrawable().apply {
+ shape = android.graphics.drawable.GradientDrawable.OVAL; setColor(c)
+ setStroke(px(if (on) 4f else 1f), if (on) MaterialColors.getColor(this@ThemeMakerActivity, com.google.android.material.R.attr.colorOnSurface, Color.WHITE) else 0x55888888)
+ }
+ contentDescription = "Accent colour"
+ setOnClickListener { t = t.copy(accent = c); updateSwatches(); updatePreview() }
+ }, LinearLayout.LayoutParams(px(40f), px(40f)).apply { marginEnd = px(8f); topMargin = px(6f); bottomMargin = px(6f) })
+ }
+ }
+
+ // ---- previews ----------------------------------------------------------------------------------
+
+ private fun bannerBitmap(): Bitmap? {
+ if (t.banner == null) return null
+ val bytes = newBanner ?: CustomThemes.get(this, t.id)?.let { CustomThemes.bannerFile(this, it)?.readBytes() } ?: return null
+ val o = BitmapFactory.Options().apply { inSampleSize = 4 }
+ return runCatching { BitmapFactory.decodeByteArray(bytes, 0, bytes.size, o) }.getOrNull()
+ }
+
+ private fun updateBanner() {
+ val bmp = bannerBitmap()
+ bannerThumb.visibility = if (bmp != null) View.VISIBLE else View.GONE
+ bannerThumb.setImageBitmap(bmp)
+ bannerRemove.isEnabled = t.banner != null
+ }
+
+ private fun updateMarker() {
+ val own = t.markerStyle != null
+ markerSwitch.isChecked = own
+ markerButton.isEnabled = own
+ markerImage.alpha = if (own) 1f else 0.3f
+ val c = MarkerPicker.Choice(t.markerStyle ?: "arrow", t.markerColor ?: "blue", t.markerSize ?: 1.0f)
+ markerImage.setImageBitmap(MarkerArt.render(MarkerArt.Style.of(c.style), MarkerArt.colorOf(c.color).argb, px(72f * c.size.coerceIn(0.6f, 1.4f) / 1.4f)))
+ }
+
+ private fun updatePreview() {
+ previewRow.removeAllViews()
+ for (dark in listOf(false, true)) {
+ previewRow.addView(preview(dark), LinearLayout.LayoutParams(0, -2, 1f).apply { if (dark) marginStart = px(8f) })
+ }
+ }
+
+ /** One miniature of the home screen in this theme's colours, light or dark. */
+ private fun preview(dark: Boolean): View {
+ val ctx = this
+ val p = CustomColors.palette(this, t.copy(mode = if (!dark) "light" else if (t.mode == "black") "black" else "dark"), dark)
+ val bg = p["background"] ?: if (dark) Color.BLACK else Color.WHITE
+ val onBg = p["on_surface"] ?: if (dark) Color.WHITE else Color.BLACK
+ val variant = p["on_surface_variant"] ?: onBg
+ val primary = p["primary"] ?: t.accent
+ val onPrimary = p["on_primary"] ?: Color.WHITE
+ val face = fontPreview.takeIf { t.font != "default" }
+ fun text(s: String, size: Float, bold: Boolean = false, c: Int = onBg) = TextView(ctx).apply {
+ text = s; textSize = size; setTextColor(c)
+ setTypeface(face ?: Typeface.DEFAULT, if (bold) Typeface.BOLD else Typeface.NORMAL)
+ }
+ val root = LinearLayout(ctx).apply {
+ orientation = LinearLayout.VERTICAL; setBackgroundColor(bg); setPadding(px(8f), px(8f), px(8f), px(10f))
+ }
+ root.addView(text(if (dark) "Dark" else "Light", 11f, c = variant))
+ bannerBitmap()?.let { b ->
+ root.addView(ImageView(ctx).apply { setImageBitmap(b); scaleType = ImageView.ScaleType.CENTER_CROP }, LinearLayout.LayoutParams(-1, px(40f)).apply { topMargin = px(4f) })
+ }
+ root.addView(text(t.title?.takeIf { it.isNotBlank() } ?: "RF Sentinel", 17f, bold = true, c = primary).apply { setPadding(0, px(4f), 0, px(4f)) })
+ val card = MaterialCardView(ctx).apply {
+ radius = px(12f).toFloat(); cardElevation = 0f
+ setCardBackgroundColor(p["surface_container"] ?: bg); strokeWidth = 0
+ }
+ val inner = LinearLayout(ctx).apply { orientation = LinearLayout.VERTICAL; setPadding(px(10f), px(8f), px(10f), px(8f)) }
+ inner.addView(text("Axon body camera", 14f, bold = true))
+ inner.addView(text("Probable - 12 m away", 12f, c = variant))
+ card.addView(inner)
+ root.addView(card, LinearLayout.LayoutParams(-1, -2))
+ val row = LinearLayout(ctx).apply { orientation = LinearLayout.HORIZONTAL; gravity = android.view.Gravity.CENTER_VERTICAL; setPadding(0, px(8f), 0, 0) }
+ row.addView(MaterialButton(ctx).apply {
+ text = "Scan"; textSize = 12f; typeface = face ?: Typeface.DEFAULT; isAllCaps = false; minHeight = 0; minimumHeight = 0
+ insetTop = 0; insetBottom = 0; isClickable = false
+ backgroundTintList = android.content.res.ColorStateList.valueOf(primary); setTextColor(onPrimary)
+ strokeWidth = 0; iconTint = android.content.res.ColorStateList.valueOf(onPrimary)
+ })
+ row.addView(MaterialSwitch(ctx).apply {
+ showText = false; isChecked = true; isClickable = false
+ trackTintList = android.content.res.ColorStateList.valueOf(primary)
+ thumbTintList = android.content.res.ColorStateList.valueOf(onPrimary)
+ trackDecorationTintList = android.content.res.ColorStateList.valueOf(primary)
+ }, LinearLayout.LayoutParams(-2, -2).apply { marginStart = px(6f) })
+ row.addView(android.widget.ImageView(ctx).apply {
+ // The tertiary and container colours as two small chips.
+ setImageDrawable(android.graphics.drawable.GradientDrawable().apply { shape = android.graphics.drawable.GradientDrawable.OVAL; setColor(p["tertiary"] ?: primary) })
+ }, LinearLayout.LayoutParams(px(16f), px(16f)).apply { marginStart = px(6f) })
+ row.addView(android.widget.ImageView(ctx).apply {
+ setImageDrawable(android.graphics.drawable.GradientDrawable().apply { shape = android.graphics.drawable.GradientDrawable.OVAL; setColor(p["primary_container"] ?: primary) })
+ }, LinearLayout.LayoutParams(px(16f), px(16f)).apply { marginStart = px(4f) })
+ root.addView(row)
+ val clip = MaterialCardView(this).apply {
+ radius = px(14f).toFloat(); cardElevation = 0f; strokeWidth = px(1f)
+ strokeColor = MaterialColors.getColor(this@ThemeMakerActivity, com.google.android.material.R.attr.colorOutlineVariant, 0x55888888)
+ addView(root)
+ }
+ return clip
+ }
+
+ // ---- colour dialog ---------------------------------------------------------------------------
+
+ private fun pickColor() {
+ val hsv = FloatArray(3).also { Color.colorToHSV(t.accent, it) }
+ var changing = false
+ val swatch = View(this)
+ val hex = EditText(this).apply { hint = "#RRGGBB"; maxLines = 1; inputType = InputType.TYPE_CLASS_TEXT; filters = arrayOf(android.text.InputFilter.LengthFilter(7)) }
+ fun current() = Color.HSVToColor(hsv)
+ fun bars(max: Int, start: Int, onChange: (Int) -> Unit): SeekBar {
+ val sb = SeekBar(this).apply {
+ this.max = max; progress = start
+ setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
+ override fun onProgressChanged(s: SeekBar?, p: Int, fromUser: Boolean) { if (fromUser) onChange(p) }
+ override fun onStartTrackingTouch(s: SeekBar?) {}
+ override fun onStopTrackingTouch(s: SeekBar?) {}
+ })
+ }
+ return sb
+ }
+ lateinit var h: SeekBar; lateinit var s: SeekBar; lateinit var v: SeekBar
+ fun refresh(fromHex: Boolean = false) {
+ changing = true
+ swatch.setBackgroundColor(current())
+ if (!fromHex) hex.setText(String.format("#%06X", current() and 0xFFFFFF))
+ changing = false
+ }
+ h = bars(360, hsv[0].toInt()) { hsv[0] = it.toFloat(); refresh() }
+ s = bars(100, (hsv[1] * 100).toInt()) { hsv[1] = it / 100f; refresh() }
+ v = bars(100, (hsv[2] * 100).toInt()) { hsv[2] = it / 100f; refresh() }
+ hex.doAfterTextChanged { e ->
+ if (changing) return@doAfterTextChanged
+ val c = runCatching { Color.parseColor(e.toString().let { if (it.startsWith("#")) it else "#$it" }) }.getOrNull() ?: return@doAfterTextChanged
+ Color.colorToHSV(c, hsv)
+ h.progress = hsv[0].toInt(); s.progress = (hsv[1] * 100).toInt(); v.progress = (hsv[2] * 100).toInt()
+ refresh(fromHex = true)
+ }
+ val box = LinearLayout(this).apply {
+ orientation = LinearLayout.VERTICAL; setPadding(px(20f), px(12f), px(20f), 0)
+ addView(swatch, LinearLayout.LayoutParams(-1, px(48f)))
+ addView(TextView(context).apply { text = "Hue" }); addView(h)
+ addView(TextView(context).apply { text = "Saturation" }); addView(s)
+ addView(TextView(context).apply { text = "Brightness" }); addView(v)
+ addView(hex)
+ }
+ refresh()
+ AlertDialog.Builder(this).setTitle("Custom colour").setView(box)
+ .setPositiveButton("Use") { _, _ -> t = t.copy(accent = current() or 0xFF000000.toInt()); updateSwatches(); updatePreview() }
+ .setNegativeButton("Cancel", null).show()
+ }
+
+ // ---- saving ------------------------------------------------------------------------------------
+
+ /** Saves the theme (its picture and font files too); returns it, or null when it can't be saved. */
+ private fun save(): CustomTheme? {
+ if (isNew && CustomThemes.all(this).size >= CustomThemes.MAX_THEMES) {
+ Toast.makeText(this, "That's ${CustomThemes.MAX_THEMES} themes - delete one first", Toast.LENGTH_LONG).show(); return null
+ }
+ val stored = CustomThemes.get(this, t.id)
+ var out = t.copy(name = CustomThemes.uniqueName(this, t.name, t.id))
+ // Banner
+ val bytes = newBanner
+ out = when {
+ t.banner == null -> { stored?.let { CustomThemes.clearBanner(this, it) }; out.copy(banner = null) }
+ bytes != null -> CustomThemes.setBanner(this, out.copy(banner = stored?.banner), bytes) ?: out.copy(banner = null)
+ stored?.banner != null && CustomThemes.bannerFile(this, stored) != null -> out.copy(banner = stored.banner)
+ else -> out.copy(banner = null)
+ }
+ // Font
+ val fontBytes = newFont
+ out = when {
+ out.font != "file" -> { stored?.let { CustomThemes.clearFont(this, it) }; out.copy(fontFile = null) }
+ fontBytes != null -> CustomThemes.setFont(this, out.copy(fontFile = stored?.fontFile), fontBytes) ?: CustomThemes.clearFont(this, out)
+ stored?.fontFile != null && CustomThemes.fontFile(this, stored) != null -> out.copy(fontFile = stored.fontFile)
+ else -> out.copy(font = "default", fontFile = null)
+ }
+ CustomThemes.save(this, out)
+ t = out; newBanner = null; newFont = null; isNew = false
+ startJson = out.toJson().toString()
+ // If it is the theme in use, open screens restyle themselves.
+ if (ThemeManager.custom(this)?.id == out.id) ThemeManager.refresh(this)
+ return out
+ }
+
+ private fun useIt() {
+ val s = save() ?: return
+ ThemeManager.setCustom(this, s.id)
+ Toast.makeText(this, "\"${s.name}\" is on", Toast.LENGTH_SHORT).show()
+ finish()
+ }
+
+ private fun duplicate() {
+ val s = save() ?: return
+ val copy = CustomThemes.duplicate(this, s)
+ Toast.makeText(this, "Duplicated as \"${copy.name}\"", Toast.LENGTH_SHORT).show()
+ startActivity(android.content.Intent(this, ThemeMakerActivity::class.java).putExtra(EXTRA_ID, copy.id))
+ finish()
+ }
+
+ private fun confirmDelete() {
+ AlertDialog.Builder(this).setTitle("Delete \"${t.name}\"?")
+ .setMessage("Its banner and font go too. Export it first if you want to keep a copy.")
+ .setPositiveButton("Delete") { _, _ ->
+ val wasUsed = ThemeManager.custom(this)?.id == t.id
+ if (wasUsed) ThemeManager.set(this, ThemeManager.AppTheme.SYSTEM)
+ CustomThemes.delete(this, t.id)
+ newBanner = null; newFont = null; startJson = t.toJson().toString()
+ finish()
+ }
+ .setNegativeButton("Cancel", null).show()
+ }
+}
diff --git a/app/src/main/java/com/rfsentinel/app/ui/ThemeManager.kt b/app/src/main/java/com/rfsentinel/app/ui/ThemeManager.kt
index a795701..e80492f 100644
--- a/app/src/main/java/com/rfsentinel/app/ui/ThemeManager.kt
+++ b/app/src/main/java/com/rfsentinel/app/ui/ThemeManager.kt
@@ -55,18 +55,60 @@ object ThemeManager {
BLUEPRINT("Blueprint", "White technical drawing on drafting blue, with dimension lines",
R.style.Theme_RFSentinel_Blueprint, true, ThemeHeaderView.Style.BLUEPRINT, "RF SENTINEL // DWG-001"),
PAPER("Paper", "Newspaper ink on newsprint - the most readable theme in bright sunlight",
- R.style.Theme_RFSentinel_Paper, false, ThemeHeaderView.Style.MASTHEAD, "Front Page")
+ R.style.Theme_RFSentinel_Paper, false, ThemeHeaderView.Style.MASTHEAD, "Front Page"),
+ /** A theme made in the theme maker (which one: [custom]); not in the built-in lists. */
+ CUSTOM("Custom theme", "Made in the theme maker", R.style.Theme_RFSentinel_Custom)
}
+ /** The built-in themes, for the pickers (the custom ones are listed from [CustomThemes]). */
+ val builtIn: List<AppTheme> get() = AppTheme.entries.filter { it != AppTheme.CUSTOM }
+
private const val PREFS = "rf_sentinel_prefs"
private const val KEY = "app_theme"
+ private const val CUSTOM_KEY = "custom_theme_id"
- /** Theme each live activity was created with, to detect stale ones. */
- private val applied = WeakHashMap<Activity, AppTheme>()
+ /** What each live activity was created with (the theme, and for a custom one its choices), to detect stale ones. */
+ private val applied = WeakHashMap<Activity, String>()
- fun current(context: Context): AppTheme =
- context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null)
+ fun current(context: Context): AppTheme {
+ val t = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(KEY, null)
?.let { runCatching { AppTheme.valueOf(it) }.getOrNull() } ?: AppTheme.SYSTEM
+ // A custom theme that is gone (deleted, or a backup restored without it) is the default look again.
+ return if (t == AppTheme.CUSTOM && custom(context) == null) AppTheme.SYSTEM else t
+ }
+
+ /** The custom theme in use, null when a built-in one is. */
+ fun custom(context: Context): CustomTheme? {
+ val sp = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
+ if (sp.getString(KEY, null) != AppTheme.CUSTOM.name) return null
+ return CustomThemes.get(context, sp.getString(CUSTOM_KEY, null))
+ }
+
+ /** Uses the custom theme [id]. */
+ fun setCustom(context: Context, id: String) {
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit(commit = true) { putString(KEY, AppTheme.CUSTOM.name); putString(CUSTOM_KEY, id) }
+ refresh(context)
+ }
+
+ /** After a custom theme was changed: the night mode follows its mode (screens restyle themselves when next shown). */
+ fun refresh(context: Context) = applyNightMode(current(context), custom(context))
+
+ /** What an open screen compares to know whether it must restyle itself. */
+ private fun signature(context: Context): String {
+ val c = custom(context)
+ return current(context).name + (c?.let { ":" + it.id + ":" + CustomThemes.stamp(context, it) } ?: "")
+ }
+
+ // The animated header, title and banner: a custom theme chooses its own; built-in ones have theirs.
+ fun headerStyle(context: Context): ThemeHeaderView.Style? {
+ val c = custom(context)
+ return if (c != null) c.header?.let { h -> runCatching { ThemeHeaderView.Style.valueOf(h) }.getOrNull() } else current(context).header
+ }
+
+ fun appTitle(context: Context): String? {
+ val c = custom(context)
+ return if (c != null) c.title?.takeIf { it.isNotBlank() } else current(context).appTitle
+ }
/** True once the user has picked a theme (the setup wizard requires one). */
fun isChosen(context: Context): Boolean =
@@ -74,7 +116,7 @@ object ThemeManager {
fun set(context: Context, theme: AppTheme) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit { putString(KEY, theme.name) }
- applyNightMode(theme)
+ applyNightMode(theme, custom(context))
}
/**
@@ -96,10 +138,17 @@ object ThemeManager {
* Optional user-chosen banner image for the styled themes (e.g. a logo the user
* owns). Copied into private app storage; never bundled or shared.
*/
- fun bannerFile(context: Context) = java.io.File(context.filesDir, "theme_banner")
+ private fun globalBannerFile(context: Context) = java.io.File(context.filesDir, "theme_banner")
+
+ /** The banner in use: a custom theme's own, else the one picked in Settings. */
+ fun bannerFile(context: Context): java.io.File =
+ custom(context)?.let { CustomThemes.bannerFile(context, it) } ?: globalBannerFile(context)
fun hasBanner(context: Context) = bannerFile(context).let { it.exists() && it.length() > 0 }
+ /** The banner picked in Settings (for the built-in styled themes). */
+ fun hasGlobalBanner(context: Context) = globalBannerFile(context).let { it.exists() && it.length() > 0 }
+
/** Copies the picked image into app storage (max 8 MB). Returns false if unreadable. */
fun setBanner(context: Context, uri: android.net.Uri): Boolean = runCatching {
context.contentResolver.openInputStream(uri)!!.use { input ->
@@ -109,17 +158,17 @@ object ThemeManager {
val opts = android.graphics.BitmapFactory.Options().apply { inJustDecodeBounds = true }
android.graphics.BitmapFactory.decodeByteArray(bytes, 0, bytes.size, opts)
require(opts.outWidth > 0 && opts.outHeight > 0)
- bannerFile(context).writeBytes(bytes)
+ globalBannerFile(context).writeBytes(bytes)
}
true
}.getOrDefault(false)
fun clearBanner(context: Context) {
- bannerFile(context).delete()
+ globalBannerFile(context).delete()
}
fun install(app: Application) {
- applyNightMode(current(app))
+ applyNightMode(current(app), custom(app))
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityPreCreated(activity: Activity, savedInstanceState: Bundle?) = style(activity)
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
@@ -128,13 +177,17 @@ object ThemeManager {
}
override fun onActivityResumed(activity: Activity) {
val was = applied[activity]
- if (was != null && was != current(activity)) activity.recreate()
+ if (was != null && was != signature(activity)) activity.recreate()
+ }
+ // A custom theme's font, set on the screen's texts once it is up.
+ override fun onActivityStarted(activity: Activity) {
+ val c = custom(activity)
+ FontApplier.attach(activity, c?.let { FontApplier.typeface(activity, it) })
}
- override fun onActivityStarted(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}
- override fun onActivityDestroyed(activity: Activity) { applied.remove(activity) }
+ override fun onActivityDestroyed(activity: Activity) { applied.remove(activity); FontApplier.detach(activity) }
})
}
@@ -142,12 +195,18 @@ object ThemeManager {
val theme = current(activity)
activity.setTheme(theme.style)
if (theme == AppTheme.MATERIAL_YOU) DynamicColors.applyToActivityIfAvailable(activity)
- applied[activity] = theme
+ custom(activity)?.let { runCatching { CustomColors.apply(activity, it) } }
+ applied[activity] = signature(activity)
}
- private fun applyNightMode(theme: AppTheme) {
+ private fun applyNightMode(theme: AppTheme, custom: CustomTheme? = null) {
+ val night = if (theme == AppTheme.CUSTOM && custom != null) when (CustomColors.Mode.of(custom.mode)) {
+ CustomColors.Mode.LIGHT -> false
+ CustomColors.Mode.DARK, CustomColors.Mode.BLACK -> true
+ CustomColors.Mode.SYSTEM -> null
+ } else theme.night
AppCompatDelegate.setDefaultNightMode(
- when (theme.night) {
+ when (night) {
false -> AppCompatDelegate.MODE_NIGHT_NO
true -> AppCompatDelegate.MODE_NIGHT_YES
null -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
diff --git a/app/src/main/java/com/rfsentinel/app/util/DeviceHistoryImport.kt b/app/src/main/java/com/rfsentinel/app/util/DeviceHistoryImport.kt
new file mode 100644
index 0000000..f103e90
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/util/DeviceHistoryImport.kt
@@ -0,0 +1,230 @@
+package com.rfsentinel.app.util
+
+import com.google.gson.stream.JsonReader
+import com.google.gson.stream.JsonToken
+import com.rfsentinel.app.data.KnownDeviceDao
+import com.rfsentinel.app.data.KnownDeviceEntity
+import java.io.BufferedReader
+import java.io.InputStream
+import java.io.InputStreamReader
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+import java.util.TimeZone
+
+/**
+ * Device history import: reads the file the app's own export writes - JSON (the history alone, or the "everything"
+ * file) or CSV - and merges the devices into what the phone remembers. Merging never loses anything and importing the
+ * same file twice changes nothing: the earliest first sighting and the latest last one are kept, the larger counts,
+ * a star or note already there stays, and a name or vendor fills in only where there is none.
+ *
+ * Reading is streamed and rows are written in batches, so a history of a hundred thousand devices does not need to fit
+ * in memory. Pure Kotlin apart from the DAO, so it is unit-tested.
+ */
+object DeviceHistoryImport {
+
+ const val MAX_BYTES = 120L * 1024 * 1024
+ /** The byte-order mark a spreadsheet may put before the first column name. */
+ private val BOM = 0xFEFF.toChar().toString()
+ private const val BATCH = 500
+ private val MAC = Regex("^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$")
+
+ class Result(val added: Int, val updated: Int, val unchanged: Int, val skipped: Int) {
+ val total get() = added + updated + unchanged
+ }
+
+ class NotHistory(message: String) : Exception(message)
+
+ // ---- times -------------------------------------------------------------------------------------
+
+ private fun parseTime(s: String?): Long {
+ val t = s?.trim().orEmpty()
+ if (t.isEmpty()) return 0L
+ t.toLongOrNull()?.let { return it }
+ runCatching {
+ return SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US).apply { timeZone = TimeZone.getTimeZone("UTC"); isLenient = false }.parse(t)!!.time
+ }
+ runCatching { return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).apply { isLenient = false }.parse(t)!!.time }
+ return 0L
+ }
+
+ // ---- one row -----------------------------------------------------------------------------------
+
+ /** A history row from a file's fields; null when the address is not a Bluetooth / WiFi address. */
+ fun row(mac: String?, name: String?, vendor: String?, type: String?, first: String?, last: String?,
+ sessions: String?, detects: String?, favorite: String?, note: String?, now: Long = System.currentTimeMillis()): KnownDeviceEntity? {
+ val m = mac?.trim().orEmpty()
+ if (!MAC.matches(m)) return null
+ val f = parseTime(first); val l = parseTime(last)
+ val seenFirst = if (f > 0) f else if (l > 0) l else now
+ val seenLast = if (l > 0) maxOf(l, seenFirst) else seenFirst
+ fun clean(s: String?, max: Int) = s?.trim()?.takeIf { it.isNotEmpty() && !it.equals("null", true) }?.take(max)
+ return KnownDeviceEntity(
+ mac = m.uppercase(Locale.US), firstSeen = seenFirst, lastSeen = seenLast,
+ sessions = (sessions?.trim()?.toIntOrNull() ?: 1).coerceIn(1, 1_000_000),
+ detectCount = (detects?.trim()?.toIntOrNull() ?: 1).coerceIn(1, 100_000_000),
+ name = clean(name, 128), vendor = clean(vendor, 128), deviceType = clean(type, 64),
+ favorite = favorite?.trim()?.equals("true", true) == true, note = clean(note, 1000)
+ )
+ }
+
+ /** The two rows as one: nothing is lost, and merging the same row again gives the same result. */
+ fun merge(mine: KnownDeviceEntity?, theirs: KnownDeviceEntity): KnownDeviceEntity {
+ if (mine == null) return theirs
+ return KnownDeviceEntity(
+ mac = mine.mac,
+ firstSeen = minOf(mine.firstSeen, theirs.firstSeen),
+ lastSeen = maxOf(mine.lastSeen, theirs.lastSeen),
+ sessions = maxOf(mine.sessions, theirs.sessions),
+ detectCount = maxOf(mine.detectCount, theirs.detectCount),
+ name = mine.name ?: theirs.name, vendor = mine.vendor ?: theirs.vendor, deviceType = mine.deviceType ?: theirs.deviceType,
+ favorite = mine.favorite || theirs.favorite,
+ note = mine.note?.takeIf { it.isNotBlank() } ?: theirs.note
+ )
+ }
+
+ // ---- reading the files -----------------------------------------------------------------------------
+
+ /**
+ * The devices of a history file, one at a time as they are read (null for an entry that was not a device); the file
+ * is only read as far as the sequence is taken. Throws [NotHistory] for another kind of file.
+ */
+ fun rows(input: InputStream): Sequence<KnownDeviceEntity?> = sequence {
+ val buffered = input.buffered()
+ buffered.mark(8)
+ // The first character that is not a space (or a byte-order mark) says which kind of file it is.
+ var first = -1
+ while (true) {
+ val b = buffered.read()
+ if (b < 0) break
+ if (b.toChar().isWhitespace() || b == 0xEF || b == 0xBB || b == 0xBF) continue
+ first = b; break
+ }
+ buffered.reset()
+ val reader = BufferedReader(InputStreamReader(buffered, Charsets.UTF_8))
+ if (first == '['.code || first == '{'.code) jsonRows(reader) else csvRows(reader)
+ }
+
+ private suspend fun SequenceScope<KnownDeviceEntity?>.jsonRows(reader: BufferedReader) {
+ val r = JsonReader(reader).apply { isLenient = true }
+ when (r.peek()) {
+ JsonToken.BEGIN_ARRAY -> arrayRows(r)
+ JsonToken.BEGIN_OBJECT -> {
+ r.beginObject()
+ var found = false
+ while (r.hasNext()) {
+ if (r.nextName() == "deviceHistory" && r.peek() == JsonToken.BEGIN_ARRAY) { found = true; arrayRows(r) } else r.skipValue()
+ }
+ r.endObject()
+ if (!found) throw NotHistory("That file has no device history in it")
+ }
+ else -> throw NotHistory("That isn't a device history file")
+ }
+ }
+
+ private suspend fun SequenceScope<KnownDeviceEntity?>.arrayRows(r: JsonReader) {
+ r.beginArray()
+ while (r.hasNext()) {
+ if (r.peek() != JsonToken.BEGIN_OBJECT) { r.skipValue(); yield(null); continue }
+ val f = HashMap<String, String?>()
+ r.beginObject()
+ while (r.hasNext()) {
+ val k = r.nextName()
+ f[k] = when (r.peek()) {
+ JsonToken.NULL -> { r.nextNull(); null }
+ JsonToken.BOOLEAN -> r.nextBoolean().toString()
+ JsonToken.BEGIN_ARRAY, JsonToken.BEGIN_OBJECT -> { r.skipValue(); null }
+ else -> r.nextString()
+ }
+ }
+ r.endObject()
+ yield(row(f["mac"], f["name"], f["vendor"], f["deviceType"], f["firstSeen"], f["lastSeen"], f["sessions"], f["detectCount"], f["favorite"], f["note"]))
+ }
+ r.endArray()
+ }
+
+ private suspend fun SequenceScope<KnownDeviceEntity?>.csvRows(reader: BufferedReader) {
+ val it = csvRecords(reader).iterator()
+ if (!it.hasNext()) throw NotHistory("That file is empty")
+ val header = it.next().map { h -> h.trim().lowercase(Locale.US).removePrefix(BOM) }
+ if ("mac" !in header) throw NotHistory("That isn't a device history file (no \"mac\" column)")
+ fun col(r: List<String>, vararg names: String) = names.firstNotNullOfOrNull { n -> header.indexOf(n).takeIf { i -> i >= 0 } }?.let { i -> r.getOrNull(i) }
+ while (it.hasNext()) {
+ val r = it.next()
+ if (r.all { f -> f.isBlank() }) continue
+ yield(row(col(r, "mac"), col(r, "name"), col(r, "vendor"), col(r, "device_type", "devicetype"), col(r, "first_seen", "firstseen"),
+ col(r, "last_seen", "lastseen"), col(r, "sessions"), col(r, "detect_count", "detectcount"), col(r, "favorite"), col(r, "note")))
+ }
+ }
+
+ /** The CSV's records, quotes and quoted line breaks included (fields are quoted with doubled quotes). */
+ internal fun csvRecords(reader: BufferedReader): Sequence<List<String>> = sequence {
+ val field = StringBuilder(); var row = ArrayList<String>(); var quoted = false
+ var c = reader.read()
+ while (c >= 0) {
+ val ch = c.toChar()
+ when {
+ quoted && ch == '"' -> { reader.mark(1); val n = reader.read(); if (n == '"'.code) field.append('"') else { quoted = false; if (n >= 0) reader.reset() } }
+ quoted -> field.append(ch)
+ ch == '"' && field.isEmpty() -> quoted = true
+ ch == ',' -> { row.add(field.toString()); field.setLength(0) }
+ ch == '\n' || ch == '\r' -> {
+ if (ch == '\r') { reader.mark(1); if (reader.read() != '\n'.code) reader.reset() }
+ row.add(field.toString()); field.setLength(0)
+ if (row.size > 1 || row[0].isNotEmpty()) yield(row)
+ row = ArrayList()
+ }
+ else -> field.append(ch)
+ }
+ c = reader.read()
+ }
+ if (field.isNotEmpty() || row.isNotEmpty()) { row.add(field.toString()); yield(row) }
+ }
+
+ // ---- into the database -------------------------------------------------------------------------------
+
+ /** Merges the file into the history; [onProgress] gets the rows handled so far. Throws [NotHistory] for another kind of file. */
+ suspend fun importInto(dao: KnownDeviceDao, input: InputStream, onProgress: (Int) -> Unit = {}): Result {
+ var added = 0; var updated = 0; var same = 0; var skipped = 0; var seen = 0
+ val batch = ArrayList<KnownDeviceEntity>()
+ suspend fun flush() {
+ if (batch.isEmpty()) return
+ // A file can list a device twice: the later rows merge into the earlier ones first.
+ val byMac = LinkedHashMap<String, KnownDeviceEntity>()
+ for (b in batch) byMac[b.mac] = merge(byMac[b.mac], b)
+ val have = dao.getAll(byMac.keys.toList()).associateBy { it.mac }
+ val write = ArrayList<KnownDeviceEntity>()
+ for ((mac, incoming) in byMac) {
+ val old = have[mac]
+ val merged = merge(old, incoming)
+ when {
+ old == null -> { added++; write += merged }
+ merged != old -> { updated++; write += merged }
+ else -> same++
+ }
+ }
+ if (write.isNotEmpty()) dao.upsertAll(write)
+ batch.clear()
+ }
+ for (row in rows(input)) {
+ seen++
+ if (row == null) skipped++ else batch += row
+ if (batch.size >= BATCH) { flush(); onProgress(seen) }
+ }
+ flush(); onProgress(seen)
+ return Result(added, updated, same, skipped)
+ }
+
+ /** Passes the file on, but stops it past [limit] bytes: a wrong, huge file is refused, not read to the end. */
+ class Limited(private val inner: InputStream, private val limit: Long = MAX_BYTES) : InputStream() {
+ private var n = 0L
+ override fun read(): Int { val b = inner.read(); if (b >= 0 && ++n > limit) throw NotHistory("That file is too big to be a device history"); return b }
+ override fun read(b: ByteArray, off: Int, len: Int): Int {
+ val r = inner.read(b, off, len); if (r > 0) { n += r; if (n > limit) throw NotHistory("That file is too big to be a device history") }; return r
+ }
+ override fun close() = inner.close()
+ }
+
+ fun fileName(now: Long = System.currentTimeMillis()) =
+ "rf_sentinel_device_history_" + SimpleDateFormat("yyyyMMdd_HHmm", Locale.US).format(Date(now)) + ".json"
+}
diff --git a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
index 1bab35b..26bb95a 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Exporter.kt
@@ -53,6 +53,9 @@ object Exporter {
.show()
}
+ /** Shortcut straight to the device history's formats (CSV / JSON): what Import history reads back. */
+ fun showHistoryExport(activity: AppCompatActivity) = chooseFormat(activity, Scope.HISTORY)
+
/** Shortcut straight to the "all nearby devices" formats. */
fun showExportAll(activity: AppCompatActivity) = chooseFormat(activity, Scope.SESSION)
diff --git a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
index 9e0a2c3..a7f6278 100644
--- a/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
+++ b/app/src/main/java/com/rfsentinel/app/util/Prefs.kt
@@ -565,6 +565,17 @@ object Prefs {
sp(context).getFloat("map_3d_tilt", MAP_TILT_DEFAULT.toFloat()).toDouble().coerceIn(30.0, 60.0)
fun setMap3dTilt(context: Context, value: Double) = sp(context).edit().putFloat("map_3d_tilt", value.toFloat()).apply()
+ /** The marker for your position on the map ([com.rfsentinel.app.ui.MarkerArt]): its style, colour and size (1.0 = 56 dp tall). */
+ fun markerStyle(context: Context): String = sp(context).getString("map_marker_style", "arrow") ?: "arrow"
+ fun markerColor(context: Context): String = sp(context).getString("map_marker_color", "blue") ?: "blue"
+ fun markerSize(context: Context): Float = sp(context).getFloat("map_marker_size", 1.0f).coerceIn(0.6f, 2.0f)
+ fun setMarker(context: Context, style: String, color: String, size: Float) =
+ sp(context).edit().putString("map_marker_style", style).putString("map_marker_color", color).putFloat("map_marker_size", size).apply()
+
+ /** The live map goes back to following you a few seconds after you stop touching it while you drive (as Google Maps does). */
+ fun mapAutoRecenter(context: Context): Boolean = bool(context, "map_auto_recenter", true)
+ fun setMapAutoRecenter(context: Context, value: Boolean) = setBool(context, "map_auto_recenter", value)
+
/** The speedometer in the corner of the live map: your speed, and the posted limit while it is known. */
fun mapSpeedometer(context: Context): Boolean = bool(context, "map_speedometer", true)
fun setMapSpeedometer(context: Context, value: Boolean) = setBool(context, "map_speedometer", value)
diff --git a/app/src/main/java/com/rfsentinel/app/util/SettingsBackup.kt b/app/src/main/java/com/rfsentinel/app/util/SettingsBackup.kt
new file mode 100644
index 0000000..054b0cc
--- /dev/null
+++ b/app/src/main/java/com/rfsentinel/app/util/SettingsBackup.kt
@@ -0,0 +1,188 @@
+package com.rfsentinel.app.util
+
+import android.content.Context
+import com.rfsentinel.app.BuildConfig
+import com.rfsentinel.app.ui.CustomThemes
+import org.json.JSONArray
+import org.json.JSONObject
+import java.io.InputStream
+
+/**
+ * Settings > Data > Back up / Restore settings: the app's settings, your watchlist rules, Home / Work / starred places, the
+ * floating windows' positions and your custom themes (with their banners and fonts), as one JSON file you keep. Left out on
+ * purpose: API keys and other secrets (they never leave the phone's secure store), the "I accept the risk" acknowledgements
+ * (asked again), recent places, snoozes and other short-lived state, where the map last looked, and detections, devices and
+ * traces (those have their own export).
+ *
+ * Restoring asks which [Section]s to take, so a file can bring back just the themes, or everything but them.
+ *
+ * Pure Kotlin on top of SharedPreferences, so it is unit-tested.
+ */
+object SettingsBackup {
+
+ const val FORMAT = 1
+ /** Themes carry pictures and fonts, so the file can be big; a file over this is refused. */
+ const val MAX_BYTES = 48_000_000
+
+ /** What a restore can take, one at a time. */
+ enum class Section(val label: String) {
+ SETTINGS("Settings"),
+ WATCHLIST("Watchlist rules"),
+ PLACES("Home, Work and starred places"),
+ FLOATING("Floating map and bubble positions"),
+ THEMES("Custom themes (with their banners and fonts)")
+ }
+
+ /** The preference files that are backed up, and for each the keys it never includes (all of them when [only] is set). */
+ private class Part(val file: String, val section: Section, val skip: Set<String> = emptySet(), val only: Set<String>? = null)
+
+ private val parts = listOf(
+ Part("rf_sentinel_prefs", Section.SETTINGS, skip = setOf(
+ // Short-lived state and where you were.
+ "alerts_snoozed_until", "tracker_follow_paused_until", "last_update_check", "map_center", "map_zoom", "deflock_updated", "started_by_car",
+ // Acknowledgements that must be given again, and folder access that does not carry over.
+ "waze_accepted", "waze_direct_accepted", "live_export", "live_export_tree")),
+ Part("nav_places", Section.PLACES, only = setOf("nav_home", "nav_work", "nav_favorites")),
+ Part("oui_watchlist_prefs", Section.WATCHLIST),
+ Part("floating_map", Section.FLOATING),
+ Part("threat_bubble", Section.FLOATING)
+ )
+
+ private const val THEMES = "customThemes"
+
+ private fun wanted(p: Part, key: String) = (p.only?.contains(key) ?: true) && key !in p.skip
+
+ /** The backup file's text. */
+ fun create(context: Context, now: Long = System.currentTimeMillis()): String {
+ val files = JSONObject()
+ for (p in parts) {
+ val out = JSONObject()
+ for ((k, v) in context.getSharedPreferences(p.file, Context.MODE_PRIVATE).all) {
+ if (!wanted(p, k) || v == null) continue
+ out.put(k, when (v) {
+ is Boolean -> JSONObject().put("t", "b").put("v", v)
+ is Int -> JSONObject().put("t", "i").put("v", v)
+ is Long -> JSONObject().put("t", "l").put("v", v)
+ is Float -> JSONObject().put("t", "f").put("v", v.toDouble())
+ is String -> JSONObject().put("t", "s").put("v", v)
+ is Set<*> -> JSONObject().put("t", "ss").put("v", JSONArray(v.map { it.toString() }))
+ else -> continue
+ })
+ }
+ files.put(p.file, out)
+ }
+ val root = JSONObject().put("app", "RF Sentinel").put("format", FORMAT).put("version", BuildConfig.VERSION_NAME)
+ .put("created", now).put("files", files)
+ val themes = CustomThemes.backup(context)
+ if (themes.length() > 0) root.put(THEMES, themes)
+ return root.toString(2)
+ }
+
+ /** Reads a backup file's text; null when it is bigger than [MAX_BYTES] (or unreadable). */
+ fun read(input: InputStream): String? {
+ val out = java.io.ByteArrayOutputStream()
+ val buf = ByteArray(64 * 1024)
+ while (true) {
+ val n = input.read(buf)
+ if (n < 0) break
+ out.write(buf, 0, n)
+ if (out.size() > MAX_BYTES) return null
+ }
+ return out.toString(Charsets.UTF_8.name())
+ }
+
+ sealed class Result {
+ class Restored(val count: Int) : Result()
+ class Refused(val why: String) : Result()
+ }
+
+ /** What a backup file holds: the sections in it, or why it is not a backup. */
+ sealed class Inspect {
+ class Ok(val sections: List<Section>, val themes: Int) : Inspect()
+ class Bad(val why: String) : Inspect()
+ }
+
+ private class Opened(val files: JSONObject?, val themes: JSONArray?)
+
+ private fun open(text: String): Any {
+ if (text.length > MAX_BYTES) return Result.Refused("That file is too big to be an RF Sentinel backup")
+ val root = runCatching { JSONObject(text) }.getOrNull() ?: return Result.Refused("That isn't a backup file (not valid JSON)")
+ if (root.optString("app") != "RF Sentinel") return Result.Refused("That isn't an RF Sentinel backup")
+ val format = root.optInt("format", 0)
+ if (format < 1 || format > FORMAT) return Result.Refused("That backup is from a newer version of RF Sentinel - update the app first")
+ val files = root.optJSONObject("files")
+ val themes = root.optJSONArray(THEMES)
+ if (files == null && themes == null) return Result.Refused("The backup has no settings in it")
+ return Opened(files, themes)
+ }
+
+ fun inspect(text: String): Inspect {
+ val o = open(text)
+ if (o is Result.Refused) return Inspect.Bad(o.why)
+ o as Opened
+ val found = LinkedHashSet<Section>()
+ for (p in parts) if (o.files?.optJSONObject(p.file) != null) found += p.section
+ val themes = o.themes?.length() ?: 0
+ if (themes > 0) found += Section.THEMES
+ return Inspect.Ok(Section.entries.filter { it in found }, themes)
+ }
+
+ /**
+ * Puts the file's settings in place of this phone's: in each backed-up file of the chosen [only] sections (all by default)
+ * every setting that is backed up is replaced (one the file has not got goes back to its default); the custom themes
+ * replace this phone's. Nothing changes if the file is not a backup of this app, or is damaged anywhere.
+ */
+ fun restore(context: Context, text: String, only: Set<Section> = Section.entries.toSet()): Result {
+ val o = open(text)
+ if (o is Result.Refused) return o
+ o as Opened
+ // Read everything first: a bad entry anywhere means nothing is applied.
+ val plan = HashMap<String, Map<String, Any>>()
+ for (p in parts) {
+ if (p.section !in only) continue
+ val f = o.files?.optJSONObject(p.file) ?: continue
+ val values = HashMap<String, Any>()
+ for (k in f.keys()) {
+ if (!wanted(p, k)) continue
+ val e = f.optJSONObject(k) ?: return Result.Refused("The backup is damaged ($k)")
+ values[k] = when (e.optString("t")) {
+ "b" -> e.optBoolean("v")
+ "i" -> e.optInt("v")
+ "l" -> e.optLong("v")
+ "f" -> e.optDouble("v").toFloat()
+ "s" -> e.optString("v")
+ "ss" -> (e.optJSONArray("v") ?: return Result.Refused("The backup is damaged ($k)")).let { a -> (0 until a.length()).map { a.getString(it) }.toSet() }
+ else -> return Result.Refused("The backup is damaged ($k)")
+ }
+ }
+ plan[p.file] = values
+ }
+ val themes = if (Section.THEMES in only && o.themes != null && o.themes.length() > 0) {
+ try { CustomThemes.parseBackup(o.themes) } catch (e: CustomThemes.BadThemeFile) { return Result.Refused("The backup is damaged (a theme: ${e.message})") }
+ } else null
+ var count = 0
+ for (p in parts) {
+ val values = plan[p.file] ?: continue
+ val sp = context.getSharedPreferences(p.file, Context.MODE_PRIVATE)
+ val e = sp.edit()
+ for (k in sp.all.keys) if (wanted(p, k)) e.remove(k)
+ for ((k, v) in values) {
+ when (v) {
+ is Boolean -> e.putBoolean(k, v)
+ is Int -> e.putInt(k, v)
+ is Long -> e.putLong(k, v)
+ is Float -> e.putFloat(k, v)
+ is String -> e.putString(k, v)
+ is Set<*> -> e.putStringSet(k, v.map { it.toString() }.toSet())
+ }
+ count++
+ }
+ e.commit() // written before the app restarts
+ }
+ if (themes != null) count += CustomThemes.applyBackup(context, themes)
+ return Result.Restored(count)
+ }
+
+ fun fileName(now: Long = System.currentTimeMillis()): String =
+ "rf-sentinel-settings-" + java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US).format(java.util.Date(now)) + ".json"
+}
diff --git a/app/src/main/res/layout/activity_settings.xml b/app/src/main/res/layout/activity_settings.xml
index 8f70454..bdda241 100644
--- a/app/src/main/res/layout/activity_settings.xml
+++ b/app/src/main/res/layout/activity_settings.xml
@@ -33,7 +33,7 @@
android:layout_height="wrap_content"
android:text="Discreet mode" />
- <TextView style="@style/SettingsLabel" android:text="Screen while the app is open" />
+ <TextView android:id="@+id/screenLabel" style="@style/SettingsLabel" android:text="Screen while the app is open" />
<RadioGroup
android:id="@+id/screenModeGroup"
@@ -45,16 +45,16 @@
<RadioButton android:id="@+id/screenNormal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Normal" />
</RadioGroup>
- <TextView style="@style/SettingsLabel" android:text="Screen rotation" />
+ <TextView android:id="@+id/rotationLabel" style="@style/SettingsLabel" android:text="Screen rotation" />
<RadioGroup
android:id="@+id/rotationGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content">
- <RadioButton android:id="@+id/rotationNormal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Normal (follows auto-rotate)" />
+ <RadioButton android:id="@+id/rotationNormal" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Normal" />
<RadioButton android:id="@+id/rotationAllWays" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Auto-rotate, upside down too" />
- <RadioButton android:id="@+id/rotationUpsideDown" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Always upside down (USB-C port at the top)" />
+ <RadioButton android:id="@+id/rotationUpsideDown" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Always upside down" />
</RadioGroup>
</LinearLayout>
@@ -101,7 +101,7 @@
android:id="@+id/hideTrustedSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="Hide trusted (whitelisted) devices from the list and radar" />
+ android:text="Hide trusted devices" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/bleSwitch"
@@ -115,19 +115,19 @@
android:layout_height="wrap_content"
android:text="WiFi scanning" />
- <TextView style="@style/SettingsLabel" android:text="Bluetooth scan intensity" />
+ <TextView android:id="@+id/scanModeLabel" style="@style/SettingsLabel" android:text="Bluetooth scan intensity" />
<RadioGroup
android:id="@+id/scanModeGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content">
- <RadioButton android:id="@+id/scanModeLowLatency" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Maximum (most battery)" />
+ <RadioButton android:id="@+id/scanModeLowLatency" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Maximum" />
<RadioButton android:id="@+id/scanModeBalanced" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Balanced" />
<RadioButton android:id="@+id/scanModeLowPower" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Battery saver" />
</RadioGroup>
- <TextView android:id="@+id/intervalLabel" style="@style/SettingsLabel" android:text="WiFi scan interval (seconds)" />
+ <TextView android:id="@+id/intervalLabel" style="@style/SettingsLabel" android:text="WiFi scan interval" />
<EditText
android:id="@+id/intervalInput"
@@ -215,15 +215,15 @@
<TextView android:id="@+id/headerAlerts" style="@style/SettingsHeader" android:text="Alerts" />
<LinearLayout android:id="@+id/sectionAlerts" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical">
- <TextView style="@style/SettingsLabel" android:text="Alert for matches that are at least" />
+ <TextView android:id="@+id/thresholdLabel" style="@style/SettingsLabel" android:text="Alert for matches that are at least" />
<RadioGroup
android:id="@+id/thresholdGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content">
- <RadioButton android:id="@+id/thresholdWeak" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Weak (more false alarms)" />
- <RadioButton android:id="@+id/thresholdMedium" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Probable (recommended)" />
+ <RadioButton android:id="@+id/thresholdWeak" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Weak" />
+ <RadioButton android:id="@+id/thresholdMedium" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Probable" />
<RadioButton android:id="@+id/thresholdStrong" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Strong only" />
</RadioGroup>
@@ -243,13 +243,13 @@
android:id="@+id/radarBeepSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="Radar-detector beeps (faster as it gets closer)" />
+ android:text="Radar-detector beeps" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/detectorSoundSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="Radar-detector sound (Ka / K / X tones, GPS connected)" />
+ android:text="Radar-detector sound" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/startupSweepSwitch"
@@ -278,7 +278,7 @@
android:layout_height="wrap_content"
android:text="Test intro" />
- <TextView style="@style/SettingsLabel" android:text="Re-alert the same device after (minutes)" />
+ <TextView android:id="@+id/dedupeLabel" style="@style/SettingsLabel" android:text="Re-alert the same device after" />
<EditText
android:id="@+id/dedupeInput"
@@ -402,7 +402,7 @@
android:layout_weight="1"
android:orientation="vertical">
- <TextView style="@style/SettingsLabel" android:text="For at least (minutes)" />
+ <TextView style="@style/SettingsLabel" android:text="For at least" />
<EditText
android:id="@+id/followMinutesInput"
@@ -418,7 +418,7 @@
android:layout_weight="1"
android:orientation="vertical">
- <TextView style="@style/SettingsLabel" android:text="Over (metres)" />
+ <TextView style="@style/SettingsLabel" android:text="Over" />
<EditText
android:id="@+id/followMetersInput"
@@ -482,7 +482,16 @@
android:valueFrom="30"
android:valueTo="60" />
- <TextView style="@style/SettingsLabel" android:text="Map provider" />
+ <TextView style="@style/SettingsLabel" android:text="Position marker" />
+
+ <com.google.android.material.button.MaterialButton
+ android:id="@+id/mapMarkerButton"
+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Arrow" />
+
+ <TextView android:id="@+id/mapProviderLabel" style="@style/SettingsLabel" android:text="Map provider" />
<com.google.android.material.button.MaterialButton
android:id="@+id/mapProviderButton"
@@ -497,17 +506,23 @@
android:layout_height="wrap_content"
android:text="Show plate, speed and red-light cameras" />
+ <com.google.android.material.switchmaterial.SwitchMaterial
+ android:id="@+id/mapAutoRecenterSwitch"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Auto-recenter" />
+
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/mapSpeedometerSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="Speedometer on the map (your speed and the posted limit)" />
+ android:text="Speedometer" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/mapSpeedLimitLiveSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="Posted limit when not navigating (asks the route server about your road)" />
+ android:text="Speed limit without a route" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/mapTowersSwitch"
@@ -548,13 +563,13 @@
android:id="@+id/autoCamerasSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="Download cameras automatically for the map area" />
+ android:text="Download cameras for the map area" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/mapCctvSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="Show CCTV cameras (OpenStreetMap)" />
+ android:text="Show CCTV cameras" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/mapCctvPrivateSwitch"
@@ -604,7 +619,7 @@
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:text="US &amp; Canada plate cameras (18 MB)" />
+ android:text="US &amp; Canada plate cameras · 18 MB" />
<TextView
android:id="@+id/deflockText"
@@ -637,7 +652,7 @@
android:layout_height="wrap_content"
android:text="Alert when the cell tower changes" />
- <TextView android:id="@+id/disable2gLabel" style="@style/SettingsLabel" android:text="Turn off 2G: best protection against fake towers" />
+ <TextView android:id="@+id/disable2gLabel" style="@style/SettingsLabel" android:text="Turn off 2G" />
<Button
android:id="@+id/disable2gButton"
@@ -646,7 +661,7 @@
android:layout_height="wrap_content"
android:text="Open SIM settings" />
- <TextView android:id="@+id/cellSecurityLabel" style="@style/SettingsLabel" android:text="Android 15+: network security alerts" />
+ <TextView android:id="@+id/cellSecurityLabel" style="@style/SettingsLabel" android:text="Network security alerts" />
<Button
android:id="@+id/cellSecurityButton"
@@ -693,7 +708,7 @@
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:text="Record frames (.pcap)" />
+ android:text="Record frames" />
<Button
android:id="@+id/pcapShareButton"
@@ -719,25 +734,25 @@
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:text="Pair OUI-SPY board (Bluetooth)" />
+ android:text="Pair OUI-SPY board" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/ouiSpyRelaySwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="OUI-SPY: relay everything it hears" />
+ android:text="OUI-SPY: relay everything" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/rtl5gSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="AWUS036ACS (RTL8811AU / 8821AU): also scan 5 GHz (experimental)" />
+ android:text="AWUS036ACS: also scan 5 GHz" />
<com.google.android.material.switchmaterial.SwitchMaterial
android:id="@+id/usbLightSwitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
- android:text="AWUS036ACS (RTL8811AU / 8821AU): adapter light blinks with traffic" />
+ android:text="AWUS036ACS: light blinks with traffic" />
</LinearLayout>
<!-- ================= RTL-SDR radio (filled in by SettingsActivity.setupRadioSection) ================= -->
@@ -790,7 +805,7 @@
android:paddingTop="0dp"
android:textSize="12sp" />
- <TextView android:id="@+id/retentionLabel" style="@style/SettingsLabel" android:text="Keep history for (days, 0 = forever)" />
+ <TextView android:id="@+id/retentionLabel" style="@style/SettingsLabel" android:text="Keep history for" />
<EditText
android:id="@+id/retentionInput"
@@ -800,20 +815,43 @@
android:importantForAutofill="no"
android:inputType="number" />
+ <Button
+ android:id="@+id/importHistoryButton"
+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:text="Import device history from a file" />
+
+ <Button
+ android:id="@+id/backupSettingsButton"
+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="8dp"
+ android:text="Back up settings to a file" />
+
+ <Button
+ android:id="@+id/restoreSettingsButton"
+ style="@style/Widget.MaterialComponents.Button.OutlinedButton"
+ android:layout_width="match_parent"
+ android:layout_height="wrap_content"
+ android:text="Restore settings from a file" />
+
<Button
android:id="@+id/exportAllButton"
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
- android:text="Export all devices (CSV, JSON, KML...)" />
+ android:text="Export all devices" />
<Button
android:id="@+id/forgetHistoryButton"
style="@style/Widget.MaterialComponents.Button.TextButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
- android:text="Forget device history (keeps favorites)" />
+ android:text="Forget device history" />
<Button
android:id="@+id/clearLogButton"
@@ -841,7 +879,7 @@
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
- android:text="Whitelist (trusted devices)" />
+ android:text="Whitelist" />
<Button
android:id="@+id/checkUpdateButton"
diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml
index 166d1e2..731eb61 100644
--- a/app/src/main/res/values/themes.xml
+++ b/app/src/main/res/values/themes.xml
@@ -27,6 +27,16 @@
<item name="actionBarTheme">@style/ThemeOverlay.Material3.ActionBar</item>
</style>
+ <!-- A theme made in the theme maker: Material 3 components; ThemeManager recolours it from the maker's accent (Android 11+). -->
+ <style name="Theme.RFSentinel.Custom" parent="Theme.Material3.DayNight">
+ <item name="rfAccent">?attr/colorPrimary</item>
+ <item name="rfOnAccent">?attr/colorOnPrimary</item>
+ <item name="rfScopeColor">?attr/colorPrimary</item>
+ <item name="rfScopeTextColor">?attr/colorOnSurfaceVariant</item>
+ <item name="rfTraceColor">?attr/colorTertiary</item>
+ <item name="actionBarTheme">@style/ThemeOverlay.Material3.ActionBar</item>
+ </style>
+
<!-- DedSec-inspired hacktivist poster: black and white with electric blue, monospace. -->
<style name="Theme.RFSentinel.DedSec" parent="Theme.MaterialComponents">
<!-- Selected chips / toggles use this theme's own primary colour. -->
diff --git a/app/src/test/java/com/rfsentinel/app/ui/CustomThemeTest.kt b/app/src/test/java/com/rfsentinel/app/ui/CustomThemeTest.kt
new file mode 100644
index 0000000..647d4bc
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/CustomThemeTest.kt
@@ -0,0 +1,269 @@
+package com.rfsentinel.app.ui
+
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Color
+import androidx.test.core.app.ApplicationProvider
+import org.json.JSONArray
+import org.json.JSONObject
+import org.junit.Assert.assertArrayEquals
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Assert.fail
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.annotation.GraphicsMode
+import java.io.ByteArrayOutputStream
+
+/** Custom themes: reading, saving, sharing as a file, importing part by part, the settings backup, and the colours they make. */
+@RunWith(RobolectricTestRunner::class)
+@GraphicsMode(GraphicsMode.Mode.NATIVE)
+@Config(sdk = [35], application = android.app.Application::class)
+class CustomThemeTest {
+
+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()
+
+ @Before fun clean() {
+ ctx.getSharedPreferences("custom_themes", Context.MODE_PRIVATE).edit().clear().commit()
+ ctx.getSharedPreferences("rf_sentinel_prefs", Context.MODE_PRIVATE).edit().clear().commit()
+ java.io.File(ctx.filesDir, "custom_themes").deleteRecursively()
+ }
+
+ private fun png(color: Int = Color.RED): ByteArray {
+ val b = Bitmap.createBitmap(8, 4, Bitmap.Config.ARGB_8888).apply { eraseColor(color) }
+ return ByteArrayOutputStream().also { b.compress(Bitmap.CompressFormat.PNG, 100, it) }.toByteArray()
+ }
+
+ /** A theme with every part set. */
+ private fun full(c: Context = ctx, name: String = "Neon"): CustomTheme {
+ val base = CustomTheme(id = CustomThemes.newId(), name = name, accent = 0xFFE91E63.toInt(), scheme = "vibrant", mode = "black",
+ font = "serif", header = "HUD", title = "Neon Sentinel", markerStyle = "taxi", markerColor = "red", markerSize = 1.4f)
+ val withBanner = CustomThemes.setBanner(c, base, png())!!
+ CustomThemes.save(c, withBanner)
+ return withBanner
+ }
+
+ @Test
+ fun aHandEditedFileCannotBreakTheApp() {
+ val t = CustomTheme.fromJson(JSONObject("""{"id":"a","name":" ${"x".repeat(80)} ","accent":16711680,"scheme":"nope","mode":"???",
+ "font":"comic-sans","fontFile":"../../etc/passwd","banner":"..\\..\\evil","header":"BOGUS","markerStyle":"spaceship","markerSize":99}"""))
+ assertEquals(40, t.name.length)
+ assertEquals("accent is made opaque", 0xFFFF0000.toInt(), t.accent)
+ assertEquals("tonal", t.scheme); assertEquals("system", t.mode); assertEquals("default", t.font)
+ assertNull("a font file only goes with the font choice 'file'", t.fontFile)
+ assertEquals("evil", t.banner)
+ assertNull(t.header); assertNull(t.markerStyle); assertNull("no marker, so no size", t.markerSize)
+ val m = CustomTheme.fromJson(JSONObject("""{"id":"b","name":"m","markerStyle":"suv","markerColor":"mauve","markerSize":99}"""))
+ assertEquals("blue", m.markerColor); assertEquals(2.0f, m.markerSize!!, 0f)
+ assertEquals("a name is never empty", "My theme", CustomTheme.fromJson(JSONObject("""{"id":"c","name":" "}""")).name)
+ assertEquals("passwd", CustomTheme.safeName("../../etc/passwd")); assertEquals("a_b-c.ttf", CustomTheme.safeName("C:\\x\\a_b-c.ttf"))
+ }
+
+ @Test
+ fun themesAreSavedFoundRenamedAndDeletedWithTheirFiles() {
+ val a = full(name = "Neon")
+ val b = CustomTheme(id = CustomThemes.newId(), name = CustomThemes.uniqueName(ctx, "Neon"))
+ assertEquals("a taken name gets a number", "Neon 2", b.name)
+ assertEquals("a theme keeps its own name when renaming it", "Neon", CustomThemes.uniqueName(ctx, "Neon", exceptId = a.id))
+ CustomThemes.save(ctx, b)
+ assertEquals(2, CustomThemes.all(ctx).size)
+ assertEquals(a, CustomThemes.get(ctx, a.id))
+ assertNotNull(CustomThemes.bannerFile(ctx, a))
+ val stamp = CustomThemes.stamp(ctx, a)
+ CustomThemes.save(ctx, a.copy(accent = 0xFF00FF00.toInt()))
+ assertNotEquals("a changed choice changes the stamp open screens compare", stamp, CustomThemes.stamp(ctx, CustomThemes.get(ctx, a.id)!!))
+ CustomThemes.delete(ctx, a.id)
+ assertNull(CustomThemes.get(ctx, a.id)); assertFalse(CustomThemes.dir(ctx, a.id).exists())
+ assertEquals(1, CustomThemes.all(ctx).size)
+ }
+
+ @Test
+ fun onlyAPictureCanBeABannerAndOnlyAFontCanBeAFont() {
+ val t = CustomTheme(id = CustomThemes.newId(), name = "x")
+ assertNull(CustomThemes.setBanner(ctx, t, "not a picture".toByteArray()))
+ assertNull(CustomThemes.setBanner(ctx, t, ByteArray(0)))
+ assertNull(CustomThemes.setBanner(ctx, t, ByteArray(CustomThemes.MAX_BANNER_BYTES + 1)))
+ assertEquals("banner", CustomThemes.setBanner(ctx, t, png())!!.banner)
+ assertNull(CustomThemes.setFont(ctx, t, "not a font at all".toByteArray()))
+ assertNull(CustomThemes.setFont(ctx, t, ByteArray(CustomThemes.MAX_FONT_BYTES + 1)))
+ assertFalse("a rejected font leaves nothing behind", java.io.File(CustomThemes.dir(ctx, t.id), "font.tmp").exists())
+ val cleared = CustomThemes.clearBanner(ctx, CustomThemes.setBanner(ctx, t, png())!!)
+ assertNull(cleared.banner); assertFalse(java.io.File(CustomThemes.dir(ctx, t.id), "banner").exists())
+ }
+
+ @Test
+ fun aSharedThemeComesBackWithItsPicture() {
+ val a = full()
+ val file = CustomThemes.toShareJson(ctx, a)
+ val shared = CustomThemes.parseShared(file)
+ assertEquals(a.copy(id = ""), shared.theme.copy(id = ""))
+ assertArrayEquals(CustomThemes.bannerFile(ctx, a)!!.readBytes(), shared.banner)
+ assertNull(shared.font)
+ assertEquals(setOf(ThemePart.COLORS, ThemePart.FONT, ThemePart.BANNER, ThemePart.HEADER, ThemePart.MARKER), CustomThemes.partsIn(shared))
+ assertEquals(CustomThemes.partsIn(shared), a.parts)
+ }
+
+ @Test
+ fun aFileThatIsNotAThemeIsRefusedWithAReason() {
+ fun why(text: String) = try { CustomThemes.parseShared(text); fail("accepted"); "" } catch (e: CustomThemes.BadThemeFile) { e.message!! }
+ assertTrue(why("hello").contains("not valid JSON"))
+ assertTrue(why("""{"app":"Other","type":"theme","format":1}""").contains("isn't an RF Sentinel theme"))
+ assertTrue(why("""{"app":"RF Sentinel","type":"backup","format":1}""").contains("isn't an RF Sentinel theme"))
+ assertTrue(why("""{"app":"RF Sentinel","type":"theme","format":9,"theme":{}}""").contains("newer version"))
+ assertTrue(why("""{"app":"RF Sentinel","type":"theme","format":1}""").contains("no theme"))
+ // A picture that is not a picture offers no banner to take.
+ val s = CustomThemes.parseShared("""{"app":"RF Sentinel","type":"theme","format":1,"theme":{"name":"p","banner":"banner"},"assets":{"banner":"AAAA"}}""")
+ assertNull(s.banner); assertFalse(ThemePart.BANNER in CustomThemes.partsIn(s))
+ }
+
+ @Test
+ fun importTakesOnlyTheTickedPartsIntoANewTheme() {
+ val src = CustomThemes.parseShared(CustomThemes.toShareJson(ctx, full()))
+ val t = CustomThemes.import(ctx, src, null, setOf(ThemePart.COLORS, ThemePart.MARKER), "Mine")
+ assertEquals("Mine", t.name)
+ assertEquals(src.theme.accent, t.accent); assertEquals("vibrant", t.scheme); assertEquals("black", t.mode)
+ assertEquals("taxi", t.markerStyle); assertEquals(1.4f, t.markerSize!!, 0f)
+ assertEquals("default", t.font); assertNull(t.banner); assertNull(t.header); assertNull(t.title)
+ assertEquals(t, CustomThemes.get(ctx, t.id))
+ assertNull(CustomThemes.bannerFile(ctx, t))
+ }
+
+ @Test
+ fun importIntoAnExistingThemeReplacesOnlyTheTickedParts() {
+ val mine = CustomTheme(id = CustomThemes.newId(), name = "Old", accent = 0xFF112233.toInt(), font = "mono", header = "CRT", title = "Old title",
+ markerStyle = "arrow", markerColor = "green", markerSize = 1.0f)
+ val withBanner = CustomThemes.setBanner(ctx, mine, png(Color.BLUE))!!
+ CustomThemes.save(ctx, withBanner)
+ val src = CustomThemes.parseShared(CustomThemes.toShareJson(ctx, full()))
+
+ val out = CustomThemes.import(ctx, src, withBanner, setOf(ThemePart.FONT, ThemePart.HEADER))
+ assertEquals("Old", out.name); assertEquals("the same theme, not a new one", withBanner.id, out.id)
+ assertEquals("serif", out.font); assertEquals("HUD", out.header); assertEquals("Neon Sentinel", out.title)
+ assertEquals("colours stay", 0xFF112233.toInt(), out.accent)
+ assertEquals("marker stays", "green", out.markerColor)
+ assertNotNull("banner stays", CustomThemes.bannerFile(ctx, out))
+ assertEquals(1, CustomThemes.all(ctx).filter { it.name.startsWith("Old") }.size)
+
+ val withNewBanner = CustomThemes.import(ctx, src, out, setOf(ThemePart.BANNER))
+ assertArrayEquals(src.banner, CustomThemes.bannerFile(ctx, withNewBanner)!!.readBytes())
+ assertEquals("serif", withNewBanner.font)
+ }
+
+ @Test
+ fun aFontThatCannotBeLoadedFallsBackToTheStandardFont() {
+ val src = CustomThemes.Shared(CustomTheme("", "f", font = "file", fontFile = "font"), null, "garbage".toByteArray())
+ val t = CustomThemes.import(ctx, src, null, setOf(ThemePart.FONT))
+ assertEquals("default", t.font); assertNull(t.fontFile)
+ // And a font choice without its file is not offered as a part to take.
+ assertFalse(ThemePart.FONT in CustomThemes.partsIn(CustomThemes.Shared(CustomTheme("", "f", font = "file"), null, null)))
+ }
+
+ @Test
+ fun duplicateCopiesThePictureToo() {
+ val a = full()
+ val copy = CustomThemes.duplicate(ctx, a)
+ assertNotEquals(a.id, copy.id); assertEquals("Neon copy", copy.name)
+ assertEquals(a.accent, copy.accent); assertEquals(a.markerStyle, copy.markerStyle)
+ assertArrayEquals(CustomThemes.bannerFile(ctx, a)!!.readBytes(), CustomThemes.bannerFile(ctx, copy)!!.readBytes())
+ CustomThemes.delete(ctx, a.id)
+ assertNotNull("deleting one does not take the other's picture", CustomThemes.bannerFile(ctx, CustomThemes.get(ctx, copy.id)!!))
+ }
+
+ @Test
+ fun theBackupBringsThemesBackWithTheirIdsAndPictures() {
+ val a = full(); val b = full(name = "Other")
+ val arr = CustomThemes.backup(ctx)
+ CustomThemes.delete(ctx, a.id); CustomThemes.delete(ctx, b.id)
+ CustomThemes.save(ctx, CustomTheme(id = "stray", name = "Stray"))
+ assertEquals(2, CustomThemes.restoreBackup(ctx, arr))
+ assertNull("a theme not in the backup is replaced", CustomThemes.get(ctx, "stray"))
+ assertEquals(a, CustomThemes.get(ctx, a.id))
+ assertNotNull(CustomThemes.bannerFile(ctx, CustomThemes.get(ctx, b.id)!!))
+ }
+
+ @Test
+ fun aDamagedThemeInABackupChangesNothing() {
+ val a = full()
+ val bad = JSONArray().put(JSONObject().put("id", "x").put("app", "Other"))
+ try { CustomThemes.restoreBackup(ctx, bad); fail("accepted") } catch (_: CustomThemes.BadThemeFile) {}
+ assertEquals(a, CustomThemes.get(ctx, a.id))
+ }
+
+ // ---- colours -------------------------------------------------------------------------------
+
+ @Test
+ fun theAccentMakesAPaletteAndPureBlackMakesBlackBackgrounds() {
+ assertTrue(CustomColors.available)
+ val t = CustomTheme("p", "p", accent = 0xFFE53935.toInt())
+ val normal = CustomColors.overrides(ctx, t, dark = true)
+ assertTrue("a palette is made (${normal.size})", normal.size > 20)
+ val black = CustomColors.overrides(ctx, t.copy(mode = "black"), dark = true)
+ fun colorOf(map: Map<Int, Int>, name: String): Int? {
+ val id = ctx.resources.getIdentifier(name, "color", ctx.packageName); assertNotEquals(name, 0, id); return map[id]
+ }
+ assertEquals(0xFF000000.toInt(), colorOf(black, "material_personalized_color_surface"))
+ assertEquals(0xFF000000.toInt(), colorOf(black, "material_personalized_color_background"))
+ assertNotEquals("the normal dark surface is not black", 0xFF000000.toInt(), colorOf(normal, "material_personalized_color_surface"))
+ assertNotEquals("raised containers stay a step lighter so cards still show", 0xFF000000.toInt(), colorOf(black, "material_personalized_color_surface_container_high"))
+ assertEquals("the accent colours are not touched by black", colorOf(normal, "material_personalized_color_primary"), colorOf(black, "material_personalized_color_primary"))
+ val light = CustomColors.overrides(ctx, t.copy(mode = "black"), dark = false)
+ assertNotEquals("black only changes the dark side", 0xFF000000.toInt(), colorOf(light, "material_personalized_color_surface"))
+ assertNull(CustomColors.blackFor("m3_sys_color_dynamic_dark_surface")); assertNull(CustomColors.blackFor("material_personalized_color_primary"))
+ }
+
+ @Test
+ fun everyPaletteStyleAndModeWorks() {
+ for (s in CustomColors.Scheme.entries) for (dark in listOf(false, true)) {
+ val sch = CustomColors.scheme(CustomTheme("p", "p", scheme = s.key), dark)
+ assertNotEquals(s.key, sch.primary, sch.surface)
+ }
+ assertEquals(CustomColors.Mode.SYSTEM, CustomColors.Mode.of("whatever")); assertEquals(CustomColors.Scheme.TONAL, CustomColors.Scheme.of(null))
+ assertTrue(CustomColors.isDark(ctx, CustomTheme("p", "p", mode = "dark"))); assertTrue(CustomColors.isDark(ctx, CustomTheme("p", "p", mode = "black")))
+ assertFalse(CustomColors.isDark(ctx, CustomTheme("p", "p", mode = "light")))
+ }
+
+ // ---- the theme in use --------------------------------------------------------------------------
+
+ @Test
+ fun theThemeInUseDecidesTheHeaderTitleBannerAndMarker() {
+ assertEquals(ThemeManager.AppTheme.SYSTEM, ThemeManager.current(ctx))
+ val a = full()
+ ThemeManager.setCustom(ctx, a.id)
+ assertEquals(ThemeManager.AppTheme.CUSTOM, ThemeManager.current(ctx)); assertEquals(a.id, ThemeManager.custom(ctx)!!.id)
+ assertEquals(ThemeHeaderView.Style.HUD, ThemeManager.headerStyle(ctx)); assertEquals("Neon Sentinel", ThemeManager.appTitle(ctx))
+ assertTrue(ThemeManager.hasBanner(ctx)); assertFalse("the Settings banner is a different one", ThemeManager.hasGlobalBanner(ctx))
+ val m = MarkerPicker.effective(ctx)
+ assertEquals("taxi", m.style); assertEquals("red", m.color); assertEquals(1.4f, m.size, 0f)
+ // A built-in theme is back: the marker is the one chosen in Settings.
+ ThemeManager.set(ctx, ThemeManager.builtIn.first { it != ThemeManager.AppTheme.SYSTEM })
+ assertNull(ThemeManager.custom(ctx)); assertEquals("arrow", MarkerPicker.effective(ctx).style)
+ assertFalse(ThemeManager.AppTheme.CUSTOM in ThemeManager.builtIn)
+ }
+
+ @Test
+ fun aDeletedThemeInUseIsTheDefaultLookAgain() {
+ val a = full()
+ ThemeManager.setCustom(ctx, a.id)
+ CustomThemes.delete(ctx, a.id)
+ assertEquals(ThemeManager.AppTheme.SYSTEM, ThemeManager.current(ctx)); assertNull(ThemeManager.custom(ctx))
+ }
+
+ @Test
+ fun theFontsAreRealOnes() {
+ assertNull(FontApplier.typeface(ctx, CustomTheme("p", "p", font = "default")))
+ for (f in FontApplier.families.filter { it.system != null }) assertNotNull(f.key, FontApplier.typeface(ctx, CustomTheme("p", "p", font = f.key)))
+ assertNull("a font file that is missing is the standard font", FontApplier.typeface(ctx, CustomTheme("p", "p", font = "file", fontFile = "font")))
+ val tv = android.widget.TextView(ctx).apply { setTypeface(android.graphics.Typeface.DEFAULT, android.graphics.Typeface.BOLD) }
+ val group = android.widget.LinearLayout(ctx).apply { addView(tv) }
+ FontApplier.apply(group, android.graphics.Typeface.SERIF)
+ assertTrue("bold is kept", tv.typeface.isBold)
+ assertNotEquals(android.graphics.Typeface.DEFAULT_BOLD, tv.typeface)
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/ui/MarkerArtTest.kt b/app/src/test/java/com/rfsentinel/app/ui/MarkerArtTest.kt
new file mode 100644
index 0000000..498e4ef
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/ui/MarkerArtTest.kt
@@ -0,0 +1,117 @@
+package com.rfsentinel.app.ui
+
+import android.graphics.Bitmap
+import android.graphics.Color
+import androidx.test.core.app.ApplicationProvider
+import com.rfsentinel.app.util.Prefs
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+import org.robolectric.annotation.GraphicsMode
+
+/** The position marker: every style in every colour draws, points up, and can be told apart. */
+@RunWith(RobolectricTestRunner::class)
+@GraphicsMode(GraphicsMode.Mode.NATIVE)
+@Config(sdk = [35], application = android.app.Application::class)
+class MarkerArtTest {
+
+ private val blue = MarkerArt.colorOf("blue").argb
+
+ private fun count(b: Bitmap, rows: IntRange, match: (Int) -> Boolean): Int {
+ var n = 0
+ for (y in rows) for (x in 0 until b.width) if (match(b.getPixel(x, y))) n++
+ return n
+ }
+
+ private fun opaque(b: Bitmap) = count(b, 0 until b.height) { Color.alpha(it) > 200 }
+
+ @Test
+ fun everyStyleInEveryColourDrawsAtTheSizeAsked() {
+ for (s in MarkerArt.Style.entries) for (c in MarkerArt.colors) {
+ val b = MarkerArt.render(s, c.argb, 120)
+ assertEquals("${s.key}/${c.key}", 120, b.height); assertEquals(60, b.width)
+ assertTrue("${s.key}/${c.key} has something drawn", opaque(b) > 600)
+ assertEquals("${s.key}: the corners are clear", 0, Color.alpha(b.getPixel(0, 0)))
+ assertEquals(0, Color.alpha(b.getPixel(b.width - 1, b.height - 1)))
+ }
+ }
+
+ @Test
+ fun theFrontIsAtTheTopOfEveryCarAndTheBackAtTheBottom() {
+ fun headlight(p: Int) = Color.red(p) > 235 && Color.green(p) > 225 && Color.blue(p) in 150..215 && Color.alpha(p) > 200
+ fun tail(p: Int) = Color.red(p) in 180..230 && Color.green(p) < 80 && Color.blue(p) < 80 && Color.alpha(p) > 200
+ for (s in MarkerArt.Style.entries.filter { it != MarkerArt.Style.ARROW && it != MarkerArt.Style.CHEVRON }) {
+ val b = MarkerArt.render(s, blue, 300)
+ val top = 0 until b.height / 4; val bottom = b.height * 3 / 4 until b.height
+ assertTrue("${s.key}: headlights at the front", count(b, top, ::headlight) > 20)
+ assertEquals("${s.key}: none at the back", 0, count(b, bottom, ::headlight))
+ assertTrue("${s.key}: tail lights at the back", count(b, bottom, ::tail) > 20)
+ assertEquals("${s.key}: none at the front", 0, count(b, top, ::tail))
+ }
+ }
+
+ @Test
+ fun anArrowPointsUp() {
+ for (s in listOf(MarkerArt.Style.ARROW, MarkerArt.Style.CHEVRON)) {
+ val b = MarkerArt.render(s, blue, 200)
+ // The tip is at the top, in the middle; the top corners are empty and the base is wide.
+ assertTrue(Color.alpha(b.getPixel(b.width / 2, 40)) > 200)
+ assertEquals(0, Color.alpha(b.getPixel(4, 40)))
+ assertTrue("wider at the back than at the tip", count(b, 150..150) { Color.alpha(it) > 200 } > count(b, 40..40) { Color.alpha(it) > 200 })
+ }
+ }
+
+ @Test
+ fun theColourChangesTheMarker() {
+ val a = MarkerArt.render(MarkerArt.Style.SEDAN, MarkerArt.colorOf("red").argb, 200)
+ val b = MarkerArt.render(MarkerArt.Style.SEDAN, MarkerArt.colorOf("green").argb, 200)
+ val side = a.width / 2 - 14 // on the body, beside the cabin
+ assertNotEquals(a.getPixel(side, 100), b.getPixel(side, 100))
+ assertTrue("red is red", Color.red(a.getPixel(side, 100)) > Color.green(a.getPixel(side, 100)) + 60)
+ assertTrue("green is green", Color.green(b.getPixel(side, 100)) > Color.red(b.getPixel(side, 100)) + 30)
+ }
+
+ @Test
+ fun theStylesLookDifferent() {
+ val seen = HashSet<Int>()
+ for (s in MarkerArt.Style.entries) {
+ val b = MarkerArt.render(s, blue, 100)
+ val px = IntArray(b.width * b.height); b.getPixels(px, 0, b.width, 0, 0, b.width, b.height)
+ assertTrue("${s.key} differs from the others", seen.add(px.contentHashCode()))
+ }
+ assertEquals(15, MarkerArt.Style.entries.size)
+ assertEquals(16, MarkerArt.colors.size)
+ }
+
+ @Test
+ fun keysFindTheirStyleAndColourAndFallBackToTheDefaults() {
+ assertEquals(MarkerArt.Style.SPORTS, MarkerArt.Style.of("sports"))
+ assertEquals(MarkerArt.Style.ARROW, MarkerArt.Style.of("something else"))
+ assertEquals(MarkerArt.Style.ARROW, MarkerArt.Style.of(null))
+ assertEquals("blue", MarkerArt.colorOf("nope").key)
+ assertEquals("pink", MarkerArt.colorOf("pink").key)
+ assertEquals(MarkerArt.Style.entries.size, MarkerArt.Style.entries.map { it.key }.toSet().size)
+ assertEquals(MarkerArt.colors.size, MarkerArt.colors.map { it.key }.toSet().size)
+ }
+
+ @Test
+ fun theChoiceIsSavedAndTheSizeStaysInRange() {
+ val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()
+ assertEquals("arrow", Prefs.markerStyle(ctx)); assertEquals("blue", Prefs.markerColor(ctx)); assertEquals(1.0f, Prefs.markerSize(ctx), 0f)
+ Prefs.setMarker(ctx, "taxi", "yellow", 1.4f)
+ assertEquals("taxi", Prefs.markerStyle(ctx)); assertEquals("yellow", Prefs.markerColor(ctx)); assertEquals(1.4f, Prefs.markerSize(ctx), 1e-6f)
+ Prefs.setMarker(ctx, "taxi", "yellow", 9f)
+ assertEquals(2.0f, Prefs.markerSize(ctx), 0f)
+ Prefs.setMarker(ctx, "taxi", "yellow", 0.1f)
+ assertEquals(0.6f, Prefs.markerSize(ctx), 0f)
+ Prefs.setMarker(ctx, "taxi", "yellow", 1.0f)
+ val h = MarkerPicker.current(ctx).height
+ assertEquals(MarkerPicker.heightPx(ctx, 1.0f), h)
+ assertTrue(MarkerPicker.heightPx(ctx, 2.0f) > MarkerPicker.heightPx(ctx, 1.0f))
+ assertEquals("Taxi · Yellow", MarkerPicker.summary(ctx))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/util/DeviceHistoryImportTest.kt b/app/src/test/java/com/rfsentinel/app/util/DeviceHistoryImportTest.kt
new file mode 100644
index 0000000..7c35642
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/util/DeviceHistoryImportTest.kt
@@ -0,0 +1,123 @@
+package com.rfsentinel.app.util
+
+import androidx.room.Room
+import androidx.test.core.app.ApplicationProvider
+import com.rfsentinel.app.data.AppDatabase
+import com.rfsentinel.app.data.KnownDeviceEntity
+import kotlinx.coroutines.runBlocking
+import org.junit.After
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/** Device history import: the app's own JSON and CSV exports are read back, and merging loses nothing. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = android.app.Application::class)
+class DeviceHistoryImportTest {
+
+ private lateinit var db: AppDatabase
+
+ @Before fun open() { db = Room.inMemoryDatabaseBuilder(ApplicationProvider.getApplicationContext(), AppDatabase::class.java).allowMainThreadQueries().build() }
+ @After fun close() { db.close() }
+
+ private val json = """[
+ {"mac":"aa:bb:cc:00:00:01","name":"Tag one","vendor":"Acme","deviceType":"Tracker","firstSeen":"2026-01-02T03:04:05Z","lastSeen":"2026-02-03T04:05:06Z","sessions":4,"detectCount":9,"favorite":true,"note":"mine"},
+ {"mac":"AA:BB:CC:00:00:02","name":null,"vendor":"Other","deviceType":null,"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-01T00:00:00Z","sessions":1,"detectCount":1,"favorite":false,"note":null},
+ {"mac":"not a mac","name":"junk"},
+ "stray"
+ ]"""
+
+ private fun run(text: String) = runBlocking { DeviceHistoryImport.importInto(db.knownDeviceDao(), text.byteInputStream()) }
+
+ @Test
+ fun theJsonExportIsReadBackWithItsDetails() {
+ val r = run(json)
+ assertEquals(2, r.added); assertEquals(0, r.updated); assertEquals(2, r.skipped)
+ val d = runBlocking { db.knownDeviceDao().get("AA:BB:CC:00:00:01") }!!
+ assertEquals("Tag one", d.name); assertEquals("Acme", d.vendor); assertEquals("Tracker", d.deviceType)
+ assertEquals(4, d.sessions); assertEquals(9, d.detectCount); assertTrue(d.favorite); assertEquals("mine", d.note)
+ assertTrue("the time was read (UTC)", d.firstSeen > 1_700_000_000_000L && d.lastSeen > d.firstSeen)
+ assertNull(runBlocking { db.knownDeviceDao().get("AA:BB:CC:00:00:02") }!!.name)
+ }
+
+ @Test
+ fun importingTheSameFileAgainChangesNothing() {
+ run(json)
+ val again = run(json)
+ assertEquals(0, again.added); assertEquals(0, again.updated); assertEquals(2, again.unchanged)
+ assertEquals(2, runBlocking { db.knownDeviceDao().count() })
+ }
+
+ @Test
+ fun theEverythingExportAndTheCsvAreReadToo() {
+ val everything = """{"exportedBy":"RF Sentinel 2.20.0","sessionDevices":[{"mac":"11:11:11:11:11:11"}],"deviceHistory":[
+ {"mac":"DE:AD:BE:EF:00:01","name":"Cam","vendor":"V","deviceType":"Camera","firstSeen":"2026-03-01T10:00:00Z","lastSeen":"2026-03-02T10:00:00Z","sessions":2,"detectCount":3,"favorite":false,"note":"a, \"quoted\" note"}],"matchLog":[]}"""
+ assertEquals(1, run(everything).added)
+ assertNull("the live session list is not history", runBlocking { db.knownDeviceDao().get("11:11:11:11:11:11") })
+ val csv = "mac,name,vendor,device_type,first_seen,last_seen,sessions,detect_count,favorite,note\n" +
+ "AA:00:00:00:00:01,\"Name, with comma\",Vend,Phone,2026-04-01 08:00:00,2026-04-02 09:30:00,5,12,true,\"line one\nline two\"\r\n" +
+ "AA:00:00:00:00:02,,,,,,,,,\n"
+ val r = run(csv)
+ assertEquals(2, r.added)
+ val d = runBlocking { db.knownDeviceDao().get("AA:00:00:00:00:01") }!!
+ assertEquals("Name, with comma", d.name); assertEquals("line one\nline two", d.note); assertTrue(d.favorite); assertEquals(12, d.detectCount)
+ assertNotNull(runBlocking { db.knownDeviceDao().get("AA:00:00:00:00:02") })
+ assertEquals("a, \"quoted\" note", runBlocking { db.knownDeviceDao().get("DE:AD:BE:EF:00:01") }!!.note)
+ }
+
+ @Test
+ fun mergingKeepsWhatIsThereAndFillsInTheRest() {
+ fun e(first: Long, last: Long, sessions: Int, detects: Int, name: String?, fav: Boolean, note: String?, vendor: String? = null) =
+ KnownDeviceEntity("AA:BB:CC:DD:EE:FF", first, last, sessions, detects, name, vendor, null, fav, note)
+ val mine = e(1000, 5000, 3, 8, "Mine", false, null)
+ val theirs = e(500, 4000, 9, 5, "Theirs", true, "their note", "Vendor")
+ val m = DeviceHistoryImport.merge(mine, theirs)
+ assertEquals(500L, m.firstSeen); assertEquals(5000L, m.lastSeen)
+ assertEquals(9, m.sessions); assertEquals(8, m.detectCount)
+ assertEquals("my name stays", "Mine", m.name); assertEquals("a missing vendor is filled in", "Vendor", m.vendor)
+ assertTrue("a star is never lost", m.favorite); assertEquals("their note fills the gap", "their note", m.note)
+ assertEquals("merging again changes nothing", m, DeviceHistoryImport.merge(m, theirs))
+ assertEquals(theirs, DeviceHistoryImport.merge(null, theirs))
+ assertEquals("my note stays", "mine!", DeviceHistoryImport.merge(e(1, 2, 1, 1, null, false, "mine!"), theirs).note)
+ }
+
+ @Test
+ fun deviceListedTwiceInOneFileMergesAndRowsAreCheckedAndCleaned() {
+ val twice = """[{"mac":"AA:BB:CC:00:00:09","sessions":2,"detectCount":1,"firstSeen":"2026-01-01T00:00:00Z","lastSeen":"2026-01-02T00:00:00Z"},
+ {"mac":"aa:bb:cc:00:00:09","sessions":7,"detectCount":1,"firstSeen":"2026-01-05T00:00:00Z","lastSeen":"2026-01-06T00:00:00Z","name":" Spaced "}]"""
+ assertEquals(1, run(twice).added)
+ val d = runBlocking { db.knownDeviceDao().get("AA:BB:CC:00:00:09") }!!
+ assertEquals(7, d.sessions); assertEquals("Spaced", d.name)
+ assertNull(DeviceHistoryImport.row("12:34", null, null, null, null, null, null, null, null, null))
+ assertNull(DeviceHistoryImport.row("AA:BB:CC:DD:EE:GG", null, null, null, null, null, null, null, null, null))
+ val bare = DeviceHistoryImport.row("aa:bb:cc:dd:ee:ff", "null", "", null, null, null, "-3", "0", "no", null, now = 5_000L)!!
+ assertEquals("AA:BB:CC:DD:EE:FF", bare.mac); assertNull(bare.name); assertNull(bare.vendor)
+ assertEquals(1, bare.sessions); assertEquals(1, bare.detectCount); assertFalse(bare.favorite)
+ assertEquals("a missing time is now", 5_000L, bare.firstSeen)
+ }
+
+ @Test
+ fun otherFilesAreRefusedWithAReason() {
+ fun refused(text: String): String = runCatching { run(text) }.exceptionOrNull().let { (it as DeviceHistoryImport.NotHistory).message!! }
+ assertTrue(refused("""{"hello":"world"}""").contains("no device history"))
+ assertTrue(refused("name,vendor\nA,B\n").contains("no \"mac\" column"))
+ assertTrue(refused("").contains("empty"))
+ assertTrue(refused("\"just a string\"").contains("isn't a device history"))
+ assertEquals(0, runBlocking { db.knownDeviceDao().count() })
+ }
+
+ @Test
+ fun aHugeFileIsStoppedNotReadToTheEnd() {
+ val big = java.io.ByteArrayInputStream(ByteArray(200))
+ val e = runCatching { DeviceHistoryImport.Limited(big, limit = 100).readBytes() }.exceptionOrNull()
+ assertTrue(e is DeviceHistoryImport.NotHistory)
+ assertTrue(DeviceHistoryImport.fileName(0L).startsWith("rf_sentinel_device_history_"))
+ }
+}
diff --git a/app/src/test/java/com/rfsentinel/app/util/SettingsBackupTest.kt b/app/src/test/java/com/rfsentinel/app/util/SettingsBackupTest.kt
new file mode 100644
index 0000000..19864c7
--- /dev/null
+++ b/app/src/test/java/com/rfsentinel/app/util/SettingsBackupTest.kt
@@ -0,0 +1,166 @@
+package com.rfsentinel.app.util
+
+import android.content.Context
+import androidx.test.core.app.ApplicationProvider
+import com.rfsentinel.app.ui.MapFragment
+import org.json.JSONObject
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotNull
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.annotation.Config
+
+/** Settings backup and restore, and when the live map takes you back to your position. */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [35], application = android.app.Application::class)
+class SettingsBackupTest {
+
+ private val ctx get() = ApplicationProvider.getApplicationContext<Context>()
+ private fun sp(file: String) = ctx.getSharedPreferences(file, Context.MODE_PRIVATE)
+
+ @Test
+ fun aBackupRestoresEveryKindOfSettingAndLeavesTheRest() {
+ val main = sp("rf_sentinel_prefs")
+ main.edit().putBoolean("map_3d", true).putInt("retention_days", 45).putFloat("map_default_zoom", 16.5f)
+ .putString("map_marker_style", "taxi").putLong("scan_interval_ms", 4000L)
+ .putStringSet("cat_x", setOf("a", "b"))
+ .putString("map_center", "1.0,2.0").putBoolean("waze_accepted", true).putLong("alerts_snoozed_until", 99L).commit()
+ sp("nav_places").edit().putString("nav_home", "HOME-JSON").putString("recent_destinations", "RECENT").commit()
+ sp("oui_watchlist_prefs").edit().putString("entries", "[rule]").commit()
+ val file = SettingsBackup.create(ctx, now = 1_000L)
+
+ // Another state of the phone: everything changed, plus things that must survive.
+ main.edit().clear().putBoolean("map_3d", false).putInt("retention_days", 7).putString("map_marker_style", "arrow")
+ .putBoolean("waze_accepted", false).putString("map_center", "9.0,9.0").putBoolean("stale_setting", true).commit()
+ sp("nav_places").edit().putString("nav_home", "OTHER").putString("recent_destinations", "OTHER-RECENT").commit()
+
+ val r = SettingsBackup.restore(ctx, file)
+ assertTrue(r is SettingsBackup.Result.Restored)
+ assertTrue(main.getBoolean("map_3d", false)); assertEquals(45, main.getInt("retention_days", 0))
+ assertEquals(16.5f, main.getFloat("map_default_zoom", 0f), 0f); assertEquals("taxi", main.getString("map_marker_style", null))
+ assertEquals(4000L, main.getLong("scan_interval_ms", 0L)); assertEquals(setOf("a", "b"), main.getStringSet("cat_x", null))
+ assertFalse("a setting the backup does not have goes back to its default", main.contains("stale_setting"))
+ assertEquals("[rule]", sp("oui_watchlist_prefs").getString("entries", null))
+ assertEquals("HOME-JSON", sp("nav_places").getString("nav_home", null))
+ // Never part of it: where the map was, acknowledgements, snoozes, recent places.
+ assertEquals("9.0,9.0", main.getString("map_center", null))
+ assertFalse("the risk acknowledgement stays as this phone has it", main.getBoolean("waze_accepted", true))
+ assertEquals("OTHER-RECENT", sp("nav_places").getString("recent_destinations", null))
+ }
+
+ @Test
+ fun theFileNeverCarriesSecretsOrState() {
+ sp("rf_sentinel_prefs").edit().putString("map_center", "1.0,2.0").putBoolean("waze_direct_accepted", true).putString("live_export_tree", "content://x")
+ .putString("tracker_follow_paused_until", "5").putBoolean("sound_enabled", true).commit()
+ sp("secure_store").edit().putString("owninja_key", "SECRET-VALUE").commit()
+ sp("nav_places").edit().putString("recent_destinations", "RECENT").commit()
+ sp("tracker_mutes").edit().putString("mutes", "AA:BB").commit()
+ val file = SettingsBackup.create(ctx)
+ for (bad in listOf("SECRET-VALUE", "map_center", "waze_direct_accepted", "live_export_tree", "RECENT", "tracker_follow_paused_until", "AA:BB"))
+ assertFalse("$bad is not in the backup", file.contains(bad))
+ assertTrue(file.contains("sound_enabled"))
+ val root = JSONObject(file)
+ assertEquals("RF Sentinel", root.getString("app")); assertEquals(SettingsBackup.FORMAT, root.getInt("format"))
+ }
+
+ @Test
+ fun aFileThatIsNotABackupChangesNothing() {
+ val main = sp("rf_sentinel_prefs"); main.edit().clear().putInt("retention_days", 12).commit()
+ fun refused(text: String): String = (SettingsBackup.restore(ctx, text) as SettingsBackup.Result.Refused).why
+ assertTrue(refused("not json at all").contains("not valid JSON"))
+ assertTrue(refused("""{"app":"Something else","format":1,"files":{}}""").contains("isn't an RF Sentinel backup"))
+ assertTrue(refused("""{"app":"RF Sentinel","format":99,"files":{}}""").contains("newer version"))
+ assertTrue(refused("""{"app":"RF Sentinel","format":1}""").contains("no settings"))
+ // One damaged entry stops the whole restore: nothing is half applied.
+ refused("""{"app":"RF Sentinel","format":1,"files":{"rf_sentinel_prefs":{"retention_days":{"t":"i","v":3},"broken":{"t":"zzz","v":1}}}}""")
+ assertEquals(12, main.getInt("retention_days", 0))
+ assertTrue(refused("x".repeat(SettingsBackup.MAX_BYTES + 1)).contains("too big"))
+ assertNull(main.getString("broken", null))
+ }
+
+ @Test
+ fun aRestoreCanTakeJustSomeSections() {
+ val main = sp("rf_sentinel_prefs")
+ main.edit().clear().putInt("retention_days", 45).commit()
+ sp("nav_places").edit().putString("nav_home", "HOME").commit()
+ sp("oui_watchlist_prefs").edit().putString("entries", "[rule]").commit()
+ val file = SettingsBackup.create(ctx)
+ val found = SettingsBackup.inspect(file) as SettingsBackup.Inspect.Ok
+ assertEquals(listOf(SettingsBackup.Section.SETTINGS, SettingsBackup.Section.WATCHLIST, SettingsBackup.Section.PLACES, SettingsBackup.Section.FLOATING), found.sections)
+ main.edit().putInt("retention_days", 7).commit()
+ sp("nav_places").edit().putString("nav_home", "ELSEWHERE").commit()
+ sp("oui_watchlist_prefs").edit().putString("entries", "[mine]").commit()
+
+ SettingsBackup.restore(ctx, file, setOf(SettingsBackup.Section.WATCHLIST, SettingsBackup.Section.PLACES))
+ assertEquals("settings not ticked: untouched", 7, main.getInt("retention_days", 0))
+ assertEquals("[rule]", sp("oui_watchlist_prefs").getString("entries", null))
+ assertEquals("HOME", sp("nav_places").getString("nav_home", null))
+ }
+
+ @Test
+ fun customThemesTravelInTheBackupAndRestoreOnTheirOwn() {
+ val pic = java.io.ByteArrayOutputStream().also { out ->
+ android.graphics.Bitmap.createBitmap(4, 4, android.graphics.Bitmap.Config.ARGB_8888).compress(android.graphics.Bitmap.CompressFormat.PNG, 100, out)
+ }.toByteArray()
+ val t = com.rfsentinel.app.ui.CustomThemes.setBanner(ctx, com.rfsentinel.app.ui.CustomTheme(id = "tabc", name = "Mine", font = "mono", markerStyle = "suv", markerColor = "teal", markerSize = 1.2f), pic)!!
+ com.rfsentinel.app.ui.CustomThemes.save(ctx, t)
+ sp("rf_sentinel_prefs").edit().clear().putInt("retention_days", 45).commit()
+ val file = SettingsBackup.create(ctx)
+ val found = SettingsBackup.inspect(file) as SettingsBackup.Inspect.Ok
+ assertTrue(SettingsBackup.Section.THEMES in found.sections); assertEquals(1, found.themes)
+
+ com.rfsentinel.app.ui.CustomThemes.delete(ctx, "tabc")
+ sp("rf_sentinel_prefs").edit().putInt("retention_days", 7).commit()
+ val r = SettingsBackup.restore(ctx, file, setOf(SettingsBackup.Section.THEMES)) as SettingsBackup.Result.Restored
+ assertEquals(1, r.count)
+ assertEquals(t, com.rfsentinel.app.ui.CustomThemes.get(ctx, "tabc"))
+ assertNotNull(com.rfsentinel.app.ui.CustomThemes.bannerFile(ctx, t))
+ assertEquals("only themes were ticked", 7, sp("rf_sentinel_prefs").getInt("retention_days", 0))
+
+ // Everything but the themes: they stay as they are.
+ com.rfsentinel.app.ui.CustomThemes.delete(ctx, "tabc")
+ SettingsBackup.restore(ctx, file, SettingsBackup.Section.entries.toSet() - SettingsBackup.Section.THEMES)
+ assertNull(com.rfsentinel.app.ui.CustomThemes.get(ctx, "tabc"))
+ assertEquals(45, sp("rf_sentinel_prefs").getInt("retention_days", 0))
+ }
+
+ @Test
+ fun aDamagedThemeStopsTheWholeRestore() {
+ val main = sp("rf_sentinel_prefs"); main.edit().clear().putInt("retention_days", 12).commit()
+ val bad = """{"app":"RF Sentinel","format":1,"files":{"rf_sentinel_prefs":{"retention_days":{"t":"i","v":3}}},"customThemes":[{"id":"x","app":"Other"}]}"""
+ assertTrue(SettingsBackup.restore(ctx, bad) is SettingsBackup.Result.Refused)
+ assertEquals(12, main.getInt("retention_days", 0))
+ assertTrue(SettingsBackup.inspect("nope") is SettingsBackup.Inspect.Bad)
+ }
+
+ @Test
+ fun readingStopsAtTheLimit() {
+ assertEquals("hello", SettingsBackup.read("hello".byteInputStream()))
+ val big = object : java.io.InputStream() { override fun read() = 'x'.code }
+ assertNull(SettingsBackup.read(big))
+ }
+
+ @Test
+ fun theFileNameCarriesTheDate() {
+ assertTrue(SettingsBackup.fileName(0L).startsWith("rf-sentinel-settings-19"))
+ assertTrue(SettingsBackup.fileName().endsWith(".json"))
+ }
+
+ @Test
+ fun theMapTakesYouBackOnlyWhileDrivingAndAfterTenQuietSeconds() {
+ fun go(enabled: Boolean = true, following: Boolean = false, live: Boolean = true, guiding: Boolean = false, speed: Float = 10f,
+ card: Boolean = false, idle: Long = 11_000L) = MapFragment.shouldRecenter(enabled, following, live, guiding, speed, card, idle)
+ assertTrue("moving, left alone for 11 s", go())
+ assertTrue("guided, even when stopped at a light", go(guiding = true, speed = 0f))
+ assertFalse("not yet", go(idle = 9_000L))
+ assertFalse("parked and browsing", go(speed = 0f))
+ assertFalse("switched off", go(enabled = false))
+ assertFalse("already following", go(following = true))
+ assertFalse("a saved trace", go(live = false))
+ assertFalse("looking at a place", go(card = true))
+ }
+}
diff --git a/docs/index.html b/docs/index.html
index 26a8203..51b9254 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -24,7 +24,7 @@
<link rel="icon" href="favicon.svg" type="image/svg+xml">
<link rel="preload" href="assets/fonts/share-tech-mono.ttf" as="font" type="font/ttf" crossorigin>
<link rel="stylesheet" href="assets/style.css">
-<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF-Sentinel", "RF Sentinel app", "RF Sentinel Android", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.20.0", "dateModified": "2026-10-13", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF-Sentinel"], "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>
+<script type="application/ld+json">{"@context": "https://schema.org", "@graph": [{"@type": "SoftwareApplication", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF-Sentinel", "RF Sentinel app", "RF Sentinel Android", "RF Sentinel police scanner"], "applicationCategory": "UtilitiesApplication", "operatingSystem": "Android 8.0+", "description": "Free police detector for Android: spots police body cams, patrol cars, Flock plate cameras and fake cell towers via Bluetooth and WiFi. No root. Download free.", "url": "https://cis-c0.github.io/RFSentinel/", "downloadUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "installUrl": "https://github.com/CIS-C0/RFSentinel/releases/latest", "softwareHelp": "https://cis-c0.github.io/RFSentinel/qa.html", "license": "https://www.gnu.org/licenses/gpl-3.0.html", "isAccessibleForFree": true, "offers": {"@type": "Offer", "price": "0", "priceCurrency": "USD"}, "codeRepository": "https://github.com/CIS-C0/RFSentinel", "programmingLanguage": "Kotlin", "image": "https://cis-c0.github.io/RFSentinel/assets/og.png", "screenshot": "https://cis-c0.github.io/RFSentinel/screenshots/list-dedsec.jpg", "softwareVersion": "2.21.0", "dateModified": "2026-10-13", "author": {"@type": "Organization", "name": "CIS-C0", "url": "https://github.com/CIS-C0"}, "sameAs": ["https://github.com/CIS-C0/RFSentinel", "https://discord.gg/NDTjn8HMGq"]}, {"@type": "WebSite", "name": "RF Sentinel", "alternateName": ["RFSentinel", "RF-Sentinel"], "url": "https://cis-c0.github.io/RFSentinel/"}]}</script>
</head>
<body>
<a class="skip" href="#main">Skip to content</a>
@@ -105,7 +105,7 @@
<div class="card"><h3>ESP32 boards</h3><p>OUI-Spy over USB OTG or Bluetooth, GhostESP and Marauder over USB (dual-band on ESP32-C5, or through a Flipper Zero with a BFFB). The board's detections merge into the app. <a href="esp32.html">Details</a></p></div>
<div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement. Search every device the app remembers, in range or not, by address, name, vendor, type or your note.</p></div>
<div class="card"><h3>Export</h3><p>CSV, JSON, KML, GPX, GeoJSON. Everything stays on the phone until you export or share it.</p></div>
- <div class="card"><h3>13 themes</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT.</p></div>
+ <div class="card"><h3>13 themes and a theme maker</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT. Make your own: colours, font, banner, header and map marker, and share it as a file.</p></div>
</div>
<h2 id="screens">Screenshots</h2>
diff --git a/site/pages/index.html b/site/pages/index.html
index 4a2ffbb..780ed40 100644
--- a/site/pages/index.html
+++ b/site/pages/index.html
@@ -65,7 +65,7 @@
<div class="card"><h3>ESP32 boards</h3><p>OUI-Spy over USB OTG or Bluetooth, GhostESP and Marauder over USB (dual-band on ESP32-C5, or through a Flipper Zero with a BFFB). The board's detections merge into the app. <a href="esp32.html">Details</a></p></div>
<div class="card"><h3>Device details</h3><p>Evidence, identity, decoded protocol data, signal graph, Locate mode (beeps faster as you get closer, and keeps following a tag when it changes its address), history and the raw advertisement. Search every device the app remembers, in range or not, by address, name, vendor, type or your note.</p></div>
<div class="card"><h3>Export</h3><p>CSV, JSON, KML, GPX, GeoJSON. Everything stays on the phone until you export or share it.</p></div>
- <div class="card"><h3>13 themes</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT.</p></div>
+ <div class="card"><h3>13 themes and a theme maker</h3><p>Including DedSec (Watch Dogs 2) and fsociety (Mr. Robot) fan themes with animated terminal headers, Night Drive red HUD, Night Vision, Amber CRT. Make your own: colours, font, banner, header and map marker, and share it as a file.</p></div>
</div>
<h2 id="screens">Screenshots</h2>