diff --git a/AndroidManifest.xml b/AndroidManifest.xml index 1a43587..ea994fe 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -44,16 +44,20 @@ + + + + @@ -79,6 +83,7 @@ + safeCurrent) return safeCurrent + 1; + if (safeTarget < safeCurrent) return safeCurrent - 1; + return safeCurrent; + } + + /** Infers the unmodified driver reference from a manual audible-volume change. */ + public static float referenceFraction(float audibleFraction, float multiplierPercent) { + float audible = finite(audibleFraction) ? clamp(audibleFraction, 0f, 1f) : 0f; + float multiplier = finite(multiplierPercent) ? multiplierPercent / 100f : 1f; + return clamp(audible / Math.max(0.01f, multiplier), 0f, 1f); + } + + private static float interpolate(float value, float start, float end, + float startValue, float endValue) { + if (end <= start) return endValue; + float progress = (value - start) / (end - start); + return startValue + (endValue - startValue) * progress; + } + + private static int clamp(int value, int minimum, int maximum) { + return Math.max(minimum, Math.min(maximum, value)); + } + + private static float clamp(float value, float minimum, float maximum) { + return Math.max(minimum, Math.min(maximum, value)); + } + + private static boolean finite(float value) { + return !Float.isNaN(value) && !Float.isInfinite(value); + } +} diff --git a/src/cloud/molberg/mgutility/AdaptiveAudioLevelingActivity.java b/src/cloud/molberg/mgutility/AdaptiveAudioLevelingActivity.java new file mode 100644 index 0000000..0a2ace7 --- /dev/null +++ b/src/cloud/molberg/mgutility/AdaptiveAudioLevelingActivity.java @@ -0,0 +1,215 @@ +package cloud.molberg.mgutility; + +import android.graphics.Typeface; +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.SeekBar; +import android.widget.Switch; +import android.widget.TextView; +import android.widget.Toast; + +/** Settings for the three-point adaptive media-volume curve. */ +public final class AdaptiveAudioLevelingActivity extends AnimatedActivity { + private Switch enabled; + private final SeekBar[] audio = new SeekBar[3]; + private final SeekBar[] speed = new SeekBar[3]; + private final TextView[] audioValue = new TextView[3]; + private final TextView[] speedValue = new TextView[3]; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + setRequestedOrientation(android.content.pm.ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); + immersive(); + setContentView(buildUi()); + } + + @Override public void onWindowFocusChanged(boolean focused) { + super.onWindowFocusChanged(focused); + if (focused) immersive(); + } + + private void immersive() { + getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + private View buildUi() { + AdaptiveAudioLevelingManager.Config cfg = AdaptiveAudioLevelingManager.config(this); + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setPadding(28, 16, 28, 16); + root.setBackgroundColor(UiTheme.BACKGROUND); + + LinearLayout bar = new LinearLayout(this); + bar.setGravity(Gravity.CENTER_VERTICAL); + bar.addView(UiTheme.title(this, "ADAPTIVE AUDIO LEVELING", 26), + new LinearLayout.LayoutParams(0, 58, 1)); + Button save = UiTheme.button(this, "SAVE & APPLY", new View.OnClickListener() { + @Override public void onClick(View v) { saveAll(); } + }, true); + bar.addView(save, new LinearLayout.LayoutParams(190, 58)); + Button back = UiTheme.backButton(this, new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }); + LinearLayout.LayoutParams backParams = new LinearLayout.LayoutParams(120, 58); + backParams.setMargins(12, 0, 0, 0); + bar.addView(back, backParams); + root.addView(bar); + + TextView intro = text("Keeps your chosen media volume, then gently scales it as road speed changes. The three speed points blend smoothly, so there are no sudden volume jumps.", + 12, UiTheme.MUTED, Typeface.NORMAL); + intro.setPadding(4, 4, 4, 10); + root.addView(intro); + + ScrollView scroll = new ScrollView(this); + scroll.setFillViewport(true); + LinearLayout list = new LinearLayout(this); + list.setOrientation(LinearLayout.VERTICAL); + list.setBackground(UiTheme.surface(UiTheme.SURFACE, 12)); + + enabled = new Switch(this); + enabled.setText("ADJUST MEDIA VOLUME WHILE DRIVING"); + enabled.setTextColor(UiTheme.TEXT); + enabled.setTextSize(14); + enabled.setChecked(cfg.enabled); + list.addView(card("FEATURE", enabled)); + + addLevel(list, 0, cfg.level1AudioPercent, cfg.level1SpeedKph, + "Used at and below this speed"); + addLevel(list, 1, cfg.level2AudioPercent, cfg.level2SpeedKph, + "Blends from Level 1 to this point"); + addLevel(list, 2, cfg.level3AudioPercent, cfg.level3SpeedKph, + "Used at and above this speed"); + + TextView footer = text("100% leaves your chosen volume unchanged. For example, 90% makes it slightly quieter and 110% makes it slightly louder. Automatic changes ramp one volume notch at a time; steering-wheel changes remain immediate and become the new reference volume.", + 11, UiTheme.MUTED, Typeface.NORMAL); + footer.setPadding(12, 12, 12, 14); + list.addView(footer); + + scroll.addView(list); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private void addLevel(LinearLayout parent, final int index, int audioPercent, + int speedKph, String hint) { + LinearLayout group = new LinearLayout(this); + group.setOrientation(LinearLayout.VERTICAL); + group.setPadding(14, 10, 14, 10); + group.setBackground(UiTheme.surface(UiTheme.SURFACE_HIGH, 10)); + + TextView heading = text("LEVEL " + (index + 1), 13, UiTheme.TEXT, Typeface.BOLD); + group.addView(heading); + TextView description = text(hint, 10, UiTheme.MUTED, Typeface.NORMAL); + description.setPadding(0, 1, 0, 5); + group.addView(description); + + audio[index] = new SeekBar(this); + UiTheme.tintSeekBar(audio[index]); + audio[index].setMax(AdaptiveAudioLevelingManager.MAX_AUDIO_PERCENT - + AdaptiveAudioLevelingManager.MIN_AUDIO_PERCENT); + audio[index].setProgress(AdaptiveAudioLevelingManager.clampAudio(audioPercent) - + AdaptiveAudioLevelingManager.MIN_AUDIO_PERCENT); + audio[index].setContentDescription("Level " + (index + 1) + " audio multiplier"); + audioValue[index] = valueLabel(formatAudio(audioPercent)); + audio[index].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { + audioValue[index].setText(formatAudio(audioPercent(index))); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { } + }); + group.addView(sliderRow("AUDIO LEVEL", audio[index], audioValue[index])); + + speed[index] = new SeekBar(this); + UiTheme.tintSeekBar(speed[index]); + speed[index].setMax(AdaptiveAudioLevelingManager.MAX_SPEED_KPH); + speed[index].setProgress(AdaptiveAudioLevelingManager.clampSpeed(speedKph)); + speed[index].setContentDescription("Level " + (index + 1) + " speed"); + speedValue[index] = valueLabel(formatSpeed(speedKph)); + speed[index].setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { + speedValue[index].setText(formatSpeed(bar.getProgress())); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { } + }); + group.addView(sliderRow("SPEED", speed[index], speedValue[index])); + + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.setMargins(8, 8, 8, 0); + parent.addView(group, params); + } + + private View card(String label, View control) { + LinearLayout card = new LinearLayout(this); + card.setOrientation(LinearLayout.VERTICAL); + card.setPadding(14, 10, 14, 10); + card.setBackground(UiTheme.surface(UiTheme.SURFACE_HIGH, 10)); + card.addView(text(label, 12, UiTheme.TEXT, Typeface.BOLD)); + card.addView(control); + LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2); + params.setMargins(8, 8, 8, 0); + card.setLayoutParams(params); + return card; + } + + private View sliderRow(String label, SeekBar slider, TextView value) { + LinearLayout row = new LinearLayout(this); + row.setGravity(Gravity.CENTER_VERTICAL); + TextView name = text(label, 11, UiTheme.MUTED, Typeface.BOLD); + row.addView(name, new LinearLayout.LayoutParams(125, 44)); + row.addView(slider, new LinearLayout.LayoutParams(0, 44, 1)); + row.addView(value, new LinearLayout.LayoutParams(105, 44)); + return row; + } + + private TextView valueLabel(String value) { + TextView label = text(value, 11, UiTheme.RED, Typeface.BOLD); + label.setGravity(Gravity.CENTER); + return label; + } + + private void saveAll() { + int speed1 = speed[0].getProgress(); + int speed2 = speed[1].getProgress(); + int speed3 = speed[2].getProgress(); + if (speed1 >= speed2 || speed2 >= speed3) { + Toast.makeText(this, "Level speeds must increase from Level 1 to Level 3", + Toast.LENGTH_LONG).show(); + return; + } + AdaptiveAudioLevelingManager.save(this, enabled.isChecked(), + audioPercent(0), speed1, audioPercent(1), speed2, audioPercent(2), speed3); + Toast.makeText(this, "Adaptive audio leveling saved", Toast.LENGTH_SHORT).show(); + } + + private int audioPercent(int index) { + return AdaptiveAudioLevelingManager.MIN_AUDIO_PERCENT + audio[index].getProgress(); + } + + private static String formatAudio(int percent) { + return String.format(java.util.Locale.US, "%.2f× (%d%%)", percent / 100f, percent); + } + + private static String formatSpeed(int speedKph) { return speedKph + " km/h"; } + + private TextView text(String value, int size, int color, int style) { + TextView view = new TextView(this); + view.setText(value); + view.setTextSize(size * 1.25f); + view.setTextColor(color); + view.setTypeface(Typeface.create("sans-serif", style)); + return view; + } +} diff --git a/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java b/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java new file mode 100644 index 0000000..1ccb593 --- /dev/null +++ b/src/cloud/molberg/mgutility/AdaptiveAudioLevelingManager.java @@ -0,0 +1,300 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.content.SharedPreferences; +import android.media.AudioManager; +import android.os.Build; +import android.os.SystemClock; + +/** Applies a speed-sensitive multiplier to the driver's media-volume setting. */ +public final class AdaptiveAudioLevelingManager { + public static final String PREFS = "adaptive_audio_leveling"; + + private static final String KEY_ENABLED = "adaptive_enabled"; + private static final String KEY_LEVEL_1_AUDIO = "adaptive_level_1_audio"; + private static final String KEY_LEVEL_1_SPEED = "adaptive_level_1_speed"; + private static final String KEY_LEVEL_2_AUDIO = "adaptive_level_2_audio"; + private static final String KEY_LEVEL_2_SPEED = "adaptive_level_2_speed"; + private static final String KEY_LEVEL_3_AUDIO = "adaptive_level_3_audio"; + private static final String KEY_LEVEL_3_SPEED = "adaptive_level_3_speed"; + + public static final int MIN_AUDIO_PERCENT = 50; + public static final int MAX_AUDIO_PERCENT = 150; + public static final int MAX_SPEED_KPH = 200; + public static final int DEFAULT_LEVEL_1_AUDIO = 90; + public static final int DEFAULT_LEVEL_1_SPEED = 20; + public static final int DEFAULT_LEVEL_2_AUDIO = 100; + public static final int DEFAULT_LEVEL_2_SPEED = 70; + public static final int DEFAULT_LEVEL_3_AUDIO = 110; + public static final int DEFAULT_LEVEL_3_SPEED = 110; + private static final long AUTOMATIC_STEP_INTERVAL_MS = 750L; + private static final long VOLUME_WRITE_SETTLE_MS = 600L; + + private static final Object LOCK = new Object(); + private static float baseFraction = Float.NaN; + private static float lastAppliedFraction = Float.NaN; + private static float lastMultiplier = 1f; + private static float fractionBeforeLastWrite = Float.NaN; + private static long lastAutomaticStepAt; + private static long lastVolumeWriteAt; + private static int cachedMgMinimum = -1; + private static int cachedMgMaximum = -1; + + private AdaptiveAudioLevelingManager() { } + + public static final class Config { + public final boolean enabled; + public final int level1AudioPercent; + public final int level1SpeedKph; + public final int level2AudioPercent; + public final int level2SpeedKph; + public final int level3AudioPercent; + public final int level3SpeedKph; + + Config(boolean enabled, int level1AudioPercent, int level1SpeedKph, + int level2AudioPercent, int level2SpeedKph, + int level3AudioPercent, int level3SpeedKph) { + this.enabled = enabled; + this.level1AudioPercent = clampAudio(level1AudioPercent); + this.level1SpeedKph = Math.min(MAX_SPEED_KPH - 2, clampSpeed(level1SpeedKph)); + this.level2AudioPercent = clampAudio(level2AudioPercent); + this.level2SpeedKph = Math.max(this.level1SpeedKph + 1, + Math.min(MAX_SPEED_KPH - 1, clampSpeed(level2SpeedKph))); + this.level3AudioPercent = clampAudio(level3AudioPercent); + this.level3SpeedKph = Math.max(this.level2SpeedKph + 1, + clampSpeed(level3SpeedKph)); + } + + public float multiplierPercent(float speedKph) { + return AdaptiveAudioCurve.multiplierPercent(speedKph, + level1SpeedKph, level1AudioPercent, + level2SpeedKph, level2AudioPercent, + level3SpeedKph, level3AudioPercent); + } + } + + public static Config config(Context context) { + if (context == null) return defaults(); + SharedPreferences p = preferences(context); + return new Config(p.getBoolean(KEY_ENABLED, false), + p.getInt(KEY_LEVEL_1_AUDIO, DEFAULT_LEVEL_1_AUDIO), + p.getInt(KEY_LEVEL_1_SPEED, DEFAULT_LEVEL_1_SPEED), + p.getInt(KEY_LEVEL_2_AUDIO, DEFAULT_LEVEL_2_AUDIO), + p.getInt(KEY_LEVEL_2_SPEED, DEFAULT_LEVEL_2_SPEED), + p.getInt(KEY_LEVEL_3_AUDIO, DEFAULT_LEVEL_3_AUDIO), + p.getInt(KEY_LEVEL_3_SPEED, DEFAULT_LEVEL_3_SPEED)); + } + + public static void save(Context context, boolean enabled, + int level1AudioPercent, int level1SpeedKph, + int level2AudioPercent, int level2SpeedKph, + int level3AudioPercent, int level3SpeedKph) { + if (context == null) return; + Config safe = new Config(enabled, level1AudioPercent, level1SpeedKph, + level2AudioPercent, level2SpeedKph, level3AudioPercent, level3SpeedKph); + preferences(context).edit() + .putBoolean(KEY_ENABLED, safe.enabled) + .putInt(KEY_LEVEL_1_AUDIO, safe.level1AudioPercent) + .putInt(KEY_LEVEL_1_SPEED, safe.level1SpeedKph) + .putInt(KEY_LEVEL_2_AUDIO, safe.level2AudioPercent) + .putInt(KEY_LEVEL_2_SPEED, safe.level2SpeedKph) + .putInt(KEY_LEVEL_3_AUDIO, safe.level3AudioPercent) + .putInt(KEY_LEVEL_3_SPEED, safe.level3SpeedKph) + .apply(); + if (!safe.enabled) stopAndRestore(context); + } + + public static boolean shouldPoll(Context context) { + return config(context).enabled; + } + + /** Called by the always-on vehicle worker whenever a fresh speed is available. */ + public static void updateSpeed(Context context, float speedKph) { + if (context == null || Float.isNaN(speedKph) || Float.isInfinite(speedKph)) return; + Config cfg = config(context); + if (!cfg.enabled) { + stopAndRestore(context); + return; + } + synchronized (LOCK) { + VolumeState volume = readVolume(context); + if (volume == null) return; + float multiplier = cfg.multiplierPercent(Math.max(0f, speedKph)) / 100f; + float currentFraction = volume.fraction(); + float tolerance = Math.max(0.01f, 0.55f / volume.range()); + long now = SystemClock.elapsedRealtime(); + + if (Float.isNaN(baseFraction)) { + // The volume in place when the feature starts is the driver's base. + baseFraction = currentFraction; + } else if (Float.isNaN(lastAppliedFraction) || + Math.abs(currentFraction - lastAppliedFraction) > tolerance) { + // Some MG mixers briefly return the value from immediately before + // our last acknowledged write. Wait for that write to settle rather + // than mistaking it for steering-wheel input. + boolean staleOwnWrite = lastVolumeWriteAt > 0L && + now - lastVolumeWriteAt < VOLUME_WRITE_SETTLE_MS && + !Float.isNaN(fractionBeforeLastWrite) && + Math.abs(currentFraction - fractionBeforeLastWrite) <= tolerance; + if (staleOwnWrite) return; + // A volume key/knob changed the stream after our last write. Treat + // the newly selected audible value as authoritative and infer the + // corresponding unmodified base for subsequent speed changes. + baseFraction = AdaptiveAudioCurve.referenceFraction(currentFraction, + multiplier * 100f); + lastAutomaticStepAt = now; + lastVolumeWriteAt = 0L; + } + + float targetFraction = clampFraction(baseFraction * multiplier); + int target = volume.fromFraction(targetFraction); + if (target != volume.current) { + // The underlying mixer is integer-stepped, so ramp one notch at a + // time. Steering-wheel changes bypass this path and remain immediate. + if (lastAutomaticStepAt != 0L && + now - lastAutomaticStepAt < AUTOMATIC_STEP_INTERVAL_MS) { + lastAppliedFraction = currentFraction; + lastMultiplier = multiplier; + return; + } + int next = AdaptiveAudioCurve.stepToward(volume.current, target, + volume.minimum, volume.maximum); + if (!volume.write(context, next)) return; + fractionBeforeLastWrite = currentFraction; + lastAppliedFraction = volume.fraction(next); + lastAutomaticStepAt = now; + lastVolumeWriteAt = now; + } else { + lastAppliedFraction = currentFraction; + } + lastMultiplier = multiplier; + } + } + + /** Restores the driver's unmodified volume when leveling stops. */ + public static void stopAndRestore(Context context) { + if (context == null) return; + synchronized (LOCK) { + if (Float.isNaN(baseFraction)) return; + VolumeState volume = readVolume(context); + if (volume != null) { + float currentFraction = volume.fraction(); + float tolerance = Math.max(0.01f, 0.55f / volume.range()); + long now = SystemClock.elapsedRealtime(); + boolean staleOwnWrite = lastVolumeWriteAt > 0L && + now - lastVolumeWriteAt < VOLUME_WRITE_SETTLE_MS && + !Float.isNaN(fractionBeforeLastWrite) && + Math.abs(currentFraction - fractionBeforeLastWrite) <= tolerance; + if (!Float.isNaN(lastAppliedFraction) && + Math.abs(currentFraction - lastAppliedFraction) > tolerance && + !staleOwnWrite) { + baseFraction = AdaptiveAudioCurve.referenceFraction(currentFraction, + lastMultiplier * 100f); + } + int target = volume.fromFraction(baseFraction); + if (target != volume.current) volume.write(context, target); + } + resetSession(); + } + } + + public static int clampAudio(int value) { + return Math.max(MIN_AUDIO_PERCENT, Math.min(MAX_AUDIO_PERCENT, value)); + } + + public static int clampSpeed(int value) { + return Math.max(0, Math.min(MAX_SPEED_KPH, value)); + } + + private static void resetSession() { + baseFraction = Float.NaN; + lastAppliedFraction = Float.NaN; + lastMultiplier = 1f; + fractionBeforeLastWrite = Float.NaN; + lastAutomaticStepAt = 0L; + lastVolumeWriteAt = 0L; + } + + private static float clampFraction(float value) { + return Math.max(0f, Math.min(1f, value)); + } + + private static VolumeState readVolume(Context context) { + MgServiceBridge bridge = MgServiceBridge.get(); + try { bridge.ensureBound(context); } catch (Exception ignored) { } + int current = bridge.getVolume(MgServiceBridge.VOL_TYPE_MEDIA); + int maximum = cachedMgMaximum; + int minimum = cachedMgMinimum; + if (current >= 0 && maximum <= minimum) { + maximum = bridge.getMaxVolume(MgServiceBridge.VOL_TYPE_MEDIA); + minimum = bridge.getMinVolume(MgServiceBridge.VOL_TYPE_MEDIA); + if (minimum < 0) minimum = 0; + if (maximum > minimum) { + cachedMgMinimum = minimum; + cachedMgMaximum = maximum; + } + } + if (maximum > minimum && current >= minimum && current <= maximum) { + return new VolumeState(current, minimum, maximum, true); + } + + AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); + if (audio == null) return null; + try { + maximum = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC); + minimum = Build.VERSION.SDK_INT >= 28 + ? audio.getStreamMinVolume(AudioManager.STREAM_MUSIC) : 0; + current = audio.getStreamVolume(AudioManager.STREAM_MUSIC); + return maximum > minimum ? new VolumeState(current, minimum, maximum, false) : null; + } catch (Exception ignored) { + return null; + } + } + + private static final class VolumeState { + final int current; + final int minimum; + final int maximum; + final boolean mgService; + + VolumeState(int current, int minimum, int maximum, boolean mgService) { + this.current = current; + this.minimum = minimum; + this.maximum = maximum; + this.mgService = mgService; + } + + int range() { return maximum - minimum; } + float fraction() { return fraction(current); } + float fraction(int value) { return (value - minimum) / (float) range(); } + int fromFraction(float value) { + return Math.max(minimum, Math.min(maximum, + minimum + Math.round(clampFraction(value) * range()))); + } + + boolean write(Context context, int value) { + if (mgService) { + return MgServiceBridge.get().setVolume(MgServiceBridge.VOL_TYPE_MEDIA, value); + } + AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); + if (audio == null) return false; + try { + audio.setStreamVolume(AudioManager.STREAM_MUSIC, value, 0); + return true; + } catch (Exception ignored) { + return false; + } + } + } + + private static Config defaults() { + return new Config(false, + DEFAULT_LEVEL_1_AUDIO, DEFAULT_LEVEL_1_SPEED, + DEFAULT_LEVEL_2_AUDIO, DEFAULT_LEVEL_2_SPEED, + DEFAULT_LEVEL_3_AUDIO, DEFAULT_LEVEL_3_SPEED); + } + + private static SharedPreferences preferences(Context context) { + return context.getApplicationContext().getSharedPreferences(PREFS, Context.MODE_PRIVATE); + } +} diff --git a/src/cloud/molberg/mgutility/ArrivalBriefing.java b/src/cloud/molberg/mgutility/ArrivalBriefing.java new file mode 100644 index 0000000..9a5d065 --- /dev/null +++ b/src/cloud/molberg/mgutility/ArrivalBriefing.java @@ -0,0 +1,31 @@ +package cloud.molberg.mgutility; + +import java.util.Locale; + +/** Human-readable post-drive summary. Range depletion is intentionally in km. */ +final class ArrivalBriefing { + private ArrivalBriefing() { } + + static String tripText(TripDatabase.TripSummary trip, String location) { + if (trip == null) return "Drive completed"; + StringBuilder text = new StringBuilder(); + text.append(location == null || location.length() == 0 ? "Drive completed" : "Arrived at " + location); + text.append("\n").append(String.format(Locale.US, "%.1f km driven", trip.distanceKm())); + text.append(" • ").append(formatDuration(trip.durationMillis())); + if (trip.startRangeKm >= 0 && trip.endRangeKm >= 0) { + text.append("\nEstimated range depleted: ") + .append(String.format(Locale.US, "%.0f km", Math.max(0, trip.startRangeKm - trip.endRangeKm))); + } + double energy = trip.reportedEnergyUsed(); + if (!Double.isNaN(energy)) text.append("\nEnergy used: ").append(String.format(Locale.US, "%.2f kWh", energy)); + return text.toString(); + } + + private static String formatDuration(long millis) { + long minutes = Math.max(0L, millis) / 60000L; + long hours = minutes / 60L; + minutes %= 60L; + return hours > 0 ? String.format(Locale.US, "%dh %02dm", hours, minutes) + : String.format(Locale.US, "%dm", minutes); + } +} diff --git a/src/cloud/molberg/mgutility/ArrivalGeofence.java b/src/cloud/molberg/mgutility/ArrivalGeofence.java new file mode 100644 index 0000000..8897622 --- /dev/null +++ b/src/cloud/molberg/mgutility/ArrivalGeofence.java @@ -0,0 +1,79 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.content.SharedPreferences; + +import org.json.JSONArray; +import org.json.JSONObject; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; + +/** Local, user-defined arrival areas. No network/location service is required. */ +final class ArrivalGeofence { + private static final String KEY_JSON = "arrival_geofences"; + private static final float MIN_RADIUS_M = 50f; + private static final float MAX_RADIUS_M = 2000f; + + final String id; + final String name; + final double latitude; + final double longitude; + final float radiusM; + final boolean enabled; + + ArrivalGeofence(String id, String name, double latitude, double longitude, + float radiusM, boolean enabled) { + this.id = id == null || id.length() == 0 ? UUID.randomUUID().toString() : id; + this.name = name == null || name.trim().length() == 0 ? "Unnamed area" : name.trim(); + this.latitude = latitude; + this.longitude = longitude; + this.radiusM = Math.max(MIN_RADIUS_M, Math.min(MAX_RADIUS_M, radiusM)); + this.enabled = enabled; + } + + boolean contains(double lat, double lon) { + float[] result = new float[1]; + android.location.Location.distanceBetween(latitude, longitude, lat, lon, result); + return result[0] <= radiusM; + } + + static List load(Context context) { + String raw = ConfigStore.of(context).getString(KEY_JSON, "[]"); + ArrayList result = new ArrayList(); + try { + JSONArray values = new JSONArray(raw); + for (int i = 0; i < values.length(); i++) { + JSONObject value = values.optJSONObject(i); + if (value == null) continue; + result.add(new ArrivalGeofence(value.optString("id"), value.optString("name"), + value.optDouble("latitude", 0d), value.optDouble("longitude", 0d), + (float) value.optDouble("radius_m", 150d), value.optBoolean("enabled", true))); + } + } catch (Exception ignored) { } + return result; + } + + static void save(Context context, List input) { + JSONArray values = new JSONArray(); + if (input != null) for (ArrivalGeofence fence : input) { + if (fence == null) continue; + JSONObject value = new JSONObject(); + try { + value.put("id", fence.id).put("name", fence.name) + .put("latitude", fence.latitude).put("longitude", fence.longitude) + .put("radius_m", fence.radiusM).put("enabled", fence.enabled); + values.put(value); + } catch (Exception ignored) { } + } + ConfigStore.of(context).sharedPreferences().edit().putString(KEY_JSON, values.toString()).apply(); + } + + static List matches(Context context, double lat, double lon) { + ArrayList result = new ArrayList(); + for (ArrivalGeofence fence : load(context)) if (fence.enabled && fence.contains(lat, lon)) result.add(fence); + return result; + } +} diff --git a/src/cloud/molberg/mgutility/ArrivalGeofenceActivity.java b/src/cloud/molberg/mgutility/ArrivalGeofenceActivity.java new file mode 100644 index 0000000..db840e3 --- /dev/null +++ b/src/cloud/molberg/mgutility/ArrivalGeofenceActivity.java @@ -0,0 +1,121 @@ +package cloud.molberg.mgutility; + +import android.Manifest; +import android.app.AlertDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.pm.PackageManager; +import android.location.Location; +import android.location.LocationManager; +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.view.WindowManager; +import android.widget.Button; +import android.widget.EditText; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TextView; + +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +/** Editor for multiple local arrival areas. */ +public final class ArrivalGeofenceActivity extends AnimatedActivity { + private LinearLayout list; + private List fences; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + immersive(); + fences = new ArrayList(ArrivalGeofence.load(this)); + setContentView(buildUi()); + render(); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); root.setPadding(24, 14, 24, 18); + root.setBackgroundColor(UiTheme.BACKGROUND); + LinearLayout header = new LinearLayout(this); header.setGravity(Gravity.CENTER_VERTICAL); + header.addView(UiTheme.title(this, "ARRIVAL AREAS", 28), new LinearLayout.LayoutParams(0, 56, 1)); + Button add = UiTheme.button(this, "ADD CURRENT LOCATION", new View.OnClickListener() { + @Override public void onClick(View v) { addCurrent(); } + }, true); header.addView(add, new LinearLayout.LayoutParams(250, 52)); + Button manual = UiTheme.button(this, "ADD MANUALLY", new View.OnClickListener() { + @Override public void onClick(View v) { edit(new ArrivalGeofence(null, "New area", 0d, 0d, 150f, true)); } + }, false); header.addView(manual, new LinearLayout.LayoutParams(170, 52)); + Button back = UiTheme.backButton(this, new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); + header.addView(back, new LinearLayout.LayoutParams(130, 52)); root.addView(header); + TextView hint = UiTheme.text(this, "Charging price windows are shown only after arriving inside an enabled area. Areas use a configurable radius and can be enabled independently.", 12, UiTheme.MUTED, android.graphics.Typeface.NORMAL); + hint.setPadding(0, 10, 0, 12); root.addView(hint, new LinearLayout.LayoutParams(-1, -2)); + ScrollView scroll = new ScrollView(this); list = new LinearLayout(this); list.setOrientation(LinearLayout.VERTICAL); scroll.addView(list); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); return root; + } + + private void render() { + list.removeAllViews(); + if (fences.isEmpty()) { list.addView(UiTheme.text(this, "No arrival areas configured.", 15, UiTheme.MUTED, android.graphics.Typeface.NORMAL)); return; } + for (final ArrivalGeofence fence : fences) { + LinearLayout row = new LinearLayout(this); row.setGravity(Gravity.CENTER_VERTICAL); row.setPadding(14, 8, 8, 8); + row.setBackground(UiTheme.surface(UiTheme.SURFACE_HIGH, 10)); + TextView label = UiTheme.text(this, fence.name + "\n" + String.format(Locale.US, "%.5f, %.5f • %.0f m", fence.latitude, fence.longitude, fence.radiusM), 13, UiTheme.TEXT, android.graphics.Typeface.NORMAL); + row.addView(label, new LinearLayout.LayoutParams(0, 62, 1)); + Button toggle = UiTheme.button(this, fence.enabled ? "ON" : "OFF", new View.OnClickListener() { + @Override public void onClick(View v) { replace(new ArrivalGeofence(fence.id, fence.name, fence.latitude, fence.longitude, fence.radiusM, !fence.enabled)); } + }, fence.enabled); row.addView(toggle, new LinearLayout.LayoutParams(70, 44)); + Button edit = UiTheme.button(this, "EDIT", new View.OnClickListener() { @Override public void onClick(View v) { edit(fence); } }, false); row.addView(edit, new LinearLayout.LayoutParams(80, 44)); + Button remove = UiTheme.button(this, "REMOVE", new View.OnClickListener() { @Override public void onClick(View v) { fences.remove(fence); ArrivalGeofence.save(ArrivalGeofenceActivity.this, fences); render(); } }, false); row.addView(remove, new LinearLayout.LayoutParams(105, 44)); + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 80); p.setMargins(0, 0, 0, 6); list.addView(row, p); + } + } + + private void addCurrent() { + if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 7001); return; + } + LocationManager manager = (LocationManager) getSystemService(LOCATION_SERVICE); Location location = null; + try { location = manager == null ? null : manager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null && manager != null) location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); } catch (Exception ignored) { } + if (location == null) { + // The always-on tracker may have a newer fix than the provider cache + // exposed to this Activity. + android.content.SharedPreferences tracker = getSharedPreferences("trip_tracker", MODE_PRIVATE); + try { + String lat = tracker.getString("last_latitude", ""); + String lon = tracker.getString("last_longitude", ""); + if (lat.length() > 0 && lon.length() > 0) { + location = new Location("mg-tracker"); + location.setLatitude(Double.parseDouble(lat)); + location.setLongitude(Double.parseDouble(lon)); + } + } catch (Exception ignored) { } + } + if (location == null) { UiTheme.dialog(this).setTitle("Location unavailable").setMessage("Wait for a GPS fix, then try again.").setPositiveButton("OK", null).show(); return; } + edit(new ArrivalGeofence(null, "New area", location.getLatitude(), location.getLongitude(), 150f, true)); + } + + private void edit(final ArrivalGeofence original) { + LinearLayout form = new LinearLayout(this); form.setOrientation(LinearLayout.VERTICAL); form.setPadding(20, 4, 20, 0); + final EditText name = new EditText(this); name.setHint("Name (e.g. Home)"); name.setText(original.name); form.addView(name); + final EditText radius = new EditText(this); radius.setHint("Radius in metres (50–2000)"); radius.setInputType(2 | 8192); radius.setText(String.format(Locale.US, "%.0f", original.radiusM)); form.addView(radius); + final EditText coordinates = new EditText(this); coordinates.setHint("latitude, longitude"); coordinates.setText(String.format(Locale.US, "%.6f, %.6f", original.latitude, original.longitude)); form.addView(coordinates); + new AlertDialog.Builder(this).setTitle("Arrival area").setView(form).setNegativeButton("CANCEL", null).setPositiveButton("SAVE", new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { + try { + String[] parts = coordinates.getText().toString().split(","); + float r = Float.parseFloat(radius.getText().toString()); + replace(new ArrivalGeofence(original.id, name.getText().toString(), Double.parseDouble(parts[0].trim()), Double.parseDouble(parts[1].trim()), r, true)); + } catch (Exception ignored) { UiTheme.dialog(ArrivalGeofenceActivity.this).setTitle("Invalid area").setMessage("Enter coordinates as latitude, longitude and a numeric radius.").setPositiveButton("OK", null).show(); } + } + }).show(); + } + + private void replace(ArrivalGeofence value) { + for (int i = 0; i < fences.size(); i++) if (fences.get(i).id.equals(value.id)) { fences.set(i, value); ArrivalGeofence.save(this, fences); render(); return; } + fences.add(value); ArrivalGeofence.save(this, fences); render(); + } + + private void immersive() { getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().getDecorView().setSystemUiVisibility(5894); } +} diff --git a/src/cloud/molberg/mgutility/BootReceiver.java b/src/cloud/molberg/mgutility/BootReceiver.java index 762da1f..ac9b7c2 100644 --- a/src/cloud/molberg/mgutility/BootReceiver.java +++ b/src/cloud/molberg/mgutility/BootReceiver.java @@ -18,6 +18,9 @@ public final class BootReceiver extends BroadcastReceiver { if (context == null) return; String action = intent == null ? null : intent.getAction(); if (!isStartAction(context, intent, action)) return; + // Restore the daily brightness alarm across boot, unlock, updates and + // screen/power broadcasts. The scheduler is a no-op when disabled. + BrightnessScheduler.rearm(context); // Keep the last trigger visible in preferences so an installation can be // diagnosed without attaching a debugger to the head unit. This write is diff --git a/src/cloud/molberg/mgutility/BrightnessSchedule.java b/src/cloud/molberg/mgutility/BrightnessSchedule.java new file mode 100644 index 0000000..d4bf5a4 --- /dev/null +++ b/src/cloud/molberg/mgutility/BrightnessSchedule.java @@ -0,0 +1,61 @@ +package cloud.molberg.mgutility; + +import java.util.Calendar; +import java.util.Locale; + +/** Pure-Java automatic brightness schedule and smooth transition math. */ +public final class BrightnessSchedule { + private BrightnessSchedule() { } + static final int DEFAULT_PEAK_MINUTES = 7 * 60; + static final int DEFAULT_DARK_MINUTES = 21 * 60; + static final int DEFAULT_TRANSITION_MINUTES = 10; + static final int DEFAULT_PEAK_PERCENT = 100; + static final int DEFAULT_DARK_PERCENT = 0; + static final int MIN_TRANSITION_MINUTES = 1; + static final int MAX_TRANSITION_MINUTES = 60; + static final long USER_OVERRIDE_PAUSE_MS = 30L * 60L * 1000L; + + /** Return the target brightness percentage for an epoch timestamp. */ + public static int compute(long nowMillis, int peakMinutes, int darkMinutes, int transitionMinutes, + int peakPercent, int darkPercent, int lastAppliedPercent) { + int peak = clamp(peakPercent, 0, 100), dark = clamp(darkPercent, 0, 100); + int transition = clamp(transitionMinutes, MIN_TRANSITION_MINUTES, MAX_TRANSITION_MINUTES); + int now = minutesOfDay(nowMillis); + int peakTime = clamp(peakMinutes, 0, 1439), darkTime = clamp(darkMinutes, 0, 1439); + int brightDuration = (darkTime - peakTime + 1440) % 1440; + if (brightDuration == 0) return peak; + int darkDuration = 1440 - brightDuration; + int fadeDown = Math.min(transition, Math.max(1, brightDuration / 2)); + int fadeUp = Math.min(transition, Math.max(1, darkDuration / 2)); + int sincePeak = (now - peakTime + 1440) % 1440; + if (sincePeak < brightDuration) { + if (sincePeak >= brightDuration - fadeDown) { + return lerp(peak, dark, smooth(sincePeak - (brightDuration - fadeDown), fadeDown)); + } + return peak; + } + if (sincePeak >= 1440 - fadeUp) { + return lerp(dark, peak, smooth(sincePeak - (1440 - fadeUp), fadeUp)); + } + return dark; + } + + public static int minutesOfDay(long epochMillis) { + Calendar c = Calendar.getInstance(); + c.setTimeInMillis(epochMillis); + return c.get(Calendar.HOUR_OF_DAY) * 60 + c.get(Calendar.MINUTE); + } + + private static float smooth(int distance, int duration) { + float t = Math.max(0f, Math.min(1f, (float) distance / (float) Math.max(1, duration))); + return t * t * (3f - 2f * t); + } + + private static int lerp(int from, int to, float t) { return clamp(Math.round(from + (to - from) * t), 0, 100); } + private static int clamp(int v, int lo, int hi) { return Math.max(lo, Math.min(hi, v)); } + + public static String formatMinutes(int minutes) { + int value = clamp(minutes, 0, 1439); + return String.format(Locale.US, "%02d:%02d", value / 60, value % 60); + } +} diff --git a/src/cloud/molberg/mgutility/BrightnessScheduler.java b/src/cloud/molberg/mgutility/BrightnessScheduler.java new file mode 100644 index 0000000..fa0c00d --- /dev/null +++ b/src/cloud/molberg/mgutility/BrightnessScheduler.java @@ -0,0 +1,81 @@ +package cloud.molberg.mgutility; + +import android.app.AlarmManager; +import android.app.PendingIntent; +import android.content.BroadcastReceiver; +import android.content.Context; +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Build; +import android.provider.Settings; + +/** Alarm-driven automatic display brightness controller. */ +public final class BrightnessScheduler extends BroadcastReceiver { + static final String ACTION_TICK = "cloud.molberg.mgutility.AUTO_BRIGHTNESS_TICK"; + private static final int REQUEST = 9182; + private static final long TICK_MS = 60_000L; + + /** Rebuild the minute alarm; safe to call after every settings edit or boot. */ + public static void rearm(Context context) { + if (context == null) return; + Context app = context.getApplicationContext(); + AlarmManager alarms = (AlarmManager) app.getSystemService(Context.ALARM_SERVICE); + if (alarms == null) return; + PendingIntent pending = pendingIntent(app); + alarms.cancel(pending); + if (!prefs(app).getBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false)) return; + applyNow(app, System.currentTimeMillis()); + long next = ((System.currentTimeMillis() / TICK_MS) + 1L) * TICK_MS; + if (Build.VERSION.SDK_INT >= 23) alarms.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, next, pending); + else alarms.setExact(AlarmManager.RTC_WAKEUP, next, pending); + } + + public static void pauseForManualOverride(Context context) { + if (context == null) return; + prefs(context).edit().putLong(UiTheme.PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL, + System.currentTimeMillis() + BrightnessSchedule.USER_OVERRIDE_PAUSE_MS).apply(); + } + + @Override public void onReceive(Context context, Intent intent) { + if (context == null) return; + if (ACTION_TICK.equals(intent == null ? null : intent.getAction())) rearm(context); + } + + private static void applyNow(Context context, long now) { + SharedPreferences p = prefs(context); + long overrideUntil = p.getLong(UiTheme.PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL, 0L); + if (overrideUntil > now) return; + int last = p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_VALUE, 50); + int target = BrightnessSchedule.compute(now, + p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_MINUTES, BrightnessSchedule.DEFAULT_PEAK_MINUTES), + p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_DARK_MINUTES, BrightnessSchedule.DEFAULT_DARK_MINUTES), + p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES, BrightnessSchedule.DEFAULT_TRANSITION_MINUTES), + p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_PERCENT, BrightnessSchedule.DEFAULT_PEAK_PERCENT), + p.getInt(UiTheme.PREF_AUTO_BRIGHTNESS_DARK_PERCENT, BrightnessSchedule.DEFAULT_DARK_PERCENT), last); + int system = Math.max(0, Math.min(255, Math.round(target * 255f / 100f))); + MgServiceBridge bridge = MgServiceBridge.get(); + try { bridge.ensureBound(context); } catch (Exception ignored) { } + if (!bridge.setBrightness(system)) { + try { + if (Build.VERSION.SDK_INT < 23 || Settings.System.canWrite(context)) { + Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS, system); + Settings.System.putInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS_MODE, + Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL); + } + } catch (Exception ignored) { } + } + p.edit().putInt(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_VALUE, target) + .putLong(UiTheme.PREF_AUTO_BRIGHTNESS_LAST_TICK_AT, now).apply(); + } + + private static SharedPreferences prefs(Context context) { + return context.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE); + } + + private static PendingIntent pendingIntent(Context context) { + Intent intent = new Intent(context, BrightnessScheduler.class).setAction(ACTION_TICK); + int flags = PendingIntent.FLAG_UPDATE_CURRENT; + if (Build.VERSION.SDK_INT >= 23) flags |= PendingIntent.FLAG_IMMUTABLE; + return PendingIntent.getBroadcast(context, REQUEST, intent, flags); + } +} diff --git a/src/cloud/molberg/mgutility/ChargingActivity.java b/src/cloud/molberg/mgutility/ChargingActivity.java index 75b8882..2257ee7 100644 --- a/src/cloud/molberg/mgutility/ChargingActivity.java +++ b/src/cloud/molberg/mgutility/ChargingActivity.java @@ -313,17 +313,10 @@ public final class ChargingActivity extends AnimatedActivity { } final List points = loadedPoints; final String error = fetchError; - float liveSoc; - try { - EnergyActivity.VehicleGateway gateway = vehicle; - liveSoc = gateway == null ? Float.NaN : gateway.read().soc; - } catch (Exception ignored) { - liveSoc = Float.NaN; - } final ChargingAutomation.Prediction prediction = points.isEmpty() ? null : ChargingAutomation.predictNext( - ChargingActivity.this, points, liveSoc, System.currentTimeMillis()); + ChargingActivity.this, points, System.currentTimeMillis()); runOnUiThread(new Runnable() { @Override public void run() { if (isFinishing() || !dialog.isShowing()) return; diff --git a/src/cloud/molberg/mgutility/ChargingAutomation.java b/src/cloud/molberg/mgutility/ChargingAutomation.java index 4bc623b..f6408cc 100644 --- a/src/cloud/molberg/mgutility/ChargingAutomation.java +++ b/src/cloud/molberg/mgutility/ChargingAutomation.java @@ -609,14 +609,12 @@ final class ChargingAutomation { } /** - * Walk the saved rules forward in time and report the next matching start/stop - * transitions against the supplied price series. Time-only rules contribute - * their deterministic matches; price and SOC rules are evaluated per interval. - * When the caller provides a current SOC, charging is assumed to add about - * 6.6 kW into a 64 kWh pack so SOC-bound windows can flip during the projection. + * Walk price slots forward and report the next charging transitions. This is + * deliberately a price-only forecast: arrival planning must not pretend to + * know the future SOC, connector state, or time-window state. Non-price rules + * (and non-price AND clauses) are ignored for this look-ahead. */ - static Prediction predictNext(Context context, List prices, - float currentSoc, long nowMs) { + static Prediction predictNext(Context context, List prices, long nowMs) { long startAt = Long.MAX_VALUE; long stopAt = Long.MAX_VALUE; String startRule = ""; @@ -628,13 +626,9 @@ final class ChargingAutomation { } List rules = loadRules(context); - long lastIndexAt = prices.get(prices.size() - 1).timestamp; - boolean hasSoc = !Float.isNaN(currentSoc) && !Float.isInfinite(currentSoc) - && currentSoc >= 0f && currentSoc <= 100f; - float soc = hasSoc ? currentSoc : 50f; - final float perIntervalFraction = 6.6f * (MINUTES_PER_PRICE_POINT / 60f) / 64f * 100f; - - Integer previousDesired = null; + // Treat the state immediately before the first visible slot as idle so a + // currently-cheap first slot is reported as an actionable START. + Integer previousDesired = ACTION_NONE; for (int i = 0; i < prices.size(); i++) { PricePoint point = prices.get(i); long intervalEnd = point.timestamp + MINUTES_PER_PRICE_POINT * 60L * 1000L; @@ -642,38 +636,49 @@ final class ChargingAutomation { String matched = ""; for (Rule rule : rules) { if (!rule.enabled) continue; - float probe = hasSoc ? soc : (rule.condition == CONDITION_TIME_WINDOW ? soc : 50f); - if (probe < 0f || Float.isNaN(probe)) probe = 50f; - if (!matches(rule, probe, point.price, point.timestamp)) continue; + if (!matchesPriceOnly(rule, point.price)) continue; resolved = rule.action; matched = describe(rule, point.price); } if (previousDesired != null && previousDesired != resolved) { - if (previousDesired == ACTION_START && intervalEnd > nowMs && startAt == Long.MAX_VALUE) { - startAt = intervalEnd; + if (resolved == ACTION_START && intervalEnd > nowMs && startAt == Long.MAX_VALUE) { + startAt = Math.max(nowMs, point.timestamp); startRule = matched; startPrice = point.price; - } else if (previousDesired == ACTION_STOP && intervalEnd > nowMs && stopAt == Long.MAX_VALUE) { - stopAt = intervalEnd; + } else if (resolved == ACTION_STOP && intervalEnd > nowMs && stopAt == Long.MAX_VALUE) { + stopAt = Math.max(nowMs, point.timestamp); stopRule = matched; stopPrice = point.price; } if (startAt != Long.MAX_VALUE && stopAt != Long.MAX_VALUE) break; } previousDesired = resolved; - - if (hasSoc && resolved == ACTION_START) { - soc = Math.min(100f, soc + perIntervalFraction); - } } - long horizonMs = lastIndexAt + MINUTES_PER_PRICE_POINT * 60L * 1000L; - if (startAt == Long.MAX_VALUE) startAt = horizonMs <= nowMs ? Long.MAX_VALUE : horizonMs; - if (stopAt == Long.MAX_VALUE) stopAt = horizonMs <= nowMs ? Long.MAX_VALUE : horizonMs; return new Prediction(startAt, stopAt, startRule, stopRule, startPrice, stopPrice); } + private static boolean matchesPriceOnly(Rule rule, double price) { + boolean primary = isPriceCondition(rule.condition) && + matchesPriceCondition(rule.condition, rule.value, price); + if (!primary) return false; + for (Condition extra : rule.andConditions) { + if (extra == null || !isPriceCondition(extra.condition)) continue; + if (!matchesPriceCondition(extra.condition, extra.value, price)) return false; + } + return true; + } + + private static boolean isPriceCondition(int condition) { + return condition == CONDITION_PRICE_BELOW || condition == CONDITION_PRICE_ABOVE; + } + + private static boolean matchesPriceCondition(int condition, float value, double price) { + if (Double.isNaN(price) || Double.isInfinite(price)) return false; + return condition == CONDITION_PRICE_BELOW ? price < value : price > value; + } + private static double currentPrice(Context context, long now) { SharedPreferences p = prefs(context); String area = getPriceArea(context); diff --git a/src/cloud/molberg/mgutility/ConfigStore.java b/src/cloud/molberg/mgutility/ConfigStore.java new file mode 100644 index 0000000..127d167 --- /dev/null +++ b/src/cloud/molberg/mgutility/ConfigStore.java @@ -0,0 +1,284 @@ +package cloud.molberg.mgutility; + +import android.content.Context; +import android.content.SharedPreferences; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Writer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** Centralized preference store and JSON export/import helper. */ +public final class ConfigStore { + public static final String STORE_NAME = "mg_config"; + public static final int SCHEMA_VERSION = 1; + + /** Pure-JSON variant of {@link #exportJson()} for tests. */ + public static String exportJson(Map values) throws JSONException { + JSONObject root = new JSONObject(); + root.put("schema", SCHEMA_VERSION); + root.put("store", STORE_NAME); + JSONObject settings = new JSONObject(); + for (Map.Entry e : values.entrySet()) { + if (!isExportableKey(e.getKey())) continue; + settings.put(e.getKey(), e.getValue()); + } + root.put("settings", settings); + return root.toString(2); + } + + /** Pure-JSON variant of {@link #importJson()} for tests. */ + public static ImportResult importJsonToMap(String json, java.util.Map sink) + throws JSONException { + JSONObject root = new JSONObject(json); + int schema = root.optInt("schema", -1); + if (schema != SCHEMA_VERSION) throw new IllegalArgumentException("Unsupported config schema " + schema); + JSONObject settings = root.optJSONObject("settings"); + int count = 0; + if (settings != null) { + java.util.Iterator keys = settings.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = settings.get(key); + if (value instanceof Boolean) sink.put(key, value); + else if (value instanceof Integer) sink.put(key, value); + else if (value instanceof Long) sink.put(key, value); + else if (value instanceof Number) sink.put(key, ((Number) value).floatValue()); + else if (value instanceof JSONArray || value instanceof JSONObject) sink.put(key, value.toString()); + else if (value != JSONObject.NULL) sink.put(key, String.valueOf(value)); + count++; + } + } + return new ImportResult(count); + } + + private static final String KEY_MIGRATED = "__migrated__"; + private static final String KEY_SCHEMA = "__schema__"; + private static final String[] LEGACY_FILES = { + UiTheme.UI_PREFS, "trip_tracker", "vehicle_defaults", "soundboard", + "charging_automation", "key_remapping", "speed_reactive_audio", "adaptive_audio_leveling", + "map_tile_cache", "speed_test_records", "energy" + }; + private static ConfigStore singleton; + private final Context appContext; + private final SharedPreferences prefs; + + private ConfigStore(Context context) { + appContext = context.getApplicationContext(); + prefs = appContext.getSharedPreferences(STORE_NAME, Context.MODE_PRIVATE); + migrateLegacyIfNeeded(); + } + + public static synchronized ConfigStore of(Context context) { + if (singleton == null) singleton = new ConfigStore(context); + return singleton; + } + + public String getString(String key, String fallback) { return prefs.getString(key, fallback); } + public boolean getBoolean(String key, boolean fallback) { return prefs.getBoolean(key, fallback); } + public int getInt(String key, int fallback) { return prefs.getInt(key, fallback); } + public long getLong(String key, long fallback) { return prefs.getLong(key, fallback); } + public float getFloat(String key, float fallback) { return prefs.getFloat(key, fallback); } + public boolean contains(String key) { return prefs.contains(key); } + public Map snapshot() { return new HashMap(prefs.getAll()); } + /** Number of user-visible keys (internal migration metadata excluded). */ + public int visibleKeyCount() { + int count = 0; + for (String key : prefs.getAll().keySet()) if (isExportableKey(key)) count++; + return count; + } + public SharedPreferences sharedPreferences() { return prefs; } + + /** Export all settings to a versioned, diffable JSON document. */ + public String exportJson() throws JSONException { + // Existing screens in older releases still write their legacy preference + // file directly. Pull those values in immediately before exporting so + // the document always reflects the live app state. + refreshFromLegacy(); + JSONObject root = new JSONObject(); + root.put("schema", SCHEMA_VERSION); + root.put("store", STORE_NAME); + JSONObject settings = new JSONObject(); + for (Map.Entry e : prefs.getAll().entrySet()) { + if (isExportableKey(e.getKey())) settings.put(e.getKey(), e.getValue()); + } + root.put("settings", settings); + return root.toString(2); + } + + public void exportTo(OutputStream out) throws IOException, JSONException { + Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8); + writer.write(exportJson()); + writer.flush(); + writer.close(); + } + + /** Replace current settings with values from a JSON export. */ + public ImportResult importJson(String json) throws JSONException { + JSONObject root = new JSONObject(json); + int schema = root.optInt("schema", -1); + if (schema != SCHEMA_VERSION) throw new IllegalArgumentException("Unsupported config schema " + schema); + JSONObject settings = root.optJSONObject("settings"); + SharedPreferences.Editor editor = prefs.edit().clear(); + int count = 0; + if (settings != null) { + java.util.Iterator keys = settings.keys(); + while (keys.hasNext()) { + String key = keys.next(); + Object value = settings.get(key); + if (value instanceof Boolean) editor.putBoolean(key, ((Boolean) value).booleanValue()); + else if (value instanceof Integer) editor.putInt(key, ((Integer) value).intValue()); + else if (value instanceof Long) editor.putLong(key, ((Long) value).longValue()); + else if (value instanceof Number) editor.putFloat(key, ((Number) value).floatValue()); + else if (value instanceof JSONArray || value instanceof JSONObject) editor.putString(key, value.toString()); + else if (value != JSONObject.NULL) editor.putString(key, String.valueOf(value)); + count++; + } + } + editor.putBoolean(KEY_MIGRATED, true).putInt(KEY_SCHEMA, SCHEMA_VERSION).apply(); + syncToLegacy(); + return new ImportResult(count); + } + + public ImportResult importFrom(InputStream in) throws IOException, JSONException { + BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8)); + StringBuilder json = new StringBuilder(); + String line; + while ((line = reader.readLine()) != null) json.append(line).append('\n'); + reader.close(); + return importJson(json.toString()); + } + + public static final class ImportResult { + public final int keysApplied; + public ImportResult(int keysApplied) { this.keysApplied = keysApplied; } + } + + public void resetAll() { + SharedPreferences.Editor editor = prefs.edit(); + for (String key : prefs.getAll().keySet()) if (!key.startsWith("__")) editor.remove(key); + editor.apply(); + // Keep older runtime code (which may still read a legacy file) in sync + // with the reset so defaults take effect immediately on every screen. + for (String name : LEGACY_FILES) { + if (STORE_NAME.equals(name)) continue; + appContext.getSharedPreferences(name, Context.MODE_PRIVATE).edit().clear().apply(); + } + } + + public Map sectionSummary() { + Map result = new HashMap(); + for (String key : prefs.getAll().keySet()) { + if (key.startsWith("__")) continue; + String section = sectionFor(key); + Integer count = result.get(section); + result.put(section, count == null ? 1 : count + 1); + } + return result; + } + + public static List sections() { + ArrayList sections = new ArrayList(); + Collections.addAll(sections, "Appearance", "Pinned apps", "Home screen", "Trip tracker", + "Audio", "Charging automation", "Vehicle defaults", "Key remapping", "Map cache", "0–100 leaderboard"); + return Collections.unmodifiableList(sections); + } + + public static String sectionFor(String key) { + if (key == null) return "Other"; + int separator = key.indexOf("::"); + if (separator >= 0) key = key.substring(separator + 2); + if (key.equals("theme") || key.equals("theme_id") || key.equals("custom_themes") || key.equals("font_scale") || key.startsWith("custom_color_") || key.startsWith("page_")) return "Appearance"; + if (key.equals("launcher_pins")) return "Pinned apps"; + if (key.startsWith("home_") || key.equals("apps_reorder_enabled")) return "Home screen"; + if (key.startsWith("trip_") || key.startsWith("arrival_")) return "Trip tracker"; + if (key.startsWith("soundboard") || key.startsWith("speed_") || key.startsWith("adaptive_") || key.startsWith("music_")) return "Audio"; + if (key.startsWith("charging_") || key.contains("automation")) return "Charging automation"; + if (key.startsWith("vehicle_") || key.equals("drive_mode") || key.equals("regenerative_level")) return "Vehicle defaults"; + if (key.startsWith("key_") || key.contains("remap")) return "Key remapping"; + if (key.startsWith("map_") || key.contains("tile")) return "Map cache"; + return "Other"; + } + + private void migrateLegacyIfNeeded() { + if (prefs.getBoolean(KEY_MIGRATED, false)) return; + SharedPreferences.Editor editor = prefs.edit(); + for (String name : LEGACY_FILES) { + if (STORE_NAME.equals(name)) continue; + for (Map.Entry e : appContext.getSharedPreferences(name, Context.MODE_PRIVATE).getAll().entrySet()) { + String key = scopedKey(name, e.getKey()); + if (prefs.contains(key)) continue; + Object v = e.getValue(); + if (v instanceof Boolean) editor.putBoolean(key, ((Boolean) v).booleanValue()); + else if (v instanceof Integer) editor.putInt(key, ((Integer) v).intValue()); + else if (v instanceof Long) editor.putLong(key, ((Long) v).longValue()); + else if (v instanceof Float) editor.putFloat(key, ((Float) v).floatValue()); + else editor.putString(key, String.valueOf(v)); + } + } + editor.putBoolean(KEY_MIGRATED, true).putInt(KEY_SCHEMA, SCHEMA_VERSION).apply(); + } + + /** Merge values from legacy files, allowing newer edits made by old call sites. */ + private void refreshFromLegacy() { + SharedPreferences.Editor editor = prefs.edit(); + for (String name : LEGACY_FILES) { + if (STORE_NAME.equals(name)) continue; + for (Map.Entry e : appContext.getSharedPreferences(name, Context.MODE_PRIVATE).getAll().entrySet()) { + String key = scopedKey(name, e.getKey()); + Object v = e.getValue(); + if (v instanceof Boolean) editor.putBoolean(key, ((Boolean) v).booleanValue()); + else if (v instanceof Integer) editor.putInt(key, ((Integer) v).intValue()); + else if (v instanceof Long) editor.putLong(key, ((Long) v).longValue()); + else if (v instanceof Float) editor.putFloat(key, ((Float) v).floatValue()); + else editor.putString(key, String.valueOf(v)); + } + } + editor.apply(); + } + + /** Mirror imported values back to every legacy file so existing screens update immediately. */ + private void syncToLegacy() { + Map values = prefs.getAll(); + for (String name : LEGACY_FILES) { + if (STORE_NAME.equals(name)) continue; + SharedPreferences.Editor editor = appContext.getSharedPreferences(name, Context.MODE_PRIVATE).edit(); + for (Map.Entry e : values.entrySet()) { + if (!isExportableKey(e.getKey())) continue; + int separator = e.getKey().indexOf("::"); + if (separator <= 0) continue; + String target = e.getKey().substring(0, separator); + String key = e.getKey().substring(separator + 2); + if (!name.equals(target)) continue; + Object v = e.getValue(); + if (v instanceof Boolean) editor.putBoolean(key, ((Boolean) v).booleanValue()); + else if (v instanceof Integer) editor.putInt(key, ((Integer) v).intValue()); + else if (v instanceof Long) editor.putLong(key, ((Long) v).longValue()); + else if (v instanceof Float) editor.putFloat(key, ((Float) v).floatValue()); + else editor.putString(key, String.valueOf(v)); + } + editor.apply(); + } + } + + private static String scopedKey(String file, String key) { return file + "::" + key; } + + /** Internal migration metadata is excluded, plus transient energy baseline. */ + private static boolean isExportableKey(String key) { + if (key == null || key.startsWith("__")) return false; + return !key.startsWith("energy::"); + } +} diff --git a/src/cloud/molberg/mgutility/ControlPanelOverlay.java b/src/cloud/molberg/mgutility/ControlPanelOverlay.java index 418239e..951410a 100644 --- a/src/cloud/molberg/mgutility/ControlPanelOverlay.java +++ b/src/cloud/molberg/mgutility/ControlPanelOverlay.java @@ -508,6 +508,12 @@ final class ControlPanelOverlay extends FrameLayout { private void applySliderValue(String id, int target) { if ("brightness".equals(id)) { + // A deliberate slider move temporarily wins over the automatic + // schedule, then normal scheduling resumes after 30 minutes. + if (activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) + .getBoolean(UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false)) { + BrightnessScheduler.pauseForManualOverride(activity); + } int system = Math.max(0, Math.min(255, Math.round(target * 255f / 100f))); MgServiceBridge bridge = MgServiceBridge.get(); try { bridge.ensureBound(activity); } catch (Exception ignored) { } diff --git a/src/cloud/molberg/mgutility/CustomThemeEditActivity.java b/src/cloud/molberg/mgutility/CustomThemeEditActivity.java index 371550a..cea9c08 100644 --- a/src/cloud/molberg/mgutility/CustomThemeEditActivity.java +++ b/src/cloud/molberg/mgutility/CustomThemeEditActivity.java @@ -249,6 +249,7 @@ public final class CustomThemeEditActivity extends AnimatedActivity { sliderLabel.setPadding(6, 12, 0, 4); rightContent.addView(sliderLabel, new LinearLayout.LayoutParams(-1, 28)); SeekBar slider = new SeekBar(this); + UiTheme.tintSeekBar(slider); slider.setMax(100); slider.setProgress(42); slider.setPadding(0, 4, 0, 12); diff --git a/src/cloud/molberg/mgutility/EnergyActivity.java b/src/cloud/molberg/mgutility/EnergyActivity.java index c17294b..ad87039 100644 --- a/src/cloud/molberg/mgutility/EnergyActivity.java +++ b/src/cloud/molberg/mgutility/EnergyActivity.java @@ -52,6 +52,15 @@ public class EnergyActivity extends AnimatedActivity { * compile-time dependency on the OEM APK while still using its exported service. */ static class VehicleGateway { + /** + * The condition-service speed is the unrounded road-speed signal. MG's + * instrument cluster intentionally displays a small positive speedometer + * tolerance, so showing the raw value makes the dashboard appear 1–3 km/h + * slow at normal motorway speeds. Keep the correction at the telemetry + * boundary so the home gauge, drive logger, exports, and speed tools all + * use the same value. + */ + static final float DISPLAY_SPEED_FACTOR = 1.03f; static final String HUB_TOKEN="com.saicmotor.sdk.vehiclesettings.IHubService"; static final String SETTING_TOKEN="com.saicmotor.sdk.vehiclesettings.IVehicleSettingService"; static final String CHARGING_TOKEN="com.saicmotor.sdk.vehiclesettings.IVehicleChargingService"; @@ -250,7 +259,7 @@ public class EnergyActivity extends AnimatedActivity { Sample read(){ float soc=f(charging,CHARGING_TOKEN,3), - speed=f(condition,CONDITION_TOKEN,3), + speed=calibratedSpeed(f(condition,CONDITION_TOKEN,3)), volts=f(charging,CHARGING_TOKEN,64), total=f(charging,CHARGING_TOKEN,75), regenEnergyStart=f(charging,CHARGING_TOKEN, @@ -283,7 +292,12 @@ public class EnergyActivity extends AnimatedActivity { } /** Fast, read-only speed signal used by the dashboard's 100 ms instrument loop. */ - float readSpeed(){ return f(condition, CONDITION_TOKEN, 3); } + float readSpeed(){ return calibratedSpeed(f(condition, CONDITION_TOKEN, 3)); } + + static float calibratedSpeed(float value) { + if (Float.isNaN(value) || Float.isInfinite(value) || value < 0f) return value; + return Math.min(300f, value * DISPLAY_SPEED_FACTOR); + } private static boolean validCounter(float value){ return !Float.isNaN(value) && !Float.isInfinite(value) && value >= 0f; diff --git a/src/cloud/molberg/mgutility/MainActivity.java b/src/cloud/molberg/mgutility/MainActivity.java index ade3c8b..f747cf0 100644 --- a/src/cloud/molberg/mgutility/MainActivity.java +++ b/src/cloud/molberg/mgutility/MainActivity.java @@ -20,9 +20,18 @@ import android.graphics.LinearGradient; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Path; +import android.graphics.RadialGradient; import android.graphics.RectF; import android.graphics.Shader; import android.graphics.Typeface; +import android.graphics.PixelFormat; +import android.graphics.SurfaceTexture; +import android.opengl.EGL14; +import android.opengl.EGLConfig; +import android.opengl.EGLContext; +import android.opengl.EGLDisplay; +import android.opengl.EGLSurface; +import android.opengl.GLES20; import android.media.audiofx.Visualizer; import android.media.MediaMetadata; import android.os.Build; @@ -33,6 +42,8 @@ import android.provider.Settings; import android.text.TextUtils; import android.view.Gravity; import android.view.MotionEvent; +import android.view.Surface; +import android.view.TextureView; import android.view.View; import android.view.WindowManager; import android.widget.Button; @@ -43,6 +54,21 @@ import android.widget.LinearLayout; import android.widget.Switch; import android.widget.TextView; import android.widget.Toast; +import android.widget.SeekBar; +import android.webkit.PermissionRequest; +import android.webkit.JavascriptInterface; +import android.webkit.WebChromeClient; +import android.webkit.WebSettings; +import android.webkit.WebView; +import android.webkit.WebViewClient; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.FloatBuffer; import java.util.Locale; /** @@ -60,6 +86,12 @@ public class MainActivity extends AnimatedActivity { static final String PREF_BOOT_AUTOLAUNCH_BANNER = "boot_autolaunch_banner"; private static final String PREF_BOOT_SEEN = "boot_animation_seen"; static final String PREF_VISUALIZER_FPS = "home_visualizer_fps"; + static final String PREF_VISUALIZER_EFFECT = "home_visualizer_effect"; + static final String PREF_VISUALIZER_OPACITY = "home_visualizer_opacity"; + static final int VISUALIZER_EFFECT_SPECTRUM = 0; + static final int VISUALIZER_EFFECT_OSCILLOSCOPE = 1; + static final int VISUALIZER_EFFECT_SPEED_RING = 2; + static final int VISUALIZER_EFFECT_FERROFLUID = 3; static final String PREF_APP_DRAWER_ENABLED = "home_app_drawer_enabled"; static final String PREF_APP_DRAWER_OPACITY = "home_app_drawer_opacity"; static final String PREF_WIDGETS_PANEL_ENABLED = "home_widgets_panel_enabled"; @@ -68,6 +100,8 @@ public class MainActivity extends AnimatedActivity { private TextView connection, updated; private DashboardGauges dashboardGauges; + private FerrofluidLayer ferrofluidShader; + private FerrofluidShaderView ferrofluidFallback; private MusicPlayerPanel musicPanel; private FrameLayout screenRoot; private AppDrawerOverlay appDrawer; @@ -80,6 +114,7 @@ public class MainActivity extends AnimatedActivity { private float widgetsPanelTouchDownX; private float widgetsPanelTouchDownY; private boolean widgetsPanelTrackingTouch; + private boolean musicProgressGesture; private long renderedThemeVersion; private EngineBootView bootOverlay; private Button startupSettingsButton; @@ -127,6 +162,7 @@ public class MainActivity extends AnimatedActivity { @Override public void onCreate(Bundle state) { super.onCreate(state); + BrightnessScheduler.rearm(this); UiTheme.applyFontScale(this); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); immersive(); @@ -146,13 +182,28 @@ public class MainActivity extends AnimatedActivity { /** Read-only now-playing card: metadata comes from the active system media session. */ private static final class MusicPlayerPanel extends FrameLayout { - private final TextView title, artist, status; + private final TextView title, artist, status, elapsed, duration; + private final SeekBar progress; private final android.widget.FrameLayout albumArtHolder; private final ImageView albumArtCurrent; private final ControlIcon previous, play, next; private final Activity host; private boolean controlsLive; + private boolean seekDragging; private android.graphics.Bitmap currentArt; + private final Handler progressTicker = new Handler(); + private final Runnable progressRefresh = new Runnable() { + @Override public void run() { + if (!seekDragging && controlsLive) updateProgress(MusicPlayerManager.state()); + progressTicker.postDelayed(this, 250L); + } + }; + private final Runnable progressSync = new Runnable() { + @Override public void run() { + if (!seekDragging && controlsLive) updateProgress(MusicPlayerManager.state()); + progressTicker.postDelayed(this, 5000L); + } + }; MusicPlayerPanel(Activity host) { super(host); @@ -194,6 +245,40 @@ public class MainActivity extends AnimatedActivity { artist.setGravity(Gravity.CENTER); artist.setSingleLine(true); column.addView(artist, new LinearLayout.LayoutParams(-1, UiTheme.dp(host, 24))); + progress = new SeekBar(host); + progress.setMax(1000); + // SeekBar has no setMinHeight/setMaxHeight methods on API 28; + // constrain its parent row instead and use the supported minimum. + progress.setMinimumHeight(UiTheme.dp(host, 2)); + progress.setThumb(null); + progress.setBackground(null); + progress.setFocusable(false); + progress.setPadding(0, 0, 0, 0); + UiTheme.tintSeekBar(progress); + progress.setContentDescription("Song progress"); + progress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int value, boolean fromUser) { + if (fromUser && seekDragging) { + MusicPlayerManager.State current = MusicPlayerManager.state(); + if (current.durationMs > 0L) elapsed.setText(formatTime(current.durationMs * value / 1000L)); + } + } + @Override public void onStartTrackingTouch(SeekBar bar) { seekDragging = true; } + @Override public void onStopTrackingTouch(SeekBar bar) { + MusicPlayerManager.State current = MusicPlayerManager.state(); + if (current.durationMs > 0L) MusicPlayerManager.seekTo(current.durationMs * bar.getProgress() / 1000L); + seekDragging = false; + } + }); + column.addView(progress, new LinearLayout.LayoutParams(-1, UiTheme.dp(host, 18))); + LinearLayout timeRow = new LinearLayout(host); + timeRow.setGravity(Gravity.CENTER_VERTICAL); + elapsed = UiTheme.text(host, "0:00", 10, UiTheme.MUTED, Typeface.NORMAL); + duration = UiTheme.text(host, "0:00", 10, UiTheme.MUTED, Typeface.NORMAL); + timeRow.addView(elapsed, new LinearLayout.LayoutParams(0, UiTheme.dp(host, 18), 1f)); + duration.setGravity(Gravity.RIGHT); + timeRow.addView(duration, new LinearLayout.LayoutParams(0, UiTheme.dp(host, 18), 1f)); + column.addView(timeRow, new LinearLayout.LayoutParams(-1, UiTheme.dp(host, 18))); LinearLayout controls = new LinearLayout(host); controls.setGravity(Gravity.CENTER); controls.setPadding(0, UiTheme.dp(host, 4), 0, 0); @@ -227,6 +312,20 @@ public class MainActivity extends AnimatedActivity { addView(column, new FrameLayout.LayoutParams(-1, -1)); } + @Override protected void onAttachedToWindow() { + super.onAttachedToWindow(); + progressTicker.removeCallbacks(progressRefresh); + progressTicker.removeCallbacks(progressSync); + progressTicker.post(progressRefresh); + progressTicker.postDelayed(progressSync, 5000L); + } + + @Override protected void onDetachedFromWindow() { + progressTicker.removeCallbacks(progressRefresh); + progressTicker.removeCallbacks(progressSync); + super.onDetachedFromWindow(); + } + /** Compact clock and live system-status strip above the artwork. */ private static final class StatusStrip extends View { private final Paint statusPaint = new Paint(Paint.ANTI_ALIAS_FLAG); @@ -465,6 +564,7 @@ public class MainActivity extends AnimatedActivity { albumArtCurrent.setColorFilter(UiTheme.WARNING); currentArt = null; setControlsEnabled(false); + updateProgress(null); return; } if (!hasMedia) { @@ -476,14 +576,18 @@ public class MainActivity extends AnimatedActivity { albumArtCurrent.setImageResource(android.R.drawable.ic_media_play); albumArtCurrent.setColorFilter(UiTheme.MUTED); } - } else if (state.art != null) { + } else { // MusicPlayerManager supplies only decoded/preloaded artwork here. Commit // the bitmap and metadata in one UI pass, so a track change is instantaneous // and never exposes an empty artwork frame. - if (!sameArt(state.art, currentArt)) { + if (state.art != null) { albumArtCurrent.setImageBitmap(state.art); albumArtCurrent.clearColorFilter(); currentArt = state.art; + } else if (state.art == null && currentArt != null) { + currentArt = null; + albumArtCurrent.setImageResource(android.R.drawable.ic_media_play); + albumArtCurrent.setColorFilter(UiTheme.MUTED); } title.setText(state.title); artist.setText(state.artist); @@ -491,9 +595,35 @@ public class MainActivity extends AnimatedActivity { } boolean live = hasMedia && MusicPlayerManager.hasController(); setControlsEnabled(live); + updateProgress(hasMedia ? state : null); play.setPlaying(state != null && state.playing); } + private void updateProgress(MusicPlayerManager.State state) { + long position = state == null ? 0L : state.positionMs; + long total = state == null ? 0L : state.durationMs; + progress.setEnabled(total > 0L && controlsLive); + progress.setProgress(total > 0L ? (int) Math.min(1000L, position * 1000L / total) : 0); + elapsed.setText(formatTime(position)); + duration.setText(formatTime(total)); + } + + private static String formatTime(long millis) { + long seconds = Math.max(0L, millis) / 1000L; + return String.format(Locale.US, "%d:%02d", seconds / 60L, seconds % 60L); + } + + boolean isProgressTouch(MotionEvent event) { + if (event == null || progress.getVisibility() != View.VISIBLE) return false; + int[] location = new int[2]; + progress.getLocationOnScreen(location); + float x = event.getRawX(); + float y = event.getRawY(); + int touchSlop = UiTheme.dp(getContext(), 12); + return x >= location[0] - touchSlop && x <= location[0] + progress.getWidth() + touchSlop + && y >= location[1] - touchSlop && y <= location[1] + progress.getHeight() + touchSlop; + } + private void launchAndroidAuto() { if (host == null) return; Intent intent = new Intent(); @@ -569,6 +699,11 @@ public class MainActivity extends AnimatedActivity { getSharedPreferences(UI_PREFS, MODE_PRIVATE).getBoolean("home_visualizer_enabled", true)); if (dashboardGauges != null) dashboardGauges.setVisualizerFps( getSharedPreferences(UI_PREFS, MODE_PRIVATE).getInt(PREF_VISUALIZER_FPS, 30)); + if (dashboardGauges != null) dashboardGauges.setVisualizerEffect( + getSharedPreferences(UI_PREFS, MODE_PRIVATE).getInt(PREF_VISUALIZER_EFFECT, + VISUALIZER_EFFECT_SPECTRUM)); + if (dashboardGauges != null) dashboardGauges.setVisualizerOpacity( + getSharedPreferences(UI_PREFS, MODE_PRIVATE).getInt(PREF_VISUALIZER_OPACITY, 80)); MusicPlayerManager.setListener(musicState); refreshMusicPanel(); requestAudioAccess(); @@ -706,6 +841,22 @@ public class MainActivity extends AnimatedActivity { // short gestures continue through to the existing child views unchanged. // Only one overlay is ever open at a time, so opening either closes the // other before its own swipe gesture is recognised. + // Once a scrub starts, reserve the complete pointer sequence for the + // SeekBar so horizontal movement cannot open any dashboard panel. + if (musicProgressGesture) { + boolean handled = super.dispatchTouchEvent(event); + if (event.getActionMasked() == MotionEvent.ACTION_UP + || event.getActionMasked() == MotionEvent.ACTION_CANCEL) musicProgressGesture = false; + return handled; + } + if (event.getActionMasked() == MotionEvent.ACTION_DOWN + && (widgetsPanel == null || !widgetsPanel.isOpen()) + && (appDrawer == null || !appDrawer.isOpen()) + && (controlPanel == null || !controlPanel.isOpen()) + && musicPanel != null && musicPanel.isShown() && musicPanel.isProgressTouch(event)) { + musicProgressGesture = true; + return super.dispatchTouchEvent(event); + } if (widgetsPanel != null && widgetsPanel.isOpen()) { // While widgets are visible, vertical swipes belong to this page and // must not open or close the app drawer/control panel. Only a left @@ -880,11 +1031,22 @@ public class MainActivity extends AnimatedActivity { homeRow.setPadding(UiTheme.dp(this, 12), UiTheme.dp(this, 12), UiTheme.dp(this, 12), UiTheme.dp(this, 12)); dashboardGauges = new DashboardGauges(this); - musicPanel = new MusicPlayerPanel(this); + ferrofluidShader = new FerrofluidLayer(this); + ferrofluidFallback = new FerrofluidShaderView(this); + FrameLayout gaugeLayer = new FrameLayout(this); + gaugeLayer.setBackground(UiTheme.surface(UiTheme.SURFACE, 12)); + gaugeLayer.addView(ferrofluidShader, new FrameLayout.LayoutParams(-1, -1)); + gaugeLayer.addView(ferrofluidFallback, new FrameLayout.LayoutParams(-1, -1)); + // The GPU surface is deliberately the background; the Canvas gauge is + // drawn above it so arcs, values, labels, and touch handling remain clear. + gaugeLayer.addView(dashboardGauges, new FrameLayout.LayoutParams(-1, -1)); + dashboardGauges.setFerrofluidShader(ferrofluidShader); + dashboardGauges.setFerrofluidFallback(ferrofluidFallback); + musicPanel = new MusicPlayerPanel(this); LinearLayout.LayoutParams musicParams = new LinearLayout.LayoutParams(0, -1, 1f); musicParams.setMargins(0, 0, UiTheme.dp(this, 12), 0); homeRow.addView(musicPanel, musicParams); - homeRow.addView(dashboardGauges, new LinearLayout.LayoutParams(0, -1, 3f)); + homeRow.addView(gaugeLayer, new LinearLayout.LayoutParams(0, -1, 3f)); home.addView(homeRow, new FrameLayout.LayoutParams(-1, -1)); // The SETTINGS button lives on the home screen only when the // swipe-down control panel is disabled. When the panel is on, the @@ -1221,13 +1383,22 @@ public class MainActivity extends AnimatedActivity { /** Compact, glanceable instrument cluster for the launch screen. */ private static final class DashboardGauges extends View { private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Path ferrofluidBody = new Path(); + private final Path ferrofluidSpike = new Path(); private final Context context; private final float[] spectrum = new float[64]; + private final float[] ferrofluidSpectrum = new float[64]; + private final float[] waveform = new float[128]; private EnergyActivity.Sample sample; private float liveSpeed = Float.NaN; private long lastFastSpeedAt; private boolean visualizerEnabled = true; private int visualizerFps = 30; + private int visualizerEffect = VISUALIZER_EFFECT_SPECTRUM; + private int visualizerOpacity = 80; + private FerrofluidLayer ferrofluidShader; + private FerrofluidShaderView ferrofluidFallback; + private boolean ferrofluidShaderActive; private long lastVisualizerFrameNanos; private Visualizer visualizer; private float touchDownX; @@ -1241,7 +1412,9 @@ public class MainActivity extends AnimatedActivity { DashboardGauges(Context context) { super(context); this.context = context; - setBackground(UiTheme.surface(UiTheme.SURFACE, 12)); + // The wrapper owns the opaque panel background; keeping this view + // transparent lets the ferrofluid texture render behind the gauges. + setBackgroundColor(Color.TRANSPARENT); setClickable(true); } @@ -1273,7 +1446,14 @@ public class MainActivity extends AnimatedActivity { if (target < 0) return; Intent intent; if (target == 0) intent = new Intent(context, SpeedTestActivity.class); - else if (target == 1) intent = new Intent(context, EnergyActivity.class); + else if (target == 1) { + Intent oem = new Intent(); + oem.setComponent(new ComponentName( + "com.saicmotor.hmi.vehiclesettings", + "com.saicmotor.hmi.vehiclesettings.chargemanagement.ui.ChargeManagementActivity")); + intent = oem.resolveActivity(context.getPackageManager()) != null + ? oem : new Intent(context, EnergyActivity.class); + } else intent = new Intent(context, TripsActivity.class); try { context.startActivity(intent); } catch (Exception ignored) { } } @@ -1293,6 +1473,7 @@ public class MainActivity extends AnimatedActivity { } void setVisualizerEnabled(boolean enabled) { visualizerEnabled = enabled; + updateFerrofluidVisibility(); if (enabled) startVisualizer(); else stopVisualizer(); invalidate(); } @@ -1308,6 +1489,51 @@ public class MainActivity extends AnimatedActivity { invalidate(); } + void setVisualizerEffect(int effect) { + if (effect != VISUALIZER_EFFECT_SPECTRUM && effect != VISUALIZER_EFFECT_OSCILLOSCOPE + && effect != VISUALIZER_EFFECT_SPEED_RING && effect != VISUALIZER_EFFECT_FERROFLUID) { + effect = VISUALIZER_EFFECT_SPECTRUM; + } + if (visualizerEffect == effect) return; + visualizerEffect = effect; + ferrofluidShaderActive = effect == VISUALIZER_EFFECT_FERROFLUID && ferrofluidShader != null; + updateFerrofluidVisibility(); + synchronized (waveform) { + for (int i = 0; i < waveform.length; i++) waveform[i] = 0f; + } + invalidate(); + } + + void setVisualizerOpacity(int opacity) { + visualizerOpacity = Math.max(0, Math.min(100, opacity)); + if (ferrofluidShader != null) ferrofluidShader.setOpacity(visualizerOpacity / 100f); + if (ferrofluidFallback != null) ferrofluidFallback.setOpacity(visualizerOpacity / 100f); + invalidate(); + } + + void setFerrofluidShader(FerrofluidLayer shader) { + ferrofluidShader = shader; + shader.setCapabilityListener(new Runnable() { + @Override public void run() { updateFerrofluidVisibility(); } + }); + ferrofluidShaderActive = visualizerEffect == VISUALIZER_EFFECT_FERROFLUID; + shader.setOpacity(visualizerOpacity / 100f); + updateFerrofluidVisibility(); + } + + void setFerrofluidFallback(FerrofluidShaderView fallback) { + ferrofluidFallback = fallback; + fallback.setOpacity(visualizerOpacity / 100f); + updateFerrofluidVisibility(); + } + + private void updateFerrofluidVisibility() { + boolean enabled = visualizerEnabled && visualizerEffect == VISUALIZER_EFFECT_FERROFLUID; + if (ferrofluidShader != null) ferrofluidShader.setActive(enabled); + if (ferrofluidFallback != null) ferrofluidFallback.setActive(enabled + && (ferrofluidShader == null || !ferrofluidShader.isWebGlReady())); + } + @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (visualizerEnabled) startVisualizer(); @@ -1328,11 +1554,13 @@ public class MainActivity extends AnimatedActivity { live.setCaptureSize(range[1]); live.setScalingMode(Visualizer.SCALING_MODE_NORMALIZED); live.setDataCaptureListener(new Visualizer.OnDataCaptureListener() { - @Override public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveform, int samplingRate) { } + @Override public void onWaveFormDataCapture(Visualizer visualizer, byte[] waveformData, int samplingRate) { + updateWaveform(waveformData); + } @Override public void onFftDataCapture(Visualizer visualizer, byte[] fft, int samplingRate) { updateSpectrum(fft); } - }, Math.min(visualizerFps * 1000, Math.max(1000, Visualizer.getMaxCaptureRate())), false, true); + }, Math.min(visualizerFps * 1000, Math.max(1000, Visualizer.getMaxCaptureRate())), true, true); live.setEnabled(true); visualizer = live; } catch (Exception error) { @@ -1350,6 +1578,21 @@ public class MainActivity extends AnimatedActivity { synchronized (spectrum) { for (int i = 0; i < spectrum.length; i++) spectrum[i] = 0f; } + synchronized (waveform) { + for (int i = 0; i < waveform.length; i++) waveform[i] = 0f; + } + postInvalidate(); + } + + private void updateWaveform(byte[] data) { + if (data == null || data.length == 0) return; + synchronized (waveform) { + for (int i = 0; i < waveform.length; i++) { + int source = i * data.length / waveform.length; + // Visualizer waveform samples are unsigned bytes centered at 128. + waveform[i] = ((data[source] & 0xff) - 128) / 128f; + } + } postInvalidate(); } @@ -1379,6 +1622,8 @@ public class MainActivity extends AnimatedActivity { spectrum[bar] = Math.max(target, spectrum[bar] * .68f); } } + if (ferrofluidShader != null) ferrofluidShader.setSpectrum(spectrum); + if (ferrofluidFallback != null) ferrofluidFallback.setSpectrum(spectrum); postInvalidate(); } @@ -1400,12 +1645,30 @@ public class MainActivity extends AnimatedActivity { this.speedCx = speedCx; this.speedCy = speedCy; this.speedRadius = speedRadius; this.batteryCx = rightCx; this.batteryCy = batteryCy; this.batteryRadius = smallRadius; this.driveCx = rightCx; this.driveCy = driveCy; this.driveRadius = smallRadius; - if (visualizerEnabled) drawVisualizer(canvas, width, height); + if (visualizerEnabled) { + if (visualizerEffect == VISUALIZER_EFFECT_OSCILLOSCOPE) { + drawOscilloscope(canvas, width, height); + } else if (visualizerEffect == VISUALIZER_EFFECT_SPEED_RING) { + drawSpeedRing(canvas, speedCx, speedCy, speedRadius); + } else if (visualizerEffect == VISUALIZER_EFFECT_FERROFLUID) { + if (!ferrofluidShaderActive) drawFerrofluid(canvas, speedCx, speedCy, speedRadius); + } else { + drawVisualizer(canvas, width, height); + } + } // Dominant speed gauge on the left. - drawGauge(canvas, speedCx, speedCy, speedRadius, Math.min(1f, speed / 180f), UiTheme.RED, "SPEED", String.format(Locale.US, "%.0f", speed), "KM/H", false); + drawGauge(canvas, speedCx, speedCy, speedRadius, Math.min(1f, speed / 180f), UiTheme.RED, "SPEED", String.format(Locale.US, "%.0f", speed), "KM/H", false, false, false); // Battery and Drive Use stacked on the right, with compact typography. - drawGauge(canvas, rightCx, batteryCy, smallRadius, soc / 100f, UiTheme.SUCCESS, "BATTERY", sample == null ? "—" : String.format(Locale.US, "%.0f", soc), "% SOC", true); - drawGauge(canvas, rightCx, driveCy, smallRadius, Math.min(1f, energy / 30f), UiTheme.BLUE, "DRIVE USE", sample == null ? "—" : String.format(Locale.US, "%.1f", energy), "KWH", true); + boolean batteryAnimation = sample != null + && (ChargingStatus.isChargingActive(sample.charging) + || ChargingStatus.isDischargingActive(sample.discharging)); + boolean batteryDischarging = sample != null + && ChargingStatus.isDischargingActive(sample.discharging); + drawGauge(canvas, rightCx, batteryCy, smallRadius, soc / 100f, + batteryDischarging ? UiTheme.CYAN_BRIGHT : UiTheme.SUCCESS, + "BATTERY", sample == null ? "—" : String.format(Locale.US, "%.0f", soc), + "% SOC", true, batteryAnimation, batteryDischarging); + drawGauge(canvas, rightCx, driveCy, smallRadius, Math.min(1f, energy / 30f), UiTheme.BLUE, "DRIVE USE", sample == null ? "—" : String.format(Locale.US, "%.1f", energy), "KWH", true, false, false); paint.setStyle(Paint.Style.FILL); paint.setTextAlign(Paint.Align.CENTER); paint.setTypeface(Typeface.create("sans-serif-medium", Typeface.NORMAL)); @@ -1475,6 +1738,7 @@ public class MainActivity extends AnimatedActivity { new int[] { dim, glow, highlight, glow, dim }, new float[] { 0f, .35f, .5f, .65f, 1f }, Shader.TileMode.MIRROR); float travel = (phase * 2f - 1f) * half * 2f; + if (discharging) travel = -travel; bannerGradientMatrix.setTranslate(travel, 0f); gradient.setLocalMatrix(bannerGradientMatrix); paint.setShader(gradient); @@ -1521,7 +1785,7 @@ public class MainActivity extends AnimatedActivity { float baseline = height; float maxHeight = Math.min(118f, height * .20f); paint.setStyle(Paint.Style.FILL); - paint.setColor(UiTheme.withAlpha(UiTheme.CYAN, 70)); + paint.setColor(UiTheme.withAlpha(UiTheme.CYAN, visualizerAlpha(70))); synchronized (spectrum) { for (int i = 0; i < count; i++) { float barHeight = spectrum[i] * maxHeight; @@ -1532,15 +1796,175 @@ public class MainActivity extends AnimatedActivity { } } - private void drawGauge(Canvas canvas, float cx, float cy, float radius, float fraction, int color, String label, String value, String unit, boolean compact) { + private void drawOscilloscope(Canvas canvas, int width, int height) { + float centerY = height * .50f; + float amplitude = Math.min(height * .25f, 150f); + Path line = new Path(); + synchronized (waveform) { + for (int i = 0; i < waveform.length; i++) { + float x = i * width / (float)(waveform.length - 1); + float y = centerY - waveform[i] * amplitude; + if (i == 0) line.moveTo(x, y); else line.lineTo(x, y); + } + } + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(3f); + paint.setStrokeCap(Paint.Cap.ROUND); + paint.setColor(UiTheme.withAlpha(UiTheme.CYAN_BRIGHT, visualizerAlpha(210))); + canvas.drawPath(line, paint); + paint.setStyle(Paint.Style.FILL); + } + + private void drawSpeedRing(Canvas canvas, float cx, float cy, float radius) { + float ringRadius = Math.min(radius + Math.max(14f, radius * .11f), heightAvailableForRing(cy)); + float amplitude = Math.min(24f, Math.max(8f, radius * .075f)); + Path ring = new Path(); + int start = 0; + float smallestJump = Float.MAX_VALUE; + synchronized (waveform) { + // Pick the quietest sample boundary as the seam so the cyclic + // waveform joins cleanly instead of producing a visible jump at 12 o'clock. + for (int i = 0; i < waveform.length; i++) { + float jump = Math.abs(waveform[i] - waveform[(i + 1) % waveform.length]); + if (jump < smallestJump) { smallestJump = jump; start = i + 1; } + } + for (int i = 0; i < waveform.length; i++) { + int sample = (start + i) % waveform.length; + float angle = (float)(-Math.PI / 2d + i * Math.PI * 2d / waveform.length); + float pointRadius = ringRadius + waveform[sample] * amplitude; + float x = cx + (float)Math.cos(angle) * pointRadius; + float y = cy + (float)Math.sin(angle) * pointRadius; + if (i == 0) ring.moveTo(x, y); else ring.lineTo(x, y); + } + ring.close(); + } + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(3f); + paint.setStrokeCap(Paint.Cap.ROUND); + paint.setStrokeJoin(Paint.Join.ROUND); + paint.setColor(UiTheme.withAlpha(UiTheme.CYAN_BRIGHT, visualizerAlpha(190))); + canvas.drawPath(ring, paint); + paint.setStyle(Paint.Style.FILL); + } + + /** + * A compact ferrofluid-inspired bubble for the speed-gauge position. It + * uses a single smooth body and a handful of tapered magnetic spikes; + * both are driven by the live FFT and waveform energy, so the effect + * feels fluid without the cost of a particle or pixel simulation. + */ + private void drawFerrofluid(Canvas canvas, float cx, float cy, float radius) { + final int points = 48; + final int spikes = 14; + final float baseRadius = radius * .57f; + float low = 0f, high = 0f, rms = 0f; + synchronized (spectrum) { + System.arraycopy(spectrum, 0, ferrofluidSpectrum, 0, spectrum.length); + int lowCount = Math.max(1, spectrum.length / 8); + int highStart = spectrum.length * 3 / 5; + for (int i = 0; i < lowCount; i++) low += ferrofluidSpectrum[i]; + for (int i = highStart; i < spectrum.length; i++) high += ferrofluidSpectrum[i]; + low /= lowCount; + high /= Math.max(1, spectrum.length - highStart); + } + synchronized (waveform) { + for (float value : waveform) rms += value * value; + } + rms = (float)Math.sqrt(rms / waveform.length); + float beat = Math.min(1f, low * .95f + rms * .55f); + float shimmer = Math.min(1f, high * 1.2f + rms * .25f); + float time = SystemClock.uptimeMillis() * .001f; + float pulse = 1f + beat * .12f + (float)Math.sin(time * 2.2f) * .018f; + float bodyRadius = baseRadius * pulse; + + // A soft halo sells the glossy, magnetic material while remaining a + // single inexpensive draw behind the silhouette. + paint.setStyle(Paint.Style.FILL); + paint.setShader(new RadialGradient(cx - bodyRadius * .22f, cy - bodyRadius * .28f, + bodyRadius * 1.45f, + new int[] { UiTheme.withAlpha(UiTheme.CYAN_BRIGHT, visualizerAlpha(72)), + UiTheme.withAlpha(UiTheme.CYAN, visualizerAlpha(28)), Color.TRANSPARENT }, + new float[] { 0f, .48f, 1f }, Shader.TileMode.CLAMP)); + canvas.drawCircle(cx, cy, bodyRadius * 1.42f, paint); + paint.setShader(null); + + // Magnetic spikes sit behind the main body and vary with the upper + // spectrum, which produces the characteristic ferrofluid crown. + for (int i = 0; i < spikes; i++) { + float angle = (float)(-Math.PI / 2d + i * Math.PI * 2d / spikes + time * .16f); + int bin = (i * (spectrum.length - 1)) / spikes; + float band = ferrofluidSpectrum[bin]; + float length = bodyRadius * (.10f + band * .42f + shimmer * .08f); + float width = (float)(Math.PI * 2d / spikes) * (.18f + band * .10f); + float inner = bodyRadius * .72f; + float outer = bodyRadius + length; + ferrofluidSpike.reset(); + ferrofluidSpike.moveTo(cx + (float)Math.cos(angle - width) * inner, + cy + (float)Math.sin(angle - width) * inner); + ferrofluidSpike.lineTo(cx + (float)Math.cos(angle) * outer, + cy + (float)Math.sin(angle) * outer); + ferrofluidSpike.lineTo(cx + (float)Math.cos(angle + width) * inner, + cy + (float)Math.sin(angle + width) * inner); + ferrofluidSpike.close(); + paint.setColor(UiTheme.withAlpha(i % 3 == 0 ? UiTheme.CYAN_BRIGHT : UiTheme.CYAN, + visualizerAlpha(80 + Math.round(band * 70f)))); + canvas.drawPath(ferrofluidSpike, paint); + } + + ferrofluidBody.reset(); + for (int i = 0; i < points; i++) { + float angle = (float)(-Math.PI / 2d + i * Math.PI * 2d / points); + int bin = (i * spectrum.length) / points; + float band = ferrofluidSpectrum[Math.min(spectrum.length - 1, bin)]; + float harmonic = (float)Math.sin(time * 1.7f + i * .73f); + float contour = 1f + band * .16f + harmonic * (.018f + shimmer * .018f); + float pointRadius = bodyRadius * contour; + float x = cx + (float)Math.cos(angle) * pointRadius; + float y = cy + (float)Math.sin(angle) * pointRadius; + if (i == 0) ferrofluidBody.moveTo(x, y); else ferrofluidBody.lineTo(x, y); + } + ferrofluidBody.close(); + paint.setStyle(Paint.Style.FILL); + paint.setShader(new RadialGradient(cx - bodyRadius * .30f, cy - bodyRadius * .38f, + bodyRadius * 1.22f, + new int[] { Color.rgb(224, 255, 255), UiTheme.CYAN_BRIGHT, + UiTheme.withAlpha(UiTheme.CYAN, 220), Color.rgb(8, 19, 25) }, + new float[] { 0f, .12f, .48f, 1f }, Shader.TileMode.CLAMP)); + canvas.drawPath(ferrofluidBody, paint); + paint.setShader(null); + + // Fine luminous edge keeps the silhouette readable over the gauge. + paint.setStyle(Paint.Style.STROKE); + paint.setStrokeWidth(Math.max(2f, radius * .018f)); + paint.setStrokeJoin(Paint.Join.ROUND); + paint.setColor(UiTheme.withAlpha(UiTheme.CYAN_BRIGHT, visualizerAlpha(185))); + canvas.drawPath(ferrofluidBody, paint); + paint.setStyle(Paint.Style.FILL); + } + + private float heightAvailableForRing(float cy) { + return Math.max(1f, getHeight() - cy - 10f); + } + + private int visualizerAlpha(int base) { + return Math.round(base * visualizerOpacity / 100f); + } + + private void drawGauge(Canvas canvas, float cx, float cy, float radius, float fraction, int color, String label, String value, String unit, boolean compact, boolean animateProgress, boolean discharging) { paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(9f); paint.setStrokeCap(Paint.Cap.ROUND); + paint.setShader(null); paint.setColor(UiTheme.DIVIDER); RectF arc = new RectF(cx - radius, cy - radius, cx + radius, cy + radius); canvas.drawArc(arc, 140, 260, false, paint); - paint.setColor(color); - canvas.drawArc(arc, 140, 260 * Math.max(0f, Math.min(1f, fraction)), false, paint); + float sweep = 260 * Math.max(0f, Math.min(1f, fraction)); + if (animateProgress) { + drawAnimatedProgressArc(canvas, arc, sweep, color, discharging); + } else { + paint.setColor(color); + canvas.drawArc(arc, 140, sweep, false, paint); + } paint.setStyle(Paint.Style.FILL); paint.setTextAlign(Paint.Align.CENTER); paint.setTypeface(Typeface.create("sans-serif", Typeface.BOLD)); @@ -1560,6 +1984,32 @@ public class MainActivity extends AnimatedActivity { canvas.drawText(unit, cx, cy + (compact ? 30 : 58), paint); } + /** Apply the same moving shimmer as the status label to the battery arc. */ + private void drawAnimatedProgressArc(Canvas canvas, RectF arc, float sweep, + int accent, boolean discharging) { + if (bannerAnimationStartedAt == 0L) bannerAnimationStartedAt = SystemClock.uptimeMillis(); + long elapsed = SystemClock.uptimeMillis() - bannerAnimationStartedAt; + float phase = (elapsed % 2200L) / 2200f; + float half = Math.max(90f, (arc.right - arc.left) * .75f); + int dim = UiTheme.withAlpha(accent, 150); + int glow = discharging ? UiTheme.CYAN_BRIGHT : UiTheme.SUCCESS; + int highlight = Color.rgb( + Math.min(255, Color.red(glow) + 70), + Math.min(255, Color.green(glow) + 70), + Math.min(255, Color.blue(glow) + 70)); + LinearGradient gradient = new LinearGradient(arc.left, arc.top, arc.right, arc.bottom, + new int[] { dim, glow, highlight, glow, dim }, + new float[] { 0f, .35f, .5f, .65f, 1f }, Shader.TileMode.MIRROR); + float travel = (phase * 2f - 1f) * half * 2f; + if (discharging) travel = -travel; + bannerGradientMatrix.setTranslate(travel, 0f); + gradient.setLocalMatrix(bannerGradientMatrix); + paint.setShader(gradient); + canvas.drawArc(arc, 140, sweep, false, paint); + paint.setShader(null); + postInvalidateDelayed(45L); + } + private static boolean insideCircle(float x, float y, float cx, float cy, float radius) { float dx = x - cx; float dy = y - cy; @@ -1567,6 +2017,438 @@ public class MainActivity extends AnimatedActivity { } } + /** + * Hosts the original Robert Leitl WebGL2 ferrofluid simulation. The published + * build is loaded unchanged and only its microphone/opaque-ground hooks are + * replaced so Android playback FFT data can drive it behind the gauges. + */ + private static final class FerrofluidLayer extends WebView { + private static final String REFERENCE_URL = "https://robert-leitl.github.io/ferrofluid/dist/"; + private volatile float opacity = .82f; + private volatile boolean active; + private volatile boolean webGlReady; + private Runnable capabilityListener; + + FerrofluidLayer(Context context) { + super(context); + setBackgroundColor(Color.TRANSPARENT); + setAlpha(opacity); + setVisibility(View.GONE); + setClickable(false); + setFocusable(false); + setFocusableInTouchMode(false); + setLayerType(View.LAYER_TYPE_HARDWARE, null); + WebSettings settings = getSettings(); + settings.setJavaScriptEnabled(true); + settings.setDomStorageEnabled(true); + settings.setMediaPlaybackRequiresUserGesture(false); + settings.setAllowFileAccess(false); + setWebChromeClient(new WebChromeClient() { + @Override public void onPermissionRequest(PermissionRequest request) { + // The reference asks for a microphone; native Visualizer data is + // injected instead, so never grant capture permission. + request.deny(); + } + }); + addJavascriptInterface(new Object() { + @JavascriptInterface public void webglReady(final boolean ready) { + post(new Runnable() { + @Override public void run() { + webGlReady = ready; + if (capabilityListener != null) capabilityListener.run(); + } + }); + } + }, "__mgBridge"); + setWebViewClient(new WebViewClient() { + @Override public android.webkit.WebResourceResponse shouldInterceptRequest( + WebView view, android.webkit.WebResourceRequest request) { + String url = request.getUrl().toString(); + if (url.contains("index-") && url.endsWith(".js")) return patchedScript(url); + if (url.contains("index-") && url.endsWith(".css")) return patchedStylesheet(url); + return super.shouldInterceptRequest(view, request); + } + @Override public void onPageFinished(WebView view, String url) { + super.onPageFinished(view, url); + applyOverlayCss(view); + // The reference app updates its DOM during startup; repeat the + // small compositing hook after that update so its link/UI can + // never cover the native dashboard. + postDelayed(new Runnable() { @Override public void run() { + if (getUrl() != null) applyOverlayCss(FerrofluidLayer.this); + }}, 700L); + // Probe independently of the reference app. Old Android + // WebViews can expose WebGL but return null for WebGL2; in + // that case DashboardGauges enables the GLES fallback. + evaluateJavascript("(function(){try{var c=document.querySelector('canvas')||document.createElement('canvas');var g=c.getContext('webgl2');window.__mgBridge.webglReady(!!g);return !!g;}catch(e){window.__mgBridge.webglReady(false);return false;}})();", null); + pushAudioValue(0f); + } + @Override public void onPageCommitVisible(WebView view, String url) { + // Some WebView versions commit the first frame after + // onPageFinished; apply the compositing rule at both points. + applyOverlayCss(view); + } + }); + loadUrl(REFERENCE_URL); + } + + private void applyOverlayCss(WebView view) { + view.evaluateJavascript("(function(){var s=document.getElementById('__mg_overlay');if(!s){s=document.createElement('style');s.id='__mg_overlay';(document.head||document.documentElement).appendChild(s);}s.textContent='html,body{background:transparent!important;background-color:transparent!important;overflow:hidden!important}body> :not(canvas){display:none!important}canvas{position:fixed!important;inset:0!important;width:100%!important;height:100%!important;background:transparent!important}';if(document.documentElement)document.documentElement.style.setProperty('background','transparent','important');if(document.body)document.body.style.setProperty('background','transparent','important');})();", null); + } + + private android.webkit.WebResourceResponse patchedScript(String url) { + HttpURLConnection connection = null; + try { + connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setConnectTimeout(12000); + connection.setReadTimeout(20000); + connection.setRequestProperty("Accept", "application/javascript"); + InputStream input = connection.getInputStream(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[16384]; + int read; + while ((read = input.read(buffer)) != -1) output.write(buffer, 0, read); + input.close(); + String source = new String(output.toByteArray(), "UTF-8"); + // Keep the reference bundle byte-for-byte except for the + // canvas compositor and audio hook. A broad alpha replacement + // would also alter Tweakpane's colour-format metadata. + source = source.replace( + "getContext(\"webgl2\",{antialias:!1,alpha:!1})", + "getContext(\"webgl2\",{antialias:!1,alpha:!0,premultipliedAlpha:!0})"); + // The original ground pass clears opaque #0.05 before drawing. + // Clear transparent and make its fragment transparent so the + // native dashboard surface remains visible below this layer. + source = source.replace("t.clearColor(e,e,e,1)", "t.clearColor(0,0,0,0)"); + source = source.replace("this.audioControl.isInitialized", "true"); + source = source.replace("this.audioControl.getValue()", "(window.__mgAudioValue||-1)"); + // Preserve the reference fluid shading, but use its existing radial + // edge mask as alpha instead of compositing an opaque dark ground. + // This keeps the ferrofluid visible while the dashboard surface and + // native gauges remain visible outside/through the transparent edge. + source = source.replace( + "outColor = vec4(mix(vec3(0.05), color, edgeMask), 1.);", + "outColor = vec4(color, edgeMask);"); + return new android.webkit.WebResourceResponse("application/javascript", "UTF-8", + new ByteArrayInputStream(source.getBytes("UTF-8"))); + } catch (Exception ignored) { + return null; + } finally { + if (connection != null) connection.disconnect(); + } + } + + /** Patch the reference stylesheet before Chromium paints its opaque page background. */ + private android.webkit.WebResourceResponse patchedStylesheet(String url) { + HttpURLConnection connection = null; + try { + connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setConnectTimeout(12000); + connection.setReadTimeout(20000); + InputStream input = connection.getInputStream(); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int read; + while ((read = input.read(buffer)) != -1) output.write(buffer, 0, read); + input.close(); + String source = new String(output.toByteArray(), "UTF-8"); + source = source.replace("background-color:#000", "background-color:transparent"); + source = source.replace(".github-link{", ".github-link{display:none!important;"); + source = source.replace("#logo{", "#logo{display:none!important;"); + source = source.replace("#input-info{", "#input-info{display:none!important;"); + return new android.webkit.WebResourceResponse("text/css", "UTF-8", + new ByteArrayInputStream(source.getBytes("UTF-8"))); + } catch (Exception ignored) { + return null; + } finally { + if (connection != null) connection.disconnect(); + } + } + + void setActive(boolean value) { + active = value; + post(new Runnable() { @Override public void run() { + setVisibility(active ? View.VISIBLE : View.GONE); + // The reference uses a continuous requestAnimationFrame loop. + // Pausing WebView timers while hidden avoids consuming a render + // budget when another visualizer effect is selected. + if (active) resumeTimers(); else pauseTimers(); + }}); + } + + boolean isWebGlReady() { return webGlReady; } + + void setCapabilityListener(Runnable listener) { capabilityListener = listener; } + + void setOpacity(float value) { + opacity = Math.max(0f, Math.min(1f, value)); + post(new Runnable() { @Override public void run() { setAlpha(opacity); }}); + } + + void setSpectrum(float[] spectrum) { + if (spectrum == null || spectrum.length == 0) return; + float bass = 0f; + int count = Math.max(1, spectrum.length / 8); + for (int i = 0; i < count; i++) bass = Math.max(bass, spectrum[i]); + // The reference maps detected pitch to [-1, 1]. Use the low-frequency + // energy from Android's playback Visualizer so kick drums drive the same + // simulation zoom/impact path without opening the microphone. + pushAudioValue(bass * 2f - 1f); + } + + private void pushAudioValue(final float value) { + final float clamped = Math.max(-1f, Math.min(1f, value)); + post(new Runnable() { + @Override public void run() { + if (getUrl() != null) evaluateJavascript("window.__mgAudioValue=" + clamped + ";", null); + } + }); + } + + @Override public boolean onTouchEvent(MotionEvent event) { + // The dashboard Canvas is the owner of all gauge gestures. The + // reference page is visual-only in this embedded presentation. + return false; + } + } + + /** Legacy fallback renderer retained for devices where WebView cannot initialize. */ + private static final class FerrofluidShaderView extends TextureView implements TextureView.SurfaceTextureListener { + private final FerrofluidRenderer renderer; + private final Object frameLock = new Object(); + private volatile boolean running; + private Thread renderThread; + private Surface renderSurface; + private int surfaceWidth; + private int surfaceHeight; + + FerrofluidShaderView(Context context) { + super(context); + setOpaque(false); + renderer = new FerrofluidRenderer(); + setSurfaceTextureListener(this); + setVisibility(View.GONE); + setClickable(false); + setFocusable(false); + } + + @Override public boolean onTouchEvent(MotionEvent event) { return false; } + + void setActive(boolean active) { + setVisibility(active ? View.VISIBLE : View.GONE); + renderer.active = active; + synchronized (frameLock) { frameLock.notifyAll(); } + } + + void setOpacity(float opacity) { renderer.opacity = Math.max(0f, Math.min(1f, opacity)); } + + void setSpectrum(float[] source) { + if (source == null) return; + synchronized (renderer.bands) { + for (int i = 0; i < renderer.bands.length; i++) { + int index = i * source.length / renderer.bands.length; + renderer.bands[i] = source[Math.min(source.length - 1, index)]; + } + } + synchronized (frameLock) { frameLock.notifyAll(); } + } + + @Override public void onSurfaceTextureAvailable(SurfaceTexture texture, int width, int height) { + renderSurface = new Surface(texture); + surfaceWidth = width; + surfaceHeight = height; + running = true; + renderThread = new Thread(new Runnable() { + @Override public void run() { renderLoop(); } + }, "FerrofluidGL"); + renderThread.start(); + } + + @Override public void onSurfaceTextureSizeChanged(SurfaceTexture texture, int width, int height) { + surfaceWidth = width; surfaceHeight = height; + synchronized (frameLock) { frameLock.notifyAll(); } + } + + @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture texture) { + running = false; + synchronized (frameLock) { frameLock.notifyAll(); } + Thread thread = renderThread; + if (thread != null && thread != Thread.currentThread()) { + try { thread.join(500L); } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } + } + renderThread = null; + if (renderSurface != null) { renderSurface.release(); renderSurface = null; } + return true; + } + + @Override public void onSurfaceTextureUpdated(SurfaceTexture texture) { } + + private void renderLoop() { + EGLDisplay display = EGL14.eglGetDisplay(EGL14.EGL_DEFAULT_DISPLAY); + EGL14.eglInitialize(display, new int[2], 0, new int[2], 0); + int[] configAttrs = { EGL14.EGL_RENDERABLE_TYPE, EGL14.EGL_OPENGL_ES2_BIT, + EGL14.EGL_RED_SIZE, 8, EGL14.EGL_GREEN_SIZE, 8, EGL14.EGL_BLUE_SIZE, 8, + EGL14.EGL_ALPHA_SIZE, 8, EGL14.EGL_DEPTH_SIZE, 0, EGL14.EGL_NONE }; + EGLConfig[] configs = new EGLConfig[1]; + int[] count = new int[1]; + if (!EGL14.eglChooseConfig(display, configAttrs, 0, configs, 0, 1, count, 0) || count[0] == 0) return; + int[] contextAttrs = { EGL14.EGL_CONTEXT_CLIENT_VERSION, 2, EGL14.EGL_NONE }; + EGLContext context = EGL14.eglCreateContext(display, configs[0], EGL14.EGL_NO_CONTEXT, contextAttrs, 0); + int[] surfaceAttrs = { EGL14.EGL_NONE }; + EGLSurface surface = EGL14.eglCreateWindowSurface(display, configs[0], renderSurface, surfaceAttrs, 0); + if (context == null || surface == null || !EGL14.eglMakeCurrent(display, surface, surface, context)) return; + renderer.onSurfaceCreated(); + renderer.onSurfaceChanged(surfaceWidth, surfaceHeight); + while (running) { + if (renderer.active) { + renderer.onDrawFrame(); + EGL14.eglSwapBuffers(display, surface); + } + synchronized (frameLock) { + try { frameLock.wait(renderer.active ? 32L : 250L); } + catch (InterruptedException ignored) { Thread.currentThread().interrupt(); break; } + } + } + EGL14.eglMakeCurrent(display, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); + EGL14.eglDestroySurface(display, surface); + EGL14.eglDestroyContext(display, context); + EGL14.eglTerminate(display); + } + + private static final class FerrofluidRenderer { + private static final float[] QUAD = { -1f, -1f, 1f, -1f, -1f, 1f, 1f, 1f }; + private static final String VERTEX = + "attribute vec2 a_position; varying vec2 v_uv;" + + "void main(){ v_uv=a_position*.5+.5; gl_Position=vec4(a_position,0.0,1.0); }"; + private static final String FRAGMENT = + "precision mediump float; varying vec2 v_uv;" + + "uniform vec2 u_resolution; uniform float u_time; uniform float u_opacity;" + + "uniform float u_bands[16];" + + // Portions adapted from Robert Leitl's MIT-licensed ferrofluid + // project (github.com/robert-leitl/ferrofluid), specifically + // height-map.frag.glsl and fluid-shading.glsl. + // Adapted from robert-leitl/ferrofluid's height-map.frag.glsl: + // smooth-min distance fields turn moving particle samples into + // one continuous fluid surface. + "float almostIdentity(float x,float m,float n){ if(x>m)return x; float a=2.0*n-m; float b=2.0*m-3.0*n; float t=x/m; return (a*t+b)*t*t+n; }" + + "vec2 drift(vec2 c,float phase,float amount,float kick){" + + " return c+vec2(sin(u_time*.37+phase)*amount,cos(u_time*.29+phase*1.31)*amount*.72)" + + " + vec2(cos(u_time*.17+phase*2.0),sin(u_time*.23+phase))*kick*.06; }" + + "vec2 particleCenter(int i,float kick){" + + " if(i==0)return drift(vec2(-.28,-.10),.2,.13,kick);" + + " if(i==1)return drift(vec2(.23,-.16),1.7,.11,kick);" + + " if(i==2)return drift(vec2(.21,.21),3.4,.12,kick);" + + " if(i==3)return drift(vec2(-.23,.23),4.8,.14,kick);" + + " if(i==4)return drift(vec2(0.0,.02),5.6,.10,kick);" + + " return drift(vec2(-.03,-.30),6.4,.12,kick); }" + + "float particleRadius(int i){ if(i==0)return .215; if(i==1)return .195; if(i==2)return .205; if(i==3)return .19; if(i==4)return .18; return .17; }" + + "float heightField(vec2 pos,float kick){ float res=1.0; float w=.105;" + + " for(int i=0;i<6;i++){ vec2 c=particleCenter(i,kick); float a=atan(pos.y-c.y,pos.x-c.x);" + + " float teeth=pow(max(0.0,sin(a*5.0+u_time*(.7+float(i)*.09))),12.0)*kick*.09;" + + " float d=distance(c,pos)-particleRadius(i)*(1.0+kick*.20+teeth);" + + " float h=smoothstep(-1.0,1.0,(res-d)/w); res=mix(res,d,h)-h*(1.0-h)*(w/(1.0+3.0*w)); }" + + " res=clamp(res*(1.0+kick*.18),0.0,1.0); res=almostIdentity(res,.1,.04); return 1.0-res; }" + + // Adapted verbatim in spirit from fluid-shading.glsl: fast + // specular, Fresnel, and palette-based iridescence. + "float powFast(float a,float b){return a/((1.0-b)*a+b);}" + + "vec3 palette(float t,vec3 a,vec3 b,vec3 c,vec3 d){return a+b*cos(6.28318*(c*t+d));}" + + "vec3 fluidShading(vec3 V,vec3 N,vec3 position,float zoom,float treble){" + + " vec3 L=normalize(vec3(2.0,1.0,1.0)); vec3 R=reflect(L,N);" + + " float specularValue=powFast(max(0.0,dot(R,-V)),50.0);" + + " vec3 specular=specularValue*vec3(1.0,.4,1.0);" + + " float ft=dot(N,normalize(vec3(0.0,0.0,1.0)));" + + " float fresnelValue=smoothstep(.6,1.0,min(1.0,pow(1.0-ft,2.0)));" + + " vec3 fresnel=fresnelValue*vec3(.2,1.0,1.0);" + + " vec3 iridescence=palette(ft*3.0,vec3(.5),vec3(.5),vec3(1.0),vec3(0.0,.33,.67))*(1.0-ft)*(.08+treble*.12);" + + " return vec3(.015,.095,.115)+vec3(.025,.28,.32)*max(dot(N,L),0.0)+specular*1.2+fresnel*.42+iridescence; }" + + "void main(){" + + " float bass=clamp(u_bands[0]*1.65+u_bands[1]*1.2+u_bands[2]*.65,0.0,1.0);" + + " float treble=clamp(u_bands[10]*1.4+u_bands[13]*.7,0.0,1.0);" + + " vec2 center=vec2(u_resolution.x*.40,u_resolution.y*.38);" + + " float radius=min(u_resolution.x*.34,u_resolution.y*.40);" + + " vec2 p=(gl_FragCoord.xy-center)/radius; float radial=dot(p,p);" + + " if(radial>2.05) discard;" + + " float kick=bass*(.82+treble*.28); float f=heightField(p,kick);" + + " float e=.009; float gx=heightField(p+vec2(e,0.0),kick)-heightField(p-vec2(e,0.0),kick);" + + " float gy=heightField(p+vec2(0.0,e),kick)-heightField(p-vec2(0.0,e),kick);" + + " float body=smoothstep(.76,.94,f);" + + " float glow=(1.0-smoothstep(.56,.76,f))*(1.0-smoothstep(.35,1.75,radial))*.16;" + + " if(body<.002 && glow<.002) discard;" + + " vec3 n=normalize(vec3(-gx*2.8,-gy*2.8,.42));" + + " vec3 v=vec3(0.0,0.0,1.0); vec3 metal=fluidShading(v,n,vec3(p.x,f,p.y),kick,treble);" + + " vec3 halo=vec3(.02,.55,.66)*glow;" + + " float edge=pow(1.0-body,2.0)*body*.38;" + + " float alpha=clamp(max(body*.86+edge,glow*.55)*u_opacity,0.0,1.0);" + + " gl_FragColor=vec4(metal*body+halo,alpha); }"; + private final float[] bands = new float[16]; + private final FloatBuffer quad = ByteBuffer.allocateDirect(8 * 4) + .order(ByteOrder.nativeOrder()).asFloatBuffer(); + private volatile boolean active; + private volatile float opacity = .8f; + private int program, position, resolution, time, opacityLocation, bandsLocation; + private long startedAt; + + FerrofluidRenderer() { quad.put(QUAD).position(0); } + + void onSurfaceCreated() { + GLES20.glClearColor(0f, 0f, 0f, 0f); + GLES20.glEnable(GLES20.GL_BLEND); + GLES20.glBlendFunc(GLES20.GL_SRC_ALPHA, GLES20.GL_ONE_MINUS_SRC_ALPHA); + program = link(VERTEX, FRAGMENT); + position = GLES20.glGetAttribLocation(program, "a_position"); + resolution = GLES20.glGetUniformLocation(program, "u_resolution"); + time = GLES20.glGetUniformLocation(program, "u_time"); + opacityLocation = GLES20.glGetUniformLocation(program, "u_opacity"); + bandsLocation = GLES20.glGetUniformLocation(program, "u_bands"); + startedAt = SystemClock.uptimeMillis(); + } + + void onSurfaceChanged(int width, int height) { + GLES20.glViewport(0, 0, width, height); + GLES20.glUseProgram(program); + GLES20.glUniform2f(resolution, width, height); + } + + void onDrawFrame() { + GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT); + if (!active || program == 0) return; + GLES20.glUseProgram(program); + GLES20.glUniform1f(time, (SystemClock.uptimeMillis() - startedAt) * .001f); + GLES20.glUniform1f(opacityLocation, opacity); + synchronized (bands) { GLES20.glUniform1fv(bandsLocation, bands.length, bands, 0); } + GLES20.glEnableVertexAttribArray(position); + GLES20.glVertexAttribPointer(position, 2, GLES20.GL_FLOAT, false, 0, quad); + GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4); + GLES20.glDisableVertexAttribArray(position); + } + + private static int link(String vertexSource, String fragmentSource) { + int vertex = compile(GLES20.GL_VERTEX_SHADER, vertexSource); + int fragment = compile(GLES20.GL_FRAGMENT_SHADER, fragmentSource); + int result = GLES20.glCreateProgram(); + GLES20.glAttachShader(result, vertex); + GLES20.glAttachShader(result, fragment); + GLES20.glLinkProgram(result); + int[] status = new int[1]; + GLES20.glGetProgramiv(result, GLES20.GL_LINK_STATUS, status, 0); + if (status[0] == 0) throw new IllegalStateException(GLES20.glGetProgramInfoLog(result)); + GLES20.glDeleteShader(vertex); + GLES20.glDeleteShader(fragment); + return result; + } + + private static int compile(int type, String source) { + int shader = GLES20.glCreateShader(type); + GLES20.glShaderSource(shader, source); + GLES20.glCompileShader(shader); + int[] status = new int[1]; + GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, status, 0); + if (status[0] == 0) throw new IllegalStateException(GLES20.glGetShaderInfoLog(shader)); + return shader; + } + } + } + private final MusicPlayerManager.Listener musicState = new MusicPlayerManager.Listener() { @Override public void onMusicStateChanged(MusicPlayerManager.State state) { if (musicPanel != null) musicPanel.render(state, MusicPlayerManager.enabled(MainActivity.this) && !MusicPlayerManager.hasNotificationAccess(MainActivity.this)); diff --git a/src/cloud/molberg/mgutility/MusicPlayerManager.java b/src/cloud/molberg/mgutility/MusicPlayerManager.java index e09ddca..c3d3804 100644 --- a/src/cloud/molberg/mgutility/MusicPlayerManager.java +++ b/src/cloud/molberg/mgutility/MusicPlayerManager.java @@ -29,6 +29,10 @@ public final class MusicPlayerManager { private static final Handler MAIN = new Handler(Looper.getMainLooper()); private static MediaController.Callback callback; private static MediaController watching; + private static MediaController clockController; + private static long clockPositionMs; + private static long clockPositionAt; + private static long lastReportedPositionMs; private static final Runnable FLUSH = new Runnable() { @Override public void run() { notifyImmediate(); @@ -51,8 +55,11 @@ public final class MusicPlayerManager { public final String title, artist; public final Bitmap art; public final boolean playing; - State(String title, String artist, Bitmap art, boolean playing) { + public final long positionMs, durationMs; + State(String title, String artist, Bitmap art, boolean playing, long positionMs, long durationMs) { this.title = title; this.artist = artist; this.art = art; this.playing = playing; + this.positionMs = Math.max(0L, positionMs); + this.durationMs = Math.max(0L, durationMs); } } @@ -99,16 +106,65 @@ public final class MusicPlayerManager { } public static State state() { synchronized (LOCK) { - if (controller == null) return new State("NO MEDIA PLAYING", "", null, false); + if (controller == null) return new State("NO MEDIA PLAYING", "", null, false, 0L, 0L); MediaMetadata metadata = controller.getMetadata(); String title = metadata == null ? "NOW PLAYING" : metadata.getString(MediaMetadata.METADATA_KEY_TITLE); String artist = metadata == null ? "" : metadata.getString(MediaMetadata.METADATA_KEY_ARTIST); if (TextUtils.isEmpty(title)) title = "NOW PLAYING"; if (TextUtils.isEmpty(artist)) artist = controller.getPackageName(); - Bitmap art = metadata == null ? null : metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART); + Bitmap art = null; + if (metadata != null) { + art = metadata.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART); + if (art == null) art = metadata.getBitmap(MediaMetadata.METADATA_KEY_ART); + if (art == null) art = metadata.getBitmap(MediaMetadata.METADATA_KEY_DISPLAY_ICON); + } PlaybackState playback = controller.getPlaybackState(); - boolean playing = playback != null && playback.getState() == PlaybackState.STATE_PLAYING; - return new State(title, artist, art, playing); + boolean playing = playback != null && (playback.getState() == PlaybackState.STATE_PLAYING + || playback.getState() == PlaybackState.STATE_BUFFERING); + long duration = metadata == null ? 0L : metadata.getLong(MediaMetadata.METADATA_KEY_DURATION); + long reportedPosition = playback == null ? 0L : Math.max(0L, playback.getPosition()); + long position = reportedPosition; + long now = android.os.SystemClock.elapsedRealtime(); + if (playing) { + float speed = playback == null ? 1f : playback.getPlaybackSpeed(); + if (speed <= 0f) speed = 1f; + long updateTime = playback == null ? 0L : playback.getLastPositionUpdateTime(); + if (updateTime > 0L && now >= updateTime && now - updateTime < 120000L) { + // This is the authoritative path. Do not mix it with the + // fallback anchor or the position can oscillate backwards. + position = reportedPosition + (long) ((now - updateTime) * speed); + clockController = controller; + clockPositionMs = position; + clockPositionAt = now; + lastReportedPositionMs = reportedPosition; + } else { + // A few players omit lastPositionUpdateTime and return the + // same position forever. Advance a local clock, re-anchoring + // only for an actual seek/track jump (not normal stale reads). + boolean newController = clockController != controller || clockPositionAt == 0L; + long localPosition = newController ? reportedPosition + : clockPositionMs + (long) ((now - clockPositionAt) * speed); + boolean seekOrTrackJump = !newController + && (Math.abs(reportedPosition - lastReportedPositionMs) > 3000L + || Math.abs(reportedPosition - localPosition) > 3000L); + if (newController || seekOrTrackJump) { + clockController = controller; + clockPositionMs = reportedPosition; + clockPositionAt = now; + localPosition = reportedPosition; + } + position = localPosition; + lastReportedPositionMs = reportedPosition; + } + } else { + position = reportedPosition; + clockController = controller; + clockPositionMs = position; + clockPositionAt = now; + lastReportedPositionMs = reportedPosition; + } + if (duration > 0L) position = Math.min(position, duration); + return new State(title, artist, art, playing, position, duration); } } @@ -143,15 +199,31 @@ public final class MusicPlayerManager { } } + /** Seek the active media session to an absolute position in milliseconds. */ + public static void seekTo(long positionMs) { + synchronized (LOCK) { + if (controller == null) return; + controller.getTransportControls().seekTo(Math.max(0L, positionMs)); + } + } + private static void choose(List values) { MediaController next; synchronized (LOCK) { controller = null; next = null; + long nextUpdate = Long.MIN_VALUE; if (values != null) for (MediaController value : values) { PlaybackState state = value.getPlaybackState(); - if (state != null && state.getState() == PlaybackState.STATE_PLAYING) { next = value; break; } - if (next == null) next = value; + boolean active = state != null && (state.getState() == PlaybackState.STATE_PLAYING + || state.getState() == PlaybackState.STATE_BUFFERING); + long update = state == null ? Long.MIN_VALUE : state.getLastPositionUpdateTime(); + if (active && (next == null || nextUpdate == Long.MIN_VALUE || update > nextUpdate)) { + next = value; + nextUpdate = update; + } else if (next == null) { + next = value; + } } controller = next; if (watching != null && watching != next) { diff --git a/src/cloud/molberg/mgutility/RawSamplesActivity.java b/src/cloud/molberg/mgutility/RawSamplesActivity.java new file mode 100644 index 0000000..b7a6235 --- /dev/null +++ b/src/cloud/molberg/mgutility/RawSamplesActivity.java @@ -0,0 +1,240 @@ +package cloud.molberg.mgutility; + +import android.graphics.Typeface; +import android.os.Bundle; +import android.os.Handler; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.ScrollView; +import android.widget.TableLayout; +import android.widget.TableRow; +import android.widget.TextView; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; + +/** Full-page raw sample viewer with a sticky header. */ +public final class RawSamplesActivity extends AnimatedActivity { + static final String EXTRA_TRIP_ID = "trip_id"; + private static final String[] HEADERS = { + "TIME", "SPEED (km/h)", "SOC (%)", "VOLTS (V)", "ENERGY (kWh)", + "REGEN (kWh)", "RANGE (km)", "Δ REGEN (kWh)", "REGEN EVENT" + }; + private static final int[] COLUMN_WEIGHTS = { 12, 12, 8, 8, 12, 12, 12, 14, 24 }; + private TripDatabase database; + private final Handler handler = new Handler(); + private TableLayout bodyTable; + private TextView statusView; + private long renderedThemeVersion; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + immersive(); + database = new TripDatabase(this); + setContentView(buildUi()); + renderedThemeVersion = UiTheme.version(); + load(); + } + + @Override public void onDestroy() { + if (database != null) database.close(); + super.onDestroy(); + } + + @Override protected void onResume() { + super.onResume(); + UiTheme.refreshTheme(this); + if (UiTheme.version() != renderedThemeVersion && bodyTable != null) { + setContentView(buildUi()); + renderedThemeVersion = UiTheme.version(); + load(); + } + } + + private void immersive() { + getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackgroundColor(UiTheme.BACKGROUND); + root.setPadding(24, 14, 24, 18); + LinearLayout bar = new LinearLayout(this); + bar.setGravity(Gravity.CENTER_VERTICAL); + bar.addView(UiTheme.title(this, "RAW SAMPLE LOG", 26), new LinearLayout.LayoutParams(0, 56, 1)); + Button back = UiTheme.backButton(this, new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }); + LinearLayout.LayoutParams bp = new LinearLayout.LayoutParams(130, 56); + bp.setMargins(10, 0, 0, 0); + bar.addView(back, bp); + root.addView(bar); + TextView subtitle = UiTheme.text(this, + "Per-sample vehicle counters • green rows are regeneration events", + 12, UiTheme.MUTED, Typeface.NORMAL); + root.addView(subtitle, new LinearLayout.LayoutParams(-1, -2)); + statusView = UiTheme.text(this, "Loading samples…", 12, UiTheme.MUTED, Typeface.NORMAL); + statusView.setPadding(0, 8, 0, 8); + root.addView(statusView, new LinearLayout.LayoutParams(-1, -2)); + + TableLayout headerTable = new TableLayout(this); + headerTable.setBackgroundColor(UiTheme.SURFACE); + headerTable.setPadding(0, 12, 0, 12); + headerTable.addView(buildHeaderRow()); + root.addView(headerTable, new LinearLayout.LayoutParams(-1, -2)); + + ScrollView scroll = new ScrollView(this); + scroll.setFillViewport(true); + bodyTable = new TableLayout(this); + bodyTable.setBackgroundColor(UiTheme.SURFACE); + scroll.addView(bodyTable, new ScrollView.LayoutParams(-1, -2)); + root.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); + return root; + } + + private TableRow buildHeaderRow() { + TableRow row = new TableRow(this); + row.setGravity(Gravity.CENTER_VERTICAL); + for (int i = 0; i < HEADERS.length; i++) { + TextView cell = new TextView(this); + cell.setText(HEADERS[i]); + cell.setTextSize(11 * 1.25f); + cell.setTextColor(UiTheme.MUTED); + cell.setTypeface(Typeface.create("sans-serif", Typeface.BOLD)); + cell.setGravity(i == 0 || i == HEADERS.length - 1 ? Gravity.LEFT : Gravity.RIGHT); + cell.setPadding(12, 6, 12, 6); + row.addView(cell, weightedColumn(i)); + } + return row; + } + + private void load() { + final long tripId = getIntent().getLongExtra(EXTRA_TRIP_ID, TripDatabase.NO_TRIP); + if (tripId == TripDatabase.NO_TRIP) { + statusView.setText("No drive selected"); + return; + } + new Thread(new Runnable() { @Override public void run() { + final List samples = database.getSamples(tripId); + final List events = database.getRegenEvents(tripId); + handler.post(new Runnable() { @Override public void run() { + renderBody(samples, events); + } }); + } }, "mg-trip-raw-full").start(); + } + + private void renderBody(List samples, List events) { + bodyTable.removeAllViews(); + if (samples == null || samples.isEmpty()) { + statusView.setText("No raw samples recorded for this drive."); + return; + } + statusView.setText(samples.size() + " samples • " + (events == null ? 0 : events.size()) + " regen events"); + SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss", Locale.US); + boolean[] shown = new boolean[events == null ? 0 : events.size()]; + TripDatabase.TripSample previous = null; + for (int i = 0; i < samples.size(); i++) { + TripDatabase.TripSample sample = samples.get(i); + double delta = 0d; + if (previous != null && !Double.isNaN(previous.regenEnergyKwh) && !Double.isNaN(sample.regenEnergyKwh)) { + delta = sample.regenEnergyKwh - previous.regenEnergyKwh; + } + previous = sample; + String eventText = ""; + int eventIndex = -1; + if (events != null) { + for (int j = 0; j < events.size(); j++) { + TripDatabase.RegenEvent event = events.get(j); + if (sample.timestamp >= event.startTime && sample.timestamp <= event.endTime) { + eventIndex = j; + if (!shown[j]) { + shown[j] = true; + eventText = String.format(Locale.US, "#%d +%.4f kWh\n+%.3f km range", + j + 1, event.energyKwh, event.rangeKm); + } + break; + } + } + } + bodyTable.addView(buildSampleRow(fmt, sample, delta, i, eventText, + eventIndex >= 0 || delta > 0.0001d)); + } + if (events != null) { + for (int i = 0; i < events.size(); i++) if (!shown[i]) { + bodyTable.addView(buildEventOnlyRow(events.get(i), i)); + } + } + } + + private TableRow buildSampleRow(SimpleDateFormat fmt, TripDatabase.TripSample sample, + double delta, int index, String eventText, boolean highlighted) { + String[] values = { + fmt.format(new Date(sample.timestamp)), speed(sample.speedKph), percent(sample.soc), + volts(sample.volts), energy(sample.energyKwh), energy(sample.regenEnergyKwh), + range(sample.regenRangeKm), index == 0 ? "—" : deltaValue(delta), eventText + }; + TableRow row = new TableRow(this); + row.setGravity(Gravity.CENTER_VERTICAL); + if (highlighted) row.setBackgroundColor(UiTheme.withAlpha(UiTheme.SUCCESS, 45)); + for (int i = 0; i < values.length; i++) { + TextView cell = new TextView(this); + cell.setText(values[i]); + cell.setTextSize(11 * 1.25f); + cell.setTypeface(Typeface.MONOSPACE); + cell.setGravity(i == 0 || i == values.length - 1 ? Gravity.LEFT : Gravity.RIGHT); + cell.setPadding(12, 8, 12, 8); + cell.setTextColor(highlighted ? UiTheme.SUCCESS : UiTheme.TEXT); + row.addView(cell, weightedColumn(i)); + } + return row; + } + + private TableRow buildEventOnlyRow(TripDatabase.RegenEvent event, int index) { + TableRow row = new TableRow(this); + row.setGravity(Gravity.CENTER_VERTICAL); + row.setBackgroundColor(UiTheme.withAlpha(UiTheme.SUCCESS, 45)); + for (int i = 0; i < HEADERS.length; i++) { + TextView cell = new TextView(this); + if (i == HEADERS.length - 1) { + cell.setText(String.format(Locale.US, "#%d +%.4f kWh\n+%.3f km range", + index + 1, event.energyKwh, event.rangeKm)); + } else if (i == 0) { + cell.setText(new SimpleDateFormat("HH:mm:ss", Locale.US).format(new Date(event.startTime))); + } else { + cell.setText(""); + } + cell.setTextSize(11 * 1.25f); + cell.setTypeface(Typeface.MONOSPACE); + cell.setTextColor(UiTheme.SUCCESS); + cell.setGravity(i == 0 || i == HEADERS.length - 1 ? Gravity.LEFT : Gravity.RIGHT); + cell.setPadding(12, 8, 12, 8); + row.addView(cell, weightedColumn(i)); + } + return row; + } + + private TableRow.LayoutParams weightedColumn(int index) { + return new TableRow.LayoutParams(0, -2, COLUMN_WEIGHTS[index]); + } + + private static String speed(float v) { return Float.isNaN(v) ? "—" : String.format(Locale.US, "%.0f km/h", v); } + private static String percent(float v) { return Float.isNaN(v) ? "—" : String.format(Locale.US, "%.1f %%", v); } + private static String volts(float v) { return Float.isNaN(v) ? "—" : String.format(Locale.US, "%.2f V", v); } + private static String energy(double v) { return Double.isNaN(v) ? "—" : String.format(Locale.US, "%.4f kWh", v); } + private static String range(double v) { return Double.isNaN(v) ? "—" : String.format(Locale.US, "%.3f km", v); } + private static String deltaValue(double delta) { + if (Double.isNaN(delta) || delta == 0d) return "0.0000 kWh"; + return String.format(Locale.US, "%+.4f kWh", delta); + } +} diff --git a/src/cloud/molberg/mgutility/SettingsActivity.java b/src/cloud/molberg/mgutility/SettingsActivity.java index 51b0d0e..dbbf438 100644 --- a/src/cloud/molberg/mgutility/SettingsActivity.java +++ b/src/cloud/molberg/mgutility/SettingsActivity.java @@ -31,6 +31,8 @@ import android.widget.SeekBar; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; +import android.app.TimePickerDialog; +import android.widget.TimePicker; import android.widget.Toast; import java.util.ArrayList; @@ -43,8 +45,10 @@ import java.util.Locale; /** Categorized settings hub styled after the SAIC head-unit Settings experience. */ public final class SettingsActivity extends AnimatedActivity { - private static final String[] CATEGORIES = { "Driving", "Charging", "Misc", "Appearance", "Apps" }; + private static final String[] CATEGORIES = { "Driving", "Charging", "Misc", "Appearance", "Apps", "Config" }; private static final String PREF_APPS_REORDER = "apps_reorder_enabled"; + private static final int REQUEST_EXPORT = 8801; + private static final int REQUEST_IMPORT = 8802; private LinearLayout content; private LinearLayout tabs; private GridLayout appsGrid; @@ -154,7 +158,78 @@ public final class SettingsActivity extends AnimatedActivity { else if (category == 1) charging(); else if (category == 2) misc(); else if (category == 3) appearance(); - else apps(); + else if (category == 4) apps(); + else config(); + } + + /** Centralized settings export/import and reset controls. */ + private void config() { + section("Config", "Export, import, or reset every MG Utility setting"); + ConfigStore store = ConfigStore.of(this); + int keyCount = store.visibleKeyCount(); + subsection("Transfer", "Move settings between MG Utility installations"); + content.addView(row("⇧", "Export settings", "Save a versioned JSON file (" + keyCount + " keys)", new View.OnClickListener() { + @Override public void onClick(View v) { + Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("application/json"); + intent.putExtra(Intent.EXTRA_TITLE, "mg-utility-settings.json"); + try { startActivityForResult(intent, REQUEST_EXPORT); } + catch (Exception e) { Toast.makeText(SettingsActivity.this, "No file picker available", Toast.LENGTH_LONG).show(); } + } + })); + content.addView(row("⇩", "Import settings", "Restore a previously exported JSON file", new View.OnClickListener() { + @Override public void onClick(View v) { + Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType("application/json"); + try { startActivityForResult(intent, REQUEST_IMPORT); } + catch (Exception e) { Toast.makeText(SettingsActivity.this, "No file picker available", Toast.LENGTH_LONG).show(); } + } + })); + content.addView(row("↺", "Reset settings", "Clear saved settings and return to defaults", new View.OnClickListener() { + @Override public void onClick(View v) { + UiTheme.dialog(SettingsActivity.this) + .setTitle("RESET SETTINGS?") + .setMessage("This clears themes, pinned apps, vehicle defaults, automations, and every other saved preference. This cannot be undone.") + .setNegativeButton("CANCEL", null) + .setPositiveButton("RESET", new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { + ConfigStore.of(SettingsActivity.this).resetAll(); + Toast.makeText(SettingsActivity.this, "Settings reset", Toast.LENGTH_SHORT).show(); + recreate(); + } + }).show(); + } + })); + subsection("Included", "The export contains all user-visible configuration"); + for (String name : ConfigStore.sections()) { + content.addView(row("•", name, "Included in export", null)); + } + } + + @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (resultCode != RESULT_OK || data == null || data.getData() == null) return; + try { + if (requestCode == REQUEST_EXPORT) { + java.io.OutputStream out = getContentResolver().openOutputStream(data.getData()); + if (out == null) throw new java.io.IOException("Unable to open destination"); + ConfigStore.of(this).exportTo(out); + Toast.makeText(this, "Settings exported", Toast.LENGTH_SHORT).show(); + } else if (requestCode == REQUEST_IMPORT) { + java.io.InputStream in = getContentResolver().openInputStream(data.getData()); + if (in == null) throw new java.io.IOException("Unable to open file"); + ConfigStore.ImportResult result = ConfigStore.of(this).importFrom(in); + Toast.makeText(this, "Imported " + result.keysApplied + " settings", Toast.LENGTH_SHORT).show(); + UiTheme.refreshTheme(this); + recreate(); + } + } catch (IllegalArgumentException e) { + Toast.makeText(this, "Unsupported settings file", Toast.LENGTH_LONG).show(); + } catch (Exception e) { + Toast.makeText(this, "Settings transfer failed", Toast.LENGTH_LONG).show(); + } } private void section(String title, String subtitle) { @@ -168,8 +243,21 @@ public final class SettingsActivity extends AnimatedActivity { } } + /** A compact heading used for feature groups inside a top-level category. */ + private void subsection(String title, String subtitle) { + TextView heading = UiTheme.label(this, title.toUpperCase(Locale.US)); + heading.setPadding(18, 12, 0, 3); + content.addView(heading, new LinearLayout.LayoutParams(-1, 24 + Math.round(8 * UiTheme.fontScale(this)))); + if (subtitle != null) { + TextView hint = UiTheme.text(this, subtitle, 11, UiTheme.MUTED, Typeface.NORMAL); + hint.setPadding(18, 0, 0, 5); + content.addView(hint, new LinearLayout.LayoutParams(-1, 24 + Math.round(6 * UiTheme.fontScale(this)))); + } + } + private void driving() { - section("Driving", "Vehicle defaults and driving tools"); + section("Driving", "Vehicle defaults, performance, and trip history"); + subsection("Vehicle defaults", "Choose the profile applied when driving starts"); content.addView(row("V", "Vehicle settings", "Capability-gated startup profile", open(VehicleSettingsActivity.class))); content.addView(row("D", "Default drive mode", driveModeName(), new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, VehicleSettingsActivity.class)); } @@ -177,22 +265,39 @@ public final class SettingsActivity extends AnimatedActivity { content.addView(row("R", "Default recovery level", regenName(), new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, VehicleSettingsActivity.class)); } })); + subsection("Performance", "Tools for measuring acceleration"); content.addView(row("0", "0–100 tester", "Open performance timer", open(SpeedTestActivity.class))); + subsection("Trip tracking", "Choose how drive samples are collected and reviewed"); content.addView(row("T", "Trip reports", "View saved drives", open(TripsActivity.class))); + content.addView(row("A", "Arrival areas", "Configure geofences and price-window briefings", open(ArrivalGeofenceActivity.class))); + content.addView(row("S", "Drive log sample interval", sampleIntervalLabel(), new View.OnClickListener() { + @Override public void onClick(View v) { chooseSampleInterval(); } + })); + subsection("Maps", "Manage offline map tiles used by trip reports"); + content.addView(row("M", "Map tile cache storage", tileCacheLabel(), new View.OnClickListener() { + @Override public void onClick(View v) { chooseTileCache(); } + })); + content.addView(row("◆", "Map cache current use", MapTileCache.usageLabel(this), null)); } private void charging() { section("Charging", "Charging tools and energy monitoring"); + subsection("Charging management", "Automations and live energy information"); content.addView(row("⚡", "Charging automation", "Rules and price triggers", open(ChargingActivity.class))); content.addView(row("E", "Energy dashboard", "Live consumption and recovery", open(EnergyActivity.class))); + subsection("Vehicle charging", "Open the original SAIC charging controls"); content.addView(row("C", "Vehicle charging settings", "Open OEM settings", new View.OnClickListener() { - @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.vehiclesettings", "com.saicmotor.hmi.vehiclesettings.vehicleconfig.ui.VehicleSettingsActivity"); } + @Override public void onClick(View v) { openComponent("com.saicmotor.hmi.vehiclesettings", "com.saicmotor.hmi.vehiclesettings.chargemanagement.ui.ChargeManagementActivity"); } })); } private void misc() { section("Misc", "Head-unit and application tools"); + subsection("Audio", "Configure event sounds and speed-aware playback"); content.addView(row("♫", "Soundboard", "Configure event audio", open(SoundboardActivity.class))); + content.addView(row("♪", "Speed reactive audio", "Looping clip that reacts to driving speed", open(SpeedAudioActivity.class))); + content.addView(row("≈", "Adaptive audio leveling", "Scale media volume smoothly with vehicle speed", open(AdaptiveAudioLevelingActivity.class))); + subsection("Setup", "Review the first-time configuration"); content.addView(row("★", "Run setup wizard", "Reopen the first-time setup review", new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(SettingsActivity.this, SetupWizardActivity.class); @@ -200,11 +305,11 @@ public final class SettingsActivity extends AnimatedActivity { startActivity(intent); } })); - content.addView(row("♪", "Speed reactive audio", "Looping clip that reacts to driving speed", open(SpeedAudioActivity.class))); + subsection("Diagnostics", "Troubleshooting and input customization"); content.addView(row("!", "Debug console", "System properties and diagnostics", open(DebugActivity.class))); content.addView(row("K", "Key remapping", "Assign physical head-unit keys", open(KeyRemappingActivity.class))); - section("OEM Apps", "Original SAIC launchers and tools"); + subsection("OEM Apps", "Original SAIC launchers and tools"); content.addView(row("⌂", "Official SAIC launcher", "Open OEM home screen", new View.OnClickListener() { @Override public void onClick(View v) { launchOemLauncher(); } })); @@ -224,31 +329,51 @@ public final class SettingsActivity extends AnimatedActivity { private void appearance() { section("Appearance", "Personalise the MG Utility dashboard"); + subsection("Theme", "Choose colours and text sizing"); content.addView(fontScaleControl()); content.addView(row("◈", "Theme", themeName(), new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, CustomThemeEditorActivity.class)); } })); - section("Navigation", "Choose how pages open and close"); + subsection("Navigation", "Choose how pages open and close"); content.addView(toggleRow("→", "Page animations", "Slide transitions between MG Utility pages", UiTheme.UI_PREFS, AnimatedActivity.PREF_PAGE_ANIMATIONS_ENABLED, true)); - section("Home screen", "Choose what appears on the dashboard"); + subsection("Music player", "Show currently playing music on the dashboard"); content.addView(toggleRow("♫", "Music Player", "Show current song, artist, and album art", UiTheme.UI_PREFS, MusicPlayerManager.PREF_ENABLED, false)); - content.addView(toggleRow("≋", "Music Visualizer", "Live full-width playback spectrum", "ui_state", "home_visualizer_enabled", true)); + subsection("App drawer", "Control the swipe-up launcher and its appearance"); content.addView(toggleRow("⌃", "App Drawer", "Swipe up from the home screen to reveal your pinned apps", "ui_state", MainActivity.PREF_APP_DRAWER_ENABLED, false)); + content.addView(appDrawerOpacityControl()); + subsection("Control panel", "Choose the quick controls available from the dashboard"); content.addView(toggleRow("⌄", "Control panel", "Swipe down from the home screen for quick controls", "ui_state", ControlPanelCatalog.PREF_ENABLED, true)); content.addView(row("◈", "Configure control panel", "Add, remove, and reorder quick controls", new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(SettingsActivity.this, ControlPanelSettingsActivity.class)); } })); - content.addView(appDrawerOpacityControl()); + subsection("Screen brightness", "Follow a daily peak/dark schedule with a smooth fade"); + content.addView(toggleRow("☼", "Automatic brightness", "Apply the schedule while the head unit is on", + UiTheme.UI_PREFS, UiTheme.PREF_AUTO_BRIGHTNESS_ENABLED, false, new Runnable() { + @Override public void run() { BrightnessScheduler.rearm(SettingsActivity.this); } + })); + content.addView(row("↑", "Peak brightness time", BrightnessSchedule.formatMinutes(brightnessPeakMinutes()), + new View.OnClickListener() { @Override public void onClick(View v) { chooseBrightnessTime(true); } })); + content.addView(row("↓", "Dark brightness time", BrightnessSchedule.formatMinutes(brightnessDarkMinutes()), + new View.OnClickListener() { @Override public void onClick(View v) { chooseBrightnessTime(false); } })); + content.addView(brightnessSchedulePercentControl("P", "Peak brightness", UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_PERCENT, + BrightnessSchedule.DEFAULT_PEAK_PERCENT)); + content.addView(brightnessSchedulePercentControl("D", "Dark brightness", UiTheme.PREF_AUTO_BRIGHTNESS_DARK_PERCENT, + BrightnessSchedule.DEFAULT_DARK_PERCENT)); + content.addView(brightnessTransitionControl()); + subsection("Widgets panel", "Choose whether the dashboard exposes widgets"); + content.addView(toggleRow("←", "Widgets Panel", "Swipe right from the home screen for widgets", "ui_state", MainActivity.PREF_WIDGETS_PANEL_ENABLED, false)); + subsection("Music visualizer", "Choose how live playback is drawn on the dashboard"); + content.addView(toggleRow("≋", "Music Visualizer", "Show a live playback effect", "ui_state", "home_visualizer_enabled", true)); content.addView(row("F", "Visualizer framerate", visualizerFps() + " FPS", new View.OnClickListener() { @Override public void onClick(View v) { chooseVisualizerFps(); } })); - content.addView(row("M", "Map tile cache storage", tileCacheLabel(), new View.OnClickListener() { - @Override public void onClick(View v) { chooseTileCache(); } + content.addView(row("∿", "Visualizer effect", visualizerEffectName(), new View.OnClickListener() { + @Override public void onClick(View v) { chooseVisualizerEffect(); } })); - content.addView(row("◆", "Map cache current use", MapTileCache.usageLabel(this), null)); + content.addView(visualizerOpacityControl()); } private void apps() { @@ -256,6 +381,7 @@ public final class SettingsActivity extends AnimatedActivity { final boolean reorderEnabled = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE) .getBoolean(PREF_APPS_REORDER, false); section("Apps", "Pinned apps shown in the app drawer"); + subsection("Pinned apps", "Add, remove, or reorder shortcuts"); content.addView(toggleRow("↕", "Reorder", "Drag apps to change their order", UiTheme.UI_PREFS, PREF_APPS_REORDER, false, new Runnable() { @Override public void run() { showCategory(selectedCategory); } @@ -1055,6 +1181,103 @@ public final class SettingsActivity extends AnimatedActivity { .show(); } + private int brightnessPeakMinutes() { + return getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt( + UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_MINUTES, BrightnessSchedule.DEFAULT_PEAK_MINUTES); + } + + private int brightnessDarkMinutes() { + return getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt( + UiTheme.PREF_AUTO_BRIGHTNESS_DARK_MINUTES, BrightnessSchedule.DEFAULT_DARK_MINUTES); + } + + private void chooseBrightnessTime(final boolean peak) { + int initial = peak ? brightnessPeakMinutes() : brightnessDarkMinutes(); + TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { + @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { + int value = hourOfDay * 60 + minute; + getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit() + .putInt(peak ? UiTheme.PREF_AUTO_BRIGHTNESS_PEAK_MINUTES : UiTheme.PREF_AUTO_BRIGHTNESS_DARK_MINUTES, value) + .apply(); + BrightnessScheduler.rearm(SettingsActivity.this); + rebuildCategory(); + } + }, initial / 60, initial % 60, true); + dialog.setTitle(peak ? "Peak brightness time" : "Dark brightness time"); + dialog.show(); + } + + private View brightnessSchedulePercentControl(String iconText, String label, final String prefKey, int fallback) { + final LinearLayout item = new LinearLayout(this); + item.setGravity(Gravity.CENTER_VERTICAL); + item.setPadding(18, 0, 18, 0); + item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); + TextView icon = UiTheme.text(this, iconText, 18, UiTheme.CYAN, Typeface.BOLD); + icon.setGravity(Gravity.CENTER); + item.addView(icon, new LinearLayout.LayoutParams(46, 68)); + LinearLayout copy = new LinearLayout(this); + copy.setOrientation(LinearLayout.VERTICAL); + copy.setGravity(Gravity.CENTER_VERTICAL); + TextView name = UiTheme.text(this, label, 16, UiTheme.TEXT, Typeface.NORMAL); + final int initial = Math.max(0, Math.min(100, getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt(prefKey, fallback))); + final TextView value = UiTheme.text(this, initial + "%", 12, UiTheme.MUTED, Typeface.NORMAL); + copy.addView(name); copy.addView(value); + item.addView(copy, new LinearLayout.LayoutParams(330, 68)); + SeekBar slider = new SeekBar(this); + UiTheme.tintSeekBar(slider); + slider.setMax(100); slider.setProgress(initial); slider.setContentDescription(label); + slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { value.setText(progress + "%"); } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { + getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit().putInt(prefKey, bar.getProgress()).apply(); + BrightnessScheduler.rearm(SettingsActivity.this); + } + }); + item.addView(slider, new LinearLayout.LayoutParams(0, 58, 1)); + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68); + p.setMargins(0, 0, 0, 2); item.setLayoutParams(p); + return item; + } + + private View brightnessTransitionControl() { + final LinearLayout item = new LinearLayout(this); + item.setGravity(Gravity.CENTER_VERTICAL); + item.setPadding(18, 0, 18, 0); + item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); + TextView icon = UiTheme.text(this, "⇄", 18, UiTheme.CYAN, Typeface.BOLD); + icon.setGravity(Gravity.CENTER); + item.addView(icon, new LinearLayout.LayoutParams(46, 68)); + LinearLayout copy = new LinearLayout(this); + copy.setOrientation(LinearLayout.VERTICAL); copy.setGravity(Gravity.CENTER_VERTICAL); + TextView name = UiTheme.text(this, "Transition duration", 16, UiTheme.TEXT, Typeface.NORMAL); + final int initial = Math.max(BrightnessSchedule.MIN_TRANSITION_MINUTES, Math.min(BrightnessSchedule.MAX_TRANSITION_MINUTES, + getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getInt(UiTheme.PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES, + BrightnessSchedule.DEFAULT_TRANSITION_MINUTES))); + final TextView value = UiTheme.text(this, initial + " min", 12, UiTheme.MUTED, Typeface.NORMAL); + copy.addView(name); copy.addView(value); + item.addView(copy, new LinearLayout.LayoutParams(330, 68)); + SeekBar slider = new SeekBar(this); UiTheme.tintSeekBar(slider); + slider.setMax(BrightnessSchedule.MAX_TRANSITION_MINUTES - BrightnessSchedule.MIN_TRANSITION_MINUTES); + slider.setProgress(initial - BrightnessSchedule.MIN_TRANSITION_MINUTES); + slider.setContentDescription("Brightness transition duration"); + slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { + value.setText((progress + BrightnessSchedule.MIN_TRANSITION_MINUTES) + " min"); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { + getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit().putInt(UiTheme.PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES, + bar.getProgress() + BrightnessSchedule.MIN_TRANSITION_MINUTES).apply(); + BrightnessScheduler.rearm(SettingsActivity.this); + } + }); + item.addView(slider, new LinearLayout.LayoutParams(0, 58, 1)); + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68); + p.setMargins(0, 0, 0, 2); item.setLayoutParams(p); + return item; + } + private View fontScaleControl() { final LinearLayout item = new LinearLayout(this); item.setGravity(Gravity.CENTER_VERTICAL); @@ -1071,6 +1294,7 @@ public final class SettingsActivity extends AnimatedActivity { copy.addView(name); copy.addView(value); item.addView(copy, new LinearLayout.LayoutParams(330, 68)); final SeekBar slider = new SeekBar(this); + UiTheme.tintSeekBar(slider); slider.setMax(70); slider.setProgress(fontScaleProgress()); slider.setContentDescription("Font size scale"); slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @@ -1109,6 +1333,7 @@ public final class SettingsActivity extends AnimatedActivity { copy.addView(name); copy.addView(value); item.addView(copy, new LinearLayout.LayoutParams(330, 68)); final SeekBar slider = new SeekBar(this); + UiTheme.tintSeekBar(slider); slider.setMax(100); slider.setProgress(Math.max(0, Math.min(100, initial))); slider.setContentDescription("App Drawer opacity"); @@ -1128,6 +1353,44 @@ public final class SettingsActivity extends AnimatedActivity { return item; } + private View visualizerOpacityControl() { + final LinearLayout item = new LinearLayout(this); + item.setGravity(Gravity.CENTER_VERTICAL); + item.setPadding(18, 0, 18, 0); + item.setBackground(UiTheme.surface(UiTheme.SURFACE, 0)); + TextView icon = UiTheme.text(this, "◐", 18, UiTheme.CYAN, Typeface.BOLD); + icon.setGravity(Gravity.CENTER); + item.addView(icon, new LinearLayout.LayoutParams(46, 68)); + LinearLayout copy = new LinearLayout(this); + copy.setOrientation(LinearLayout.VERTICAL); + copy.setGravity(Gravity.CENTER_VERTICAL); + TextView name = UiTheme.text(this, "Visualizer opacity", 16, UiTheme.TEXT, Typeface.NORMAL); + final int initial = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE) + .getInt(MainActivity.PREF_VISUALIZER_OPACITY, 80); + final TextView value = UiTheme.text(this, Math.max(0, Math.min(100, initial)) + "%", 12, UiTheme.MUTED, Typeface.NORMAL); + copy.addView(name); copy.addView(value); + item.addView(copy, new LinearLayout.LayoutParams(330, 68)); + final SeekBar slider = new SeekBar(this); + UiTheme.tintSeekBar(slider); + slider.setMax(100); + slider.setProgress(Math.max(0, Math.min(100, initial))); + slider.setContentDescription("Visualizer opacity"); + slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean fromUser) { + value.setText(progress + "%"); + } + @Override public void onStartTrackingTouch(SeekBar bar) { } + @Override public void onStopTrackingTouch(SeekBar bar) { + getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).edit() + .putInt(MainActivity.PREF_VISUALIZER_OPACITY, bar.getProgress()).apply(); + } + }); + item.addView(slider, new LinearLayout.LayoutParams(0, 58, 1)); + LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(-1, 68); + p.setMargins(0, 0, 0, 2); item.setLayoutParams(p); + return item; + } + private int fontScaleProgress() { return Math.max(0, Math.min(70, Math.round((UiTheme.fontScale(this) - .80f) * 100f))); } @@ -1152,6 +1415,22 @@ public final class SettingsActivity extends AnimatedActivity { .getInt(MainActivity.PREF_VISUALIZER_FPS, 30)); } + private String visualizerEffectName() { + int effect = getSharedPreferences("ui_state", MODE_PRIVATE) + .getInt(MainActivity.PREF_VISUALIZER_EFFECT, MainActivity.VISUALIZER_EFFECT_SPECTRUM); + if (effect == MainActivity.VISUALIZER_EFFECT_OSCILLOSCOPE) return "Oscilloscope"; + if (effect == MainActivity.VISUALIZER_EFFECT_SPEED_RING) return "Speed Gauge Ring"; + if (effect == MainActivity.VISUALIZER_EFFECT_FERROFLUID) return "Ferrofluid"; + return "Spectrum Bars"; + } + + private String sampleIntervalLabel() { + int seconds = getSharedPreferences("trip_tracker", MODE_PRIVATE) + .getInt(TripTrackingService.PREF_SAMPLE_INTERVAL_SECONDS, + TripTrackingService.DEFAULT_SAMPLE_INTERVAL_SECONDS); + return seconds + (seconds == 1 ? " second" : " seconds"); + } + private String themeName() { String customId = getSharedPreferences(UiTheme.UI_PREFS, MODE_PRIVATE).getString("theme_id", ""); if (customId.length() > 0) { @@ -1185,6 +1464,51 @@ public final class SettingsActivity extends AnimatedActivity { }).show(); } + private void chooseVisualizerEffect() { + final String[] values = { "Spectrum Bars", "Oscilloscope", "Speed Gauge Ring", "Ferrofluid" }; + final int[] effects = { + MainActivity.VISUALIZER_EFFECT_SPECTRUM, + MainActivity.VISUALIZER_EFFECT_OSCILLOSCOPE, + MainActivity.VISUALIZER_EFFECT_SPEED_RING, + MainActivity.VISUALIZER_EFFECT_FERROFLUID + }; + int current = getSharedPreferences("ui_state", MODE_PRIVATE) + .getInt(MainActivity.PREF_VISUALIZER_EFFECT, MainActivity.VISUALIZER_EFFECT_SPECTRUM); + int selected = current == MainActivity.VISUALIZER_EFFECT_OSCILLOSCOPE ? 1 + : current == MainActivity.VISUALIZER_EFFECT_SPEED_RING ? 2 + : current == MainActivity.VISUALIZER_EFFECT_FERROFLUID ? 3 : 0; + UiTheme.dialog(this).setTitle("VISUALIZER EFFECT").setSingleChoiceItems(values, selected, + new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { + getSharedPreferences("ui_state", MODE_PRIVATE).edit() + .putInt(MainActivity.PREF_VISUALIZER_EFFECT, effects[which]).apply(); + dialog.dismiss(); showCategory(selectedCategory); + } + }).show(); + } + + private void chooseSampleInterval() { + final int[] seconds = { 1, 2, 5, 10, 15, 30, 60 }; + final String[] values = new String[seconds.length]; + int current = getSharedPreferences("trip_tracker", MODE_PRIVATE) + .getInt(TripTrackingService.PREF_SAMPLE_INTERVAL_SECONDS, + TripTrackingService.DEFAULT_SAMPLE_INTERVAL_SECONDS); + int selected = 2; + for (int i = 0; i < seconds.length; i++) { + values[i] = seconds[i] + (seconds[i] == 1 ? " second" : " seconds"); + if (seconds[i] == current) selected = i; + } + UiTheme.dialog(this).setTitle("DRIVE LOG SAMPLE INTERVAL") + .setSingleChoiceItems(values, selected, new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { + getSharedPreferences("trip_tracker", MODE_PRIVATE).edit() + .putInt(TripTrackingService.PREF_SAMPLE_INTERVAL_SECONDS, seconds[which]).apply(); + dialog.dismiss(); + showCategory(selectedCategory); + } + }).show(); + } + private void chooseDriveMode() { final String[] values = { "Snow", "Eco", "Normal", "Sport", "Custom" }; UiTheme.dialog(this).setTitle("DRIVE MODE").setSingleChoiceItems(values, diff --git a/src/cloud/molberg/mgutility/SoundboardActivity.java b/src/cloud/molberg/mgutility/SoundboardActivity.java index e1d3cff..68ab8e6 100644 --- a/src/cloud/molberg/mgutility/SoundboardActivity.java +++ b/src/cloud/molberg/mgutility/SoundboardActivity.java @@ -139,6 +139,7 @@ public final class SoundboardActivity extends AnimatedActivity { file.setEllipsize(android.text.TextUtils.TruncateAt.MIDDLE); volume = new SeekBar(SoundboardActivity.this); + UiTheme.tintSeekBar(volume); volume.setMax(100); volume.setProgress(saved.volumePercent); volumeValue = text(saved.volumePercent + "%", 12, UiTheme.RED, Typeface.BOLD); diff --git a/src/cloud/molberg/mgutility/SpeedAudioActivity.java b/src/cloud/molberg/mgutility/SpeedAudioActivity.java index 0fa5f38..6b89e83 100644 --- a/src/cloud/molberg/mgutility/SpeedAudioActivity.java +++ b/src/cloud/molberg/mgutility/SpeedAudioActivity.java @@ -124,6 +124,7 @@ public final class SpeedAudioActivity extends AnimatedActivity { list.addView(row("SOUND FILE", fileRow)); volume = new SeekBar(this); + UiTheme.tintSeekBar(volume); volume.setMax(100); volume.setProgress(cfg.volumePercent); volumeValue = text(cfg.volumePercent + "%", 12, UiTheme.RED, Typeface.BOLD); diff --git a/src/cloud/molberg/mgutility/TripCharts.java b/src/cloud/molberg/mgutility/TripCharts.java index 64af3ac..8b6531e 100644 --- a/src/cloud/molberg/mgutility/TripCharts.java +++ b/src/cloud/molberg/mgutility/TripCharts.java @@ -4,9 +4,14 @@ import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; +import android.graphics.RectF; import android.graphics.Typeface; +import android.view.MotionEvent; import android.view.View; +import java.util.Date; + +import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; @@ -14,32 +19,316 @@ import java.util.Locale; /** Dashboard charts that always render with whatever raw samples the trip has. */ final class TripCharts extends View { private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint guidePaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint markerPaint = new Paint(Paint.ANTI_ALIAS_FLAG); + private final Paint tooltipPaint = new Paint(Paint.ANTI_ALIAS_FLAG); private List samples = new ArrayList<>(); private boolean overview; + private boolean scrubbing; + private float scrubRatio = -1f; + private boolean overviewScrubbing; + private int overviewScrubGraph; + private TripDatabase.Summary overviewSummary; + private List overviewTrips = new ArrayList<>(); TripCharts(Context context) { super(context); UiTheme.loadTheme(context); setBackground(UiTheme.surface(UiTheme.SURFACE, 12)); paint.setTypeface(Typeface.create("sans-serif", Typeface.NORMAL)); + guidePaint.setColor(UiTheme.withAlpha(UiTheme.CYAN, 200)); + guidePaint.setStyle(Paint.Style.STROKE); + guidePaint.setStrokeWidth(2f); + markerPaint.setColor(UiTheme.CYAN); + markerPaint.setStyle(Paint.Style.FILL); + tooltipPaint.setColor(UiTheme.withAlpha(UiTheme.SURFACE_HIGH, 245)); + tooltipPaint.setStyle(Paint.Style.FILL); + setClickable(true); } void setSamples(List values, boolean isOverview) { samples = values == null ? new ArrayList() : new ArrayList<>(values); overview = isOverview; + scrubbing = false; + scrubRatio = -1f; + overviewScrubbing = false; + overviewScrubGraph = -1; invalidate(); } + void setOverviewData(TripDatabase.Summary summary, List trips) { + overviewSummary = summary; + overviewTrips = trips == null ? new ArrayList() : new ArrayList<>(trips); + overview = true; + scrubbing = false; + scrubRatio = -1f; + overviewScrubbing = false; + overviewScrubGraph = -1; + invalidate(); + } + + @Override public boolean onTouchEvent(MotionEvent event) { + if (overview) return onOverviewTouch(event); + if (samples.size() < 2) return super.onTouchEvent(event); + switch (event.getActionMasked()) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_MOVE: + scrubbing = true; + int gap = 12; + int cardWidth = (getWidth() - gap * 2 - 28) / 3; + int chartIndex = Math.max(0, Math.min(2, + (int) ((event.getX() - 14) / (float) Math.max(1, cardWidth + gap)))); + int chartLeft = 14 + (cardWidth + gap) * chartIndex; + scrubRatio = Math.max(0f, Math.min(1f, + (event.getX() - chartLeft - 14) / (float) Math.max(1, cardWidth - 28))); + if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(true); + invalidate(); + return true; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + scrubbing = false; + scrubRatio = -1f; + if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(false); + invalidate(); + return true; + default: + return super.onTouchEvent(event); + } + } + + private boolean onOverviewTouch(MotionEvent event) { + if (overviewTrips.isEmpty()) return super.onTouchEvent(event); + switch (event.getActionMasked()) { + case MotionEvent.ACTION_DOWN: + case MotionEvent.ACTION_MOVE: + int width = getWidth(), height = getHeight(); + int graphTop = overviewGraphTop(); + int graphHeight = overviewGraphHeight(height, graphTop); + int graphWidth = Math.max(1, (width - 56) / 2 - 6); + int secondLeft = 28 + (width - 56) / 2 + 6; + float x = event.getX(); + if (event.getY() < graphTop || event.getY() > graphTop + graphHeight) return true; + if (x >= 28 && x <= 28 + graphWidth) overviewScrubGraph = 0; + else if (x >= secondLeft && x <= secondLeft + graphWidth) overviewScrubGraph = 1; + else return true; + int left = overviewScrubGraph == 0 ? 28 : secondLeft; + overviewScrubRatio = Math.max(0f, Math.min(1f, + (x - left - 12f) / Math.max(1f, graphWidth - 24f))); + overviewScrubbing = true; + if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(true); + invalidate(); + return true; + case MotionEvent.ACTION_UP: + case MotionEvent.ACTION_CANCEL: + overviewScrubbing = false; + overviewScrubGraph = -1; + overviewScrubRatio = -1f; + if (getParent() != null) getParent().requestDisallowInterceptTouchEvent(false); + invalidate(); + return true; + default: + return true; + } + } + + private float overviewScrubRatio = -1f; + + private int overviewGraphTop() { + return 24 + 2 * (76 + 10) + 16; + } + + private int overviewGraphHeight(int height, int graphTop) { + return Math.max(1, height - graphTop - 28); + } + @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int width = getWidth(), height = getHeight(); if (width < 100 || height < 80) return; + if (overview) { + drawOverview(canvas, width, height); + return; + } int gap = 12; int cardWidth = (width - gap * 2 - 28) / 3; int top = 14; drawChart(canvas, 14, top, cardWidth, height - 28, "SPEED", "km/h", UiTheme.CYAN, 0, false); drawChart(canvas, 14 + cardWidth + gap, top, cardWidth, height - 28, "BATTERY", "%", UiTheme.SUCCESS, 1, false); drawChart(canvas, 14 + (cardWidth + gap) * 2, top, cardWidth, height - 28, overview ? "ENERGY COUNTER" : "ENERGY", "kWh", UiTheme.WARNING, 2, true); + if (scrubbing && scrubRatio >= 0f) drawScrubOverlay(canvas, width, height, cardWidth, gap, top); + } + + private void drawOverview(Canvas canvas, int width, int height) { + paint.setStyle(Paint.Style.FILL); + paint.setColor(UiTheme.SURFACE_HIGH); + canvas.drawRoundRect(14, 14, width - 14, height - 14, 10, 10, paint); + TripDatabase.Summary summary = overviewSummary; + if (summary == null) { + paint.setColor(UiTheme.MUTED); + paint.setTextSize(13); + canvas.drawText("No drive history recorded yet", 30, height / 2f, paint); + return; + } + double highestRange = 0d; + double topSpeed = 0d; + for (TripDatabase.TripSummary trip : overviewTrips) { + if (trip.startRangeKm >= 0) highestRange = Math.max(highestRange, trip.startRangeKm); + if (trip.endRangeKm >= 0) highestRange = Math.max(highestRange, trip.endRangeKm); + if (Double.isFinite(trip.topSpeedKph)) topSpeed = Math.max(topSpeed, trip.topSpeedKph); + } + // distance is stored in metres and movingMillis in milliseconds. + // Convert m/ms to km/h by multiplying by 3,600. + double averageSpeed = summary.movingMillis > 0 + ? summary.distanceMeters / summary.movingMillis * 3600d : 0d; + String[] labels = { "TOTAL DRIVES", "TOP LOGGED SPEED", "BEST REGEN RECORD", "TOTAL DISTANCE", + "TOTAL DRIVE TIME", "AVERAGE DRIVING SPEED", "HIGHEST BATTERY RANGE" }; + String[] values = { + String.format(Locale.US, "%d", summary.tripCount), + formatUnit(topSpeed, "km/h", "%.0f"), + String.format(Locale.US, "+%.2f km", summary.bestRegenRangeKm), + String.format(Locale.US, "%.1f km", summary.distanceMeters / 1000d), + formatDuration(summary.movingMillis), + formatUnit(averageSpeed, "km/h", "%.1f"), + highestRange > 0d ? String.format(Locale.US, "%.0f km", highestRange) : "—" + }; + int columns = 4; + int cardGap = 10; + int cardWidth = (width - 28 - cardGap * (columns - 1)) / columns; + int cardHeight = 76; + for (int i = 0; i < labels.length; i++) { + int col = i % columns; + int row = i / columns; + float left = 14 + col * (cardWidth + cardGap); + float top = 24 + row * (cardHeight + cardGap); + paint.setColor(UiTheme.SURFACE); + canvas.drawRoundRect(left, top, left + cardWidth, top + cardHeight, 8, 8, paint); + paint.setTextSize(10); + paint.setColor(UiTheme.MUTED); + canvas.drawText(labels[i], left + 12, top + 20, paint); + paint.setTextSize(19); + paint.setColor(i == 2 ? UiTheme.SUCCESS : UiTheme.TEXT); + canvas.drawText(values[i], left + 12, top + 51, paint); + } + int graphTop = overviewGraphTop(); + int graphHeight = overviewGraphHeight(height, graphTop); + int historyWidth = Math.max(1, (width - 56) / 2 - 6); + drawHistoryGraph(canvas, 28, graphTop, historyWidth, graphHeight, + "CUMULATIVE DISTANCE", false); + drawHistoryGraph(canvas, 28 + (width - 56) / 2 + 6, graphTop, + historyWidth, graphHeight, "TOP SPEED BY DRIVE", true); + if (overviewScrubbing && overviewScrubGraph >= 0 && overviewScrubRatio >= 0f) + drawOverviewScrubOverlay(canvas, width, graphTop, graphHeight); + } + + private void drawHistoryGraph(Canvas canvas, int left, int top, int width, int height, + String title, boolean speedGraph) { + paint.setColor(UiTheme.SURFACE); + paint.setStyle(Paint.Style.FILL); + canvas.drawRoundRect(left, top, left + width, top + height, 8, 8, paint); + paint.setColor(UiTheme.MUTED); + paint.setTextSize(11); + canvas.drawText(title, left + 12, top + 20, paint); + if (width < 30 || height < 30) return; + int plotLeft = left + 12, plotRight = left + width - 12, plotTop = top + 30, plotBottom = top + height - 14; + paint.setColor(UiTheme.withAlpha(UiTheme.DIVIDER, 150)); + paint.setStyle(Paint.Style.STROKE); + canvas.drawLine(plotLeft, plotBottom, plotRight, plotBottom, paint); + if (overviewTrips.isEmpty()) { + paint.setStyle(Paint.Style.FILL); + canvas.drawText("Record a drive to build history", plotLeft, (plotTop + plotBottom) / 2f, paint); + return; + } + int count = Math.min(24, overviewTrips.size()); + double baseline = 0d; + for (int i = count; i < overviewTrips.size(); i++) { + if (!speedGraph) baseline += Math.max(0d, overviewTrips.get(i).distanceKm()); + } + double max = speedGraph ? 0d : baseline; + if (speedGraph) { + for (int i = 0; i < count; i++) { + double value = overviewTrips.get(i).topSpeedKph; + if (Double.isFinite(value)) max = Math.max(max, value); + } + } else { + // The line is cumulative; scale against the final cumulative value, + // rather than the largest single trip distance. + double cumulativeMax = baseline; + for (int i = count - 1; i >= 0; i--) + cumulativeMax += Math.max(0d, overviewTrips.get(i).distanceKm()); + if (Double.isFinite(cumulativeMax)) max = Math.max(max, cumulativeMax); + } + if (max <= 0d) max = 1d; + paint.setStyle(speedGraph ? Paint.Style.FILL : Paint.Style.STROKE); + paint.setStrokeWidth(2.5f); + paint.setColor(speedGraph ? UiTheme.CYAN : UiTheme.SUCCESS); + Path path = new Path(); + double cumulative = baseline; + for (int i = 0; i < count; i++) { + TripDatabase.TripSummary trip = overviewTrips.get(count - 1 - i); + double raw = speedGraph ? trip.topSpeedKph : (cumulative += Math.max(0d, trip.distanceKm())); + if (!Double.isFinite(raw)) raw = 0d; + float x = count == 1 ? plotLeft : plotLeft + (plotRight - plotLeft) * i / (float) (count - 1); + float y = (float) (plotBottom - (plotBottom - plotTop) * raw / max); + y = Math.max(plotTop, Math.min(plotBottom, y)); + if (speedGraph) canvas.drawRect(x - 4, y, x + 4, plotBottom, paint); + else if (i == 0) path.moveTo(x, y); else path.lineTo(x, y); + } + if (!speedGraph) canvas.drawPath(path, paint); + paint.setStyle(Paint.Style.FILL); + paint.setColor(UiTheme.MUTED); + paint.setTextSize(10); + canvas.drawText(speedGraph ? "km/h" : "km", plotLeft, plotBottom - 4, paint); + } + + private void drawOverviewScrubOverlay(Canvas canvas, int width, int graphTop, int graphHeight) { + int graphWidth = Math.max(1, (width - 56) / 2 - 6); + int left = overviewScrubGraph == 0 ? 28 : 28 + (width - 56) / 2 + 6; + int plotLeft = left + 12, plotRight = left + graphWidth - 12; + int count = Math.min(24, overviewTrips.size()); + if (count == 0 || plotRight <= plotLeft) return; + int index = Math.round(overviewScrubRatio * (count - 1)); + index = Math.max(0, Math.min(count - 1, index)); + TripDatabase.TripSummary trip = overviewTrips.get(count - 1 - index); + float cursorX = count == 1 ? plotLeft : plotLeft + (plotRight - plotLeft) * index / (float) (count - 1); + int plotTop = graphTop + 30, plotBottom = graphTop + graphHeight - 14; + guidePaint.setColor(UiTheme.CYAN); + canvas.drawLine(cursorX, plotTop, cursorX, plotBottom, guidePaint); + String value = overviewScrubGraph == 0 + ? String.format(Locale.US, "%.1f km cumulative", cumulativeDistanceAt(count, index)) + : String.format(Locale.US, "%.0f km/h top speed", finiteOrZero(trip.topSpeedKph)); + String detail = new SimpleDateFormat("EEE d MMM HH:mm", Locale.US).format(new Date(trip.startTime)); + paint.setTextSize(11); + float padding = 8f; + float boxWidth = Math.max(paint.measureText(value), paint.measureText(detail)) + padding * 2; + float boxLeft = cursorX + 12f + boxWidth > left + graphWidth ? cursorX - 12f - boxWidth : cursorX + 12f; + boxLeft = Math.max(left + 6f, Math.min(left + graphWidth - boxWidth - 6f, boxLeft)); + float boxTop = plotTop + 4f, boxHeight = paint.getTextSize() * 2f + padding * 1.5f; + canvas.drawRoundRect(new RectF(boxLeft, boxTop, boxLeft + boxWidth, boxTop + boxHeight), 6f, 6f, tooltipPaint); + paint.setColor(UiTheme.CYAN); canvas.drawText(value, boxLeft + padding, boxTop + paint.getTextSize() + 2f, paint); + paint.setColor(UiTheme.MUTED); canvas.drawText(detail, boxLeft + padding, boxTop + paint.getTextSize() * 2f + 4f, paint); + } + + private double cumulativeDistanceAt(int count, int index) { + double cumulative = 0d; + for (int i = count; i < overviewTrips.size(); i++) + cumulative += Math.max(0d, overviewTrips.get(i).distanceKm()); + for (int i = count - 1; i >= count - 1 - index; i--) + cumulative += Math.max(0d, overviewTrips.get(i).distanceKm()); + return cumulative; + } + + private static double finiteOrZero(double value) { + return Double.isFinite(value) ? Math.max(0d, value) : 0d; + } + + private static String formatUnit(double value, String unit, String pattern) { + return String.format(Locale.US, pattern + " %s", value, unit); + } + + private static String formatDuration(long millis) { + long minutes = Math.max(0, millis / 60000L); + return minutes < 60 ? String.format(Locale.US, "%dm", minutes) + : String.format(Locale.US, "%dh %02dm", minutes / 60, minutes % 60); } private void drawChart(Canvas canvas, int left, int top, int width, int height, String title, String unit, int color, int metric, boolean showSecondary) { @@ -85,14 +374,19 @@ final class TripCharts extends View { private void line(Canvas canvas, int left, int top, int right, int bottom, int color, int metric, List series) { double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY; - for (TripDatabase.TripSample sample : series) { double value = value(sample, metric); if (Double.isNaN(value)) continue; min = Math.min(min, value); max = Math.max(max, value); } + for (TripDatabase.TripSample sample : series) { + double value = value(sample, metric); + if (!Double.isFinite(value)) continue; + min = Math.min(min, value); max = Math.max(max, value); + } if (!Double.isFinite(min) || !Double.isFinite(max)) return; if (max - min < 0.5) { max += 0.5; min -= 0.5; } Path path = new Path(); boolean started = false; for (int i = 0; i < series.size(); i++) { - double value = value(series.get(i), metric); if (Double.isNaN(value)) continue; + double value = value(series.get(i), metric); if (!Double.isFinite(value)) continue; float x = left + (right - left) * i / (float) Math.max(1, series.size() - 1); float y = (float) (bottom - (bottom - top) * (value - min) / (max - min)); + y = Math.max(top, Math.min(bottom, y)); if (!started) { path.moveTo(x, y); started = true; } else path.lineTo(x, y); } paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(3f); paint.setStrokeCap(Paint.Cap.ROUND); paint.setColor(color); @@ -112,4 +406,75 @@ final class TripCharts extends View { private static String format(double value) { return Double.isNaN(value) ? "—" : String.format(Locale.US, "%.2f", value); } + private void drawScrubOverlay(Canvas canvas, int width, int height, int cardWidth, int gap, int top) { + List points = downsample(samples); + if (points.size() < 2) return; + int index = Math.round(scrubRatio * (points.size() - 1)); + index = Math.max(0, Math.min(points.size() - 1, index)); + TripDatabase.TripSample sample = points.get(index); + String[] titles = { "SPEED", "BATTERY", overview ? "ENERGY COUNTER" : "ENERGY" }; + String[] units = { "km/h", "%", "kWh" }; + int[] colors = { UiTheme.CYAN, UiTheme.SUCCESS, UiTheme.WARNING }; + double[] values = { value(sample, 0), value(sample, 1), value(sample, 2) }; + SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss", Locale.US); + for (int i = 0; i < 3; i++) { + int chartLeft = 14 + (cardWidth + gap) * i; + int plotLeft = chartLeft + 14; + int plotRight = chartLeft + cardWidth - 14; + float cursorX = plotLeft + (plotRight - plotLeft) * scrubRatio; + int plotTop = top + 36; + int plotBottom = top + height - 28 - 26; + canvas.drawLine(cursorX, plotTop, cursorX, plotBottom, guidePaint); + drawChartMarker(canvas, chartLeft, plotTop, plotBottom, cardWidth, i, + cursorX, titles[i], units[i], colors[i], values[i], fmt.format(new Date(sample.timestamp))); + } + } + + private void drawChartMarker(Canvas canvas, int chartLeft, int plotTop, int plotBottom, + int chartWidth, int metricIndex, float scrubX, String title, String unit, int color, + double value, String timeText) { + List points = downsample(samples); + if (points.size() < 2) return; + int plotLeft = chartLeft + 14; + int plotRight = chartLeft + chartWidth - 14; + double min = Double.POSITIVE_INFINITY, max = Double.NEGATIVE_INFINITY; + int currentMetric = metricIndex == 2 ? 2 : metricIndex; + for (TripDatabase.TripSample sample : points) { + double v = value(sample, currentMetric); + if (Double.isNaN(v)) continue; + min = Math.min(min, v); + max = Math.max(max, v); + } + if (!Double.isFinite(min) || !Double.isFinite(max)) return; + if (max - min < 0.5) { max += 0.5; min -= 0.5; } + int index = Math.round((scrubX - plotLeft) / (float) (plotRight - plotLeft) * (points.size() - 1)); + index = Math.max(0, Math.min(points.size() - 1, index)); + double sampleValue = value(points.get(index), currentMetric); + float markerY; + if (Double.isNaN(sampleValue)) { + markerY = (plotTop + plotBottom) / 2f; + } else { + markerY = (float) (plotBottom - (plotBottom - plotTop) * (sampleValue - min) / (max - min)); + } + markerPaint.setColor(color); + canvas.drawCircle(scrubX, markerY, 5f, markerPaint); + String valueText = Double.isNaN(value) ? "—" : String.format(Locale.US, "%.2f %s", value, unit); + String line1 = title + " " + valueText; + paint.setStyle(Paint.Style.FILL); + paint.setTextSize(11); + float padding = 8f; + float textWidth = Math.max(paint.measureText(line1), paint.measureText(timeText)); + float boxWidth = textWidth + padding * 2; + float boxHeight = paint.getTextSize() * 2f + padding * 1.5f; + float boxLeft = scrubX + 12f + boxWidth > chartLeft + chartWidth + ? scrubX - 12f - boxWidth + : scrubX + 12f; + if (boxLeft < chartLeft + 6f) boxLeft = chartLeft + 6f; + float boxTop = plotTop + 4f; + canvas.drawRoundRect(new RectF(boxLeft, boxTop, boxLeft + boxWidth, boxTop + boxHeight), 6f, 6f, tooltipPaint); + paint.setColor(color); + canvas.drawText(line1, boxLeft + padding, boxTop + paint.getTextSize() + 2f, paint); + paint.setColor(UiTheme.MUTED); + canvas.drawText(timeText, boxLeft + padding, boxTop + paint.getTextSize() * 2f + 4f, paint); + } } diff --git a/src/cloud/molberg/mgutility/TripDatabase.java b/src/cloud/molberg/mgutility/TripDatabase.java index 7e1ddb8..b07d34f 100644 --- a/src/cloud/molberg/mgutility/TripDatabase.java +++ b/src/cloud/molberg/mgutility/TripDatabase.java @@ -6,6 +6,10 @@ import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + import java.util.ArrayList; import java.util.List; @@ -15,7 +19,7 @@ import java.util.List; */ final class TripDatabase extends SQLiteOpenHelper { private static final String NAME = "mg_trips.db"; - private static final int VERSION = 3; + private static final int VERSION = 4; static final long NO_TRIP = -1L; @@ -24,6 +28,226 @@ final class TripDatabase extends SQLiteOpenHelper { setWriteAheadLoggingEnabled(true); } + /** + * Export recorded drives only. Configuration is intentionally kept out of + * this document; the Config screen has a separate settings export. + */ + synchronized String exportJson() throws JSONException { + JSONObject root = new JSONObject(); + root.put("schema", 1); + root.put("type", "mg-utility-drive-log"); + root.put("database", NAME); + root.put("overview", overviewJson(NO_TRIP)); + JSONObject tables = new JSONObject(); + SQLiteDatabase db = getReadableDatabase(); + exportTable(db, "trips", tables); + exportTable(db, "trip_points", tables); + exportTable(db, "trip_samples", tables); + exportTable(db, "regen_events", tables); + root.put("tables", tables); + return root.toString(2); + } + + synchronized String exportJson(long tripId) throws JSONException { + if (tripId == NO_TRIP) return exportJson(); + JSONObject root = new JSONObject(); + root.put("schema", 1); + root.put("type", "mg-utility-drive-log"); + root.put("scope", "single-drive"); + root.put("trip_id", tripId); + root.put("overview", overviewJson(tripId)); + JSONObject tables = new JSONObject(); + SQLiteDatabase db = getReadableDatabase(); + exportTable(db, "trips", tables, "id = " + tripId); + exportTable(db, "trip_points", tables, "trip_id = " + tripId); + exportTable(db, "trip_samples", tables, "trip_id = " + tripId); + exportTable(db, "regen_events", tables, "trip_id = " + tripId); + root.put("tables", tables); + return root.toString(2); + } + + synchronized String exportCsv(long tripId) { + StringBuilder out = new StringBuilder(); + appendCsvOverview(out, tripId); + SQLiteDatabase db = getReadableDatabase(); + appendCsvTable(db, "trips", out, tripId == NO_TRIP ? null : "id = " + tripId); + appendCsvTable(db, "trip_points", out, tripId == NO_TRIP ? null : "trip_id = " + tripId); + appendCsvTable(db, "trip_samples", out, tripId == NO_TRIP ? null : "trip_id = " + tripId); + appendCsvTable(db, "regen_events", out, tripId == NO_TRIP ? null : "trip_id = " + tripId); + return out.toString(); + } + + synchronized String exportHtml(long tripId) throws JSONException { + StringBuilder html = new StringBuilder(); + html.append("MG Utility Drive Log") + .append("") + .append("

MG Utility Drive Log

Recorded vehicle data export

"); + JSONObject all = new JSONObject(exportJson(tripId)); + JSONObject tables = all.optJSONObject("tables"); + if (tables != null) { + java.util.Iterator names = tables.keys(); + while (names.hasNext()) { + String table = names.next(); + html.append("

").append(escapeHtml(table)).append("

"); + JSONArray rows = tables.optJSONArray(table); + appendHtmlTable(html, rows); + html.append("
"); + } + } + html.append("

Route preview

"); + JSONArray points = tables == null ? null : tables.optJSONArray("trip_points"); + appendRouteSvg(html, points); + html.append("

Speed graph

"); + JSONArray samples = tables == null ? null : tables.optJSONArray("trip_samples"); + appendSpeedSvg(html, samples); + html.append("
"); + return html.toString(); + } + + private static void appendCsvTable(SQLiteDatabase db, String table, StringBuilder out, String where) { + Cursor cursor = db.query(table, null, where, null, null, null, "id ASC"); + try { + String[] columns = cursor.getColumnNames(); + out.append("# ").append(table).append('\n'); + for (int i = 0; i < columns.length; i++) { if (i > 0) out.append(','); out.append(csv(columns[i])); } + out.append('\n'); + while (cursor.moveToNext()) { + for (int i = 0; i < columns.length; i++) { + if (i > 0) out.append(','); + out.append(csv(cursor.isNull(i) ? "" : cursor.getString(i))); + } + out.append('\n'); + } + } finally { cursor.close(); } + } + + private void appendCsvOverview(StringBuilder out, long tripId) { + Summary summary = tripId == NO_TRIP ? summary() : summaryForTrip(tripId); + out.append("# overview\nmetric,value\n") + .append("trip_count,").append(summary.tripCount).append('\n') + .append("distance_meters,").append(summary.distanceMeters).append('\n') + .append("moving_millis,").append(summary.movingMillis).append('\n') + .append("energy_kwh,").append(summary.energyKwh).append('\n') + .append("regen_energy_kwh,").append(summary.regenEnergyKwh).append('\n') + .append("regen_range_km,").append(summary.regenRangeKm).append('\n') + .append("regen_event_count,").append(summary.regenEventCount).append('\n'); + } + + private JSONObject overviewJson(long tripId) throws JSONException { + Summary summary = tripId == NO_TRIP ? summary() : summaryForTrip(tripId); + JSONObject object = new JSONObject(); + object.put("trip_count", summary.tripCount); + object.put("distance_meters", summary.distanceMeters); + object.put("moving_millis", summary.movingMillis); + object.put("energy_kwh", summary.energyKwh); + object.put("regen_energy_kwh", summary.regenEnergyKwh); + object.put("regen_range_km", summary.regenRangeKm); + object.put("regen_event_count", summary.regenEventCount); + return object; + } + + private static String csv(String value) { + String text = value == null ? "" : value; + return "\"" + text.replace("\"", "\"\"") + "\""; + } + + private static void appendHtmlTable(StringBuilder html, JSONArray rows) throws JSONException { + if (rows == null || rows.length() == 0) { html.append("

No rows

"); return; } + JSONObject first = rows.optJSONObject(0); + if (first == null) return; + java.util.List columns = new java.util.ArrayList(); + java.util.Iterator keys = first.keys(); + while (keys.hasNext()) columns.add(keys.next()); + html.append(""); + for (String column : columns) html.append(""); + html.append(""); + for (int i = 0; i < rows.length(); i++) { + JSONObject row = rows.optJSONObject(i); if (row == null) continue; + html.append(""); + for (String column : columns) html.append(""); + html.append(""); + } + html.append("
").append(escapeHtml(column)).append("
").append(escapeHtml(String.valueOf(row.opt(column)))).append("
"); + } + + private static void appendRouteSvg(StringBuilder html, JSONArray points) throws JSONException { + if (points == null || points.length() < 2) { html.append("

No GPS route recorded.

"); return; } + double minLat = Double.MAX_VALUE, maxLat = -Double.MAX_VALUE, minLon = Double.MAX_VALUE, maxLon = -Double.MAX_VALUE; + for (int i = 0; i < points.length(); i++) { + JSONObject p = points.optJSONObject(i); if (p == null) continue; + double lat = p.optDouble("latitude", 0), lon = p.optDouble("longitude", 0); + minLat = Math.min(minLat, lat); maxLat = Math.max(maxLat, lat); minLon = Math.min(minLon, lon); maxLon = Math.max(maxLon, lon); + } + double latSpan = Math.max(0.000001, maxLat - minLat), lonSpan = Math.max(0.000001, maxLon - minLon); + StringBuilder path = new StringBuilder(); + for (int i = 0; i < points.length(); i++) { + JSONObject p = points.optJSONObject(i); if (p == null) continue; + double x = 10 + 780 * (p.optDouble("longitude", 0) - minLon) / lonSpan; + double y = 170 - 150 * (p.optDouble("latitude", 0) - minLat) / latSpan; + path.append(i == 0 ? "M" : " L").append(String.format(java.util.Locale.US, "%.1f %.1f", x, y)); + } + html.append(""); + } + + private static void appendSpeedSvg(StringBuilder html, JSONArray samples) throws JSONException { + if (samples == null || samples.length() < 2) { html.append("

No speed samples recorded.

"); return; } + double max = 1d; + for (int i = 0; i < samples.length(); i++) { + JSONObject sample = samples.optJSONObject(i); + if (sample != null) max = Math.max(max, sample.optDouble("speed_kph", 0)); + } + StringBuilder path = new StringBuilder(); + for (int i = 0; i < samples.length(); i++) { + JSONObject sample = samples.optJSONObject(i); if (sample == null) continue; + double x = 10 + 780d * i / Math.max(1, samples.length() - 1); + double y = 170 - 150d * sample.optDouble("speed_kph", 0) / max; + path.append(i == 0 ? "M" : " L").append(String.format(java.util.Locale.US, "%.1f %.1f", x, y)); + } + html.append(""); + } + + private static String escapeHtml(String value) { + if (value == null) return ""; + return value.replace("&", "&").replace("<", "<").replace(">", ">").replace("\"", """); + } + + private static void exportTable(SQLiteDatabase db, String table, JSONObject target) + throws JSONException { + exportTable(db, table, target, null); + } + + private static void exportTable(SQLiteDatabase db, String table, JSONObject target, String where) + throws JSONException { + JSONArray rows = new JSONArray(); + Cursor cursor = db.query(table, null, where, null, null, null, "id ASC"); + try { + String[] columns = cursor.getColumnNames(); + while (cursor.moveToNext()) { + JSONObject row = new JSONObject(); + for (int i = 0; i < columns.length; i++) { + if (cursor.isNull(i)) { + row.put(columns[i], JSONObject.NULL); + } else { + switch (cursor.getType(i)) { + case Cursor.FIELD_TYPE_INTEGER: row.put(columns[i], cursor.getLong(i)); break; + case Cursor.FIELD_TYPE_FLOAT: + double value = cursor.getDouble(i); + row.put(columns[i], Double.isNaN(value) || Double.isInfinite(value) + ? JSONObject.NULL : value); + break; + case Cursor.FIELD_TYPE_BLOB: row.put(columns[i], "[blob]"); break; + default: row.put(columns[i], cursor.getString(i)); break; + } + } + } + rows.put(row); + } + } finally { + cursor.close(); + } + target.put(table, rows); + } + @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE trips (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + @@ -118,6 +342,27 @@ final class TripDatabase extends SQLiteOpenHelper { "FOREIGN KEY(trip_id) REFERENCES trips(id) ON DELETE CASCADE)"); db.execSQL("CREATE INDEX IF NOT EXISTS trip_samples_trip_time ON trip_samples(trip_id, timestamp)"); } + if (oldVersion < 4) { + // Existing installations recorded the raw condition-service speed + // before the dashboard compensation was introduced. Bring those + // rows into the same units as newly recorded drives. + db.execSQL("UPDATE trips SET top_speed_kph = top_speed_kph * 1.03"); + db.execSQL("UPDATE trip_points SET speed_kph = speed_kph * 1.03 WHERE speed_kph IS NOT NULL"); + db.execSQL("UPDATE trip_samples SET speed_kph = speed_kph * 1.03 WHERE speed_kph IS NOT NULL"); + db.execSQL("UPDATE regen_events SET peak_speed_kph = peak_speed_kph * 1.03"); + db.execSQL("UPDATE trip_samples SET energy_kwh = (" + + "SELECT MAX(previous.energy_kwh) FROM trip_samples previous " + + "WHERE previous.trip_id = trip_samples.trip_id " + + "AND previous.id <= trip_samples.id) " + + "WHERE energy_kwh IS NOT NULL"); + // Reconstruct summaries from the raw cumulative counter when the + // old final sample was a transient zero/reset. + db.execSQL("UPDATE trips SET energy_end_kwh = (" + + "SELECT MAX(energy_kwh) FROM trip_samples " + + "WHERE trip_samples.trip_id = trips.id) " + + "WHERE EXISTS (SELECT 1 FROM trip_samples " + + "WHERE trip_samples.trip_id = trips.id AND energy_kwh IS NOT NULL)"); + } } synchronized long startTrip(long startedAt, EnergyActivity.Sample sample) { @@ -144,13 +389,20 @@ final class TripDatabase extends SQLiteOpenHelper { db.beginTransaction(); try { db.execSQL("UPDATE trips SET " + - "end_soc = ?, end_range_km = ?, energy_end_kwh = ?, " + + "end_soc = ?, end_range_km = ?, " + + // The OEM counter can briefly reset to zero while the vehicle + // transitions to Park. Preserve the highest valid cumulative + // value so the final parked sample cannot erase drive energy. + "energy_end_kwh = CASE WHEN ? IS NULL THEN energy_end_kwh " + + "WHEN energy_end_kwh IS NULL OR ? > energy_end_kwh THEN ? " + + "ELSE energy_end_kwh END, " + "top_speed_kph = MAX(top_speed_kph, ?), " + "max_voltage = MAX(max_voltage, ?), " + "distance_m = distance_m + ?, moving_ms = moving_ms + ?, " + "sample_count = sample_count + ?, gps_points = gps_points + ? " + "WHERE id = ?", new Object[]{nullableFloat(sample.soc), nullableInt(sample.range), + nullableFloat(sample.total), nullableFloat(sample.total), nullableFloat(sample.total), safe(sample.speed), safe(sample.volts), Math.max(0f, distanceMeters), Math.max(0L, movingMillis), 1, point == null ? 0 : 1, tripId}); @@ -174,13 +426,15 @@ final class TripDatabase extends SQLiteOpenHelper { synchronized void finishTrip(long tripId, long endedAt, EnergyActivity.Sample sample) { SQLiteDatabase db = getWritableDatabase(); - ContentValues values = new ContentValues(); - values.put("end_time", endedAt); - putFloat(values, "end_soc", sample.soc); - putInt(values, "end_range_km", sample.range); - putFloat(values, "energy_end_kwh", sample.total); - db.update("trips", values, "id = ? AND end_time IS NULL", - new String[]{String.valueOf(tripId)}); + // A final parked read is sometimes a transient zero/reset from the OEM + // service. Keep the largest cumulative counter recorded for this trip. + db.execSQL("UPDATE trips SET end_time = ?, end_soc = ?, end_range_km = ?, " + + "energy_end_kwh = CASE WHEN ? IS NULL THEN energy_end_kwh " + + "WHEN energy_end_kwh IS NULL OR ? > energy_end_kwh THEN ? " + + "ELSE energy_end_kwh END WHERE id = ? AND end_time IS NULL", + new Object[]{endedAt, nullableFloat(sample.soc), nullableInt(sample.range), + nullableFloat(sample.total), nullableFloat(sample.total), + nullableFloat(sample.total), tripId}); } synchronized boolean addRegenEvent(long tripId, long startedAt, long endedAt, @@ -192,24 +446,24 @@ final class TripDatabase extends SQLiteOpenHelper { double efficiency = energy > 0.000001d && range > 0d ? range / energy : 0d; db.beginTransaction(); try { - // Personal Best is global across completed and current drives. The - // per-trip best below is retained for the trip report, but it must - // not make a large event on a later trip look like a new record when - // an earlier drive already recovered more energy. + // Personal Best is global across completed and current drives, ranked + // by the recovered range the car reports (the metric that most + // reflects a single strong brake). When range is unavailable, the + // energy counter remains the fallback metric. double oldGlobalEnergy = 0d; double oldGlobalRange = 0d; Cursor global = db.rawQuery( "SELECT energy_kwh, range_km FROM regen_events " + - "ORDER BY energy_kwh DESC, range_km DESC LIMIT 1", null); + "ORDER BY range_km DESC, energy_kwh DESC LIMIT 1", null); try { if (global.moveToFirst()) { oldGlobalEnergy = global.getDouble(0); oldGlobalRange = global.getDouble(1); } } finally { global.close(); } - boolean personalBest = energy > 0.000001d - ? energy > oldGlobalEnergy + 0.000001d - : oldGlobalEnergy <= 0.000001d && range > oldGlobalRange + 0.000001d; + boolean personalBest = range > 0.000001d + ? range > oldGlobalRange + 0.000001d + : energy > oldGlobalEnergy + 0.000001d; double oldBestEnergy = 0d; double oldBestRange = 0d; @@ -222,12 +476,11 @@ final class TripDatabase extends SQLiteOpenHelper { oldBestRange = best.getDouble(1); } } finally { best.close(); } - // A Personal Best is one complete braking event. Prefer the event with - // the most recovered kWh; if the OEM energy counter is unavailable, - // fall back to the event with the greatest recovered range. - boolean better = energy > oldBestEnergy + 0.000001d || - (energy <= 0.000001d && oldBestEnergy <= 0.000001d && - range > oldBestRange + 0.000001d); + // Per-trip Best uses the same range-first ranking as the global + // record so the displayed metric stays consistent across pages. + boolean better = range > 0.000001d + ? range > oldBestRange + 0.000001d + : energy > oldBestEnergy + 0.000001d; ContentValues event = new ContentValues(); event.put("trip_id", tripId); @@ -350,9 +603,28 @@ final class TripDatabase extends SQLiteOpenHelper { putFloat(values, "speed_kph", sample.speed); putFloat(values, "soc", sample.soc); putFloat(values, "volts", sample.volts); - putFloat(values, "energy_kwh", sample.total); - putFloat(values, "regen_energy_kwh", sample.regenEnergyKwh); - putFloat(values, "regen_range_km", sample.regenRangeKm); + // Consumption is a cumulative OEM counter. Store the running maximum + // so a stale/reset read at the end of a trip cannot make the graph dip + // to zero or make the summary report zero energy. + float energy = sample.total; + float regenEnergy = sample.regenEnergyKwh; + float regenRange = sample.regenRangeKm; + Cursor previous = db.rawQuery("SELECT MAX(energy_kwh), MAX(regen_energy_kwh), " + + "MAX(regen_range_km) FROM trip_samples WHERE trip_id = ?", + new String[]{String.valueOf(tripId)}); + try { + if (previous.moveToFirst()) { + if (!previous.isNull(0) && !Float.isNaN(energy) && !Float.isInfinite(energy)) + energy = Math.max(energy, previous.getFloat(0)); + if (!previous.isNull(1) && !Float.isNaN(regenEnergy) && !Float.isInfinite(regenEnergy)) + regenEnergy = Math.max(regenEnergy, previous.getFloat(1)); + if (!previous.isNull(2) && !Float.isNaN(regenRange) && !Float.isInfinite(regenRange)) + regenRange = Math.max(regenRange, previous.getFloat(2)); + } + } finally { previous.close(); } + putFloat(values, "energy_kwh", energy); + putFloat(values, "regen_energy_kwh", regenEnergy); + putFloat(values, "regen_range_km", regenRange); db.insert("trip_samples", null, values); } @@ -372,7 +644,7 @@ final class TripDatabase extends SQLiteOpenHelper { Cursor best = getReadableDatabase().query("trips", new String[]{"best_regen_energy_kwh", "best_regen_range_km", "best_regen_km_per_kwh"}, "end_time IS NOT NULL AND regen_event_count > 0", null, null, null, - "best_regen_energy_kwh DESC, best_regen_range_km DESC", "1"); + "best_regen_range_km DESC, best_regen_energy_kwh DESC", "1"); try { if (best.moveToFirst()) { bestEnergy = best.getDouble(0); @@ -537,7 +809,11 @@ final class TripDatabase extends SQLiteOpenHelper { } double reportedEnergyUsed() { - return valid(energyStartKwh) && valid(energyEndKwh) + // Trust the trip header first. A stale "zero" parked read cannot + // make the headline statistic read 0.00 kWh while the chart still + // shows the correct consumption, because addSample/finishTrip now + // store the running maximum of the OEM counter. + return valid(energyStartKwh) && valid(energyEndKwh) && energyEndKwh >= energyStartKwh ? Math.max(0d, energyEndKwh - energyStartKwh) : Double.NaN; } @@ -586,4 +862,20 @@ final class TripDatabase extends SQLiteOpenHelper { this.bestRegenKmPerKwh = bestRegenKmPerKwh; } } + synchronized Summary summaryForTrip(long tripId) { + SQLiteDatabase db = getReadableDatabase(); + Cursor c = db.rawQuery( + "SELECT COUNT(*), COALESCE(SUM(distance_m),0), COALESCE(SUM(moving_ms),0), " + + "COALESCE(SUM(CASE WHEN energy_end_kwh >= energy_start_kwh " + + "THEN energy_end_kwh - energy_start_kwh ELSE 0 END),0), " + + "COALESCE(SUM(regen_energy_kwh),0), COALESCE(SUM(regen_range_km),0), " + + "COALESCE(SUM(regen_event_count),0) " + + "FROM trips WHERE id = ?", + new String[] { String.valueOf(tripId) }); + try { + if (c.moveToFirst()) return new Summary(c.getInt(0), c.getDouble(1), c.getLong(2), + c.getDouble(3), c.getDouble(4), c.getDouble(5), c.getInt(6), 0d, 0d, 0d); + return new Summary(0, 0d, 0L, 0d, 0d, 0d, 0, 0d, 0d, 0d); + } finally { c.close(); } + } } diff --git a/src/cloud/molberg/mgutility/TripMapActivity.java b/src/cloud/molberg/mgutility/TripMapActivity.java new file mode 100644 index 0000000..327e8c1 --- /dev/null +++ b/src/cloud/molberg/mgutility/TripMapActivity.java @@ -0,0 +1,68 @@ +package cloud.molberg.mgutility; + +import android.os.Bundle; +import android.view.Gravity; +import android.view.View; +import android.widget.Button; +import android.widget.LinearLayout; +import android.widget.TextView; + +import java.util.List; + +/** Full-page interactive map for a selected drive. */ +public final class TripMapActivity extends AnimatedActivity { + static final String EXTRA_TRIP_ID = "trip_id"; + private TripDatabase database; + private RouteMapView map; + + @Override public void onCreate(Bundle state) { + super.onCreate(state); + UiTheme.applyFontScale(this); + immersive(); + database = new TripDatabase(this); + setContentView(buildUi()); + loadRoute(); + } + + @Override public void onDestroy() { + if (database != null) database.close(); + super.onDestroy(); + } + + private void immersive() { + getWindow().setFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, + android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + getWindow().getDecorView().setSystemUiVisibility( + View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | + View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | + View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE); + } + + private View buildUi() { + LinearLayout root = new LinearLayout(this); + root.setOrientation(LinearLayout.VERTICAL); + root.setBackgroundColor(UiTheme.BACKGROUND); + map = new RouteMapView(this); + root.addView(map, new LinearLayout.LayoutParams(-1, 0, 1)); + LinearLayout bar = new LinearLayout(this); + bar.setGravity(Gravity.CENTER_VERTICAL); + bar.setPadding(20, 0, 20, 0); + TextView hint = UiTheme.text(this, "Drag to pan • pinch to zoom", 11, UiTheme.MUTED, android.graphics.Typeface.NORMAL); + bar.addView(hint, new LinearLayout.LayoutParams(0, 58, 1)); + Button close = UiTheme.button(this, "BACK TO DRIVE", new View.OnClickListener() { + @Override public void onClick(View v) { finish(); } + }, false); + bar.addView(close, new LinearLayout.LayoutParams(170, 44)); + root.addView(bar, new LinearLayout.LayoutParams(-1, 58)); + return root; + } + + private void loadRoute() { + final long tripId = getIntent().getLongExtra(EXTRA_TRIP_ID, TripDatabase.NO_TRIP); + if (tripId == TripDatabase.NO_TRIP) return; + new Thread(new Runnable() { @Override public void run() { + final List route = database.getRoute(tripId); + runOnUiThread(new Runnable() { @Override public void run() { if (map != null) map.setRoute(route); } }); + } }, "mg-trip-map-full").start(); + } +} diff --git a/src/cloud/molberg/mgutility/TripTrackingService.java b/src/cloud/molberg/mgutility/TripTrackingService.java index 56d8ba7..0a5dec8 100644 --- a/src/cloud/molberg/mgutility/TripTrackingService.java +++ b/src/cloud/molberg/mgutility/TripTrackingService.java @@ -37,10 +37,17 @@ public final class TripTrackingService extends Service { static final String ACTION_RESTART = "cloud.molberg.mgutility.RESTART_TRACKING"; static final String CHANNEL_ID = "mg_trip_tracking"; static final int NOTIFICATION_ID = 1404; + private static final int ARRIVAL_NOTIFICATION_ID = 1406; - private static final long SAMPLE_INTERVAL_MS = 5000L; + static final String PREF_SAMPLE_INTERVAL_SECONDS = "sample_interval_seconds"; + static final int DEFAULT_SAMPLE_INTERVAL_SECONDS = 5; + private static final int MIN_SAMPLE_INTERVAL_SECONDS = 1; + private static final int MAX_SAMPLE_INTERVAL_SECONDS = 60; private static final long SPEED_AUDIO_INTERVAL_MS = 200L; - private static final long STOP_GRACE_MS = 5 * 60 * 1000L; + private static final long PARKED_GRACE_MS = 45 * 1000L; + /** SAIC VehicleConstant.CarGearValue.CAR_GEAR_PARK_RANGE is 1. */ + private static final int PARK_GEAR_VALUE = 1; + private static final float PARKED_SPEED_KPH = 0.5f; private static final float MOVING_SPEED_KPH = 3f; private static final float DISTANCE_SPEED_KPH = 1f; private static final long MAX_DISTANCE_INTERVAL_MS = 15000L; @@ -68,6 +75,7 @@ public final class TripTrackingService extends Service { private Location lastDistanceLocation; private Location lastStoredLocation; private long stoppedSince; + private long parkedSince; private String lastNotificationText = ""; private int settingsApplyGeneration; private int lastIgnition = Integer.MIN_VALUE; @@ -97,16 +105,19 @@ public final class TripTrackingService extends Service { private final Runnable poll = new Runnable() { @Override public void run() { collect(); - if (worker != null) worker.postDelayed(this, SAMPLE_INTERVAL_MS); + if (worker != null) worker.postDelayed(this, sampleIntervalMs()); } }; private final Runnable speedAudioPoll = new Runnable() { @Override public void run() { - if (SpeedAudioManager.shouldPoll(TripTrackingService.this)) pollSpeedAudio(); - else SpeedAudioManager.stopReactive(); + boolean reactiveAudio = SpeedAudioManager.shouldPoll(TripTrackingService.this); + boolean adaptiveLeveling = AdaptiveAudioLevelingManager.shouldPoll(TripTrackingService.this); + if (reactiveAudio || adaptiveLeveling) pollSpeedAudio(reactiveAudio, adaptiveLeveling); + if (!reactiveAudio) SpeedAudioManager.stopReactive(); + if (!adaptiveLeveling) AdaptiveAudioLevelingManager.stopAndRestore(TripTrackingService.this); if (worker != null) worker.postDelayed(this, - SpeedAudioManager.shouldPoll(TripTrackingService.this) ? SPEED_AUDIO_INTERVAL_MS : 1000L); + reactiveAudio || adaptiveLeveling ? SPEED_AUDIO_INTERVAL_MS : 1000L); } }; @@ -150,6 +161,8 @@ public final class TripTrackingService extends Service { .putBoolean("gps_ready", true) .putLong("last_fix", System.currentTimeMillis()) .putString("gps_provider", location.getProvider() == null ? "unknown" : location.getProvider()) + .putString("last_latitude", String.valueOf(location.getLatitude())) + .putString("last_longitude", String.valueOf(location.getLongitude())) .apply(); updateStatus("GPS route ready"); } @@ -245,7 +258,7 @@ public final class TripTrackingService extends Service { bindVehicleService(); configureLocation(); collect(); - worker.postDelayed(poll, SAMPLE_INTERVAL_MS); + worker.postDelayed(poll, sampleIntervalMs()); worker.post(speedAudioPoll); } }); @@ -274,6 +287,7 @@ public final class TripTrackingService extends Service { try { unregisterReceiver(soundboardReceiver); } catch (Exception ignored) { } vehicle = null; SpeedAudioManager.stopReactive(); + AdaptiveAudioLevelingManager.stopAndRestore(this); if (workerThread != null) workerThread.quitSafely(); finishRegenEvent(System.currentTimeMillis()); if (database != null) database.close(); @@ -359,6 +373,10 @@ public final class TripTrackingService extends Service { Location last = locationManager.getLastKnownLocation(provider); if (last != null && (latestLocation == null || last.getTime() > latestLocation.getTime())) { latestLocation = new Location(last); + getSharedPreferences("trip_tracker", MODE_PRIVATE).edit() + .putString("last_latitude", String.valueOf(last.getLatitude())) + .putString("last_longitude", String.valueOf(last.getLongitude())) + .apply(); } providerFound = true; } catch (SecurityException ignored) { @@ -399,13 +417,22 @@ public final class TripTrackingService extends Service { processSample(sample, System.currentTimeMillis()); } - private void pollSpeedAudio() { + private void pollSpeedAudio(boolean reactiveAudio, boolean adaptiveLeveling) { EnergyActivity.VehicleGateway gateway = vehicle; if (gateway == null) return; float speed; try { speed = gateway.readSpeed(); } catch (Exception ignored) { return; } - SpeedAudioManager.updateSpeed(this, validSpeed(speed)); + float validSpeed = validSpeed(speed); + if (reactiveAudio) SpeedAudioManager.updateSpeed(this, validSpeed); + if (adaptiveLeveling) AdaptiveAudioLevelingManager.updateSpeed(this, validSpeed); + } + + private int readGearSafely() { + VehicleSettingsGateway gateway = vehicleSettingsGateway; + if (gateway == null) return -1; + try { return gateway.getGear(); } + catch (Exception ignored) { return -1; } } private void processSample(EnergyActivity.Sample sample, long now) { @@ -414,7 +441,7 @@ public final class TripTrackingService extends Service { } final float speed = validSpeed(sample.speed); final boolean moving = speed >= MOVING_SPEED_KPH; - final long elapsed = lastSampleAt == 0 ? 0 : Math.min(MAX_DISTANCE_INTERVAL_MS, + final long elapsed = lastSampleAt == 0 ? 0 : Math.min(maxDistanceIntervalMs(), Math.max(0, now - lastSampleAt)); float distance = distanceDelta(speed, elapsed); long movingMillis = moving ? elapsed : 0; @@ -431,10 +458,18 @@ public final class TripTrackingService extends Service { trackRegeneration(sample, now, elapsed); + int gear = readGearSafely(); + boolean parked = speed <= PARKED_SPEED_KPH && gear == PARK_GEAR_VALUE; + if (parked) { if (parkedSince == 0) parkedSince = now; } + else parkedSince = 0; + if (activeTripId != TripDatabase.NO_TRIP) { - // If the process was restarted while the car was already parked, close the - // recovered open trip on its first stationary observation. - if (lastSampleAt == 0 && !moving) stoppedSince = now - STOP_GRACE_MS; + // If the process was restarted while the car was already parked, start a + // fresh 45-second Park observation for the recovered open trip. + if (lastSampleAt == 0 && !moving) { + stoppedSince = now; + if (parkedSince == 0) parkedSince = now; + } database.addSample(activeTripId, now, sample, distance, movingMillis, routePoint); if (moving) { @@ -442,16 +477,28 @@ public final class TripTrackingService extends Service { updateStatus("Drive recording"); } else { if (stoppedSince == 0) stoppedSince = now; - if (now - stoppedSince >= STOP_GRACE_MS) { + long parkedDuration = parkedSince == 0 ? 0 : now - parkedSince; + // Trip finalises once the car is parked (gear == Park and speed ~0) + // for the full 45 s window. A stopped car in Neutral/Drive must + // remain an open trip until Park is reported. + boolean finishNow = parkedSince != 0 && parkedDuration >= PARKED_GRACE_MS; + if (finishNow) { finishRegenEvent(now); - database.finishTrip(activeTripId, lastSampleAt == 0 ? now : stoppedSince, sample); + long finishedTripId = activeTripId; + Location arrivalLocation = usableLocation(); + database.finishTrip(finishedTripId, parkedSince + PARKED_GRACE_MS, sample); + publishArrivalBriefing(finishedTripId, arrivalLocation); activeTripId = TripDatabase.NO_TRIP; lastDistanceLocation = null; lastStoredLocation = null; stoppedSince = 0; + parkedSince = 0; updateStatus("Parked • trip saved"); + } else if (parkedSince != 0) { + updateStatus("Parked • finishing trip in " + + Math.max(0L, (PARKED_GRACE_MS - parkedDuration) / 1000L) + "s"); } else { - updateStatus("Parked • finishing trip timer"); + updateStatus("Stationary • waiting for park"); } } } else { @@ -513,7 +560,7 @@ public final class TripTrackingService extends Service { } if (regenEventTripId == TripDatabase.NO_TRIP) { regenEventTripId = activeTripId; - long lookback = elapsed > 0 ? Math.min(elapsed, MAX_DISTANCE_INTERVAL_MS) : SAMPLE_INTERVAL_MS; + long lookback = elapsed > 0 ? Math.min(elapsed, maxDistanceIntervalMs()) : sampleIntervalMs(); regenEventStartedAt = Math.max(0L, now - lookback); regenEventEnergyKwh = 0d; regenEventRangeKm = 0d; @@ -524,11 +571,28 @@ public final class TripTrackingService extends Service { regenEventPeakSpeedKph = Math.max(regenEventPeakSpeedKph, validSpeed(sample.speed)); regenEventLastIncreaseAt = now; } else if (regenEventTripId != TripDatabase.NO_TRIP && - now - regenEventLastIncreaseAt >= REGEN_EVENT_GAP_MS) { + now - regenEventLastIncreaseAt >= regenEventGapMs()) { finishRegenEvent(now); } } + private long sampleIntervalMs() { + int seconds = getSharedPreferences("trip_tracker", MODE_PRIVATE) + .getInt(PREF_SAMPLE_INTERVAL_SECONDS, DEFAULT_SAMPLE_INTERVAL_SECONDS); + seconds = Math.max(MIN_SAMPLE_INTERVAL_SECONDS, Math.min(MAX_SAMPLE_INTERVAL_SECONDS, seconds)); + return seconds * 1000L; + } + + private long maxDistanceIntervalMs() { + return Math.max(15000L, sampleIntervalMs() * 3L); + } + + private long regenEventGapMs() { + // Close a regen event after two missed counter increases so short brakes + // are still grouped, even when the user has raised the sample interval. + return Math.max(REGEN_EVENT_GAP_MS, sampleIntervalMs() * 2L); + } + private void finishRegenEvent(long endedAt) { if (regenEventTripId == TripDatabase.NO_TRIP) return; boolean personalBest = false; @@ -614,6 +678,48 @@ public final class TripTrackingService extends Service { if (manager != null) manager.notify(NOTIFICATION_ID, notification(text)); } + private void publishArrivalBriefing(final long tripId, Location location) { + if (database == null) return; + final java.util.List matches = location == null + ? java.util.Collections.emptyList() + : ArrivalGeofence.matches(this, location.getLatitude(), location.getLongitude()); + final TripDatabase.TripSummary trip = database.getTrip(tripId); + if (trip == null) return; + final String locationName = matches.isEmpty() ? null : matches.get(0).name; + notifyArrival(ArrivalBriefing.tripText(trip, locationName)); + // A price forecast is meaningful only for a named geofenced arrival. + if (matches.isEmpty()) return; + new Thread(new Runnable() { + @Override public void run() { + try { + java.util.List prices = ChargingAutomation.loadPriceSeries(TripTrackingService.this); + ChargingAutomation.Prediction prediction = ChargingAutomation.predictNext( + TripTrackingService.this, prices, System.currentTimeMillis()); + StringBuilder text = new StringBuilder(ArrivalBriefing.tripText(trip, locationName)); + java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("HH:mm", Locale.US); + if (prediction.nextStartAt != Long.MAX_VALUE) { + text.append("\nCharge price window: START ").append(format.format(new java.util.Date(prediction.nextStartAt))); + if (prediction.nextStopAt != Long.MAX_VALUE) text.append(" – STOP ").append(format.format(new java.util.Date(prediction.nextStopAt))); + } else text.append("\nNo matching price window found in the available forecast"); + notifyArrival(text.toString()); + } catch (Exception ignored) { } + } + }, "mg-arrival-prices").start(); + } + + private void notifyArrival(String text) { + NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); + if (manager == null) return; + Notification.Builder builder = Build.VERSION.SDK_INT >= 26 + ? new Notification.Builder(this, CHANNEL_ID) : new Notification.Builder(this); + builder.setSmallIcon(R.drawable.ic_mg_utility) + .setContentTitle("MG Utility arrival briefing") + .setContentText(text.replace('\n', ' ')) + .setStyle(new Notification.BigTextStyle().bigText(text)) + .setOnlyAlertOnce(true).setAutoCancel(true).setCategory(Notification.CATEGORY_STATUS); + manager.notify(ARRIVAL_NOTIFICATION_ID, builder.build()); + } + private Notification notification(String text) { Intent open = new Intent(this, MainActivity.class); PendingIntent pending = PendingIntent.getActivity(this, 0, open, diff --git a/src/cloud/molberg/mgutility/TripsActivity.java b/src/cloud/molberg/mgutility/TripsActivity.java index 87688eb..cc11bdb 100644 --- a/src/cloud/molberg/mgutility/TripsActivity.java +++ b/src/cloud/molberg/mgutility/TripsActivity.java @@ -1,7 +1,9 @@ package cloud.molberg.mgutility; import android.app.Activity; -import android.app.Dialog; +import android.app.AlertDialog; +import android.content.Intent; +import android.content.DialogInterface; import android.graphics.Color; import android.graphics.Typeface; import android.graphics.drawable.GradientDrawable; @@ -9,11 +11,11 @@ import android.os.Bundle; import android.os.Handler; import android.text.Spannable; import android.text.SpannableString; +import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.text.style.RelativeSizeSpan; import android.view.Gravity; import android.view.View; -import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.LinearLayout; @@ -28,13 +30,15 @@ import java.util.Locale; /** * Trip history with a clean overview landing page and drive-specific reports. - * Stats are rendered as compact pills rather than free-form labels; the - * regenerating-event list lives inside the raw-samples dialog. + * Stats are rendered as compact pills rather than free-form labels; the raw + * sample table and fullscreen map are opened as dedicated pages so the + * per-drive header row can stay visible while scrolling. */ public final class TripsActivity extends AnimatedActivity { + private static final int REQUEST_EXPORT_DRIVE_LOG = 8901; private final Handler handler = new Handler(); private TripDatabase database; - private LinearLayout tripList, overviewPills, drivePills, overviewExtras, driveExtras; + private LinearLayout tripList, drivePills, driveExtras; private TextView trackerStatus, reportTitle, reportSubtitle, dashboardEmpty; private TripCharts charts; private long selectedTripId = TripDatabase.NO_TRIP; @@ -73,6 +77,10 @@ public final class TripsActivity extends AnimatedActivity { header.addView(trackerStatus, new LinearLayout.LayoutParams(430, 56)); Button refresh = actionButton("REFRESH", new View.OnClickListener() { @Override public void onClick(View v) { loadTrips(); } }); header.addView(refresh, new LinearLayout.LayoutParams(130, 56)); + exportButton = actionButton("EXPORT", new View.OnClickListener() { @Override public void onClick(View v) { promptExportOptions(); } }); + LinearLayout.LayoutParams exportHeaderParams = new LinearLayout.LayoutParams(130, 56); + exportHeaderParams.setMargins(10, 0, 0, 0); + header.addView(exportButton, exportHeaderParams); Button back = UiTheme.backButton(this, new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); LinearLayout.LayoutParams bp = new LinearLayout.LayoutParams(130, 56); bp.setMargins(10, 0, 0, 0); header.addView(back, bp); root.addView(header); @@ -80,7 +88,9 @@ public final class TripsActivity extends AnimatedActivity { LinearLayout sidebar = new LinearLayout(this); sidebar.setOrientation(LinearLayout.VERTICAL); sidebar.setPadding(18, 16, 18, 12); sidebar.setBackground(UiTheme.surface(UiTheme.SURFACE, 12)); Button overviewButton = sidebarButton("OVERVIEW • ALL DRIVES"); overviewButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showOverview(); } }); sidebar.addView(overviewButton, new LinearLayout.LayoutParams(-1, 56)); - TextView history = text("RECENT DRIVES", 11, UiTheme.MUTED, Typeface.BOLD); history.setPadding(0, 10, 0, 8); sidebar.addView(history, new LinearLayout.LayoutParams(-1, 32)); + TextView history = text("RECENT DRIVES", 11, UiTheme.MUTED, Typeface.BOLD); + history.setPadding(0, 6, 0, 4); + sidebar.addView(history, new LinearLayout.LayoutParams(-1, -2)); tripList = new LinearLayout(this); tripList.setOrientation(LinearLayout.VERTICAL); ScrollView listScroll = new ScrollView(this); listScroll.setFillViewport(true); listScroll.addView(tripList); sidebar.addView(listScroll, new LinearLayout.LayoutParams(-1, 0, 1)); body.addView(sidebar, new LinearLayout.LayoutParams(360, -1)); @@ -88,8 +98,6 @@ public final class TripsActivity extends AnimatedActivity { reportTitle = text("OVERVIEW", 23, UiTheme.TEXT, Typeface.BOLD); report.addView(reportTitle, new LinearLayout.LayoutParams(-1, 38)); reportSubtitle = text("All drives ever recorded", 12, UiTheme.MUTED, Typeface.NORMAL); report.addView(reportSubtitle, new LinearLayout.LayoutParams(-1, 22)); - overviewPills = new LinearLayout(this); overviewPills.setOrientation(LinearLayout.HORIZONTAL); overviewPills.setPadding(0, 12, 0, 0); report.addView(overviewPills, new LinearLayout.LayoutParams(-1, -2)); - overviewExtras = new LinearLayout(this); overviewExtras.setOrientation(LinearLayout.HORIZONTAL); overviewExtras.setPadding(0, 8, 0, 0); report.addView(overviewExtras, new LinearLayout.LayoutParams(-1, -2)); drivePills = new LinearLayout(this); drivePills.setOrientation(LinearLayout.HORIZONTAL); drivePills.setPadding(0, 12, 0, 0); drivePills.setVisibility(View.GONE); report.addView(drivePills, new LinearLayout.LayoutParams(-1, -2)); driveExtras = new LinearLayout(this); driveExtras.setOrientation(LinearLayout.HORIZONTAL); driveExtras.setPadding(0, 8, 0, 0); driveExtras.setVisibility(View.GONE); report.addView(driveExtras, new LinearLayout.LayoutParams(-1, -2)); @@ -98,9 +106,9 @@ public final class TripsActivity extends AnimatedActivity { report.addView(dashboardEmpty, new LinearLayout.LayoutParams(-1, -2)); LinearLayout actions = new LinearLayout(this); actions.setGravity(Gravity.CENTER_VERTICAL); - Button mapButton = actionButton("OPEN FULLSCREEN MAP", new View.OnClickListener() { @Override public void onClick(View v) { openFullscreenMap(); } }); + Button mapButton = actionButton("OPEN FULLSCREEN MAP", new View.OnClickListener() { @Override public void onClick(View v) { openTripMapPage(); } }); mapButton.setEnabled(false); actions.addView(mapButton, new LinearLayout.LayoutParams(0, 50, 1)); - Button rawButton = actionButton("VIEW RAW SAMPLES", new View.OnClickListener() { @Override public void onClick(View v) { openRawSamples(); } }); + Button rawButton = actionButton("VIEW RAW SAMPLES", new View.OnClickListener() { @Override public void onClick(View v) { openRawSamplesPage(); } }); rawButton.setEnabled(false); LinearLayout.LayoutParams rp = new LinearLayout.LayoutParams(0, 50, 1); rp.setMargins(12, 0, 0, 0); actions.addView(rawButton, rp); report.addView(actions, new LinearLayout.LayoutParams(-1, 60)); overviewActions = mapButton; driveActions = rawButton; @@ -109,7 +117,7 @@ public final class TripsActivity extends AnimatedActivity { return root; } - private Button overviewActions, driveActions; + private Button overviewActions, driveActions, exportButton; private void loadTrips() { if (trackerStatus != null) trackerStatus.setText(trackerStatusText()); @@ -129,15 +137,14 @@ public final class TripsActivity extends AnimatedActivity { private void showOverview() { selectedTripId = TripDatabase.NO_TRIP; new Thread(new Runnable() { @Override public void run() { - final TripDatabase.Summary summary = database.summary(); List loaded = database.getAllSamples(); - final List samples = loaded.size() < 2 ? routeAsSamples(database.getAllRoutePoints()) : loaded; + final TripDatabase.Summary summary = database.summary(); + final List trips = database.listTrips(); handler.post(new Runnable() { @Override public void run() { reportTitle.setText("OVERVIEW"); reportSubtitle.setText("All drives ever recorded"); overviewActions.setEnabled(false); driveActions.setEnabled(false); setDrivePillsVisibility(false); - renderOverviewPills(summary, samples); - charts.setSamples(samples, true); - dashboardEmpty.setVisibility(samples.size() < 2 ? View.VISIBLE : View.GONE); + charts.setOverviewData(summary, trips); + dashboardEmpty.setVisibility(View.GONE); } }); } }, "mg-trip-overview").start(); loadTripsRowsOnly(); @@ -168,17 +175,6 @@ public final class TripsActivity extends AnimatedActivity { driveExtras.setVisibility(drive ? View.VISIBLE : View.GONE); } - private void renderOverviewPills(TripDatabase.Summary summary, List samples) { - overviewPills.removeAllViews(); overviewExtras.removeAllViews(); - addPill(overviewPills, "DRIVES", String.format(Locale.US, "%d", summary.tripCount)); - addPill(overviewPills, "DISTANCE", String.format(Locale.US, "%.0f km", summary.distanceMeters / 1000d)); - addPill(overviewPills, "DRIVE TIME", formatDuration(summary.movingMillis)); - addPill(overviewExtras, "ENERGY", String.format(Locale.US, "%.1f kWh", summary.energyKwh)); - addPill(overviewExtras, "REGEN", String.format(Locale.US, "%.1f kWh", summary.regenEnergyKwh)); - addPill(overviewExtras, "TOP SPEED", topSpeed(samples) > 0f ? String.format(Locale.US, "%.0f km/h", topSpeed(samples)) : "—"); - addPill(overviewExtras, "BEST REGEN", summary.bestRegenEnergyKwh > 0d ? String.format(Locale.US, "%.2f kWh", summary.bestRegenEnergyKwh) : "—"); - } - private void renderDrivePills(TripDatabase.TripSummary trip, List samples) { drivePills.removeAllViews(); driveExtras.removeAllViews(); addPill(drivePills, "DISTANCE", String.format(Locale.US, "%.1f km", trip.distanceKm())); @@ -186,7 +182,8 @@ public final class TripsActivity extends AnimatedActivity { addPill(drivePills, "TOP SPEED", String.format(Locale.US, "%.0f km/h", trip.topSpeedKph)); addPill(driveExtras, "ENERGY", Double.isNaN(trip.reportedEnergyUsed()) ? "—" : String.format(Locale.US, "%.2f kWh", trip.reportedEnergyUsed())); addPill(driveExtras, "REGEN", String.format(Locale.US, "%.2f kWh", trip.regenEnergyKwh)); - addPill(driveExtras, "BEST REGEN", trip.regenEventCount > 0 ? String.format(Locale.US, "%.2f kWh", trip.bestRegenEnergyKwh) : "—"); + addPill(driveExtras, "BEST REGEN", trip.regenEventCount > 0 && trip.bestRegenRangeKm > 0d + ? String.format(Locale.US, "+%.2f km", trip.bestRegenRangeKm) : "—"); addPill(driveExtras, "GPS POINTS", String.format(Locale.US, "%d", trip.gpsPoints)); } @@ -239,79 +236,122 @@ public final class TripsActivity extends AnimatedActivity { return span; } - private void openFullscreenMap() { + private void openTripMapPage() { if (selectedTripId == TripDatabase.NO_TRIP) return; - final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout box = new LinearLayout(this); box.setOrientation(LinearLayout.VERTICAL); box.setBackgroundColor(UiTheme.BACKGROUND); - RouteMapView fullscreen = new RouteMapView(this); box.addView(fullscreen, new LinearLayout.LayoutParams(-1, 0, 1)); - LinearLayout bar = new LinearLayout(this); bar.setGravity(Gravity.CENTER_VERTICAL); bar.setPadding(20, 0, 20, 0); - bar.setBackgroundColor(UiTheme.BACKGROUND); - TextView hint = text("Drag to pan • pinch to zoom", 11, UiTheme.MUTED, Typeface.NORMAL); bar.addView(hint, new LinearLayout.LayoutParams(0, 58, 1)); - Button close = actionButton("CLOSE MAP", new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); - bar.addView(close, new LinearLayout.LayoutParams(150, 44)); - box.addView(bar, new LinearLayout.LayoutParams(-1, 58)); - dialog.setContentView(box); Window window = dialog.getWindow(); if (window != null) window.setLayout(-1, -1); - dialog.show(); if (window != null) window.setLayout(-1, -1); - new Thread(new Runnable() { @Override public void run() { final List route = database.getRoute(selectedTripId); handler.post(new Runnable() { @Override public void run() { fullscreen.setRoute(route); } }); } }, "mg-trip-map").start(); + Intent intent = new Intent(this, TripMapActivity.class); + intent.putExtra(TripMapActivity.EXTRA_TRIP_ID, selectedTripId); + startActivity(intent); } - private void openRawSamples() { + private void openRawSamplesPage() { if (selectedTripId == TripDatabase.NO_TRIP) return; - final Dialog dialog = new Dialog(this); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); - LinearLayout box = new LinearLayout(this); box.setOrientation(LinearLayout.VERTICAL); box.setPadding(22, 18, 22, 12); box.setBackgroundColor(UiTheme.BACKGROUND); - TextView title = text("RAW SAMPLE LOG", 19, UiTheme.TEXT, Typeface.BOLD); box.addView(title, new LinearLayout.LayoutParams(-1, 36)); - TextView subtitle = text("Tab-separated, monospace", 11, UiTheme.MUTED, Typeface.NORMAL); box.addView(subtitle, new LinearLayout.LayoutParams(-1, 22)); - TextView regenHeader = text("", 12, UiTheme.TEXT, Typeface.BOLD); regenHeader.setPadding(0, 12, 0, 6); box.addView(regenHeader, new LinearLayout.LayoutParams(-1, -2)); - TextView regenView = text("", 11, UiTheme.MUTED, Typeface.NORMAL); regenView.setTypeface(Typeface.MONOSPACE); regenView.setLineSpacing(1, 1f); box.addView(regenView, new LinearLayout.LayoutParams(-1, -2)); - final TextView content = text("Loading samples…", 11, UiTheme.TEXT, Typeface.NORMAL); content.setTypeface(Typeface.MONOSPACE); - content.setPadding(12, 12, 12, 12); content.setBackgroundColor(UiTheme.SURFACE); - ScrollView scroll = new ScrollView(this); scroll.addView(content); box.addView(scroll, new LinearLayout.LayoutParams(-1, 0, 1)); - Button close = actionButton("CLOSE", new View.OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); - LinearLayout.LayoutParams cl = new LinearLayout.LayoutParams(130, 46); cl.setMargins(0, 12, 0, 0); box.addView(close, cl); - dialog.setContentView(box); Window window = dialog.getWindow(); if (window != null) window.setLayout(-1, -1); - dialog.show(); if (window != null) window.setLayout(-1, -1); - new Thread(new Runnable() { @Override public void run() { - final List samples = database.getSamples(selectedTripId); - final List events = database.getRegenEvents(selectedTripId); - handler.post(new Runnable() { @Override public void run() { regenHeader.setText("REGENERATION EVENTS"); regenView.setText(renderRegenText(events)); content.setText(rawText(samples)); } }); - } }, "mg-trip-raw").start(); + Intent intent = new Intent(this, RawSamplesActivity.class); + intent.putExtra(RawSamplesActivity.EXTRA_TRIP_ID, selectedTripId); + startActivity(intent); } - private static String renderRegenText(List events) { - if (events == null || events.isEmpty()) return "No measurable regeneration events recorded for this drive."; - SimpleDateFormat time = new SimpleDateFormat("HH:mm:ss", Locale.US); - StringBuilder out = new StringBuilder(); - for (int i = 0; i < events.size(); i++) { - TripDatabase.RegenEvent event = events.get(i); - out.append('#').append(i + 1).append(' ').append(time.format(new Date(event.startTime))) - .append(" +").append(String.format(Locale.US, "%.3f kWh +%.2f km range", event.energyKwh, event.rangeKm)); - if (event.peakSpeedKph > 0f) out.append(String.format(Locale.US, " (%.0f km/h)", event.peakSpeedKph)); - out.append('\n'); - } - return out.toString().trim(); + /** Two-step export prompt: choose format, then choose scope, then launch SAF. */ + private void promptExportOptions() { + final String[] formats = { "JSON", "CSV", "HTML" }; + final String[] formatExtensions = { "json", "csv", "html" }; + final String[] formatMime = { "application/json", "text/csv", "text/html" }; + UiTheme.dialog(this) + .setTitle("EXPORT DRIVE LOG") + .setSingleChoiceItems(formats, 0, new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface dialog, int which) { + dialog.dismiss(); + promptExportScope(which, formatExtensions[which], formatMime[which]); + } + }) + .setNegativeButton("CANCEL", null) + .show(); } - private String rawText(List samples) { - if (samples.isEmpty()) return "No raw samples recorded for this drive."; - StringBuilder out = new StringBuilder(); - out.append("timestamp speed_kph soc_pct volts energy_kwh regen_kwh regen_range_km\n"); - SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); - for (TripDatabase.TripSample s : samples) { - out.append(fmt.format(new Date(s.timestamp))).append(' ') - .append(pad(speed(s.speedKph))).append(' ') - .append(pad(percent(s.soc))).append(' ') - .append(pad(decimal(s.volts))).append(' ') - .append(pad(decimal(s.energyKwh))).append(' ') - .append(pad(decimal(s.regenEnergyKwh))).append(' ') - .append(pad(decimal(s.regenRangeKm))).append('\n'); + private void promptExportScope(final int formatIndex, final String extension, final String mime) { + final String[] scopes; + if (selectedTripId == TripDatabase.NO_TRIP) { + scopes = new String[] { "All drives (overview + every trip)" }; + } else { + scopes = new String[] { + "All drives (overview + every trip)", + "Selected drive only" + }; } - return out.toString(); + AlertDialog dialog = UiTheme.dialog(this) + .setTitle("EXPORT SCOPE") + .setSingleChoiceItems(scopes, 0, new DialogInterface.OnClickListener() { + @Override public void onClick(DialogInterface d, int which) { + d.dismiss(); + long scopeTripId = which == 1 ? selectedTripId : TripDatabase.NO_TRIP; + launchExport(formatIndex, extension, mime, scopeTripId); + } + }) + .setNegativeButton("CANCEL", null) + .create(); + dialog.show(); + if (dialog.getListView() != null) dialog.getListView().setItemChecked(0, true); } - private static String pad(String value) { String s = value; while (s.length() < 9) s += ' '; return s; } - private static String speed(float v) { return Float.isNaN(v) ? "-" : String.format(Locale.US, "%.0f", v); } - private static String percent(float v) { return Float.isNaN(v) ? "-" : String.format(Locale.US, "%.1f", v); } - private static String decimal(float v) { return Float.isNaN(v) ? "-" : String.format(Locale.US, "%.3f", v); } - private static String decimal(double v) { return Double.isNaN(v) ? "-" : String.format(Locale.US, "%.3f", v); } + + private void launchExport(int formatIndex, String extension, String mime, long scopeTripId) { + String stem = scopeTripId == TripDatabase.NO_TRIP ? "mg-utility-drive-log" : "mg-utility-drive-" + scopeTripId; + Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT); + intent.addCategory(Intent.CATEGORY_OPENABLE); + intent.setType(mime); + intent.putExtra(Intent.EXTRA_TITLE, stem + "." + extension); + try { + currentExportFormat = formatIndex; + currentExportScope = scopeTripId; + startActivityForResult(intent, REQUEST_EXPORT_DRIVE_LOG); + } catch (Exception e) { + android.widget.Toast.makeText(this, "No file picker available", android.widget.Toast.LENGTH_LONG).show(); + } + } + + private int currentExportFormat = -1; + private long currentExportScope = TripDatabase.NO_TRIP; + + @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + if (requestCode != REQUEST_EXPORT_DRIVE_LOG || resultCode != RESULT_OK || data == null || data.getData() == null) return; + final java.io.OutputStream out; + try { + out = getContentResolver().openOutputStream(data.getData()); + } catch (Exception e) { + android.widget.Toast.makeText(this, "Drive log export failed", android.widget.Toast.LENGTH_LONG).show(); + return; + } + if (out == null) { android.widget.Toast.makeText(this, "Drive log export failed", android.widget.Toast.LENGTH_LONG).show(); return; } + final int formatIndex = currentExportFormat; + final long scopeTripId = currentExportScope; + exportButton.setEnabled(false); + new Thread(new Runnable() { + @Override public void run() { + final boolean[] ok = new boolean[]{false}; + try { + String payload; + switch (formatIndex) { + case 1: payload = database.exportCsv(scopeTripId); break; + case 2: payload = database.exportHtml(scopeTripId); break; + case 0: + default: payload = database.exportJson(scopeTripId); break; + } + java.io.OutputStreamWriter writer = new java.io.OutputStreamWriter(out, java.nio.charset.StandardCharsets.UTF_8); + writer.write(payload); writer.flush(); writer.close(); + ok[0] = true; + } catch (Exception e) { + try { out.close(); } catch (Exception ignored) { } + } + handler.post(new Runnable() { + @Override public void run() { + exportButton.setEnabled(true); + android.widget.Toast.makeText(TripsActivity.this, ok[0] ? "Drive log exported" : "Drive log export failed", + android.widget.Toast.LENGTH_SHORT).show(); + } + }); + } + }, "mg-trip-export").start(); + } + private static float topSpeed(List samples) { float max = 0; for (TripDatabase.TripSample s : samples) if (!Float.isNaN(s.speedKph)) max = Math.max(max, s.speedKph); return max; } private void loadTripsRowsOnly() { new Thread(new Runnable() { @Override public void run() { final List trips = database.listTrips(); handler.post(new Runnable() { @Override public void run() { if (tripList == null) return; tripList.removeAllViews(); for (final TripDatabase.TripSummary trip : trips) { TextView row = tripRow(trip); row.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showTrip(trip); } }); tripList.addView(row, new LinearLayout.LayoutParams(-1, 72)); } } }); } }, "mg-trip-list-refresh").start(); } @@ -320,6 +360,8 @@ public final class TripsActivity extends AnimatedActivity { String distance = trip.distanceKm() >= 0.1 ? String.format(Locale.US, "%.1f km", trip.distanceKm()) : "<0.1 km"; TextView row = text(date + " • " + distance + " • top " + String.format(Locale.US, "%.0f km/h", trip.topSpeedKph), 12, UiTheme.TEXT, Typeface.NORMAL); row.setGravity(Gravity.CENTER_VERTICAL); row.setPadding(14, 0, 10, 0); + row.setSingleLine(true); + row.setEllipsize(TextUtils.TruncateAt.END); row.setBackground(UiTheme.surface(trip.id == selectedTripId ? UiTheme.SURFACE_PRESSED : UiTheme.SURFACE_HIGH, 8)); return row; } diff --git a/src/cloud/molberg/mgutility/UiTheme.java b/src/cloud/molberg/mgutility/UiTheme.java index 5ac5a5e..becb28f 100644 --- a/src/cloud/molberg/mgutility/UiTheme.java +++ b/src/cloud/molberg/mgutility/UiTheme.java @@ -13,6 +13,7 @@ import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; +import android.widget.SeekBar; import android.widget.TextView; /** Shared visual language for the MG/SAIC head-unit screens. */ @@ -46,6 +47,16 @@ final class UiTheme { static int withAlpha(int color, int alpha) { return Color.argb(Math.max(0, Math.min(255, alpha)), Color.red(color), Color.green(color), Color.blue(color)); } + + /** Apply the active palette's primary accent to a standard platform SeekBar. */ + static void tintSeekBar(SeekBar seekBar) { + if (seekBar == null) return; + // AppTheme's platform accent is only a fallback. Explicitly tint controls + // so switching to a custom/preset palette also updates the slider track/thumb. + ColorStateList colors = ColorStateList.valueOf(RED); + seekBar.setProgressTintList(colors); + seekBar.setThumbTintList(colors); + } static final String PREF_THEME = "theme"; static final String PREF_CUSTOM_PREFIX = "custom_color_"; static final int THEME_DEFAULT = 0; @@ -58,6 +69,15 @@ final class UiTheme { static final int THEME_DARK_MAGENTA = 7; static final int PAGE_HEADER_HEIGHT = 56; static final int BACK_BUTTON_WIDTH = 120; + static final String PREF_AUTO_BRIGHTNESS_ENABLED = "auto_brightness_enabled"; + static final String PREF_AUTO_BRIGHTNESS_PEAK_MINUTES = "auto_brightness_peak_minutes"; + static final String PREF_AUTO_BRIGHTNESS_DARK_MINUTES = "auto_brightness_dark_minutes"; + static final String PREF_AUTO_BRIGHTNESS_TRANSITION_MINUTES = "auto_brightness_transition_minutes"; + static final String PREF_AUTO_BRIGHTNESS_PEAK_PERCENT = "auto_brightness_peak_percent"; + static final String PREF_AUTO_BRIGHTNESS_DARK_PERCENT = "auto_brightness_dark_percent"; + static final String PREF_AUTO_BRIGHTNESS_LAST_TICK_AT = "auto_brightness_last_tick_at"; + static final String PREF_AUTO_BRIGHTNESS_LAST_VALUE = "auto_brightness_last_value"; + static final String PREF_AUTO_BRIGHTNESS_USER_OVERRIDE_UNTIL = "auto_brightness_user_override_until"; static int dp(Context c, int value) { return Math.round(value * c.getResources().getDisplayMetrics().density); diff --git a/src/cloud/molberg/mgutility/WidgetsPanelOverlay.java b/src/cloud/molberg/mgutility/WidgetsPanelOverlay.java new file mode 100644 index 0000000..0e3a608 --- /dev/null +++ b/src/cloud/molberg/mgutility/WidgetsPanelOverlay.java @@ -0,0 +1,115 @@ +package cloud.molberg.mgutility; + +import android.app.Activity; +import android.content.Context; +import android.graphics.Typeface; +import android.view.Gravity; +import android.view.MotionEvent; +import android.view.View; +import android.widget.FrameLayout; +import android.widget.LinearLayout; +import android.widget.TextView; + +/** Swipe-right panel reserved for home-screen widgets. */ +final class WidgetsPanelOverlay extends FrameLayout { + private static final float SWIPE_THRESHOLD = 80f; + + private final Activity activity; + private final FrameLayout panel; + private final int animationDuration = 230; + private boolean open; + private float downX; + private float downY; + private float panelWidth; + + WidgetsPanelOverlay(Activity activity) { + super(activity); + this.activity = activity; + setClickable(true); + setVisibility(GONE); + panel = new FrameLayout(activity); + panel.setVisibility(INVISIBLE); + panel.setBackgroundColor(UiTheme.BACKGROUND); + panel.addView(buildContent(), new FrameLayout.LayoutParams(-1, -1)); + addView(panel, new FrameLayout.LayoutParams(-1, -1, Gravity.LEFT)); + } + + boolean panelEnabled() { + return activity.getSharedPreferences(UiTheme.UI_PREFS, Context.MODE_PRIVATE) + .getBoolean(MainActivity.PREF_WIDGETS_PANEL_ENABLED, false); + } + + boolean isOpen() { return open; } + + @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { + super.onSizeChanged(w, h, oldw, oldh); + panelWidth = w; + if (!open) panel.setTranslationX(w > 0 ? -w : -Math.max(1, getWidth())); + } + + @Override public boolean onTouchEvent(MotionEvent event) { + if (!panelEnabled()) return false; + switch (event.getActionMasked()) { + case MotionEvent.ACTION_DOWN: + downX = event.getX(); + downY = event.getY(); + return true; + case MotionEvent.ACTION_UP: + float dx = event.getX() - downX; + float dy = event.getY() - downY; + if (Math.abs(dx) > SWIPE_THRESHOLD && Math.abs(dx) > Math.abs(dy)) { + if (!open && dx > 0f) openPanel(); + else if (open && dx < 0f) closePanel(); + } + return true; + case MotionEvent.ACTION_CANCEL: + return true; + default: + return true; + } + } + + void openPanel() { + if (open || !panelEnabled()) return; + open = true; + setVisibility(VISIBLE); + panel.setVisibility(VISIBLE); + panel.setTranslationX(panelWidth > 0 ? -panelWidth : -Math.max(1, getWidth())); + panel.animate().translationX(0f).setDuration(animationDuration).start(); + } + + void closePanel() { + if (!open) return; + open = false; + int end = panelWidth > 0 ? -(int) panelWidth : -Math.max(1, getWidth()); + panel.animate().translationX(end).setDuration(animationDuration) + .withEndAction(new Runnable() { + @Override public void run() { + panel.setVisibility(INVISIBLE); + setVisibility(GONE); + } + }).start(); + } + + private View buildContent() { + LinearLayout column = new LinearLayout(activity); + column.setOrientation(LinearLayout.VERTICAL); + int pad = UiTheme.dp(activity, 24); + column.setPadding(pad, UiTheme.dp(activity, 18), pad, pad); + + TextView title = UiTheme.title(activity, "WIDGETS", 24); + title.setGravity(Gravity.CENTER_VERTICAL); + column.addView(title, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 48))); + + TextView hint = UiTheme.text(activity, + "Swipe left to return to the home screen", 12, UiTheme.MUTED, Typeface.NORMAL); + hint.setGravity(Gravity.START | Gravity.CENTER_VERTICAL); + column.addView(hint, new LinearLayout.LayoutParams(-1, UiTheme.dp(activity, 30))); + + TextView empty = UiTheme.text(activity, + "Widgets will appear here in a future update.", 18, UiTheme.MUTED, Typeface.NORMAL); + empty.setGravity(Gravity.CENTER); + column.addView(empty, new LinearLayout.LayoutParams(-1, 0, 1f)); + return column; + } +} diff --git a/tests/AdaptiveAudioCurveTest.java b/tests/AdaptiveAudioCurveTest.java new file mode 100644 index 0000000..0df3726 --- /dev/null +++ b/tests/AdaptiveAudioCurveTest.java @@ -0,0 +1,57 @@ +import cloud.molberg.mgutility.AdaptiveAudioCurve; + +public final class AdaptiveAudioCurveTest { + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } + + private static void close(float actual, float expected, String message) { + if (Math.abs(actual - expected) > 0.001f) { + throw new AssertionError(message + ": expected " + expected + ", got " + actual); + } + } + + public static void main(String[] args) { + close(AdaptiveAudioCurve.multiplierPercent(0, 20, 90, 70, 100, 110, 110), + 90, "below level 1"); + close(AdaptiveAudioCurve.multiplierPercent(20, 20, 90, 70, 100, 110, 110), + 90, "at level 1"); + close(AdaptiveAudioCurve.multiplierPercent(45, 20, 90, 70, 100, 110, 110), + 95, "between levels 1 and 2"); + close(AdaptiveAudioCurve.multiplierPercent(70, 20, 90, 70, 100, 110, 110), + 100, "at level 2"); + close(AdaptiveAudioCurve.multiplierPercent(90, 20, 90, 70, 100, 110, 110), + 105, "between levels 2 and 3"); + close(AdaptiveAudioCurve.multiplierPercent(140, 20, 90, 70, 100, 110, 110), + 110, "above level 3"); + close(AdaptiveAudioCurve.multiplierPercent(300, 20, 90, 70, 100, 110, 110), + 110, "level 3 is a hard plateau"); + close(AdaptiveAudioCurve.multiplierPercent(Float.NaN, 20, 90, 70, 100, 110, 110), + 90, "invalid speed is stationary"); + + check(AdaptiveAudioCurve.targetVolume(10, 0, 20, 90) == 9, + "90 percent scales the base volume"); + check(AdaptiveAudioCurve.targetVolume(10, 0, 20, 110) == 11, + "110 percent scales the base volume"); + check(AdaptiveAudioCurve.targetVolume(19, 0, 20, 150) == 20, + "target clamps to stream maximum"); + check(AdaptiveAudioCurve.targetVolume(7, 2, 12, 50) == 5, + "nonzero stream minimum is respected"); + check(AdaptiveAudioCurve.stepToward(5, 12, 0, 20) == 6, + "automatic increase is one notch"); + check(AdaptiveAudioCurve.stepToward(12, 5, 0, 20) == 11, + "automatic decrease is one notch"); + check(AdaptiveAudioCurve.stepToward(8, 8, 0, 20) == 8, + "settled volume does not move"); + + float at80 = AdaptiveAudioCurve.multiplierPercent(80, 20, 90, 70, 100, 110, 110); + float afterTwoNotches = 12f / 20f; + float newReference = AdaptiveAudioCurve.referenceFraction(afterTwoNotches, at80); + close(newReference * at80 / 100f, afterTwoNotches, + "manual two-notch change remains authoritative at 80 km/h"); + close(AdaptiveAudioCurve.multiplierPercent(180, 20, 90, 70, 100, 110, 110), + 110f, "speed above level 3 cannot increase multiplier further"); + + System.out.println("AdaptiveAudioCurveTest: OK"); + } +} diff --git a/tests/BrightnessScheduleTest.java b/tests/BrightnessScheduleTest.java new file mode 100644 index 0000000..4ab67fa --- /dev/null +++ b/tests/BrightnessScheduleTest.java @@ -0,0 +1,58 @@ +import cloud.molberg.mgutility.BrightnessSchedule; +import java.util.Calendar; + +public final class BrightnessScheduleTest { + private static long at(int hour, int minute) { return at(2026, 9, 6, hour, minute); } + private static long at(int year, int month, int day, int hour, int minute) { + Calendar c = Calendar.getInstance(); + c.set(year, month - 1, day, hour, minute, 0); + c.set(Calendar.MILLISECOND, 0); + return c.getTimeInMillis(); + } + + private static void check(boolean condition, String message) { + if (!condition) throw new AssertionError(message); + } + + public static void main(String[] args) { + // Outside both transition windows: should land on the most recently completed anchor. + check(BrightnessSchedule.compute(at(12, 0), 7 * 60, 21 * 60, 10, 100, 0, 50) == 100, + "midday is fully peak"); + check(BrightnessSchedule.compute(at(3, 0), 7 * 60, 21 * 60, 10, 100, 0, 50) == 0, + "deep night is fully dark"); + + // The configured anchor is fully reached; the preceding minutes fade into it. + check(BrightnessSchedule.compute(at(7, 0), 7 * 60, 21 * 60, 10, 100, 0, 5) == 100, + "peak anchor is fully bright"); + int midMorning = BrightnessSchedule.compute(at(6, 55), 7 * 60, 21 * 60, 10, 100, 0, 5); + check(midMorning > 0 && midMorning < 100, "morning peak is interpolated: " + midMorning); + int midAfternoon = BrightnessSchedule.compute(at(20, 55), 7 * 60, 21 * 60, 10, 100, 0, 100); + check(midAfternoon > 0 && midAfternoon < 100, "evening dark is interpolated: " + midAfternoon); + + // Midnight wrap-around: at 23:55 the schedule should still be in dark territory. + check(BrightnessSchedule.compute(at(23, 55), 7 * 60, 21 * 60, 10, 100, 0, 100) == 0, + "late night is fully dark after wrap"); + + // Custom peak/dark percentages propagate. + check(BrightnessSchedule.compute(at(12, 0), 7 * 60, 21 * 60, 10, 80, 20, 50) == 80, + "custom peak percent applied"); + + // Zero transition still snaps at the anchor without throwing. + int snapPeak = BrightnessSchedule.compute(at(7, 0), 7 * 60, 21 * 60, 1, 100, 0, 5); + check(snapPeak == 100, "anchor is fully peak at peak time: " + snapPeak); + int snapDark = BrightnessSchedule.compute(at(21, 0), 7 * 60, 21 * 60, 1, 100, 0, 100); + check(snapDark == 0, "anchor is fully dark at dark time: " + snapDark); + + // Anchor after midnight with dark before peak should still work (custom config). + check(BrightnessSchedule.compute(at(10, 0), 1 * 60, 11 * 60, 10, 100, 0, 50) == 100, + "custom peak/dark with both daytime hours works"); + check(BrightnessSchedule.compute(at(14, 0), 1 * 60, 11 * 60, 10, 100, 0, 50) == 0, + "custom peak/dark with both daytime hours is dark outside"); + + // Format helper round-trips minutes-of-day. + check("07:30".equals(BrightnessSchedule.formatMinutes(7 * 60 + 30)), "format peak"); + check("00:00".equals(BrightnessSchedule.formatMinutes(0)), "format midnight"); + + System.out.println("BrightnessScheduleTest: OK"); + } +} diff --git a/tests/run_tests.sh b/tests/run_tests.sh index e88f225..c4bcd3e 100755 --- a/tests/run_tests.sh +++ b/tests/run_tests.sh @@ -8,8 +8,12 @@ javac -source 8 -target 8 -d "$OUT" \ "$ROOT/src/cloud/molberg/mgutility/VehicleSettingsProfile.java" \ "$ROOT/src/cloud/molberg/mgutility/VehicleSettingsApplyCoordinator.java" \ "$ROOT/src/cloud/molberg/mgutility/SpeedAudioCurve.java" \ + "$ROOT/src/cloud/molberg/mgutility/AdaptiveAudioCurve.java" \ "$ROOT/tests/VehicleSettingsCatalogTest.java" "$ROOT/tests/VehicleSettingsCoordinatorTest.java" \ - "$ROOT/tests/SpeedAudioCurveTest.java" + "$ROOT/tests/SpeedAudioCurveTest.java" "$ROOT/tests/AdaptiveAudioCurveTest.java" "$ROOT/src/cloud/molberg/mgutility/BrightnessSchedule.java" \ + "$ROOT/tests/BrightnessScheduleTest.java" java -cp "$OUT" VehicleSettingsCatalogTest java -cp "$OUT" VehicleSettingsCoordinatorTest java -cp "$OUT" SpeedAudioCurveTest +java -cp "$OUT" AdaptiveAudioCurveTest +java -cp "$OUT" BrightnessScheduleTest