From 36226a595f05eb61f9cc2e4fe05965d6d80bb35d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:06:53 -0300 Subject: [PATCH 01/12] Extract update presentation from MainActivity Co-Authored-By: Claude Opus 5.5 --- .../aureliomo/prismlock/MainActivity.java | 230 +---------------- .../github/aureliomo/prismlock/UpdateUi.java | 243 ++++++++++++++++++ app/src/main/res/values/update_strings.xml | 23 ++ .../aureliomo/prismlock/UpdateFlowTest.java | 4 +- 4 files changed, 282 insertions(+), 218 deletions(-) create mode 100644 app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java create mode 100644 app/src/main/res/values/update_strings.xml diff --git a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java index ab26ad7..302041e 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java @@ -2,82 +2,44 @@ import android.app.Activity; import android.app.AlertDialog; -import android.app.Notification; -import android.app.NotificationChannel; -import android.app.NotificationManager; -import android.app.PendingIntent; -import android.content.pm.PackageManager; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.view.ViewGroup; import android.widget.LinearLayout; -import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.io.File; -import java.lang.ref.WeakReference; public class MainActivity extends Activity { static final String PREFS = "cfg"; private static final int MIN_SIZE = 30; // seekbar 0..50 -> 30..80 - private static final int REQ_DARK = 1, REQ_LIGHT = 2, REQ_INSTALL_PERMISSION = 3; - private static final int REQ_NOTIFICATIONS = 4; - private static final String UPDATE_CHANNEL = "updates"; - private static WeakReference foreground = new WeakReference<>(null); - private static Intent pendingConfirmation; - + private static final int REQ_DARK = 1, REQ_LIGHT = 2; private int size; private ArtworkPreview fingerprintPreview, effectPreview; CatalogScreen catalogScreen; - private TextView updateDetail; - private UpdateChecker.Release pendingRelease; - private UpdateChecker.Release notificationRelease; - private String offeredVersion = ""; + final UpdateUi updates = new UpdateUi(this); @Override protected void onResume() { super.onResume(); - foreground = new WeakReference<>(this); - if (pendingRelease != null) { - UpdateChecker.Release release = pendingRelease; - pendingRelease = null; - offerUpdate(release); - } - if (pendingConfirmation != null) { - Intent confirmation = pendingConfirmation; - pendingConfirmation = null; - showInstallConfirmation(confirmation); - } else if (UpdateInstaller.takePermissionResume(this)) { - startUpdate(null); - } + updates.onResume(); } @Override protected void onPause() { - if (foreground.get() == this) foreground.clear(); + updates.onPause(); super.onPause(); } static boolean deliverInstallConfirmation(Intent confirmation) { - MainActivity activity = foreground.get(); - if (activity == null || activity.isFinishing() || activity.isDestroyed()) { - pendingConfirmation = confirmation; - return false; - } - activity.showInstallConfirmation(confirmation); - return true; + return UpdateUi.deliverInstallConfirmation(confirmation); } - private void showInstallConfirmation(Intent confirmation) { - try { - startActivity(confirmation); - } catch (Exception exception) { - new AlertDialog.Builder(this).setTitle("Could not open installer") - .setMessage("Return to Updates and try again. " + exception.getMessage()) - .setPositiveButton("Close", null).show(); - } + @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grants) { + super.onRequestPermissionsResult(requestCode, permissions, grants); + updates.onRequestPermissionsResult(requestCode, grants); } @Override @@ -152,8 +114,8 @@ protected void onCreate(Bundle state) { }).show()); LinearLayout other = screen.group(settings, "App"); screen.settingAction(other, "Preview", "Your fingerprint and touch effect.", this::showPreview); - updateDetail = screen.settingValue(other, "Updates", "Checking\u2026", - () -> checkForUpdates(true)); + updates.bindStatus(screen.settingValue(other, getString(R.string.settings_updates), getString(R.string.update_checking), + () -> updates.check(true))); screen.settingValue(other, "About this app", BuildConfig.VERSION_NAME, this::showAbout); screen.setSettings(settings); refresh(); @@ -161,7 +123,7 @@ protected void onCreate(Bundle state) { @Override protected void onStart() { super.onStart(); - checkForUpdates(false); + updates.check(false); } @Override @@ -187,165 +149,6 @@ private void showAbout() { new AlertDialog.Builder(this).setView(body).setPositiveButton("Close", null).show(); } - private void checkForUpdates(boolean manual) { - if (manual) setUpdateStatus("Checking\u2026"); - UpdateChecker.check(this, (release, error) -> { - if (isFinishing() || isDestroyed()) return; - if (error != null) { - setUpdateStatus(manual ? "Check failed" : "Tap to check"); - if (manual) showUpdateError(error); - return; - } - if (release == null) { - setUpdateStatus("Up to date"); - if (manual) toast("PrismLock is up to date."); - return; - } - setUpdateStatus("v" + release.version); - if (manual) showUpdateDialog(release); - else if (foreground.get() == this) offerUpdate(release); - else pendingRelease = release; - }); - } - - private void offerUpdate(UpdateChecker.Release release) { - if (release.version.equals(offeredVersion)) return; - offeredVersion = release.version; - notifyUpdate(release); - showUpdateDialog(release); - } - - private void notifyUpdate(UpdateChecker.Release release) { - SharedPreferences preferences = preferences(); - if (release.version.equals(preferences.getString("notified_update_version", ""))) return; - if (android.os.Build.VERSION.SDK_INT >= 33 - && checkSelfPermission("android.permission.POST_NOTIFICATIONS") != PackageManager.PERMISSION_GRANTED) { - notificationRelease = release; - requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"}, REQ_NOTIFICATIONS); - return; - } - NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); - if (android.os.Build.VERSION.SDK_INT >= 26) { - manager.createNotificationChannel(new NotificationChannel(UPDATE_CHANNEL, "Updates", NotificationManager.IMPORTANCE_DEFAULT)); - } - Intent intent = new Intent(this, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); - PendingIntent pending = PendingIntent.getActivity(this, 0, intent, - PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); - Notification.Builder builder = android.os.Build.VERSION.SDK_INT >= 26 - ? new Notification.Builder(this, UPDATE_CHANNEL) : new Notification.Builder(this); - manager.notify(1001, builder.setSmallIcon(R.mipmap.ic_launcher) - .setContentTitle("PrismLock update available") - .setContentText("Version " + release.version + " is ready to install.") - .setStyle(new Notification.BigTextStyle().bigText("Version " + release.version + " is ready to install.")) - .setContentIntent(pending).setAutoCancel(true).build()); - preferences.edit().putString("notified_update_version", release.version).apply(); - } - - @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grants) { - super.onRequestPermissionsResult(requestCode, permissions, grants); - if (requestCode == REQ_NOTIFICATIONS && grants.length > 0 - && grants[0] == PackageManager.PERMISSION_GRANTED && notificationRelease != null) { - UpdateChecker.Release release = notificationRelease; - notificationRelease = null; - notifyUpdate(release); - } - } - - private void setUpdateStatus(String value) { - if (updateDetail != null) updateDetail.setText(value); - } - - private void showUpdateDialog(UpdateChecker.Release release) { - String notes = release.notes == null ? "" : release.notes.trim(); - if (notes.length() > 900) notes = notes.substring(0, 900).trim() + "\u2026"; - String message = "Version " + release.version + " is available." - + (notes.isEmpty() ? "" : "\n\n" + notes); - new AlertDialog.Builder(this) - .setTitle("Update available") - .setMessage(message) - .setNegativeButton("Release page", (dialog, which) -> openReleases()) - .setNeutralButton("Later", null) - .setPositiveButton("Update", (dialog, which) -> startUpdate(release)) - .show(); - } - - private void showUpdateError(String detail) { - new AlertDialog.Builder(this) - .setTitle("Could not check for updates") - .setMessage(detail + "\n\nYou can download the latest release from GitHub.") - .setNegativeButton("Close", null) - .setPositiveButton("Open GitHub", (dialog, which) -> openReleases()) - .show(); - } - - private void startUpdate(UpdateChecker.Release release) { - LinearLayout body = catalogScreen.column(); - body.setPadding(dp(24), dp(16), dp(24), dp(8)); - TextView status = catalogScreen.text(release == null ? "Opening the system installer\u2026" - : "Downloading " + release.version + "\u2026", - 15, 400, catalogScreen.foreground); - ProgressBar bar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal); - bar.setMax(100); - bar.setProgress(0); - body.addView(status); - LinearLayout.LayoutParams barLayout = new LinearLayout.LayoutParams(-1, dp(24)); - barLayout.topMargin = dp(12); - body.addView(bar, barLayout); - AlertDialog dialog = new AlertDialog.Builder(this) - .setTitle("Updating PrismLock") - .setView(body) - .setCancelable(false) - .create(); - dialog.show(); - UpdateInstaller.Callback callback = new UpdateInstaller.Callback() { - @Override public void onProgress(int percent) { - if (isFinishing() || isDestroyed()) return; - bar.setProgress(percent); - status.setText("Downloading update\u2026 " + percent + "%"); - } - - @Override public void onStatus(String message) { - if (isFinishing() || isDestroyed()) return; - bar.setIndeterminate(true); - status.setText(message); - } - - @Override public void onFinished(UpdateInstaller.Result result) { - if (isFinishing() || isDestroyed()) return; - dialog.dismiss(); - if (result.needsPermission) { - UpdateInstaller.waitingForPermission(MainActivity.this, true); - try { - startActivityForResult(UpdateInstaller.unknownSourcesIntent(MainActivity.this), - REQ_INSTALL_PERMISSION); - } catch (Exception exception) { - UpdateInstaller.waitingForPermission(MainActivity.this, false); - toast("Open Settings and allow PrismLock to install unknown apps, then retry Update."); - } - } else if (result.success) { - toast(result.message); - } else { - new AlertDialog.Builder(MainActivity.this) - .setTitle("Update did not finish") - .setMessage(result.message) - .setNegativeButton("Close", null) - .setPositiveButton("Open GitHub", (dialog, which) -> openReleases()) - .show(); - } - } - }; - if (release == null) UpdateInstaller.resumeInstall(this, callback); - else UpdateInstaller.downloadAndInstall(this, release, callback); - } - - private void openReleases() { - try { - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(UpdateChecker.RELEASES_URL))); - } catch (Exception exception) { - toast("Could not open the browser."); - } - } - private long nextVersion() { return SettingsStore.nextVersion(preferences()); } @@ -377,13 +180,8 @@ private void pick(int req) { @Override protected void onActivityResult(int req, int res, Intent data) { super.onActivityResult(req, res, data); - if (req == REQ_INSTALL_PERMISSION) { - // Settings may return RESULT_CANCELED even when the permission was granted. - // onResume checks the permission itself and consumes the pending update once. - if (!getPackageManager().canRequestPackageInstalls()) { - UpdateInstaller.waitingForPermission(this, false); - toast("Installation permission was not granted. Tap Update to try again."); - } + if (req == UpdateUi.REQ_INSTALL_PERMISSION) { + updates.onInstallPermissionResult(); return; } if (res != RESULT_OK || data == null || data.getData() == null) return; @@ -410,7 +208,7 @@ private void clearSlot(String slot) { refresh(); } - private void toast(String message) { + void toast(String message) { runOnUiThread(() -> Toast.makeText(this, message, Toast.LENGTH_LONG).show()); } diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java b/app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java new file mode 100644 index 0000000..a7bb8cb --- /dev/null +++ b/app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java @@ -0,0 +1,243 @@ +package io.github.aureliomo.prismlock; + +import android.app.AlertDialog; +import android.app.Notification; +import android.app.NotificationChannel; +import android.app.NotificationManager; +import android.app.PendingIntent; +import android.content.pm.PackageManager; +import android.content.Intent; +import android.content.SharedPreferences; +import android.net.Uri; +import android.widget.LinearLayout; +import android.widget.ProgressBar; +import android.widget.TextView; + +import java.lang.ref.WeakReference; + +final class UpdateUi { + static final int REQ_INSTALL_PERMISSION = 3; + private static final int REQ_NOTIFICATIONS = 4; + private static final String UPDATE_CHANNEL = "updates"; + private static WeakReference foreground = new WeakReference<>(null); + private static Intent pendingConfirmation; + + private final MainActivity activity; + private TextView updateDetail; + private UpdateChecker.Release pendingRelease; + private UpdateChecker.Release notificationRelease; + private String offeredVersion = ""; + + UpdateUi(MainActivity activity) { + this.activity = activity; + } + + void bindStatus(TextView view) { + updateDetail = view; + } + + void onResume() { + foreground = new WeakReference<>(activity); + if (pendingRelease != null) { + UpdateChecker.Release release = pendingRelease; + pendingRelease = null; + offerUpdate(release); + } + if (pendingConfirmation != null) { + Intent confirmation = pendingConfirmation; + pendingConfirmation = null; + showInstallConfirmation(confirmation); + } else if (UpdateInstaller.takePermissionResume(activity)) { + startUpdate(null); + } + } + + void onPause() { + if (foreground.get() == activity) foreground.clear(); + } + + static boolean deliverInstallConfirmation(Intent confirmation) { + MainActivity activity = foreground.get(); + if (activity == null || activity.isFinishing() || activity.isDestroyed()) { + pendingConfirmation = confirmation; + return false; + } + activity.updates.showInstallConfirmation(confirmation); + return true; + } + + private void showInstallConfirmation(Intent confirmation) { + try { + activity.startActivity(confirmation); + } catch (Exception exception) { + new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.update_installer_open_error)) + .setMessage("Return to Updates and try again. " + exception.getMessage()) + .setPositiveButton(activity.getString(R.string.action_close), null).show(); + } + } + + void check(boolean manual) { + if (manual) setUpdateStatus(activity.getString(R.string.update_checking)); + UpdateChecker.check(activity, (release, error) -> { + if (activity.isFinishing() || activity.isDestroyed()) return; + if (error != null) { + setUpdateStatus(manual ? activity.getString(R.string.update_check_failed) : activity.getString(R.string.update_check_action)); + if (manual) showUpdateError(error); + return; + } + if (release == null) { + setUpdateStatus(activity.getString(R.string.update_up_to_date)); + if (manual) activity.toast(activity.getString(R.string.update_up_to_date_toast)); + return; + } + setUpdateStatus("v" + release.version); + if (manual) showUpdateDialog(release); + else if (foreground.get() == activity) offerUpdate(release); + else pendingRelease = release; + }); + } + + private void offerUpdate(UpdateChecker.Release release) { + if (release.version.equals(offeredVersion)) return; + offeredVersion = release.version; + notifyUpdate(release); + showUpdateDialog(release); + } + + private void notifyUpdate(UpdateChecker.Release release) { + SharedPreferences preferences = activity.preferences(); + if (release.version.equals(preferences.getString("notified_update_version", ""))) return; + if (android.os.Build.VERSION.SDK_INT >= 33 + && activity.checkSelfPermission("android.permission.POST_NOTIFICATIONS") != PackageManager.PERMISSION_GRANTED) { + notificationRelease = release; + activity.requestPermissions(new String[]{"android.permission.POST_NOTIFICATIONS"}, REQ_NOTIFICATIONS); + return; + } + NotificationManager manager = activity.getSystemService(NotificationManager.class); + manager.createNotificationChannel(new NotificationChannel(UPDATE_CHANNEL, + activity.getString(R.string.settings_updates), NotificationManager.IMPORTANCE_DEFAULT)); + Intent intent = new Intent(activity, MainActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); + PendingIntent pending = PendingIntent.getActivity(activity, 0, intent, + PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE); + Notification.Builder builder = new Notification.Builder(activity, UPDATE_CHANNEL); + manager.notify(1001, builder.setSmallIcon(R.mipmap.ic_launcher) + .setContentTitle("PrismLock update available") + .setContentText("Version " + release.version + " is ready to install.") + .setStyle(new Notification.BigTextStyle().bigText("Version " + release.version + " is ready to install.")) + .setContentIntent(pending).setAutoCancel(true).build()); + preferences.edit().putString("notified_update_version", release.version).apply(); + } + + void onRequestPermissionsResult(int requestCode, int[] grants) { + if (requestCode == REQ_NOTIFICATIONS && grants.length > 0 + && grants[0] == PackageManager.PERMISSION_GRANTED && notificationRelease != null) { + UpdateChecker.Release release = notificationRelease; + notificationRelease = null; + notifyUpdate(release); + } + } + + private void setUpdateStatus(String value) { + if (updateDetail != null) updateDetail.setText(value); + } + + private void showUpdateDialog(UpdateChecker.Release release) { + String notes = release.notes == null ? "" : release.notes.trim(); + if (notes.length() > 900) notes = notes.substring(0, 900).trim() + "\u2026"; + String message = "Version " + release.version + " is available." + + (notes.isEmpty() ? "" : "\n\n" + notes); + new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.update_available)) + .setMessage(message) + .setNegativeButton(activity.getString(R.string.update_release_page), (dialog, which) -> openReleases()) + .setNeutralButton(activity.getString(R.string.update_later), null) + .setPositiveButton(activity.getString(R.string.update_install), (dialog, which) -> startUpdate(release)) + .show(); + } + + private void showUpdateError(String detail) { + new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.update_check_error)) + .setMessage(detail + "\n\nYou can download the latest release from GitHub.") + .setNegativeButton(activity.getString(R.string.action_close), null) + .setPositiveButton(activity.getString(R.string.update_open_github), (dialog, which) -> openReleases()) + .show(); + } + + private void startUpdate(UpdateChecker.Release release) { + LinearLayout body = activity.catalogScreen.column(); + body.setPadding(activity.dp(24), activity.dp(16), activity.dp(24), activity.dp(8)); + TextView status = activity.catalogScreen.text(release == null ? activity.getString(R.string.update_opening_installer) + : "Downloading " + release.version + "\u2026", + 15, 400, activity.catalogScreen.foreground); + ProgressBar bar = new ProgressBar(activity, null, android.R.attr.progressBarStyleHorizontal); + bar.setMax(100); + bar.setProgress(0); + body.addView(status); + LinearLayout.LayoutParams barLayout = new LinearLayout.LayoutParams(-1, activity.dp(24)); + barLayout.topMargin = activity.dp(12); + body.addView(bar, barLayout); + AlertDialog dialog = new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.update_in_progress)) + .setView(body) + .setCancelable(false) + .create(); + dialog.show(); + UpdateInstaller.Callback callback = new UpdateInstaller.Callback() { + @Override public void onProgress(int percent) { + if (activity.isFinishing() || activity.isDestroyed()) return; + bar.setProgress(percent); + status.setText("Downloading update\u2026 " + percent + "%"); + } + + @Override public void onStatus(String message) { + if (activity.isFinishing() || activity.isDestroyed()) return; + bar.setIndeterminate(true); + status.setText(message); + } + + @Override public void onFinished(UpdateInstaller.Result result) { + if (activity.isFinishing() || activity.isDestroyed()) return; + dialog.dismiss(); + if (result.needsPermission) { + UpdateInstaller.waitingForPermission(activity, true); + try { + activity.startActivityForResult(UpdateInstaller.unknownSourcesIntent(activity), + REQ_INSTALL_PERMISSION); + } catch (Exception exception) { + UpdateInstaller.waitingForPermission(activity, false); + activity.toast(activity.getString(R.string.update_permission_help)); + } + } else if (result.success) { + activity.toast(result.message); + } else { + new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.update_install_error)) + .setMessage(result.message) + .setNegativeButton(activity.getString(R.string.action_close), null) + .setPositiveButton(activity.getString(R.string.update_open_github), (dialog, which) -> openReleases()) + .show(); + } + } + }; + if (release == null) UpdateInstaller.resumeInstall(activity, callback); + else UpdateInstaller.downloadAndInstall(activity, release, callback); + } + + private void openReleases() { + try { + activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(UpdateChecker.RELEASES_URL))); + } catch (Exception exception) { + activity.toast(activity.getString(R.string.update_browser_error)); + } + } + + void onInstallPermissionResult() { + // Settings may return RESULT_CANCELED even when the permission was granted. + // onResume checks the permission itself and consumes the pending update once. + if (!activity.getPackageManager().canRequestPackageInstalls()) { + UpdateInstaller.waitingForPermission(activity, false); + activity.toast(activity.getString(R.string.update_permission_denied)); + } + } +} diff --git a/app/src/main/res/values/update_strings.xml b/app/src/main/res/values/update_strings.xml new file mode 100644 index 0000000..2e77613 --- /dev/null +++ b/app/src/main/res/values/update_strings.xml @@ -0,0 +1,23 @@ + + + Checking… + Check failed + Tap to check + Up to date + PrismLock is up to date. + Update available + Release page + Later + Update + Could not check for updates + Open GitHub + Updating PrismLock + Update did not finish + Could not open installer + Could not open the browser. + Open Settings and allow PrismLock to install unknown apps, then retry Update. + Installation permission was not granted. Tap Update to try again. + Opening the system installer… + Close + Updates + diff --git a/app/src/test/java/io/github/aureliomo/prismlock/UpdateFlowTest.java b/app/src/test/java/io/github/aureliomo/prismlock/UpdateFlowTest.java index 314b7ea..ec99f10 100644 --- a/app/src/test/java/io/github/aureliomo/prismlock/UpdateFlowTest.java +++ b/app/src/test/java/io/github/aureliomo/prismlock/UpdateFlowTest.java @@ -31,7 +31,7 @@ public class UpdateFlowTest { .putLong("update_last_attempt", System.currentTimeMillis()).commit(); manager = (ShadowApplicationPackageManager) Shadows.shadowOf(app.getPackageManager()); manager.setCanRequestPackageInstalls(false); - Field pending = MainActivity.class.getDeclaredField("pendingConfirmation"); + Field pending = UpdateUi.class.getDeclaredField("pendingConfirmation"); pending.setAccessible(true); pending.set(null, null); } @@ -69,7 +69,7 @@ public class UpdateFlowTest { // Dispatch the recorded broadcast explicitly: Robolectric records explicit // PendingIntent broadcasts without consistently instantiating manifest receivers. new UpdateReceiver().onReceive(app, broadcast); - Field saved = MainActivity.class.getDeclaredField("pendingConfirmation"); + Field saved = UpdateUi.class.getDeclaredField("pendingConfirmation"); saved.setAccessible(true); Intent delivered = (Intent) saved.get(null); assertNotNull("System confirmation extras must survive PendingIntent delivery", delivered); From 4d7b2515f5d12650aa0abbde7bbb31c0dbe3c653 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:06:53 -0300 Subject: [PATCH 02/12] Separate catalog lists and artwork selection from screen navigation Co-Authored-By: Claude Opus 5.5 --- .../prismlock/CatalogCollection.java | 187 ++++++++++++++++++ .../aureliomo/prismlock/CatalogScreen.java | 181 +---------------- 2 files changed, 197 insertions(+), 171 deletions(-) create mode 100644 app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java diff --git a/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java b/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java new file mode 100644 index 0000000..6f596e4 --- /dev/null +++ b/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java @@ -0,0 +1,187 @@ +package io.github.aureliomo.prismlock; + +import android.app.Activity; +import android.graphics.Color; +import android.graphics.drawable.GradientDrawable; +import android.view.Gravity; +import android.view.View; +import android.view.ViewGroup; +import android.view.ViewOutlineProvider; +import android.widget.ImageView; +import android.widget.LinearLayout; +import android.widget.TextView; + +import android.widget.ListView; +import android.widget.BaseAdapter; +import java.util.ArrayList; +import java.util.List; + +final class CatalogCollection { + private final Activity activity; + private final CatalogScreen screen; + private final Runnable selectionChanged; + + CatalogCollection(Activity activity, CatalogScreen screen, Runnable selectionChanged) { + this.activity = activity; + this.screen = screen; + this.selectionChanged = selectionChanged; + } + + ListView create(int tab, ViewOutlineProvider outline) { + ListView list = new ListView(activity); + list.setDivider(null); + list.setDividerHeight(0); + list.setSelector(android.R.color.transparent); + list.setVerticalScrollBarEnabled(false); + list.setClipToPadding(false); + list.setPadding(0, 0, 0, screen.dp(16)); + list.setClipToOutline(true); + list.setOutlineProvider(outline); + LinearLayout header = screen.column(); + TextView heading = screen.text(tab == 0 ? "Fingerprints" : "Animations", 32, 700, screen.foreground); + CatalogScreen.heading(heading); + heading.setPadding(screen.dp(8), screen.dp(8), screen.dp(8), screen.dp(16)); + header.addView(heading); + TextView category = screen.text(tab == 0 ? "Fingerprint collection" : "Touch effects", 13, 600, screen.muted); + category.setPadding(screen.dp(12), 0, screen.dp(12), screen.dp(10)); + header.addView(category); + if (tab == 1) { + TextView warning = screen.text("Turn off LockStar's fingerprint effect to avoid conflicts.", 13, 400, screen.muted); + warning.setPadding(screen.dp(12), 0, screen.dp(12), screen.dp(12)); + header.addView(warning); + } + list.addHeaderView(header, null, false); + CatalogAdapter adapter = new CatalogAdapter(tab); + list.setAdapter(adapter); + list.setOnItemClickListener((parent, view, position, id) -> { + int index = position - list.getHeaderViewsCount(); + if (index < 0 || index >= adapter.getCount()) return; + String family = adapter.tags.get(index); + List styles = adapter.styles.get(family); + if (styles == null || styles.size() < 2) { + adapter.select(family, family, (Row) view, list); + return; + } + String[] labels = new String[styles.size()]; + int selected = 0; + for (int i = 0; i < styles.size(); i++) { + labels[i] = styles.get(i).label; + if (styles.get(i).tag.equals(adapter.selectedArtwork)) selected = i; + } + new android.app.AlertDialog.Builder(activity).setTitle(Catalog.title(family)) + .setSingleChoiceItems(labels, selected, (dialog, which) -> { + adapter.select(family, styles.get(which).tag, (Row) view, list); + dialog.dismiss(); + }).setNegativeButton("Cancel", null).show(); + }); + return list; + } + + private final class CatalogAdapter extends BaseAdapter { + final List tags = new ArrayList<>(); + final String kind, key; + String selectedFamily, selectedArtwork; + final java.util.Map> styles = new java.util.HashMap<>(); + CatalogAdapter(int tab) { + kind = tab == 0 ? "icons" : "animations"; + key = tab == 0 ? "icon" : "animation"; + String selected = activity.getSharedPreferences(MainActivity.PREFS, 0).getString(key, ""); + tags.add(""); + try { + tags.addAll(Catalog.tags(activity, kind)); + selectedFamily = Catalog.family(activity, kind, selected); + selectedArtwork = Catalog.resolve(activity, kind, selected); + for (String tag : tags) styles.put(tag, Catalog.styles(activity, kind, tag)); + } + catch (Exception failure) { + android.widget.Toast.makeText(activity, "Could not load the collection. Reopen the app to try again.", + android.widget.Toast.LENGTH_LONG).show(); + } + } + void select(String family, String tag, Row row, ListView list) { + String previousFamily = selectedFamily; + SettingsStore.select(activity.getSharedPreferences(MainActivity.PREFS, 0), key, tag); + selectedArtwork = tag; + selectedFamily = family; + for (int child = 0; child < list.getChildCount(); child++) { + int position = list.getFirstVisiblePosition() + child - list.getHeaderViewsCount(); + if (position < 0 || position >= tags.size()) continue; + String visibleTag = tags.get(position); + View visible = list.getChildAt(child); + if (visible instanceof Row && (visibleTag.equals(previousFamily) || visibleTag.equals(family))) { + getView(position, visible, list); + } + } + UiMotion.settle(row.thumbnail); + selectionChanged.run(); + } + @Override public int getCount() { return tags.size(); } + @Override public Object getItem(int position) { return tags.get(position); } + @Override public long getItemId(int position) { return position; } + @Override public boolean hasStableIds() { return true; } + @Override public View getView(int position, View recycled, ViewGroup parent) { + Row row = recycled instanceof Row ? (Row) recycled : new Row(); + String tag = tags.get(position); + boolean checked = tag.equals(selectedFamily); + String name = tag.isEmpty() ? "Samsung default" : Catalog.title(tag); + row.label.setText(name); + List choices = styles.get(tag); + String detail = ""; + if (choices != null && choices.size() > 1) { + detail = choices.size() + " styles"; + if (checked) for (Catalog.Style choice : choices) { + if (choice.tag.equals(selectedArtwork)) detail = choice.label; + } + } + row.detail.setText(detail); + row.detail.setVisibility(detail.isEmpty() ? View.INVISIBLE : View.VISIBLE); + row.check.setVisibility(checked ? View.VISIBLE : View.INVISIBLE); + row.setSelected(checked); + row.setContentDescription(name + (detail.isEmpty() ? "" : ", " + detail) + (checked ? ", selected" : "")); + float top = position == 0 ? screen.dp(24) : 0, bottom = position == getCount() - 1 ? screen.dp(24) : 0; + GradientDrawable background = new GradientDrawable(); + background.setColor(screen.panel); + background.setCornerRadii(new float[]{top, top, top, top, bottom, bottom, bottom, bottom}); + row.setBackground(background); + if (tag.isEmpty()) { + row.thumbnail.setTag(null); + row.thumbnail.setImageDrawable(screen.symbol("icons".equals(kind) ? "fingerprint" : "animation", screen.foreground)); + row.thumbnail.setPadding(screen.dp(9), screen.dp(9), screen.dp(9), screen.dp(9)); + } else { + row.thumbnail.setPadding(screen.dp(4), screen.dp(4), screen.dp(4), screen.dp(4)); + ThumbnailLoader.load(activity, "previews/" + kind + "_" + (checked ? selectedArtwork : tag) + ".png", row.thumbnail, screen.dp(36)); + } + return row; + } + } + + private final class Row extends LinearLayout { + final ImageView thumbnail = new ImageView(activity); + final TextView label = screen.text("", 16, 600, screen.foreground); + final TextView detail = screen.text("", 13, 400, screen.muted); + final ImageView check = new ImageView(activity); + Row() { + super(activity); + setGravity(Gravity.CENTER_VERTICAL); + setPadding(screen.dp(16), screen.dp(12), screen.dp(16), screen.dp(12)); + setMinimumHeight(screen.dp(76)); + setForeground(screen.ripple(Color.TRANSPARENT, 0)); + thumbnail.setBackground(screen.round(screen.dark ? 0xFF3B4049 : 0xFFE6EBF2, 14)); + thumbnail.setScaleType(ImageView.ScaleType.FIT_CENTER); + thumbnail.setClipToOutline(true); + addView(thumbnail, new LinearLayout.LayoutParams(screen.dp(44), screen.dp(44))); + LinearLayout labels = screen.column(); + labels.setMinimumHeight(screen.dp(44)); + labels.setGravity(Gravity.CENTER_VERTICAL | Gravity.START); + labels.setPadding(screen.dp(14), 0, screen.dp(4), 0); + labels.addView(label); + detail.setMinLines(1); + detail.setPadding(0, screen.dp(4), 0, 0); + labels.addView(detail); + addView(labels, new LinearLayout.LayoutParams(0, -2, 1)); + check.setImageDrawable(screen.symbol("check", screen.accent)); + addView(check, new LinearLayout.LayoutParams(screen.dp(19), screen.dp(19))); + } + } + +} diff --git a/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java b/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java index 8d7fb3f..350fe0f 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java @@ -19,21 +19,18 @@ import android.widget.TextView; import android.widget.ListView; -import android.widget.BaseAdapter; -import java.util.ArrayList; -import java.util.List; final class CatalogScreen { private final Activity activity; - private final Runnable selectionChanged; + private final CatalogCollection collection; private final Typeface regular; private final Typeface medium; private final Typeface bold; - private final boolean dark; + final boolean dark; final int foreground; final int muted; final int accent; - private final int panel; + final int panel; private final LinearLayout content; private final TextView title; private final ScrollView scroll; @@ -47,7 +44,7 @@ final class CatalogScreen { CatalogScreen(Activity activity, Runnable importFile, Runnable selectionChanged, int initialTab) { this.activity = activity; - this.selectionChanged = selectionChanged; + collection = new CatalogCollection(activity, this, selectionChanged); selectedTab = Math.max(0, Math.min(2, initialTab)); dark = Appearance.isDark(activity); Typeface family = Typeface.createFromAsset(activity.getAssets(), "fonts/OneUISans-VF.ttf"); @@ -313,175 +310,17 @@ private void render() { content.addView(settings); scroll.post(() -> scroll.scrollTo(0, scrollPositions[2])); } else if (collections[selectedTab] == null) { - collections[selectedTab] = createCollection(selectedTab); + collections[selectedTab] = collection.create(selectedTab, scroll.getOutlineProvider()); pages.addView(collections[selectedTab], new FrameLayout.LayoutParams(-1, -1)); } } - private ListView createCollection(int tab) { - ListView list = new ListView(activity); - list.setDivider(null); - list.setDividerHeight(0); - list.setSelector(android.R.color.transparent); - list.setVerticalScrollBarEnabled(false); - list.setClipToPadding(false); - list.setPadding(0, 0, 0, dp(16)); - list.setClipToOutline(true); - list.setOutlineProvider(scroll.getOutlineProvider()); - LinearLayout header = column(); - TextView heading = text(tab == 0 ? "Fingerprints" : "Animations", 32, 700, foreground); - heading(heading); - heading.setPadding(dp(8), dp(8), dp(8), dp(16)); - header.addView(heading); - TextView category = text(tab == 0 ? "Fingerprint collection" : "Touch effects", 13, 600, muted); - category.setPadding(dp(12), 0, dp(12), dp(10)); - header.addView(category); - if (tab == 1) { - TextView warning = text("Turn off LockStar's fingerprint effect to avoid conflicts.", 13, 400, muted); - warning.setPadding(dp(12), 0, dp(12), dp(12)); - header.addView(warning); - } - list.addHeaderView(header, null, false); - CatalogAdapter adapter = new CatalogAdapter(tab); - list.setAdapter(adapter); - list.setOnItemClickListener((parent, view, position, id) -> { - int index = position - list.getHeaderViewsCount(); - if (index < 0 || index >= adapter.getCount()) return; - String family = adapter.tags.get(index); - List styles = adapter.styles.get(family); - if (styles == null || styles.size() < 2) { - adapter.select(family, family, (Row) view, list); - return; - } - String[] labels = new String[styles.size()]; - int selected = 0; - for (int i = 0; i < styles.size(); i++) { - labels[i] = styles.get(i).label; - if (styles.get(i).tag.equals(adapter.selectedArtwork)) selected = i; - } - new android.app.AlertDialog.Builder(activity).setTitle(Catalog.title(family)) - .setSingleChoiceItems(labels, selected, (dialog, which) -> { - adapter.select(family, styles.get(which).tag, (Row) view, list); - dialog.dismiss(); - }).setNegativeButton("Cancel", null).show(); - }); - return list; - } - - private final class CatalogAdapter extends BaseAdapter { - final List tags = new ArrayList<>(); - final String kind, key; - String selected, selectedFamily, selectedArtwork; - final java.util.Map> styles = new java.util.HashMap<>(); - CatalogAdapter(int tab) { - kind = tab == 0 ? "icons" : "animations"; - key = tab == 0 ? "icon" : "animation"; - selected = activity.getSharedPreferences(MainActivity.PREFS, 0).getString(key, ""); - tags.add(""); - try { - tags.addAll(Catalog.tags(activity, kind)); - selectedFamily = Catalog.family(activity, kind, selected); - selectedArtwork = Catalog.resolve(activity, kind, selected); - for (String tag : tags) styles.put(tag, Catalog.styles(activity, kind, tag)); - } - catch (Exception failure) { - android.widget.Toast.makeText(activity, "Could not load the collection. Reopen the app to try again.", - android.widget.Toast.LENGTH_LONG).show(); - } - } - void select(String family, String tag, Row row, ListView list) { - String previousFamily = selectedFamily; - SettingsStore.select(activity.getSharedPreferences(MainActivity.PREFS, 0), key, tag); - selected = tag; - selectedArtwork = tag; - selectedFamily = family; - for (int child = 0; child < list.getChildCount(); child++) { - int position = list.getFirstVisiblePosition() + child - list.getHeaderViewsCount(); - if (position < 0 || position >= tags.size()) continue; - String visibleTag = tags.get(position); - View visible = list.getChildAt(child); - if (visible instanceof Row && (visibleTag.equals(previousFamily) || visibleTag.equals(family))) { - getView(position, visible, list); - } - } - UiMotion.settle(row.thumbnail); - selectionChanged.run(); - } - @Override public int getCount() { return tags.size(); } - @Override public Object getItem(int position) { return tags.get(position); } - @Override public long getItemId(int position) { return position; } - @Override public boolean hasStableIds() { return true; } - @Override public View getView(int position, View recycled, ViewGroup parent) { - Row row = recycled instanceof Row ? (Row) recycled : new Row(); - String tag = tags.get(position); - boolean checked = tag.equals(selectedFamily); - String name = tag.isEmpty() ? "Samsung default" : Catalog.title(tag); - row.label.setText(name); - List choices = styles.get(tag); - String detail = ""; - if (choices != null && choices.size() > 1) { - detail = choices.size() + " styles"; - if (checked) for (Catalog.Style choice : choices) { - if (choice.tag.equals(selectedArtwork)) detail = choice.label; - } - } - row.detail.setText(detail); - row.detail.setVisibility(detail.isEmpty() ? View.INVISIBLE : View.VISIBLE); - row.check.setVisibility(checked ? View.VISIBLE : View.INVISIBLE); - row.setSelected(checked); - row.setContentDescription(name + (detail.isEmpty() ? "" : ", " + detail) + (checked ? ", selected" : "")); - float top = position == 0 ? dp(24) : 0, bottom = position == getCount() - 1 ? dp(24) : 0; - GradientDrawable background = new GradientDrawable(); - background.setColor(panel); - background.setCornerRadii(new float[]{top, top, top, top, bottom, bottom, bottom, bottom}); - row.setBackground(background); - if (tag.isEmpty()) { - row.thumbnail.setTag(null); - row.thumbnail.setImageDrawable(symbol("icons".equals(kind) ? "fingerprint" : "animation", foreground)); - row.thumbnail.setPadding(dp(9), dp(9), dp(9), dp(9)); - } else { - row.thumbnail.setPadding(dp(4), dp(4), dp(4), dp(4)); - ThumbnailLoader.load(activity, "previews/" + kind + "_" + (checked ? selectedArtwork : tag) + ".png", row.thumbnail, dp(36)); - } - return row; - } - } - - private final class Row extends LinearLayout { - final ImageView thumbnail = new ImageView(activity); - final TextView label = text("", 16, 600, foreground); - final TextView detail = text("", 13, 400, muted); - final ImageView check = new ImageView(activity); - Row() { - super(activity); - setGravity(Gravity.CENTER_VERTICAL); - setPadding(dp(16), dp(12), dp(16), dp(12)); - setMinimumHeight(dp(76)); - setForeground(ripple(Color.TRANSPARENT, 0)); - thumbnail.setBackground(round(dark ? 0xFF3B4049 : 0xFFE6EBF2, 14)); - thumbnail.setScaleType(ImageView.ScaleType.FIT_CENTER); - thumbnail.setClipToOutline(true); - addView(thumbnail, new LinearLayout.LayoutParams(dp(44), dp(44))); - LinearLayout labels = column(); - labels.setMinimumHeight(dp(44)); - labels.setGravity(Gravity.CENTER_VERTICAL | Gravity.START); - labels.setPadding(dp(14), 0, dp(4), 0); - labels.addView(label); - detail.setMinLines(1); - detail.setPadding(0, dp(4), 0, 0); - labels.addView(detail); - addView(labels, new LinearLayout.LayoutParams(0, -2, 1)); - check.setImageDrawable(symbol("check", accent)); - addView(check, new LinearLayout.LayoutParams(dp(19), dp(19))); - } - } - private static Typeface weight(Typeface family, int weight) { return android.os.Build.VERSION.SDK_INT >= 28 ? Typeface.create(family, weight, false) : Typeface.create(family, weight >= 600 ? Typeface.BOLD : Typeface.NORMAL); } - private static void heading(View view) { + static void heading(View view) { if (android.os.Build.VERSION.SDK_INT >= 28) view.setAccessibilityHeading(true); } @@ -495,23 +334,23 @@ private ImageView action(String symbol, String label, Runnable action) { return result; } - private GradientDrawable round(int color, int radius) { + GradientDrawable round(int color, int radius) { GradientDrawable result = new GradientDrawable(); result.setColor(color); result.setCornerRadius(dp(radius)); return result; } - private Drawable ripple(int color, int radius) { + Drawable ripple(int color, int radius) { return new RippleDrawable(ColorStateList.valueOf(dark ? 0x22FFFFFF : 0x18000000), round(color, radius), round(Color.WHITE, radius)); } - private int dp(int value) { + int dp(int value) { return Math.round(value * activity.getResources().getDisplayMetrics().density); } - private Drawable symbol(String name, int color) { + Drawable symbol(String name, int color) { int resource; switch (name) { case "add": resource = R.drawable.ic_catalog_add; break; From 48196153ee7821731f50eb5e4cc891d1f1f09462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:06:53 -0300 Subject: [PATCH 03/12] Separate module configuration loading from hook registration Co-Authored-By: Claude Opus 5.5 --- .../io/github/aureliomo/prismlock/Hook.java | 40 +-------------- .../prismlock/RuntimeConfigLoader.java | 51 +++++++++++++++++++ 2 files changed, 52 insertions(+), 39 deletions(-) create mode 100644 app/src/main/java/io/github/aureliomo/prismlock/RuntimeConfigLoader.java diff --git a/app/src/main/java/io/github/aureliomo/prismlock/Hook.java b/app/src/main/java/io/github/aureliomo/prismlock/Hook.java index c948cce..bed8bac 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/Hook.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/Hook.java @@ -13,7 +13,6 @@ import android.util.Log; import android.view.View; import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.InputStream; import java.lang.reflect.Field; @@ -33,7 +32,6 @@ public final class Hook extends XposedModule { static final String TARGET = "com.samsung.android.biometrics.app.setting"; static final Uri CFG = Uri.parse("content://io.github.aureliomo.prismlock.config/cfg"); - private static final String FILE = "content://io.github.aureliomo.prismlock.config/file/"; private final AtomicBoolean installed = new AtomicBoolean(); private final AtomicBoolean refreshing = new AtomicBoolean(); private final AtomicBoolean dirty = new AtomicBoolean(); @@ -224,7 +222,7 @@ private void refreshConfig(boolean force) { lastRead = SystemClock.elapsedRealtime(); try (Cursor cursor = app.getContentResolver().query(CFG, null, null, null, null)) { if (cursor == null || !cursor.moveToFirst() || cursor.getLong(4) == config.versionCode) continue; - RuntimeConfig next = load(app, cursor); + RuntimeConfig next = RuntimeConfigLoader.load(app, cursor); config = next; main.post(this::reloadIcons); } catch (Throwable failure) { warnOnce("configuration refresh", failure); } @@ -269,42 +267,6 @@ private void reloadIcons() { } } - static RuntimeConfig load(Context app, Cursor cursor) throws Exception { - long version = cursor.getLong(4); - int size = cursor.getInt(0), stroke = cursor.getInt(1); - String dark = cursor.getString(2), light = cursor.getString(3); - if (cursor.getInt(5) != 1) return RuntimeConfig.create(version, size, stroke, false, - dark, light, null, null, null, null, null, null); - Context module = app.createPackageContext(BuildConfig.APPLICATION_ID, 0); - String tag = cursor.getString(6), effect = cursor.getString(7); - byte[] icon = null, iconLight = null, iconAod = null, animation = null; - if (tag != null && !tag.isEmpty()) { - tag = Catalog.resolve(module, "icons", tag); - icon = Catalog.selected(module, "icons", tag, size); - String lightTag = Catalog.iconTag(module, tag, "light"), aodTag = Catalog.iconTag(module, tag, "aod"); - iconLight = tag.equals(lightTag) ? icon : Catalog.selected(module, "icons", lightTag, size); - iconAod = tag.equals(aodTag) ? icon : Catalog.selected(module, "icons", aodTag, size); - } - if (effect != null && !effect.isEmpty()) animation = Catalog.selected(module, "animations", effect, size); - return RuntimeConfig.create(version, size, stroke, true, dark, light, - imported(app, "dark", dark), imported(app, "light", light), icon, iconLight, iconAod, animation); - } - - private static byte[] imported(Context app, String slot, String kind) throws Exception { - if (kind == null || kind.isEmpty()) return null; - try (InputStream input = app.getContentResolver().openInputStream(Uri.parse(FILE + slot))) { - if (input == null) throw new IllegalStateException("Imported artwork unavailable"); - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[8192]; - int count; - while ((count = input.read(buffer)) != -1) { - if (output.size() + count > 900 * 1024) throw new IllegalStateException("Imported artwork too large"); - output.write(buffer, 0, count); - } - return output.toByteArray(); - } - } - static byte[] iconPayload(RuntimeConfig snapshot, String name) { boolean light = name.contains("light"); byte[] imported = snapshot.imported(light); diff --git a/app/src/main/java/io/github/aureliomo/prismlock/RuntimeConfigLoader.java b/app/src/main/java/io/github/aureliomo/prismlock/RuntimeConfigLoader.java new file mode 100644 index 0000000..b4a37c7 --- /dev/null +++ b/app/src/main/java/io/github/aureliomo/prismlock/RuntimeConfigLoader.java @@ -0,0 +1,51 @@ +package io.github.aureliomo.prismlock; + +import android.content.Context; +import android.database.Cursor; +import android.net.Uri; + +import java.io.ByteArrayOutputStream; +import java.io.InputStream; + +final class RuntimeConfigLoader { + private static final String FILE = "content://io.github.aureliomo.prismlock.config/file/"; + + private RuntimeConfigLoader() {} + + static RuntimeConfig load(Context app, Cursor cursor) throws Exception { + long version = cursor.getLong(4); + int size = cursor.getInt(0), stroke = cursor.getInt(1); + String dark = cursor.getString(2), light = cursor.getString(3); + if (cursor.getInt(5) != 1) return RuntimeConfig.create(version, size, stroke, false, + dark, light, null, null, null, null, null, null); + Context module = app.createPackageContext(BuildConfig.APPLICATION_ID, 0); + String tag = cursor.getString(6), effect = cursor.getString(7); + byte[] icon = null, iconLight = null, iconAod = null, animation = null; + if (tag != null && !tag.isEmpty()) { + tag = Catalog.resolve(module, "icons", tag); + icon = Catalog.selected(module, "icons", tag, size); + String lightTag = Catalog.iconTag(module, tag, "light"), aodTag = Catalog.iconTag(module, tag, "aod"); + iconLight = tag.equals(lightTag) ? icon : Catalog.selected(module, "icons", lightTag, size); + iconAod = tag.equals(aodTag) ? icon : Catalog.selected(module, "icons", aodTag, size); + } + if (effect != null && !effect.isEmpty()) animation = Catalog.selected(module, "animations", effect, size); + return RuntimeConfig.create(version, size, stroke, true, dark, light, + imported(app, "dark", dark), imported(app, "light", light), icon, iconLight, iconAod, animation); + } + + private static byte[] imported(Context app, String slot, String kind) throws Exception { + if (kind == null || kind.isEmpty()) return null; + try (InputStream input = app.getContentResolver().openInputStream(Uri.parse(FILE + slot))) { + if (input == null) throw new IllegalStateException("Imported artwork unavailable"); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[8192]; + int count; + while ((count = input.read(buffer)) != -1) { + if (output.size() + count > 900 * 1024) throw new IllegalStateException("Imported artwork too large"); + output.write(buffer, 0, count); + } + return output.toByteArray(); + } + } + +} From bbb459f18f23470cdfee60c2d48d61545e3a64d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:09:17 -0300 Subject: [PATCH 04/12] Move settings construction into its own screen Co-Authored-By: Claude Opus 5.5 --- .../aureliomo/prismlock/MainActivity.java | 100 +---------------- .../aureliomo/prismlock/SettingsScreen.java | 104 ++++++++++++++++++ app/src/main/res/values/settings_strings.xml | 31 ++++++ 3 files changed, 141 insertions(+), 94 deletions(-) create mode 100644 app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java create mode 100644 app/src/main/res/values/settings_strings.xml diff --git a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java index 302041e..d36db60 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java @@ -8,7 +8,6 @@ import android.os.Bundle; import android.view.ViewGroup; import android.widget.LinearLayout; -import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; @@ -16,8 +15,7 @@ public class MainActivity extends Activity { static final String PREFS = "cfg"; - private static final int MIN_SIZE = 30; // seekbar 0..50 -> 30..80 - private static final int REQ_DARK = 1, REQ_LIGHT = 2; + static final int REQ_DARK = 1, REQ_LIGHT = 2; private int size; private ArtworkPreview fingerprintPreview, effectPreview; CatalogScreen catalogScreen; @@ -52,72 +50,7 @@ protected void onCreate(Bundle state) { fingerprintPreview = new ArtworkPreview(this, "icons"); effectPreview = new ArtworkPreview(this, "animations"); catalogScreen = new CatalogScreen(this, () -> pick(REQ_DARK), this::refresh, state == null ? 0 : state.getInt("tab", 0)); - CatalogScreen screen = catalogScreen; - LinearLayout settings = screen.column(); - LinearLayout appearance = screen.group(settings, "Appearance"); - String theme = preferences().getString("theme", "system"); - screen.settingValue(appearance, "Theme", "light".equals(theme) ? "Light" : "dark".equals(theme) ? "Dark" : "System", () -> { - String[] values = {"system", "light", "dark"}; - int selected = "light".equals(theme) ? 1 : "dark".equals(theme) ? 2 : 0; - new AlertDialog.Builder(this).setTitle("Theme") - .setSingleChoiceItems(new String[]{"System", "Light", "Dark"}, selected, (dialog, which) -> { - preferences().edit().putString("theme", values[which]).apply(); - dialog.dismiss(); - recreate(); - }).setNegativeButton("Cancel", null).show(); - }); - LinearLayout fingerprint = screen.group(settings, "Fingerprint"); - screen.settingToggle(fingerprint, "Customization", "Icons and touch effects on your lock screen.", - preferences().getBoolean("enabled", true), (button, checked) -> - preferences().edit().putBoolean("enabled", checked).putLong("ver", nextVersion()).apply()); - screen.settingValue(fingerprint, "Fingerprint size", (size * 2) + "%", () -> { - LinearLayout controls = screen.column(); - controls.setPadding(dp(24), dp(16), dp(24), dp(8)); - TextView label = screen.text((size * 2) + "%", 18, 600, screen.foreground); - controls.addView(label); - SeekBar slider = new SeekBar(this); - slider.setMax(50); - slider.setProgress(size - MIN_SIZE); - slider.setProgressTintList(android.content.res.ColorStateList.valueOf(screen.accent)); - slider.setThumbTintList(android.content.res.ColorStateList.valueOf(screen.accent)); - controls.addView(slider, new LinearLayout.LayoutParams(-1, dp(48))); - slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { - @Override public void onProgressChanged(SeekBar bar, int progress, boolean user) { - label.setText(((MIN_SIZE + progress) * 2) + "%"); - } - @Override public void onStartTrackingTouch(SeekBar bar) {} - @Override public void onStopTrackingTouch(SeekBar bar) {} - }); - new AlertDialog.Builder(this).setTitle("Fingerprint size").setView(controls) - .setNegativeButton("Cancel", null).setPositiveButton("Done", (dialog, which) -> { - size = MIN_SIZE + slider.getProgress(); - preferences().edit().putInt("size", size).putLong("ver", nextVersion()).apply(); - recreate(); - }).show(); - }); - LinearLayout data = screen.group(settings, "Your collection"); - screen.settingAction(data, "Custom icons", "Import a PNG image or Lottie file.", () -> - new AlertDialog.Builder(this).setTitle("Custom icons") - .setItems(new String[]{"Import for dark mode / AOD", "Import for light mode", "Remove imported icons"}, (dialog, which) -> { - if (which == 0) pick(REQ_DARK); - else if (which == 1) pick(REQ_LIGHT); - else { clearSlot("dark"); clearSlot("light"); } - }).setNegativeButton("Close", null).show()); - screen.settingAction(data, "Reset customization", null, () -> - new AlertDialog.Builder(this).setTitle("Restore Samsung defaults?") - .setMessage("This clears your selected fingerprint, touch effect, and imported icons.") - .setNegativeButton("Cancel", null).setPositiveButton("Reset", (dialog, which) -> { - clearSlot("dark"); clearSlot("light"); - preferences().edit().putInt("size", Icons.DEF_SIZE).putString("icon", "") - .putString("animation", "").putLong("ver", nextVersion()).apply(); - recreate(); - }).show()); - LinearLayout other = screen.group(settings, "App"); - screen.settingAction(other, "Preview", "Your fingerprint and touch effect.", this::showPreview); - updates.bindStatus(screen.settingValue(other, getString(R.string.settings_updates), getString(R.string.update_checking), - () -> updates.check(true))); - screen.settingValue(other, "About this app", BuildConfig.VERSION_NAME, this::showAbout); - screen.setSettings(settings); + new SettingsScreen(this).build(); refresh(); } @@ -132,27 +65,6 @@ protected void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); } - private void showAbout() { - LinearLayout body = catalogScreen.column(); - body.setPadding(dp(24), dp(12), dp(24), dp(16)); - body.addView(catalogScreen.text("PrismLock", 22, 700, catalogScreen.foreground)); - TextView version = catalogScreen.text(BuildConfig.VERSION_NAME, 14, 400, catalogScreen.muted); - version.setPadding(0, dp(8), 0, dp(16)); - body.addView(version); - catalogScreen.settingValue(body, "Developer", "Aur\u00e9lio", () -> - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AurelioMo")))); - catalogScreen.settingValue(body, "Repository", "AurelioMo/prismlock", () -> - startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AurelioMo/prismlock")))); - TextView credit = catalogScreen.text("Original catalog by custombeta. Samsung integration researched with RingPrint.\n\nPrismLock is an independent community project.", 13, 400, catalogScreen.muted); - credit.setPadding(0, dp(16), 0, 0); - body.addView(credit); - new AlertDialog.Builder(this).setView(body).setPositiveButton("Close", null).show(); - } - - private long nextVersion() { - return SettingsStore.nextVersion(preferences()); - } - SharedPreferences preferences() { return getSharedPreferences(PREFS, MODE_PRIVATE); } @@ -168,7 +80,7 @@ private void refresh() { effectPreview.loadCatalog(); } - private void pick(int req) { + void pick(int req) { Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); @@ -202,9 +114,9 @@ private void clearFiles(String slot) { new File(getFilesDir(), "custom_" + slot + ".json").delete(); } - private void clearSlot(String slot) { + void clearSlot(String slot) { clearFiles(slot); - preferences().edit().putString(slot + "_kind", "").putLong("ver", nextVersion()).apply(); + preferences().edit().putString(slot + "_kind", "").putLong("ver", SettingsStore.nextVersion(preferences())).apply(); refresh(); } @@ -216,7 +128,7 @@ int dp(int v) { return Math.round(v * getResources().getDisplayMetrics().density); } - private void showPreview() { + void showPreview() { LinearLayout body = catalogScreen.column(); body.setPadding(dp(20), dp(20), dp(20), dp(12)); body.addView(catalogScreen.text("Preview", 24, 700, catalogScreen.foreground)); diff --git a/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java b/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java new file mode 100644 index 0000000..5fb2295 --- /dev/null +++ b/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java @@ -0,0 +1,104 @@ +package io.github.aureliomo.prismlock; + +import android.app.AlertDialog; +import android.content.Intent; +import android.net.Uri; +import android.widget.LinearLayout; +import android.widget.SeekBar; +import android.widget.TextView; + +final class SettingsScreen { + private static final int MIN_SIZE = 30; + private final MainActivity activity; + + SettingsScreen(MainActivity activity) { + this.activity = activity; + } + + void build() { + CatalogScreen screen = activity.catalogScreen; + LinearLayout settings = screen.column(); + LinearLayout appearance = screen.group(settings, activity.getString(R.string.settings_appearance)); + String theme = activity.preferences().getString("theme", "system"); + screen.settingValue(appearance, activity.getString(R.string.settings_theme), "light".equals(theme) ? activity.getString(R.string.settings_light) : "dark".equals(theme) ? activity.getString(R.string.settings_dark) : activity.getString(R.string.settings_system), () -> { + String[] values = {"system", "light", "dark"}; + int selected = "light".equals(theme) ? 1 : "dark".equals(theme) ? 2 : 0; + new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_theme)) + .setSingleChoiceItems(new String[]{activity.getString(R.string.settings_system), activity.getString(R.string.settings_light), activity.getString(R.string.settings_dark)}, selected, (dialog, which) -> { + activity.preferences().edit().putString("theme", values[which]).apply(); + dialog.dismiss(); + activity.recreate(); + }).setNegativeButton(activity.getString(R.string.action_cancel), null).show(); + }); + LinearLayout fingerprint = screen.group(settings, activity.getString(R.string.settings_fingerprint)); + screen.settingToggle(fingerprint, activity.getString(R.string.settings_customization), activity.getString(R.string.settings_customize_description), + activity.preferences().getBoolean("enabled", true), (button, checked) -> + activity.preferences().edit().putBoolean("enabled", checked).putLong("ver", SettingsStore.nextVersion(activity.preferences())).apply()); + screen.settingValue(fingerprint, activity.getString(R.string.settings_fingerprint_size), (activity.fingerprintSize() * 2) + "%", () -> { + LinearLayout controls = screen.column(); + controls.setPadding(activity.dp(24), activity.dp(16), activity.dp(24), activity.dp(8)); + TextView label = screen.text((activity.fingerprintSize() * 2) + "%", 18, 600, screen.foreground); + controls.addView(label); + SeekBar slider = new SeekBar(activity); + slider.setMax(50); + slider.setProgress(activity.fingerprintSize() - MIN_SIZE); + slider.setProgressTintList(android.content.res.ColorStateList.valueOf(screen.accent)); + slider.setThumbTintList(android.content.res.ColorStateList.valueOf(screen.accent)); + controls.addView(slider, new LinearLayout.LayoutParams(-1, activity.dp(48))); + slider.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { + @Override public void onProgressChanged(SeekBar bar, int progress, boolean user) { + label.setText(((MIN_SIZE + progress) * 2) + "%"); + } + @Override public void onStartTrackingTouch(SeekBar bar) {} + @Override public void onStopTrackingTouch(SeekBar bar) {} + }); + new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_fingerprint_size)).setView(controls) + .setNegativeButton(activity.getString(R.string.action_cancel), null).setPositiveButton(activity.getString(R.string.action_done), (dialog, which) -> { + int newSize = MIN_SIZE + slider.getProgress(); + activity.preferences().edit().putInt("size", newSize).putLong("ver", SettingsStore.nextVersion(activity.preferences())).apply(); + activity.recreate(); + }).show(); + }); + LinearLayout data = screen.group(settings, activity.getString(R.string.settings_collection)); + screen.settingAction(data, activity.getString(R.string.settings_custom_icons), activity.getString(R.string.settings_import_description), () -> + new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_custom_icons)) + .setItems(new String[]{activity.getString(R.string.settings_import_dark), activity.getString(R.string.settings_import_light), activity.getString(R.string.settings_remove_icons)}, (dialog, which) -> { + if (which == 0) activity.pick(MainActivity.REQ_DARK); + else if (which == 1) activity.pick(MainActivity.REQ_LIGHT); + else { activity.clearSlot("dark"); activity.clearSlot("light"); } + }).setNegativeButton(activity.getString(R.string.action_close), null).show()); + screen.settingAction(data, activity.getString(R.string.settings_reset), null, () -> + new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_reset_title)) + .setMessage(activity.getString(R.string.settings_reset_description)) + .setNegativeButton(activity.getString(R.string.action_cancel), null).setPositiveButton(activity.getString(R.string.action_reset), (dialog, which) -> { + activity.clearSlot("dark"); activity.clearSlot("light"); + activity.preferences().edit().putInt("size", Icons.DEF_SIZE).putString("icon", "") + .putString("animation", "").putLong("ver", SettingsStore.nextVersion(activity.preferences())).apply(); + activity.recreate(); + }).show()); + LinearLayout other = screen.group(settings, activity.getString(R.string.settings_app)); + screen.settingAction(other, activity.getString(R.string.settings_preview), activity.getString(R.string.settings_preview_description), activity::showPreview); + activity.updates.bindStatus(screen.settingValue(other, activity.getString(R.string.settings_updates), activity.getString(R.string.update_checking), + () -> activity.updates.check(true))); + screen.settingValue(other, activity.getString(R.string.settings_about), BuildConfig.VERSION_NAME, this::showAbout); + screen.setSettings(settings); + } + + private void showAbout() { + LinearLayout body = activity.catalogScreen.column(); + body.setPadding(activity.dp(24), activity.dp(12), activity.dp(24), activity.dp(16)); + body.addView(activity.catalogScreen.text("PrismLock", 22, 700, activity.catalogScreen.foreground)); + TextView version = activity.catalogScreen.text(BuildConfig.VERSION_NAME, 14, 400, activity.catalogScreen.muted); + version.setPadding(0, activity.dp(8), 0, activity.dp(16)); + body.addView(version); + activity.catalogScreen.settingValue(body, activity.getString(R.string.settings_developer), "Aur\u00e9lio", () -> + activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AurelioMo")))); + activity.catalogScreen.settingValue(body, activity.getString(R.string.settings_repository), "AurelioMo/prismlock", () -> + activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AurelioMo/prismlock")))); + TextView credit = activity.catalogScreen.text(activity.getString(R.string.settings_about_credit), 13, 400, activity.catalogScreen.muted); + credit.setPadding(0, activity.dp(16), 0, 0); + body.addView(credit); + new AlertDialog.Builder(activity).setView(body).setPositiveButton(activity.getString(R.string.action_close), null).show(); + } + +} diff --git a/app/src/main/res/values/settings_strings.xml b/app/src/main/res/values/settings_strings.xml new file mode 100644 index 0000000..4558fed --- /dev/null +++ b/app/src/main/res/values/settings_strings.xml @@ -0,0 +1,31 @@ + + + Appearance + Theme + Light + Dark + System + Cancel + Fingerprint + Customization + Icons and touch effects on your lock screen. + Fingerprint size + Done + Your collection + Custom icons + Import a PNG image or Lottie file. + Import for dark mode / AOD + Import for light mode + Remove imported icons + Reset customization + Restore Samsung defaults? + This clears your selected fingerprint, touch effect, and imported icons. + Reset + App + Preview + Your fingerprint and touch effect. + About this app + Developer + Repository + Original catalog by custombeta. Samsung integration researched with RingPrint.\n\nPrismLock is an independent community project. + From b0c3b24d05a7bf8b69401e6d48c6c02571caef99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:09:17 -0300 Subject: [PATCH 05/12] Split APK transfer and verification from installation Co-Authored-By: Claude Opus 5.5 --- .../prismlock/UpdateApkVerifier.java | 69 ++++++++ .../aureliomo/prismlock/UpdateDownload.java | 112 +++++++++++++ .../aureliomo/prismlock/UpdateInstaller.java | 157 +----------------- .../prismlock/UpdateDownloadTest.java | 41 +++++ 4 files changed, 225 insertions(+), 154 deletions(-) create mode 100644 app/src/main/java/io/github/aureliomo/prismlock/UpdateApkVerifier.java create mode 100644 app/src/main/java/io/github/aureliomo/prismlock/UpdateDownload.java create mode 100644 app/src/test/java/io/github/aureliomo/prismlock/UpdateDownloadTest.java diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UpdateApkVerifier.java b/app/src/main/java/io/github/aureliomo/prismlock/UpdateApkVerifier.java new file mode 100644 index 0000000..f7dc795 --- /dev/null +++ b/app/src/main/java/io/github/aureliomo/prismlock/UpdateApkVerifier.java @@ -0,0 +1,69 @@ +package io.github.aureliomo.prismlock; + +import android.content.Context; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; +import android.content.pm.Signature; +import android.content.pm.SigningInfo; +import android.os.Build; + +import java.io.File; +import java.io.IOException; +import java.security.MessageDigest; + +final class UpdateApkVerifier { + private UpdateApkVerifier() {} + + static void verify(Context context, File apk) throws Exception { + PackageManager manager = context.getPackageManager(); + int flags = Build.VERSION.SDK_INT >= 28 + ? Api28.SIGNING_FLAG + : PackageManager.GET_SIGNATURES; + PackageInfo archive = manager.getPackageArchiveInfo(apk.getAbsolutePath(), flags); + if (archive == null) throw new IOException("The downloaded file is not a valid APK."); + if (!context.getPackageName().equals(archive.packageName)) { + throw new IOException("The downloaded APK belongs to another package."); + } + PackageInfo installed = manager.getPackageInfo(context.getPackageName(), flags); + String expectedSigner = signer(installed); + String actualSigner = signer(archive); + if (expectedSigner == null || !expectedSigner.equals(actualSigner)) { + throw new IOException("The downloaded APK is not signed by the PrismLock release key."); + } + if (versionCode(archive) <= versionCode(installed)) { + throw new IOException("The downloaded release is not newer than the installed version."); + } + } + + private static String signer(PackageInfo info) throws Exception { + Signature[] signatures = Build.VERSION.SDK_INT >= 28 + ? Api28.signatures(info) + : info.signatures; + if (signatures == null || signatures.length == 0) return null; + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return UpdateDownload.hex(digest.digest(signatures[0].toByteArray())); + } + + private static long versionCode(PackageInfo info) { + return Build.VERSION.SDK_INT >= 28 ? Api28.versionCode(info) : info.versionCode; + } + + /** Isolates API 28+ types so older devices never load them. */ + @android.annotation.TargetApi(28) + private static final class Api28 { + static final int SIGNING_FLAG = PackageManager.GET_SIGNING_CERTIFICATES; + + static Signature[] signatures(PackageInfo info) { + SigningInfo signing = info.signingInfo; + if (signing == null) return null; + return signing.hasMultipleSigners() + ? signing.getApkContentsSigners() + : signing.getSigningCertificateHistory(); + } + + static long versionCode(PackageInfo info) { + return info.getLongVersionCode(); + } + } + +} diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UpdateDownload.java b/app/src/main/java/io/github/aureliomo/prismlock/UpdateDownload.java new file mode 100644 index 0000000..cdbda48 --- /dev/null +++ b/app/src/main/java/io/github/aureliomo/prismlock/UpdateDownload.java @@ -0,0 +1,112 @@ +package io.github.aureliomo.prismlock; + +import android.content.Context; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.security.MessageDigest; +import java.util.Locale; +import java.util.function.IntConsumer; + +final class UpdateDownload { + private static final long MAX_APK_BYTES = 200L * 1024L * 1024L; + + private UpdateDownload() {} + + static File download(Context context, UpdateChecker.Release release, IntConsumer progress) + throws Exception { + File directory = new File(context.getCacheDir(), "updates"); + if (!directory.exists() && !directory.mkdirs()) { + throw new IOException("Could not create the update directory."); + } + long expected = release.size; + if (expected > MAX_APK_BYTES) throw new IOException("The update file is too large."); + if (expected > 0 && directory.getUsableSpace() < expected * 2) { + throw new IOException("Not enough free storage for this update."); + } + + File target = new File(directory, "prismlock-" + safe(release.version) + ".apk"); + HttpURLConnection connection = (HttpURLConnection) new URL(release.apkUrl).openConnection(); + return transfer(connection, release, progress, target); + } + + static File transfer(HttpURLConnection connection, UpdateChecker.Release release, IntConsumer progress, + File target) throws Exception { + File temporary = new File(target.getParentFile(), target.getName() + ".part"); + try { + return save(connection, release, progress, target, temporary); + } finally { + connection.disconnect(); + temporary.delete(); + } + } + + private static File save(HttpURLConnection connection, UpdateChecker.Release release, IntConsumer progress, + File target, File temporary) throws Exception { + connection.setConnectTimeout(15_000); + connection.setReadTimeout(30_000); + connection.setInstanceFollowRedirects(true); + connection.setRequestProperty("Accept", "application/octet-stream"); + connection.setRequestProperty("User-Agent", "PrismLock/" + BuildConfig.VERSION_NAME); + long total = 0L; + long completed = 0L; + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + int status = connection.getResponseCode(); + if (status != HttpURLConnection.HTTP_OK) { + throw new IOException("GitHub returned HTTP " + status + " for the update."); + } + total = connection.getContentLengthLong(); + if (total <= 0) total = release.size; + if (total > MAX_APK_BYTES) throw new IOException("The update file is too large."); + try (InputStream input = new BufferedInputStream(connection.getInputStream()); + FileOutputStream output = new FileOutputStream(temporary)) { + byte[] buffer = new byte[64 * 1024]; + int count; + int lastPercent = -1; + while ((count = input.read(buffer)) != -1) { + output.write(buffer, 0, count); + digest.update(buffer, 0, count); + completed += count; + if (completed > MAX_APK_BYTES) { + throw new IOException("The update file is too large."); + } + if (total > 0) { + int percent = (int) Math.min(100L, completed * 100L / total); + if (percent != lastPercent) { + lastPercent = percent; + progress.accept(percent); + } + } + } + output.getFD().sync(); + } + if (total > 0 && completed != total) { + throw new IOException("The update download was incomplete."); + } + String sha256 = hex(digest.digest()); + if (release.sha256 != null && !release.sha256.isEmpty() + && !release.sha256.equalsIgnoreCase(sha256)) { + throw new IOException("The update failed SHA-256 verification."); + } + if (!temporary.renameTo(target)) { + throw new IOException("Could not finish writing the update file."); + } + return target; + } + + static String hex(byte[] bytes) { + StringBuilder result = new StringBuilder(bytes.length * 2); + for (byte value : bytes) result.append(String.format(Locale.ROOT, "%02x", value)); + return result.toString(); + } + + private static String safe(String version) { + return version == null ? "update" : version.replaceAll("[^a-zA-Z0-9._-]", "_"); + } + +} diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java b/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java index badb65b..cbf43ff 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java @@ -3,35 +3,25 @@ import android.app.PendingIntent; import android.content.Context; import android.content.Intent; -import android.content.pm.PackageInfo; import android.content.pm.PackageInstaller; import android.content.pm.PackageManager; -import android.content.pm.Signature; -import android.content.pm.SigningInfo; import android.net.Uri; import android.os.Build; import android.os.Handler; import android.os.Looper; import android.provider.Settings; -import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.net.HttpURLConnection; -import java.net.URL; -import java.security.MessageDigest; -import java.util.Locale; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** Downloads, verifies and installs a release APK. */ final class UpdateInstaller { - private static final long MAX_APK_BYTES = 200L * 1024L * 1024L; private static final String PENDING_APK = "pending_update_apk"; private static final String WAITING_PERMISSION = "update_waiting_permission"; private static final Handler MAIN = new Handler(Looper.getMainLooper()); @@ -70,9 +60,9 @@ static void downloadAndInstall(Context context, UpdateChecker.Release release, C Context app = context.getApplicationContext(); EXECUTOR.execute(() -> { try { - File apk = download(app, release, callback); + File apk = UpdateDownload.download(app, release, percent -> postProgress(callback, percent)); postStatus(callback, "Verifying update\u2026"); - verify(app, apk); + UpdateApkVerifier.verify(app, apk); postStatus(callback, "Installing " + release.version + "\u2026"); RootResult root = installWithRoot(app, apk); if (root == RootResult.SUCCESS) { @@ -95,102 +85,6 @@ static void downloadAndInstall(Context context, UpdateChecker.Release release, C }); } - private static File download(Context context, UpdateChecker.Release release, Callback callback) - throws Exception { - File directory = new File(context.getCacheDir(), "updates"); - if (!directory.exists() && !directory.mkdirs()) { - throw new IOException("Could not create the update directory."); - } - long expected = release.size; - if (expected > 0 && directory.getUsableSpace() < expected * 2) { - throw new IOException("Not enough free storage for this update."); - } - - File target = new File(directory, "prismlock-" + safe(release.version) + ".apk"); - File temporary = new File(directory, target.getName() + ".part"); - delete(temporary); - HttpURLConnection connection = (HttpURLConnection) - new URL(release.apkUrl).openConnection(); - connection.setConnectTimeout(15_000); - connection.setReadTimeout(30_000); - connection.setInstanceFollowRedirects(true); - connection.setRequestProperty("Accept", "application/octet-stream"); - connection.setRequestProperty("User-Agent", "PrismLock/" + BuildConfig.VERSION_NAME); - long total = 0L; - long completed = 0L; - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - try { - int status = connection.getResponseCode(); - if (status != HttpURLConnection.HTTP_OK) { - throw new IOException("GitHub returned HTTP " + status + " for the update."); - } - total = connection.getContentLengthLong(); - if (total <= 0) total = release.size; - if (total > MAX_APK_BYTES) throw new IOException("The update file is too large."); - try (InputStream input = new BufferedInputStream(connection.getInputStream()); - FileOutputStream output = new FileOutputStream(temporary)) { - byte[] buffer = new byte[64 * 1024]; - int count; - int lastPercent = -1; - while ((count = input.read(buffer)) != -1) { - output.write(buffer, 0, count); - digest.update(buffer, 0, count); - completed += count; - if (completed > MAX_APK_BYTES) { - throw new IOException("The update file is too large."); - } - if (total > 0) { - int percent = (int) Math.min(100L, completed * 100L / total); - if (percent != lastPercent) { - lastPercent = percent; - postProgress(callback, percent); - } - } - } - output.getFD().sync(); - } - } finally { - connection.disconnect(); - } - if (total > 0 && completed != total) { - delete(temporary); - throw new IOException("The update download was incomplete."); - } - String sha256 = hex(digest.digest()); - if (release.sha256 != null && !release.sha256.isEmpty() - && !release.sha256.equalsIgnoreCase(sha256)) { - delete(temporary); - throw new IOException("The update failed SHA-256 verification."); - } - delete(target); - if (!temporary.renameTo(target)) { - delete(temporary); - throw new IOException("Could not finish writing the update file."); - } - return target; - } - - private static void verify(Context context, File apk) throws Exception { - PackageManager manager = context.getPackageManager(); - int flags = Build.VERSION.SDK_INT >= 28 - ? Api28.SIGNING_FLAG - : PackageManager.GET_SIGNATURES; - PackageInfo archive = manager.getPackageArchiveInfo(apk.getAbsolutePath(), flags); - if (archive == null) throw new IOException("The downloaded file is not a valid APK."); - if (!context.getPackageName().equals(archive.packageName)) { - throw new IOException("The downloaded APK belongs to another package."); - } - PackageInfo installed = manager.getPackageInfo(context.getPackageName(), flags); - String expectedSigner = signer(installed); - String actualSigner = signer(archive); - if (expectedSigner == null || !expectedSigner.equals(actualSigner)) { - throw new IOException("The downloaded APK is not signed by the PrismLock release key."); - } - if (versionCode(archive) <= versionCode(installed)) { - throw new IOException("The downloaded release is not newer than the installed version."); - } - } - private static RootResult installWithRoot(Context context, File apk) { Process process = null; try { @@ -289,7 +183,7 @@ static void resumeInstall(Context context, Callback callback) { } File apk = new File(new File(app.getCacheDir(), "updates"), filename); // Recheck package, version and signer after returning from Settings. - verify(app, apk); + UpdateApkVerifier.verify(app, apk); installWithSession(app, apk); postFinished(callback, new Result(true, "Follow the system installer to finish updating PrismLock.")); } catch (UnknownSourcesException exception) { @@ -300,47 +194,6 @@ static void resumeInstall(Context context, Callback callback) { }); } - private static String signer(PackageInfo info) throws Exception { - Signature[] signatures = Build.VERSION.SDK_INT >= 28 - ? Api28.signatures(info) - : info.signatures; - if (signatures == null || signatures.length == 0) return null; - MessageDigest digest = MessageDigest.getInstance("SHA-256"); - return hex(digest.digest(signatures[0].toByteArray())); - } - - private static long versionCode(PackageInfo info) { - return Build.VERSION.SDK_INT >= 28 ? Api28.versionCode(info) : info.versionCode; - } - - /** Isolates API 28+ types so older devices never load them. */ - @android.annotation.TargetApi(28) - private static final class Api28 { - static final int SIGNING_FLAG = PackageManager.GET_SIGNING_CERTIFICATES; - - static Signature[] signatures(PackageInfo info) { - SigningInfo signing = info.signingInfo; - if (signing == null) return null; - return signing.hasMultipleSigners() - ? signing.getApkContentsSigners() - : signing.getSigningCertificateHistory(); - } - - static long versionCode(PackageInfo info) { - return info.getLongVersionCode(); - } - } - - private static String hex(byte[] bytes) { - StringBuilder result = new StringBuilder(bytes.length * 2); - for (byte value : bytes) result.append(String.format(Locale.ROOT, "%02x", value)); - return result.toString(); - } - - private static String safe(String version) { - return version == null ? "update" : version.replaceAll("[^a-zA-Z0-9._-]", "_"); - } - private static String quote(String value) { return "'" + value.replace("'", "'\\''") + "'"; } @@ -359,10 +212,6 @@ private static void copyQuietly(InputStream input, ByteArrayOutputStream output) } } - private static void delete(File file) { - if (file.exists() && !file.delete()) file.deleteOnExit(); - } - private static void postProgress(Callback callback, int percent) { MAIN.post(() -> callback.onProgress(percent)); } diff --git a/app/src/test/java/io/github/aureliomo/prismlock/UpdateDownloadTest.java b/app/src/test/java/io/github/aureliomo/prismlock/UpdateDownloadTest.java new file mode 100644 index 0000000..b6cfa82 --- /dev/null +++ b/app/src/test/java/io/github/aureliomo/prismlock/UpdateDownloadTest.java @@ -0,0 +1,41 @@ +package io.github.aureliomo.prismlock; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.nio.file.Files; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import static org.junit.Assert.*; + +public class UpdateDownloadTest { + @Rule public final TemporaryFolder directory = new TemporaryFolder(); + + @Test public void interruptedTransferRemovesPartialFileAndPreservesExistingDownload() throws Exception { + File target = directory.newFile("update.apk"); + Files.write(target.toPath(), new byte[]{42}); + + byte[] content = {1, 2, 3}; + HttpURLConnection connection = new HttpURLConnection(new URL("https://example.invalid/update")) { + @Override public void connect() {} + @Override public void disconnect() {} + @Override public boolean usingProxy() { return false; } + @Override public int getResponseCode() { return HTTP_OK; } + @Override public long getContentLengthLong() { return content.length; } + @Override public InputStream getInputStream() { return new ByteArrayInputStream(content); } + }; + UpdateChecker.Release release = new UpdateChecker.Release("v99.0.0", "99.0.0", "", "", + connection.getURL().toString(), "", content.length); + assertThrows(IllegalStateException.class, () -> UpdateDownload.transfer(connection, release, percent -> { + throw new IllegalStateException("Interrupted during progress reporting"); + }, target)); + + assertFalse(new File(directory.getRoot(), "update.apk.part").exists()); + assertArrayEquals(new byte[]{42}, Files.readAllBytes(target.toPath())); + } +} From f17f27141ab95537eedc65cb89a37a070d79d3f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:10:59 -0300 Subject: [PATCH 06/12] Serialize artwork removal with imports and publish one revision per change Co-Authored-By: Claude Opus 5.5 --- .../aureliomo/prismlock/ArtworkImports.java | 25 +++++++++-- .../aureliomo/prismlock/MainActivity.java | 18 ++++---- .../aureliomo/prismlock/SettingsScreen.java | 11 ++--- .../aureliomo/prismlock/SettingsStore.java | 18 ++++++-- app/src/main/res/values/settings_strings.xml | 1 + .../aureliomo/prismlock/ArtworkTest.java | 41 +++++++++++++++++++ 6 files changed, 90 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/io/github/aureliomo/prismlock/ArtworkImports.java b/app/src/main/java/io/github/aureliomo/prismlock/ArtworkImports.java index 2958808..fec92fb 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/ArtworkImports.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/ArtworkImports.java @@ -1,6 +1,7 @@ package io.github.aureliomo.prismlock; import android.content.Context; +import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; @@ -59,9 +60,8 @@ else if (!(new JSONObject(new String(bytes, StandardCharsets.UTF_8)).opt("layers } File destination = new File(app.getFilesDir(), "custom_" + slot + "." + kind); if (!pending.renameTo(destination)) throw new IllegalStateException("Could not save this icon."); - android.content.SharedPreferences prefs = app.getSharedPreferences(MainActivity.PREFS, 0); - if (!prefs.edit().putString(slot + "_kind", kind) - .putLong("ver", SettingsStore.nextVersion(prefs)).commit()) { + SharedPreferences prefs = app.getSharedPreferences(MainActivity.PREFS, 0); + if (!SettingsStore.commitArtworkChange(prefs, editor -> editor.putString(slot + "_kind", kind))) { throw new IllegalStateException("Could not save icon settings."); } } catch (Exception exception) { @@ -74,6 +74,25 @@ else if (!(new JSONObject(new String(bytes, StandardCharsets.UTF_8)).opt("layers }); } + static void clear(Context context, boolean resetSelection, Callback callback) { + Context app = context.getApplicationContext(); + WORKER.execute(() -> { + SharedPreferences prefs = app.getSharedPreferences(MainActivity.PREFS, 0); + boolean saved = SettingsStore.commitArtworkChange(prefs, editor -> { + editor.putString("dark_kind", "").putString("light_kind", ""); + if (resetSelection) { + editor.putInt("size", Icons.DEF_SIZE).putString("icon", "").putString("animation", ""); + } + }); + if (saved) { + for (String name : new String[]{"dark.png", "dark.json", "light.png", "light.json"}) { + new File(app.getFilesDir(), "custom_" + name).delete(); + } + } + MAIN.post(() -> callback.complete(saved ? null : app.getString(R.string.settings_clear_error))); + }); + } + private static byte[] preparePng(byte[] bytes) throws Exception { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; diff --git a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java index d36db60..2d41cc9 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java @@ -11,8 +11,6 @@ import android.widget.TextView; import android.widget.Toast; -import java.io.File; - public class MainActivity extends Activity { static final String PREFS = "cfg"; static final int REQ_DARK = 1, REQ_LIGHT = 2; @@ -109,15 +107,13 @@ private void importUri(Uri uri, String slot) { }); } - private void clearFiles(String slot) { - new File(getFilesDir(), "custom_" + slot + ".png").delete(); - new File(getFilesDir(), "custom_" + slot + ".json").delete(); - } - - void clearSlot(String slot) { - clearFiles(slot); - preferences().edit().putString(slot + "_kind", "").putLong("ver", SettingsStore.nextVersion(preferences())).apply(); - refresh(); + void clearArtwork(boolean resetSelection) { + ArtworkImports.clear(this, resetSelection, error -> { + if (isFinishing() || isDestroyed()) return; + if (error != null) toast(error); + else if (resetSelection) recreate(); + else refresh(); + }); } void toast(String message) { diff --git a/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java b/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java index 5fb2295..1bea07e 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java @@ -33,7 +33,7 @@ void build() { LinearLayout fingerprint = screen.group(settings, activity.getString(R.string.settings_fingerprint)); screen.settingToggle(fingerprint, activity.getString(R.string.settings_customization), activity.getString(R.string.settings_customize_description), activity.preferences().getBoolean("enabled", true), (button, checked) -> - activity.preferences().edit().putBoolean("enabled", checked).putLong("ver", SettingsStore.nextVersion(activity.preferences())).apply()); + SettingsStore.applyArtworkChange(activity.preferences(), editor -> editor.putBoolean("enabled", checked))); screen.settingValue(fingerprint, activity.getString(R.string.settings_fingerprint_size), (activity.fingerprintSize() * 2) + "%", () -> { LinearLayout controls = screen.column(); controls.setPadding(activity.dp(24), activity.dp(16), activity.dp(24), activity.dp(8)); @@ -55,7 +55,7 @@ void build() { new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_fingerprint_size)).setView(controls) .setNegativeButton(activity.getString(R.string.action_cancel), null).setPositiveButton(activity.getString(R.string.action_done), (dialog, which) -> { int newSize = MIN_SIZE + slider.getProgress(); - activity.preferences().edit().putInt("size", newSize).putLong("ver", SettingsStore.nextVersion(activity.preferences())).apply(); + SettingsStore.applyArtworkChange(activity.preferences(), editor -> editor.putInt("size", newSize)); activity.recreate(); }).show(); }); @@ -65,16 +65,13 @@ void build() { .setItems(new String[]{activity.getString(R.string.settings_import_dark), activity.getString(R.string.settings_import_light), activity.getString(R.string.settings_remove_icons)}, (dialog, which) -> { if (which == 0) activity.pick(MainActivity.REQ_DARK); else if (which == 1) activity.pick(MainActivity.REQ_LIGHT); - else { activity.clearSlot("dark"); activity.clearSlot("light"); } + else activity.clearArtwork(false); }).setNegativeButton(activity.getString(R.string.action_close), null).show()); screen.settingAction(data, activity.getString(R.string.settings_reset), null, () -> new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_reset_title)) .setMessage(activity.getString(R.string.settings_reset_description)) .setNegativeButton(activity.getString(R.string.action_cancel), null).setPositiveButton(activity.getString(R.string.action_reset), (dialog, which) -> { - activity.clearSlot("dark"); activity.clearSlot("light"); - activity.preferences().edit().putInt("size", Icons.DEF_SIZE).putString("icon", "") - .putString("animation", "").putLong("ver", SettingsStore.nextVersion(activity.preferences())).apply(); - activity.recreate(); + activity.clearArtwork(true); }).show()); LinearLayout other = screen.group(settings, activity.getString(R.string.settings_app)); screen.settingAction(other, activity.getString(R.string.settings_preview), activity.getString(R.string.settings_preview_description), activity::showPreview); diff --git a/app/src/main/java/io/github/aureliomo/prismlock/SettingsStore.java b/app/src/main/java/io/github/aureliomo/prismlock/SettingsStore.java index c071900..38e8b30 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/SettingsStore.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/SettingsStore.java @@ -2,15 +2,27 @@ import android.content.SharedPreferences; +import java.util.function.Consumer; + /** Publishes every artwork change with a monotonic revision shared by the hook. */ final class SettingsStore { private SettingsStore() {} - static long nextVersion(SharedPreferences prefs) { - return Math.max(System.currentTimeMillis(), prefs.getLong("ver", 0) + 1); + static synchronized void applyArtworkChange(SharedPreferences prefs, Consumer change) { + artworkEditor(prefs, change).apply(); + } + + static synchronized boolean commitArtworkChange(SharedPreferences prefs, Consumer change) { + return artworkEditor(prefs, change).commit(); + } + + private static SharedPreferences.Editor artworkEditor(SharedPreferences prefs, Consumer change) { + SharedPreferences.Editor editor = prefs.edit(); + change.accept(editor); + return editor.putLong("ver", Math.max(System.currentTimeMillis(), prefs.getLong("ver", 0) + 1)); } static void select(SharedPreferences prefs, String key, String tag) { - prefs.edit().putString(key, tag).putLong("ver", nextVersion(prefs)).apply(); + applyArtworkChange(prefs, editor -> editor.putString(key, tag)); } } diff --git a/app/src/main/res/values/settings_strings.xml b/app/src/main/res/values/settings_strings.xml index 4558fed..70c5c45 100644 --- a/app/src/main/res/values/settings_strings.xml +++ b/app/src/main/res/values/settings_strings.xml @@ -28,4 +28,5 @@ Developer Repository Original catalog by custombeta. Samsung integration researched with RingPrint.\n\nPrismLock is an independent community project. + Could not save the artwork settings. diff --git a/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java b/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java index 58d528f..f017eae 100644 --- a/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java +++ b/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java @@ -33,6 +33,47 @@ public class ArtworkTest { } } + @Test public void clearingImportedArtworkPreservesSelectionUnlessResetWasRequested() throws Exception { + Context app = RuntimeEnvironment.getApplication(); + var preferences = app.getSharedPreferences(MainActivity.PREFS, 0); + preferences.edit().clear().putString("icon", "oxygenos").putString("animation", "dew") + .putString("dark_kind", "png").putInt("size", 80).putLong("ver", Long.MAX_VALUE - 10).commit(); + var imported = new java.io.File(app.getFilesDir(), "custom_dark.png"); + java.nio.file.Files.write(imported.toPath(), new byte[]{1}); + + awaitClear(app, false); + assertFalse(imported.exists()); + assertEquals("", preferences.getString("dark_kind", null)); + assertEquals("oxygenos", preferences.getString("icon", null)); + assertEquals("dew", preferences.getString("animation", null)); + assertEquals(80, preferences.getInt("size", 0)); + assertEquals(Long.MAX_VALUE - 9, preferences.getLong("ver", 0)); + + awaitClear(app, true); + assertEquals("", preferences.getString("icon", null)); + assertEquals("", preferences.getString("animation", null)); + assertEquals(Icons.DEF_SIZE, preferences.getInt("size", 0)); + assertEquals(Long.MAX_VALUE - 8, preferences.getLong("ver", 0)); + } + + private static void awaitClear(Context app, boolean reset) throws InterruptedException { + var completed = new java.util.concurrent.atomic.AtomicBoolean(); + var error = new java.util.concurrent.atomic.AtomicReference(); + ArtworkImports.clear(app, reset, message -> { + error.set(message); + completed.set(true); + }); + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(30); + var main = org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()); + while (!completed.get() && System.nanoTime() < deadline) { + main.idle(); + Thread.sleep(10); + } + main.idle(); + assertTrue("The artwork change did not finish", completed.get()); + assertNull(error.get()); + } + private static android.view.View findDescription(android.view.View view, String name) { if (name.contentEquals(view.getContentDescription() == null ? "" : view.getContentDescription())) return view; if (view instanceof android.view.ViewGroup) { From 4a5d3e7fba63d6d6895e80b8e92e2a35a467e93d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:10:59 -0300 Subject: [PATCH 07/12] Deliver preview results after detach and bound image sampling inputs Co-Authored-By: Claude Opus 5.5 --- .../aureliomo/prismlock/ArtworkPreview.java | 20 ++++++++----------- .../aureliomo/prismlock/ThumbnailLoader.java | 7 ++++--- .../aureliomo/prismlock/WallpaperLoader.java | 4 ++-- 3 files changed, 14 insertions(+), 17 deletions(-) diff --git a/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java b/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java index 3ea578c..555cbf1 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java @@ -12,17 +12,10 @@ import java.io.File; import java.util.concurrent.Future; import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; final class ArtworkPreview extends View { - private static final ThreadPoolExecutor LOADER = new ThreadPoolExecutor(1, 1, - 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), task -> { - Thread thread = new Thread(task, "prismlock-preview"); - thread.setDaemon(true); - return thread; - }); - static { LOADER.allowCoreThreadTimeOut(true); } + private static final ThreadPoolExecutor LOADER = AppWorkers.serial("prismlock-preview"); + private static final android.os.Handler MAIN = new android.os.Handler(android.os.Looper.getMainLooper()); private Future loading; private volatile long generation; private long started; @@ -123,7 +116,7 @@ void loadCatalog() { } } PreviewImages ready = next; - post(() -> { + MAIN.post(() -> { if (request != generation || !identity.equals(requested) || !isAttachedToWindow()) { recycleUnpublished(ready.frames); return; @@ -158,8 +151,11 @@ private static void recycleUnpublished(Bitmap[] frames) { } private void cancelLoading() { - if (loading != null) loading.cancel(true); - LOADER.purge(); + if (loading != null) { + loading.cancel(true); + loading = null; + LOADER.purge(); + } } @Override protected void onWindowVisibilityChanged(int visibility) { diff --git a/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java b/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java index 7c079bb..9e72ea3 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java @@ -27,7 +27,8 @@ final class ThumbnailLoader { private ThumbnailLoader() {} static void load(Context context, String filename, ImageView target, int pixels) { - String key = filename + ":" + pixels; + int size = Math.max(1, pixels); + String key = filename + ":" + size; Bitmap cached = CACHE.get(key); if (cached != null) { target.setTag(key); @@ -53,8 +54,8 @@ static void load(Context context, String filename, ImageView target, int pixels) options.inJustDecodeBounds = true; try (InputStream input = app.getAssets().open(filename)) { BitmapFactory.decodeStream(input, null, options); } options.inSampleSize = 1; - while (options.outWidth / (options.inSampleSize * 2) >= pixels - && options.outHeight / (options.inSampleSize * 2) >= pixels) options.inSampleSize *= 2; + while (options.outWidth / (options.inSampleSize * 2) >= size + && options.outHeight / (options.inSampleSize * 2) >= size) options.inSampleSize *= 2; options.inJustDecodeBounds = false; try (InputStream input = app.getAssets().open(filename)) { bitmap = BitmapFactory.decodeStream(input, null, options); } if (bitmap != null) CACHE.put(key, bitmap); diff --git a/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java b/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java index 10e7e08..b65ee34 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java @@ -26,8 +26,8 @@ private WallpaperLoader() {} static void load(Context context, ImageView target, boolean dark) { int resource = dark ? R.drawable.catalog_background_dark : R.drawable.catalog_background_light; - int width = context.getResources().getDisplayMetrics().widthPixels; - int height = context.getResources().getDisplayMetrics().heightPixels; + int width = Math.max(1, context.getResources().getDisplayMetrics().widthPixels); + int height = Math.max(1, context.getResources().getDisplayMetrics().heightPixels); String key = resource + ":" + width + ":" + height; target.setTag(key); CachedImage ready = cached; From 2d1a894c7de639c935e8dfcd39091cc4bc317755 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:11:52 -0300 Subject: [PATCH 08/12] Localize catalog labels and improve accessibility focus Co-Authored-By: Claude Opus 5.5 --- .../prismlock/CatalogCollection.java | 16 +++--- .../aureliomo/prismlock/CatalogScreen.java | 55 ++++++++++--------- .../aureliomo/prismlock/SettingsScreen.java | 19 ++++--- app/src/main/res/values/catalog_strings.xml | 17 ++++++ 4 files changed, 64 insertions(+), 43 deletions(-) create mode 100644 app/src/main/res/values/catalog_strings.xml diff --git a/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java b/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java index 6f596e4..19f89e5 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java @@ -38,15 +38,15 @@ ListView create(int tab, ViewOutlineProvider outline) { list.setClipToOutline(true); list.setOutlineProvider(outline); LinearLayout header = screen.column(); - TextView heading = screen.text(tab == 0 ? "Fingerprints" : "Animations", 32, 700, screen.foreground); + TextView heading = screen.text(activity.getString(tab == 0 ? R.string.catalog_fingerprints : R.string.catalog_animations), 32, 700, screen.foreground); CatalogScreen.heading(heading); heading.setPadding(screen.dp(8), screen.dp(8), screen.dp(8), screen.dp(16)); header.addView(heading); - TextView category = screen.text(tab == 0 ? "Fingerprint collection" : "Touch effects", 13, 600, screen.muted); + TextView category = screen.text(activity.getString(tab == 0 ? R.string.catalog_icon_collection : R.string.catalog_touch_effects), 13, 600, screen.muted); category.setPadding(screen.dp(12), 0, screen.dp(12), screen.dp(10)); header.addView(category); if (tab == 1) { - TextView warning = screen.text("Turn off LockStar's fingerprint effect to avoid conflicts.", 13, 400, screen.muted); + TextView warning = screen.text(activity.getString(R.string.catalog_lockstar_warning), 13, 400, screen.muted); warning.setPadding(screen.dp(12), 0, screen.dp(12), screen.dp(12)); header.addView(warning); } @@ -72,7 +72,7 @@ ListView create(int tab, ViewOutlineProvider outline) { .setSingleChoiceItems(labels, selected, (dialog, which) -> { adapter.select(family, styles.get(which).tag, (Row) view, list); dialog.dismiss(); - }).setNegativeButton("Cancel", null).show(); + }).setNegativeButton(R.string.action_cancel, null).show(); }); return list; } @@ -94,7 +94,7 @@ private final class CatalogAdapter extends BaseAdapter { for (String tag : tags) styles.put(tag, Catalog.styles(activity, kind, tag)); } catch (Exception failure) { - android.widget.Toast.makeText(activity, "Could not load the collection. Reopen the app to try again.", + android.widget.Toast.makeText(activity, activity.getString(R.string.catalog_load_error), android.widget.Toast.LENGTH_LONG).show(); } } @@ -123,12 +123,12 @@ void select(String family, String tag, Row row, ListView list) { Row row = recycled instanceof Row ? (Row) recycled : new Row(); String tag = tags.get(position); boolean checked = tag.equals(selectedFamily); - String name = tag.isEmpty() ? "Samsung default" : Catalog.title(tag); + String name = tag.isEmpty() ? activity.getString(R.string.catalog_samsung_default) : Catalog.title(tag); row.label.setText(name); List choices = styles.get(tag); String detail = ""; if (choices != null && choices.size() > 1) { - detail = choices.size() + " styles"; + detail = activity.getResources().getQuantityString(R.plurals.catalog_styles, choices.size(), choices.size()); if (checked) for (Catalog.Style choice : choices) { if (choice.tag.equals(selectedArtwork)) detail = choice.label; } @@ -166,6 +166,8 @@ private final class Row extends LinearLayout { setPadding(screen.dp(16), screen.dp(12), screen.dp(16), screen.dp(12)); setMinimumHeight(screen.dp(76)); setForeground(screen.ripple(Color.TRANSPARENT, 0)); + thumbnail.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); + check.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); thumbnail.setBackground(screen.round(screen.dark ? 0xFF3B4049 : 0xFFE6EBF2, 14)); thumbnail.setScaleType(ImageView.ScaleType.FIT_CENTER); thumbnail.setClipToOutline(true); diff --git a/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java b/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java index 350fe0f..89ee5b2 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java @@ -21,6 +21,9 @@ import android.widget.ListView; final class CatalogScreen { + private static final int[] TAB_LABELS = {R.string.catalog_fingerprints, R.string.catalog_animations, R.string.catalog_settings}; + private static final String[] TAB_ICONS = {"fingerprint", "animation", "settings"}; + private final Activity activity; private final CatalogCollection collection; private final Typeface regular; @@ -40,7 +43,7 @@ final class CatalogScreen { private final LinearLayout[] tabs = new LinearLayout[3]; private LinearLayout settings; private int selectedTab; - private final int[] scrollPositions = new int[3]; + private int settingsScrollPosition; CatalogScreen(Activity activity, Runnable importFile, Runnable selectionChanged, int initialTab) { this.activity = activity; @@ -96,10 +99,10 @@ final class CatalogScreen { LinearLayout toolbar = new LinearLayout(activity); toolbar.setGravity(Gravity.CENTER_VERTICAL); toolbar.setPadding(dp(16), 0, dp(16), 0); - importAction = action("add", "Import fingerprint", importFile); + importAction = action("add", activity.getString(R.string.catalog_import), importFile); toolbar.addView(importAction, new LinearLayout.LayoutParams(dp(48), dp(48))); toolbar.addView(new View(activity), new LinearLayout.LayoutParams(0, 1, 1)); - ImageView applyAction = action("refresh", "Reload collection", activity::recreate); + ImageView applyAction = action("refresh", activity.getString(R.string.catalog_reload), activity::recreate); toolbar.addView(applyAction, new LinearLayout.LayoutParams(dp(48), dp(48))); shell.addView(toolbar, new LinearLayout.LayoutParams(-1, dp(48))); @@ -131,24 +134,26 @@ final class CatalogScreen { LinearLayout navigation = new LinearLayout(activity); navigation.setPadding(dp(12), dp(5), dp(12), dp(4)); navigation.setBackground(round(dark ? 0xE6101920 : 0xE6F3F8FC, 26)); - String[] names = {"Fingerprints", "Animations", "Settings"}; - String[] symbols = {"fingerprint", "animation", "settings"}; for (int index = 0; index < tabs.length; index++) { final int destination = index; LinearLayout tab = column(); tab.setGravity(Gravity.CENTER); - tab.setContentDescription(names[index]); + String labelText = activity.getString(TAB_LABELS[index]); + tab.setContentDescription(labelText); + tab.setFocusable(true); tab.setBackground(ripple(Color.TRANSPARENT, 20)); ImageView icon = new ImageView(activity); - icon.setImageDrawable(symbol(symbols[index], muted)); + icon.setImageDrawable(symbol(TAB_ICONS[index], muted)); + icon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); tab.addView(icon, new LinearLayout.LayoutParams(dp(25), dp(25))); - TextView label = text(names[index], 11, 600, muted); + TextView label = text(labelText, 11, 600, muted); label.setGravity(Gravity.CENTER); + label.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); label.setPadding(0, dp(4), 0, 0); tab.addView(label); tab.setOnClickListener(view -> { if (selectedTab == destination) return; - if (selectedTab == 2) scrollPositions[selectedTab] = scroll.getScrollY(); + if (selectedTab == 2) settingsScrollPosition = scroll.getScrollY(); selectedTab = destination; render(); }); @@ -206,7 +211,7 @@ LinearLayout group(LinearLayout parent, String name) { return group; } - void settingAction(LinearLayout parent, String name, String subtitle, Runnable action) { + void settingAction(LinearLayout parent, int name, String subtitle, Runnable action) { LinearLayout row = new LinearLayout(activity); row.setGravity(Gravity.CENTER_VERTICAL); row.setMinimumHeight(dp(62)); @@ -214,7 +219,7 @@ void settingAction(LinearLayout parent, String name, String subtitle, Runnable a row.setBackground(ripple(Color.TRANSPARENT, 12)); addSettingIcon(row, name); LinearLayout labels = column(); - labels.addView(text(name, 16, 600, foreground)); + labels.addView(text(activity.getString(name), 16, 600, foreground)); if (subtitle != null) { TextView description = text(subtitle, 13, 400, muted); description.setPadding(0, dp(5), dp(12), 0); @@ -228,14 +233,14 @@ void settingAction(LinearLayout parent, String name, String subtitle, Runnable a parent.addView(row); } - TextView settingValue(LinearLayout parent, String name, String value, Runnable action) { + TextView settingValue(LinearLayout parent, int name, String value, Runnable action) { LinearLayout row = new LinearLayout(activity); row.setGravity(Gravity.CENTER_VERTICAL); row.setMinimumHeight(dp(62)); row.setPadding(0, dp(14), 0, dp(14)); row.setBackground(ripple(Color.TRANSPARENT, 12)); addSettingIcon(row, name); - row.addView(text(name, 16, 600, foreground), new LinearLayout.LayoutParams(0, -2, 1)); + row.addView(text(activity.getString(name), 16, 600, foreground), new LinearLayout.LayoutParams(0, -2, 1)); TextView detail = text(value, 14, 400, muted); detail.setPadding(dp(8), 0, dp(8), 0); row.addView(detail); @@ -247,17 +252,13 @@ TextView settingValue(LinearLayout parent, String name, String value, Runnable a return detail; } - private void addSettingIcon(LinearLayout row, String name) { - String glyph; - switch (name) { - case "Theme": glyph = "theme"; break; - case "Fingerprint size": glyph = "size"; break; - case "Custom icons": glyph = "import"; break; - case "Reset customization": glyph = "refresh"; break; - case "Preview": glyph = "animation"; break; - case "Updates": glyph = "refresh"; break; - default: glyph = "info"; break; - } + private void addSettingIcon(LinearLayout row, int name) { + String glyph = "info"; + if (name == R.string.settings_theme) glyph = "theme"; + else if (name == R.string.settings_fingerprint_size) glyph = "size"; + else if (name == R.string.settings_custom_icons) glyph = "import"; + else if (name == R.string.settings_reset || name == R.string.settings_updates) glyph = "refresh"; + else if (name == R.string.settings_preview) glyph = "animation"; ImageView icon = new ImageView(activity); icon.setImageDrawable(symbol(glyph, foreground)); LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(dp(22), dp(22)); @@ -291,13 +292,13 @@ void settingToggle(LinearLayout parent, String label, String description, boolea private void render() { content.removeAllViews(); - title.setText(new String[]{"Fingerprints", "Animations", "Settings"}[selectedTab]); + title.setText(TAB_LABELS[selectedTab]); importAction.setVisibility(selectedTab == 0 ? View.VISIBLE : View.INVISIBLE); for (int index = 0; index < tabs.length; index++) { boolean selected = index == selectedTab; tabs[index].setSelected(selected); ((ImageView) tabs[index].getChildAt(0)).setImageDrawable( - symbol(new String[]{"fingerprint", "animation", "settings"}[index], selected ? foreground : muted)); + symbol(TAB_ICONS[index], selected ? foreground : muted)); ((TextView) tabs[index].getChildAt(1)).setTextColor(selected ? foreground : muted); tabs[index].setAlpha(selected ? 1 : 0.7f); } @@ -308,7 +309,7 @@ private void render() { if (selectedTab == 2) { if (settings.getParent() instanceof ViewGroup) ((ViewGroup) settings.getParent()).removeView(settings); content.addView(settings); - scroll.post(() -> scroll.scrollTo(0, scrollPositions[2])); + scroll.post(() -> scroll.scrollTo(0, settingsScrollPosition)); } else if (collections[selectedTab] == null) { collections[selectedTab] = collection.create(selectedTab, scroll.getOutlineProvider()); pages.addView(collections[selectedTab], new FrameLayout.LayoutParams(-1, -1)); diff --git a/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java b/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java index 1bea07e..56778d4 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/SettingsScreen.java @@ -20,7 +20,7 @@ void build() { LinearLayout settings = screen.column(); LinearLayout appearance = screen.group(settings, activity.getString(R.string.settings_appearance)); String theme = activity.preferences().getString("theme", "system"); - screen.settingValue(appearance, activity.getString(R.string.settings_theme), "light".equals(theme) ? activity.getString(R.string.settings_light) : "dark".equals(theme) ? activity.getString(R.string.settings_dark) : activity.getString(R.string.settings_system), () -> { + screen.settingValue(appearance, R.string.settings_theme, "light".equals(theme) ? activity.getString(R.string.settings_light) : "dark".equals(theme) ? activity.getString(R.string.settings_dark) : activity.getString(R.string.settings_system), () -> { String[] values = {"system", "light", "dark"}; int selected = "light".equals(theme) ? 1 : "dark".equals(theme) ? 2 : 0; new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_theme)) @@ -34,12 +34,13 @@ void build() { screen.settingToggle(fingerprint, activity.getString(R.string.settings_customization), activity.getString(R.string.settings_customize_description), activity.preferences().getBoolean("enabled", true), (button, checked) -> SettingsStore.applyArtworkChange(activity.preferences(), editor -> editor.putBoolean("enabled", checked))); - screen.settingValue(fingerprint, activity.getString(R.string.settings_fingerprint_size), (activity.fingerprintSize() * 2) + "%", () -> { + screen.settingValue(fingerprint, R.string.settings_fingerprint_size, (activity.fingerprintSize() * 2) + "%", () -> { LinearLayout controls = screen.column(); controls.setPadding(activity.dp(24), activity.dp(16), activity.dp(24), activity.dp(8)); TextView label = screen.text((activity.fingerprintSize() * 2) + "%", 18, 600, screen.foreground); controls.addView(label); SeekBar slider = new SeekBar(activity); + slider.setContentDescription(activity.getString(R.string.settings_fingerprint_size)); slider.setMax(50); slider.setProgress(activity.fingerprintSize() - MIN_SIZE); slider.setProgressTintList(android.content.res.ColorStateList.valueOf(screen.accent)); @@ -60,24 +61,24 @@ void build() { }).show(); }); LinearLayout data = screen.group(settings, activity.getString(R.string.settings_collection)); - screen.settingAction(data, activity.getString(R.string.settings_custom_icons), activity.getString(R.string.settings_import_description), () -> + screen.settingAction(data, R.string.settings_custom_icons, activity.getString(R.string.settings_import_description), () -> new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_custom_icons)) .setItems(new String[]{activity.getString(R.string.settings_import_dark), activity.getString(R.string.settings_import_light), activity.getString(R.string.settings_remove_icons)}, (dialog, which) -> { if (which == 0) activity.pick(MainActivity.REQ_DARK); else if (which == 1) activity.pick(MainActivity.REQ_LIGHT); else activity.clearArtwork(false); }).setNegativeButton(activity.getString(R.string.action_close), null).show()); - screen.settingAction(data, activity.getString(R.string.settings_reset), null, () -> + screen.settingAction(data, R.string.settings_reset, null, () -> new AlertDialog.Builder(activity).setTitle(activity.getString(R.string.settings_reset_title)) .setMessage(activity.getString(R.string.settings_reset_description)) .setNegativeButton(activity.getString(R.string.action_cancel), null).setPositiveButton(activity.getString(R.string.action_reset), (dialog, which) -> { activity.clearArtwork(true); }).show()); LinearLayout other = screen.group(settings, activity.getString(R.string.settings_app)); - screen.settingAction(other, activity.getString(R.string.settings_preview), activity.getString(R.string.settings_preview_description), activity::showPreview); - activity.updates.bindStatus(screen.settingValue(other, activity.getString(R.string.settings_updates), activity.getString(R.string.update_checking), + screen.settingAction(other, R.string.settings_preview, activity.getString(R.string.settings_preview_description), activity::showPreview); + activity.updates.bindStatus(screen.settingValue(other, R.string.settings_updates, activity.getString(R.string.update_checking), () -> activity.updates.check(true))); - screen.settingValue(other, activity.getString(R.string.settings_about), BuildConfig.VERSION_NAME, this::showAbout); + screen.settingValue(other, R.string.settings_about, BuildConfig.VERSION_NAME, this::showAbout); screen.setSettings(settings); } @@ -88,9 +89,9 @@ private void showAbout() { TextView version = activity.catalogScreen.text(BuildConfig.VERSION_NAME, 14, 400, activity.catalogScreen.muted); version.setPadding(0, activity.dp(8), 0, activity.dp(16)); body.addView(version); - activity.catalogScreen.settingValue(body, activity.getString(R.string.settings_developer), "Aur\u00e9lio", () -> + activity.catalogScreen.settingValue(body, R.string.settings_developer, "Aur\u00e9lio", () -> activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AurelioMo")))); - activity.catalogScreen.settingValue(body, activity.getString(R.string.settings_repository), "AurelioMo/prismlock", () -> + activity.catalogScreen.settingValue(body, R.string.settings_repository, "AurelioMo/prismlock", () -> activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/AurelioMo/prismlock")))); TextView credit = activity.catalogScreen.text(activity.getString(R.string.settings_about_credit), 13, 400, activity.catalogScreen.muted); credit.setPadding(0, activity.dp(16), 0, 0); diff --git a/app/src/main/res/values/catalog_strings.xml b/app/src/main/res/values/catalog_strings.xml new file mode 100644 index 0000000..1fabd2c --- /dev/null +++ b/app/src/main/res/values/catalog_strings.xml @@ -0,0 +1,17 @@ + + + Fingerprints + Animations + Settings + Import fingerprint + Reload collection + Fingerprint collection + Touch effects + Turn off LockStar\'s fingerprint effect to avoid conflicts. + Could not load the collection. Reopen the app to try again. + Samsung default + + %d style + %d styles + + From 1c2cfc24acebe16f4351fad35e69b4fe7e22fdb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:12:14 -0300 Subject: [PATCH 09/12] Read one preference snapshot per module configuration query Co-Authored-By: Claude Opus 5.5 --- .../aureliomo/prismlock/ConfigProvider.java | 29 ++++++++++++------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/app/src/main/java/io/github/aureliomo/prismlock/ConfigProvider.java b/app/src/main/java/io/github/aureliomo/prismlock/ConfigProvider.java index bd7a7a0..80c4456 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/ConfigProvider.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/ConfigProvider.java @@ -12,6 +12,7 @@ import java.io.File; import java.io.FileNotFoundException; +import java.util.Map; /** Read-only configuration and image access for the separate biometrics process. */ public class ConfigProvider extends ContentProvider { @@ -41,16 +42,24 @@ private void enforceReader() { public Cursor query(Uri uri, String[] p, String s, String[] a, String o) { enforceReader(); if (!"/cfg".equals(uri.getPath())) throw new IllegalArgumentException("Unknown path"); - SharedPreferences sp = prefs(); - MatrixCursor c = new MatrixCursor(new String[]{"size", "stroke10", "dark_kind", "light_kind", "ver", "enabled", "icon", "animation"}); - c.addRow(new Object[]{ - sp.getInt("size", Icons.DEF_SIZE), - sp.getInt("stroke10", Icons.DEF_STROKE10), - sp.getString("dark_kind", ""), - sp.getString("light_kind", ""), - sp.getLong("ver", 0L), sp.getBoolean("enabled", true) ? 1 : 0, - sp.getString("icon", ""), sp.getString("animation", "")}); - return c; + Map snapshot = prefs().getAll(); + MatrixCursor cursor = new MatrixCursor(new String[]{ + "size", "stroke10", "dark_kind", "light_kind", "ver", "enabled", "icon", "animation"}); + cursor.addRow(new Object[]{ + value(snapshot, "size", Icons.DEF_SIZE), + value(snapshot, "stroke10", Icons.DEF_STROKE10), + value(snapshot, "dark_kind", ""), + value(snapshot, "light_kind", ""), + value(snapshot, "ver", 0L), + Boolean.TRUE.equals(value(snapshot, "enabled", true)) ? 1 : 0, + value(snapshot, "icon", ""), + value(snapshot, "animation", "")}); + return cursor; + } + + private static Object value(Map snapshot, String key, Object fallback) { + Object value = snapshot.get(key); + return fallback.getClass().isInstance(value) ? value : fallback; } @Override From 532847904d58fe17de01549085b16587364fe233 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:12:14 -0300 Subject: [PATCH 10/12] Respect disabled UI animations and preserve invalid motion timelines Co-Authored-By: Claude Opus 5.5 --- .../main/java/io/github/aureliomo/prismlock/Motion.java | 1 + .../main/java/io/github/aureliomo/prismlock/UiMotion.java | 7 +++++++ 2 files changed, 8 insertions(+) diff --git a/app/src/main/java/io/github/aureliomo/prismlock/Motion.java b/app/src/main/java/io/github/aureliomo/prismlock/Motion.java index a25dbf1..a5cac45 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/Motion.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/Motion.java @@ -13,6 +13,7 @@ static void smooth(JSONObject composition) throws Exception { double start = composition.getDouble("ip"); double end = composition.getDouble("op"); double step = composition.optDouble("catalogFrameStep", 1); + if (!Double.isFinite(start) || !Double.isFinite(end) || !Double.isFinite(step) || step <= 0) return; double half = step / 2; // Only the built-in sequential image timeline is eligible. Imports are untouched. for (int i = 0; i < layers.length(); i++) { diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java b/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java index 0693e7a..e117666 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java @@ -1,5 +1,6 @@ package io.github.aureliomo.prismlock; +import android.animation.ValueAnimator; import android.view.View; import android.view.animation.PathInterpolator; @@ -26,6 +27,12 @@ static void configureRefresh(android.app.Activity activity) { static void settle(View view) { view.animate().cancel(); + if (!ValueAnimator.areAnimatorsEnabled()) { + view.setAlpha(1); + view.setScaleX(1); + view.setScaleY(1); + return; + } view.setAlpha(0.75f); view.setScaleX(0.96f); view.setScaleY(0.96f); From dba78abebced06c9ba11ac78bf633ffed1f8280e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Wed, 25 Nov 2026 17:12:47 -0300 Subject: [PATCH 11/12] Release update dialogs and callbacks when the activity is destroyed Co-Authored-By: Claude Opus 5.5 --- .../aureliomo/prismlock/MainActivity.java | 5 + .../github/aureliomo/prismlock/UpdateUi.java | 145 ++++++++++++------ app/src/main/res/values/update_strings.xml | 1 + 3 files changed, 100 insertions(+), 51 deletions(-) diff --git a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java index 2d41cc9..fd44660 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java @@ -29,6 +29,11 @@ public class MainActivity extends Activity { super.onPause(); } + @Override protected void onDestroy() { + updates.onDestroy(); + super.onDestroy(); + } + static boolean deliverInstallConfirmation(Intent confirmation) { return UpdateUi.deliverInstallConfirmation(confirmation); } diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java b/app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java index a7bb8cb..d2fdcc3 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/UpdateUi.java @@ -24,6 +24,9 @@ final class UpdateUi { private final MainActivity activity; private TextView updateDetail; + private AlertDialog progressDialog; + private ProgressBar progressBar; + private TextView progressStatus; private UpdateChecker.Release pendingRelease; private UpdateChecker.Release notificationRelease; private String offeredVersion = ""; @@ -78,25 +81,31 @@ private void showInstallConfirmation(Intent confirmation) { void check(boolean manual) { if (manual) setUpdateStatus(activity.getString(R.string.update_checking)); + WeakReference reference = new WeakReference<>(this); UpdateChecker.check(activity, (release, error) -> { - if (activity.isFinishing() || activity.isDestroyed()) return; - if (error != null) { - setUpdateStatus(manual ? activity.getString(R.string.update_check_failed) : activity.getString(R.string.update_check_action)); - if (manual) showUpdateError(error); - return; - } - if (release == null) { - setUpdateStatus(activity.getString(R.string.update_up_to_date)); - if (manual) activity.toast(activity.getString(R.string.update_up_to_date_toast)); - return; - } - setUpdateStatus("v" + release.version); - if (manual) showUpdateDialog(release); - else if (foreground.get() == activity) offerUpdate(release); - else pendingRelease = release; + UpdateUi ui = reference.get(); + if (ui != null) ui.onCheckFinished(manual, release, error); }); } + private void onCheckFinished(boolean manual, UpdateChecker.Release release, String error) { + if (activity.isFinishing() || activity.isDestroyed()) return; + if (error != null) { + setUpdateStatus(manual ? activity.getString(R.string.update_check_failed) : activity.getString(R.string.update_check_action)); + if (manual) showUpdateError(error); + return; + } + if (release == null) { + setUpdateStatus(activity.getString(R.string.update_up_to_date)); + if (manual) activity.toast(activity.getString(R.string.update_up_to_date_toast)); + return; + } + setUpdateStatus("v" + release.version); + if (manual) showUpdateDialog(release); + else if (foreground.get() == activity) offerUpdate(release); + else pendingRelease = release; + } + private void offerUpdate(UpdateChecker.Release release) { if (release.version.equals(offeredVersion)) return; offeredVersion = release.version; @@ -165,6 +174,7 @@ private void showUpdateError(String detail) { } private void startUpdate(UpdateChecker.Release release) { + if (progressDialog != null) return; LinearLayout body = activity.catalogScreen.column(); body.setPadding(activity.dp(24), activity.dp(16), activity.dp(24), activity.dp(8)); TextView status = activity.catalogScreen.text(release == null ? activity.getString(R.string.update_opening_installer) @@ -182,46 +192,79 @@ private void startUpdate(UpdateChecker.Release release) { .setView(body) .setCancelable(false) .create(); + progressDialog = dialog; + progressBar = bar; + progressStatus = status; dialog.show(); - UpdateInstaller.Callback callback = new UpdateInstaller.Callback() { - @Override public void onProgress(int percent) { - if (activity.isFinishing() || activity.isDestroyed()) return; - bar.setProgress(percent); - status.setText("Downloading update\u2026 " + percent + "%"); - } + UpdateInstaller.Callback callback = new ProgressCallback(this); + if (release == null) UpdateInstaller.resumeInstall(activity, callback); + else UpdateInstaller.downloadAndInstall(activity, release, callback); + } - @Override public void onStatus(String message) { - if (activity.isFinishing() || activity.isDestroyed()) return; - bar.setIndeterminate(true); - status.setText(message); - } + void onDestroy() { + dismissProgress(); + } + + private void dismissProgress() { + if (progressDialog != null) progressDialog.dismiss(); + progressDialog = null; + progressBar = null; + progressStatus = null; + } - @Override public void onFinished(UpdateInstaller.Result result) { - if (activity.isFinishing() || activity.isDestroyed()) return; - dialog.dismiss(); - if (result.needsPermission) { - UpdateInstaller.waitingForPermission(activity, true); - try { - activity.startActivityForResult(UpdateInstaller.unknownSourcesIntent(activity), - REQ_INSTALL_PERMISSION); - } catch (Exception exception) { - UpdateInstaller.waitingForPermission(activity, false); - activity.toast(activity.getString(R.string.update_permission_help)); - } - } else if (result.success) { - activity.toast(result.message); - } else { - new AlertDialog.Builder(activity) - .setTitle(activity.getString(R.string.update_install_error)) - .setMessage(result.message) - .setNegativeButton(activity.getString(R.string.action_close), null) - .setPositiveButton(activity.getString(R.string.update_open_github), (dialog, which) -> openReleases()) - .show(); - } + private void finishUpdate(UpdateInstaller.Result result) { + dismissProgress(); + if (result.needsPermission) { + UpdateInstaller.waitingForPermission(activity, true); + try { + activity.startActivityForResult(UpdateInstaller.unknownSourcesIntent(activity), REQ_INSTALL_PERMISSION); + } catch (Exception exception) { + UpdateInstaller.waitingForPermission(activity, false); + activity.toast(activity.getString(R.string.update_permission_help)); } - }; - if (release == null) UpdateInstaller.resumeInstall(activity, callback); - else UpdateInstaller.downloadAndInstall(activity, release, callback); + } else if (result.success) { + activity.toast(result.message); + } else { + new AlertDialog.Builder(activity) + .setTitle(R.string.update_install_error) + .setMessage(result.message) + .setNegativeButton(R.string.action_close, null) + .setPositiveButton(R.string.update_open_github, (dialog, which) -> openReleases()) + .show(); + } + } + + private static final class ProgressCallback implements UpdateInstaller.Callback { + private final WeakReference reference; + + ProgressCallback(UpdateUi ui) { + reference = new WeakReference<>(ui); + } + + private UpdateUi current() { + UpdateUi ui = reference.get(); + if (ui == null || ui.progressDialog == null || ui.activity.isFinishing() || ui.activity.isDestroyed()) return null; + return ui; + } + + @Override public void onProgress(int percent) { + UpdateUi ui = current(); + if (ui == null) return; + ui.progressBar.setProgress(percent); + ui.progressStatus.setText(ui.activity.getString(R.string.update_download_progress, percent)); + } + + @Override public void onStatus(String message) { + UpdateUi ui = current(); + if (ui == null) return; + ui.progressBar.setIndeterminate(true); + ui.progressStatus.setText(message); + } + + @Override public void onFinished(UpdateInstaller.Result result) { + UpdateUi ui = current(); + if (ui != null) ui.finishUpdate(result); + } } private void openReleases() { diff --git a/app/src/main/res/values/update_strings.xml b/app/src/main/res/values/update_strings.xml index 2e77613..145bfe9 100644 --- a/app/src/main/res/values/update_strings.xml +++ b/app/src/main/res/values/update_strings.xml @@ -20,4 +20,5 @@ Opening the system installer… Close Updates + Downloading update… %1$d%% From e8ea4fe307eb38f2410912cf4f2b14af4010ae45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lio?= <150526913+AurelioMo@users.noreply.github.com> Date: Fri, 27 Nov 2026 08:12:50 -0300 Subject: [PATCH 12/12] Move catalog loading off the UI thread and refine app motion Co-Authored-By: Claude Opus 5.5 --- .../aureliomo/prismlock/ArtworkPreview.java | 74 +++++++----- .../github/aureliomo/prismlock/Catalog.java | 2 +- .../prismlock/CatalogCollection.java | 112 +++++++++++++----- .../aureliomo/prismlock/CatalogScreen.java | 41 +++---- .../aureliomo/prismlock/MainActivity.java | 4 +- .../aureliomo/prismlock/ThumbnailLoader.java | 1 + .../github/aureliomo/prismlock/UiMotion.java | 38 ++++-- .../aureliomo/prismlock/UpdateInstaller.java | 2 +- .../aureliomo/prismlock/WallpaperLoader.java | 5 +- app/src/main/res/anim/preview_enter.xml | 8 ++ app/src/main/res/anim/preview_exit.xml | 5 + app/src/main/res/animator/ui_press_scale.xml | 18 +++ .../interpolator/ui_emphasized_decelerate.xml | 3 + app/src/main/res/values/styles.xml | 4 + .../aureliomo/prismlock/ArtworkTest.java | 13 +- .../prismlock/CatalogFamiliesTest.java | 4 +- 16 files changed, 237 insertions(+), 97 deletions(-) create mode 100644 app/src/main/res/anim/preview_enter.xml create mode 100644 app/src/main/res/anim/preview_exit.xml create mode 100644 app/src/main/res/animator/ui_press_scale.xml create mode 100644 app/src/main/res/interpolator/ui_emphasized_decelerate.xml diff --git a/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java b/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java index 555cbf1..018aef1 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/ArtworkPreview.java @@ -14,6 +14,7 @@ import java.util.concurrent.ThreadPoolExecutor; final class ArtworkPreview extends View { + private static final int MAX_RETAINED_BYTES = 12 * 1024 * 1024; private static final ThreadPoolExecutor LOADER = AppWorkers.serial("prismlock-preview"); private static final android.os.Handler MAIN = new android.os.Handler(android.os.Looper.getMainLooper()); private Future loading; @@ -50,25 +51,17 @@ void loadCatalog() { textPaint.setTextAlign(Paint.Align.CENTER); textPaint.setTextSize(activity.dp(13)); textPaint.setTypeface(activity.catalogScreen.bodyTypeface()); + boolean lightTheme = !Appearance.isDark(activity); String tag = activity.preferences().getBoolean("enabled", true) ? activity.preferences().getString("icons".equals(category) ? "icon" : "animation", "") : ""; - if (!tag.isEmpty()) { - try { tag = Catalog.resolve(activity, category, tag); } - catch (Exception ignored) { } - } String slot = importSlot(); - String file = tag.isEmpty() ? "" : category + "_" + tag + ".json"; - if (!tag.isEmpty() && "icons".equals(category)) { - try { - boolean lightTheme = !Appearance.isDark(activity); - file = category + "_" + Catalog.iconTag(activity, tag, lightTheme ? "light" : "dark") + ".json"; - } catch (Exception exception) { - file = category + "_" + tag + ".json"; - } + String importKind = slot.isEmpty() ? "" : activity.importKind(slot); + String identity = slot.isEmpty() ? tag : slot + ":" + importKind + ":" + activity.preferences().getLong("ver", 0); + if (identity.equals(requested)) { + if (images != null) sizeToImages(images); + invalidate(); + return; } - final String previewFile = file; - String identity = slot.isEmpty() ? file : slot + ":" + activity.importKind(slot) + ":" + activity.preferences().getLong("ver", 0); - if (identity.equals(requested)) { invalidate(); return; } requested = identity; final long request = ++generation; cancelLoading(); @@ -80,7 +73,7 @@ void loadCatalog() { try { PreviewImages next; if (!slot.isEmpty()) { - if (!"png".equals(activity.importKind(slot))) { + if (!"png".equals(importKind)) { if (request == generation && identity.equals(requested)) { status = "Imported Lottie - preview unavailable"; postInvalidate(); @@ -93,7 +86,10 @@ void loadCatalog() { next = new PreviewImages(decoded, new double[]{-bitmap.getWidth() / 2.0, -bitmap.getHeight() / 2.0, bitmap.getWidth() / 2.0, bitmap.getHeight() / 2.0}, 30); } else { - JSONObject document = new JSONObject(Catalog.read(activity, previewFile)); + String resolved = "icons".equals(category) + ? Catalog.iconTag(activity, tag, lightTheme ? "light" : "dark") + : Catalog.resolve(activity, category, tag); + JSONObject document = new JSONObject(Catalog.read(activity, category + "_" + resolved + ".json")); org.json.JSONArray assets = document.getJSONArray("assets"); org.json.JSONArray bounds = document.getJSONArray("catalogBounds"); Bitmap[] frames = new Bitmap[assets.length()]; @@ -123,18 +119,7 @@ void loadCatalog() { } started = SystemClock.uptimeMillis(); images = ready; - double scale = CatalogScale.percent(category, activity.fingerprintSize(), - ready.bounds[2] - ready.bounds[0], ready.bounds[3] - ready.bounds[1]) / 100; - double extent = 288; - for (Bitmap bitmap : ready.frames) { - extent = Math.max(extent, Math.max(bitmap.getWidth() + Math.abs(ready.bounds[0] + ready.bounds[2]), - bitmap.getHeight() + Math.abs(ready.bounds[1] + ready.bounds[3])) * scale); - } - android.view.ViewGroup.LayoutParams layout = getLayoutParams(); - if (layout != null) { - layout.height = activity.dp((int) Math.ceil(132 * extent / 288)); - setLayoutParams(layout); - } + sizeToImages(ready); status = ""; invalidate(); }); @@ -145,6 +130,24 @@ void loadCatalog() { }); } + private void sizeToImages(PreviewImages ready) { + double scale = CatalogScale.percent(category, activity.fingerprintSize(), + ready.bounds[2] - ready.bounds[0], ready.bounds[3] - ready.bounds[1]) / 100; + double extent = 288; + for (Bitmap bitmap : ready.frames) { + extent = Math.max(extent, Math.max(bitmap.getWidth() + Math.abs(ready.bounds[0] + ready.bounds[2]), + bitmap.getHeight() + Math.abs(ready.bounds[1] + ready.bounds[3])) * scale); + } + android.view.ViewGroup.LayoutParams layout = getLayoutParams(); + if (layout != null) { + int height = activity.dp((int) Math.ceil(132 * extent / 288)); + if (layout.height != height) { + layout.height = height; + setLayoutParams(layout); + } + } + } + private static void recycleUnpublished(Bitmap[] frames) { if (frames == null) return; for (Bitmap frame : frames) if (frame != null && !frame.isRecycled()) frame.recycle(); @@ -165,15 +168,18 @@ private void cancelLoading() { @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); + started = SystemClock.uptimeMillis(); loadCatalog(); } @Override protected void onDetachedFromWindow() { ++generation; cancelLoading(); - requested = ""; - images = null; - status = ""; + if (images == null || images.bytes > MAX_RETAINED_BYTES) { + requested = ""; + images = null; + status = ""; + } super.onDetachedFromWindow(); } @@ -225,9 +231,13 @@ private static final class PreviewImages { final double[] bounds; final double fps; final int[] opacity; + final long bytes; PreviewImages(Bitmap[] frames, double[] bounds, double fps) { this.frames = frames; + long size = 0; + for (Bitmap frame : frames) size += frame.getAllocationByteCount(); + bytes = size; this.bounds = bounds; this.fps = fps; this.opacity = new int[frames.length]; diff --git a/app/src/main/java/io/github/aureliomo/prismlock/Catalog.java b/app/src/main/java/io/github/aureliomo/prismlock/Catalog.java index b2eadef..07d5fd0 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/Catalog.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/Catalog.java @@ -34,7 +34,7 @@ final class Catalog { } }); - private static CatalogIndex index(Context context) throws Exception { + static CatalogIndex index(Context context) throws Exception { CatalogIndex current = cachedIndex; if (current != null) return current; synchronized (Catalog.class) { diff --git a/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java b/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java index 19f89e5..317d7fd 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/CatalogCollection.java @@ -1,6 +1,8 @@ package io.github.aureliomo.prismlock; import android.app.Activity; +import android.os.Handler; +import android.os.Looper; import android.graphics.Color; import android.graphics.drawable.GradientDrawable; import android.view.Gravity; @@ -14,17 +16,46 @@ import android.widget.ListView; import android.widget.BaseAdapter; import java.util.ArrayList; +import java.util.concurrent.Executor; import java.util.List; final class CatalogCollection { + private static final Executor LOADER = AppWorkers.serial("prismlock-catalog"); + private static final Handler MAIN = new Handler(Looper.getMainLooper()); + private final Activity activity; private final CatalogScreen screen; private final Runnable selectionChanged; + private final CatalogAdapter[] adapters = new CatalogAdapter[2]; + private CatalogIndex index; + private boolean loadFailed; CatalogCollection(Activity activity, CatalogScreen screen, Runnable selectionChanged) { this.activity = activity; this.screen = screen; this.selectionChanged = selectionChanged; + android.content.Context app = activity.getApplicationContext(); + LOADER.execute(() -> { + CatalogIndex loaded; + try { + loaded = Catalog.index(app); + } catch (Exception failure) { + MAIN.post(() -> { + loadFailed = true; + if (!activity.isDestroyed() && !activity.isFinishing()) reportLoadFailure(); + }); + return; + } + MAIN.post(() -> { + if (activity.isDestroyed() || activity.isFinishing()) return; + index = loaded; + for (CatalogAdapter adapter : adapters) if (adapter != null) adapter.populate(loaded); + }); + }); + } + + private void reportLoadFailure() { + android.widget.Toast.makeText(activity, R.string.catalog_load_error, android.widget.Toast.LENGTH_LONG).show(); } ListView create(int tab, ViewOutlineProvider outline) { @@ -52,14 +83,17 @@ ListView create(int tab, ViewOutlineProvider outline) { } list.addHeaderView(header, null, false); CatalogAdapter adapter = new CatalogAdapter(tab); + adapters[tab] = adapter; + if (index != null) adapter.populate(index); + else if (loadFailed) reportLoadFailure(); list.setAdapter(adapter); list.setOnItemClickListener((parent, view, position, id) -> { int index = position - list.getHeaderViewsCount(); if (index < 0 || index >= adapter.getCount()) return; String family = adapter.tags.get(index); - List styles = adapter.styles.get(family); + List styles = adapter.styles.get(index); if (styles == null || styles.size() < 2) { - adapter.select(family, family, (Row) view, list); + adapter.select(family, family, list); return; } String[] labels = new String[styles.size()]; @@ -70,7 +104,7 @@ ListView create(int tab, ViewOutlineProvider outline) { } new android.app.AlertDialog.Builder(activity).setTitle(Catalog.title(family)) .setSingleChoiceItems(labels, selected, (dialog, which) -> { - adapter.select(family, styles.get(which).tag, (Row) view, list); + adapter.select(family, styles.get(which).tag, list); dialog.dismiss(); }).setNegativeButton(R.string.action_cancel, null).show(); }); @@ -81,24 +115,31 @@ private final class CatalogAdapter extends BaseAdapter { final List tags = new ArrayList<>(); final String kind, key; String selectedFamily, selectedArtwork; - final java.util.Map> styles = new java.util.HashMap<>(); + final List names = new ArrayList<>(); + final List> styles = new ArrayList<>(); + CatalogAdapter(int tab) { kind = tab == 0 ? "icons" : "animations"; key = tab == 0 ? "icon" : "animation"; - String selected = activity.getSharedPreferences(MainActivity.PREFS, 0).getString(key, ""); - tags.add(""); - try { - tags.addAll(Catalog.tags(activity, kind)); - selectedFamily = Catalog.family(activity, kind, selected); - selectedArtwork = Catalog.resolve(activity, kind, selected); - for (String tag : tags) styles.put(tag, Catalog.styles(activity, kind, tag)); - } - catch (Exception failure) { - android.widget.Toast.makeText(activity, activity.getString(R.string.catalog_load_error), - android.widget.Toast.LENGTH_LONG).show(); - } + addRow("", java.util.Collections.emptyList()); + selectedArtwork = activity.getSharedPreferences(MainActivity.PREFS, 0).getString(key, ""); + selectedFamily = selectedArtwork; } - void select(String family, String tag, Row row, ListView list) { + + void populate(CatalogIndex index) { + selectedFamily = index.family(kind, selectedArtwork); + selectedArtwork = index.resolve(kind, selectedArtwork); + for (String tag : index.tags(kind)) addRow(tag, index.styles(kind, tag)); + notifyDataSetChanged(); + } + + private void addRow(String tag, List choices) { + tags.add(tag); + names.add(tag.isEmpty() ? activity.getString(R.string.catalog_samsung_default) : Catalog.title(tag)); + styles.add(choices); + } + + void select(String family, String tag, ListView list) { String previousFamily = selectedFamily; SettingsStore.select(activity.getSharedPreferences(MainActivity.PREFS, 0), key, tag); selectedArtwork = tag; @@ -109,10 +150,12 @@ void select(String family, String tag, Row row, ListView list) { String visibleTag = tags.get(position); View visible = list.getChildAt(child); if (visible instanceof Row && (visibleTag.equals(previousFamily) || visibleTag.equals(family))) { - getView(position, visible, list); + bind(position, (Row) visible); + if (visibleTag.equals(family) && !family.equals(previousFamily)) { + UiMotion.confirmSelection(((Row) visible).check); + } } } - UiMotion.settle(row.thumbnail); selectionChanged.run(); } @Override public int getCount() { return tags.size(); } @@ -121,11 +164,16 @@ void select(String family, String tag, Row row, ListView list) { @Override public boolean hasStableIds() { return true; } @Override public View getView(int position, View recycled, ViewGroup parent) { Row row = recycled instanceof Row ? (Row) recycled : new Row(); + bind(position, row); + return row; + } + + private void bind(int position, Row row) { String tag = tags.get(position); boolean checked = tag.equals(selectedFamily); - String name = tag.isEmpty() ? activity.getString(R.string.catalog_samsung_default) : Catalog.title(tag); + String name = names.get(position); row.label.setText(name); - List choices = styles.get(tag); + List choices = styles.get(position); String detail = ""; if (choices != null && choices.size() > 1) { detail = activity.getResources().getQuantityString(R.plurals.catalog_styles, choices.size(), choices.size()); @@ -135,14 +183,11 @@ void select(String family, String tag, Row row, ListView list) { } row.detail.setText(detail); row.detail.setVisibility(detail.isEmpty() ? View.INVISIBLE : View.VISIBLE); + UiMotion.reset(row.check); row.check.setVisibility(checked ? View.VISIBLE : View.INVISIBLE); row.setSelected(checked); row.setContentDescription(name + (detail.isEmpty() ? "" : ", " + detail) + (checked ? ", selected" : "")); - float top = position == 0 ? screen.dp(24) : 0, bottom = position == getCount() - 1 ? screen.dp(24) : 0; - GradientDrawable background = new GradientDrawable(); - background.setColor(screen.panel); - background.setCornerRadii(new float[]{top, top, top, top, bottom, bottom, bottom, bottom}); - row.setBackground(background); + row.setCorners(position == 0, position == getCount() - 1); if (tag.isEmpty()) { row.thumbnail.setTag(null); row.thumbnail.setImageDrawable(screen.symbol("icons".equals(kind) ? "fingerprint" : "animation", screen.foreground)); @@ -151,7 +196,6 @@ void select(String family, String tag, Row row, ListView list) { row.thumbnail.setPadding(screen.dp(4), screen.dp(4), screen.dp(4), screen.dp(4)); ThumbnailLoader.load(activity, "previews/" + kind + "_" + (checked ? selectedArtwork : tag) + ".png", row.thumbnail, screen.dp(36)); } - return row; } } @@ -160,12 +204,26 @@ private final class Row extends LinearLayout { final TextView label = screen.text("", 16, 600, screen.foreground); final TextView detail = screen.text("", 13, 400, screen.muted); final ImageView check = new ImageView(activity); + final GradientDrawable background = new GradientDrawable(); + int corners = -1; + + void setCorners(boolean first, boolean last) { + int shape = (first ? 1 : 0) | (last ? 2 : 0); + if (shape == corners) return; + corners = shape; + float top = first ? screen.dp(24) : 0; + float bottom = last ? screen.dp(24) : 0; + background.setCornerRadii(new float[]{top, top, top, top, bottom, bottom, bottom, bottom}); + } + Row() { super(activity); setGravity(Gravity.CENTER_VERTICAL); setPadding(screen.dp(16), screen.dp(12), screen.dp(16), screen.dp(12)); setMinimumHeight(screen.dp(76)); setForeground(screen.ripple(Color.TRANSPARENT, 0)); + background.setColor(screen.panel); + setBackground(background); thumbnail.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); check.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); thumbnail.setBackground(screen.round(screen.dark ? 0xFF3B4049 : 0xFFE6EBF2, 14)); diff --git a/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java b/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java index 89ee5b2..d54e919 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/CatalogScreen.java @@ -35,15 +35,12 @@ final class CatalogScreen { final int accent; final int panel; private final LinearLayout content; - private final TextView title; private final ScrollView scroll; private final FrameLayout pages; private final ListView[] collections = new ListView[2]; private final ImageView importAction; private final LinearLayout[] tabs = new LinearLayout[3]; - private LinearLayout settings; private int selectedTab; - private int settingsScrollPosition; CatalogScreen(Activity activity, Runnable importFile, Runnable selectionChanged, int initialTab) { this.activity = activity; @@ -112,7 +109,7 @@ final class CatalogScreen { scroll.setVerticalScrollBarEnabled(false); LinearLayout document = column(); document.setPadding(0, 0, 0, dp(16)); - title = text("", 32, 700, foreground); + TextView title = text(activity.getString(R.string.catalog_settings), 32, 700, foreground); heading(title); title.setPadding(dp(8), dp(8), dp(8), dp(16)); document.addView(title); @@ -142,6 +139,7 @@ final class CatalogScreen { tab.setContentDescription(labelText); tab.setFocusable(true); tab.setBackground(ripple(Color.TRANSPARENT, 20)); + UiMotion.pressFeedback(tab); ImageView icon = new ImageView(activity); icon.setImageDrawable(symbol(TAB_ICONS[index], muted)); icon.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); @@ -153,9 +151,9 @@ final class CatalogScreen { tab.addView(label); tab.setOnClickListener(view -> { if (selectedTab == destination) return; - if (selectedTab == 2) settingsScrollPosition = scroll.getScrollY(); + int previous = selectedTab; selectedTab = destination; - render(); + render(previous); }); tabs[index] = tab; navigation.addView(tab, new LinearLayout.LayoutParams(0, dp(58), 1)); @@ -168,8 +166,8 @@ final class CatalogScreen { } void setSettings(LinearLayout settings) { - this.settings = settings; - render(); + content.addView(settings); + render(-1); } int currentTab() { @@ -229,6 +227,7 @@ void settingAction(LinearLayout parent, int name, String subtitle, Runnable acti ImageView chevron = new ImageView(activity); chevron.setImageDrawable(symbol("chevron", muted)); row.addView(chevron, new LinearLayout.LayoutParams(dp(20), dp(20))); + UiMotion.pressFeedback(row); row.setOnClickListener(view -> action.run()); parent.addView(row); } @@ -247,6 +246,7 @@ TextView settingValue(LinearLayout parent, int name, String value, Runnable acti ImageView chevron = new ImageView(activity); chevron.setImageDrawable(symbol("chevron", muted)); row.addView(chevron, new LinearLayout.LayoutParams(dp(18), dp(18))); + UiMotion.pressFeedback(row); row.setOnClickListener(view -> action.run()); parent.addView(row); return detail; @@ -290,30 +290,30 @@ void settingToggle(LinearLayout parent, String label, String description, boolea parent.addView(row); } - private void render() { - content.removeAllViews(); - title.setText(TAB_LABELS[selectedTab]); + private void render(int previous) { importAction.setVisibility(selectedTab == 0 ? View.VISIBLE : View.INVISIBLE); for (int index = 0; index < tabs.length; index++) { boolean selected = index == selectedTab; + if (previous >= 0 && index != previous && !selected) continue; tabs[index].setSelected(selected); - ((ImageView) tabs[index].getChildAt(0)).setImageDrawable( - symbol(TAB_ICONS[index], selected ? foreground : muted)); - ((TextView) tabs[index].getChildAt(1)).setTextColor(selected ? foreground : muted); + int color = selected ? foreground : muted; + ((ImageView) tabs[index].getChildAt(0)).getDrawable().setTint(color); + ((TextView) tabs[index].getChildAt(1)).setTextColor(color); tabs[index].setAlpha(selected ? 1 : 0.7f); } + if (previous >= 0) UiMotion.reset(previous == 2 ? scroll : collections[previous]); scroll.setVisibility(selectedTab == 2 ? View.VISIBLE : View.GONE); for (int i = 0; i < collections.length; i++) { if (collections[i] != null) collections[i].setVisibility(i == selectedTab ? View.VISIBLE : View.GONE); } - if (selectedTab == 2) { - if (settings.getParent() instanceof ViewGroup) ((ViewGroup) settings.getParent()).removeView(settings); - content.addView(settings); - scroll.post(() -> scroll.scrollTo(0, settingsScrollPosition)); - } else if (collections[selectedTab] == null) { + if (selectedTab != 2 && collections[selectedTab] == null) { collections[selectedTab] = collection.create(selectedTab, scroll.getOutlineProvider()); pages.addView(collections[selectedTab], new FrameLayout.LayoutParams(-1, -1)); } + if (previous >= 0) { + View page = selectedTab == 2 ? scroll : collections[selectedTab]; + UiMotion.enterTab(page, Integer.signum(selectedTab - previous), dp(14)); + } } private static Typeface weight(Typeface family, int weight) { @@ -331,6 +331,7 @@ private ImageView action(String symbol, String label, Runnable action) { result.setPadding(dp(12), dp(12), dp(12), dp(12)); result.setContentDescription(label); result.setBackground(ripple(Color.TRANSPARENT, 24)); + UiMotion.pressFeedback(result); result.setOnClickListener(view -> action.run()); return result; } @@ -344,7 +345,7 @@ GradientDrawable round(int color, int radius) { Drawable ripple(int color, int radius) { return new RippleDrawable(ColorStateList.valueOf(dark ? 0x22FFFFFF : 0x18000000), - round(color, radius), round(Color.WHITE, radius)); + color == Color.TRANSPARENT ? null : round(color, radius), round(Color.WHITE, radius)); } int dp(int value) { diff --git a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java index fd44660..7de1461 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/MainActivity.java @@ -140,9 +140,9 @@ void showPreview() { scroll.addView(body); AlertDialog dialog = new AlertDialog.Builder(this).setView(scroll) .setPositiveButton("Close", null).create(); - dialog.show(); dialog.getWindow().setBackgroundDrawable(catalogScreen.dialogBackground()); - refresh(); + dialog.getWindow().setWindowAnimations(R.style.PrismLockPreviewMotion); + dialog.show(); } private void addPreviewCard(LinearLayout parent, String heading, String key, ArtworkPreview view) { diff --git a/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java b/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java index 9e72ea3..b50c919 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/ThumbnailLoader.java @@ -31,6 +31,7 @@ static void load(Context context, String filename, ImageView target, int pixels) String key = filename + ":" + size; Bitmap cached = CACHE.get(key); if (cached != null) { + if (key.equals(target.getTag()) && target.getDrawable() != null) return; target.setTag(key); target.setImageBitmap(cached); return; diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java b/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java index e117666..f0ff201 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/UiMotion.java @@ -25,17 +25,33 @@ static void configureRefresh(android.app.Activity activity) { activity.getWindow().setAttributes(attributes); } - static void settle(View view) { + static void reset(View view) { view.animate().cancel(); - if (!ValueAnimator.areAnimatorsEnabled()) { - view.setAlpha(1); - view.setScaleX(1); - view.setScaleY(1); - return; - } - view.setAlpha(0.75f); - view.setScaleX(0.96f); - view.setScaleY(0.96f); - view.animate().alpha(1).scaleX(1).scaleY(1).setDuration(180).setInterpolator(EASE).start(); + view.setAlpha(1); + view.setScaleX(1); + view.setScaleY(1); + view.setTranslationX(0); + } + + static void enterTab(View view, int direction, int offset) { + reset(view); + if (!ValueAnimator.areAnimatorsEnabled()) return; + int layoutDirection = view.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL ? -1 : 1; + view.setTranslationX(direction * offset * layoutDirection); + view.setAlpha(0.72f); + view.animate().translationX(0).alpha(1).setDuration(240).setInterpolator(EASE).start(); + } + + static void confirmSelection(View check) { + if (!ValueAnimator.areAnimatorsEnabled()) return; + check.setAlpha(0); + check.setScaleX(0.88f); + check.setScaleY(0.88f); + check.animate().alpha(1).scaleX(1).scaleY(1).setDuration(220).setInterpolator(EASE).start(); + } + + static void pressFeedback(View view) { + view.setStateListAnimator(android.animation.AnimatorInflater.loadStateListAnimator( + view.getContext(), R.animator.ui_press_scale)); } } diff --git a/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java b/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java index cbf43ff..a995d81 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/UpdateInstaller.java @@ -162,7 +162,7 @@ static Intent unknownSourcesIntent(Context context) { static void waitingForPermission(Context context, boolean waiting) { context.getSharedPreferences(MainActivity.PREFS, 0).edit() - .putBoolean(WAITING_PERMISSION, waiting).commit(); + .putBoolean(WAITING_PERMISSION, waiting).apply(); } static boolean takePermissionResume(Context context) { diff --git a/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java b/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java index b65ee34..0c1127d 100644 --- a/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java +++ b/app/src/main/java/io/github/aureliomo/prismlock/WallpaperLoader.java @@ -51,7 +51,10 @@ static void load(Context context, ImageView target, boolean dark) { Bitmap result = current.bitmap; MAIN.post(() -> { ImageView view = reference.get(); - if (view != null && key.equals(view.getTag())) view.setImageBitmap(result); + if (view != null && key.equals(view.getTag())) { + view.setImageBitmap(result); + view.setBackground(null); + } }); }); } diff --git a/app/src/main/res/anim/preview_enter.xml b/app/src/main/res/anim/preview_enter.xml new file mode 100644 index 0000000..9ba6bd4 --- /dev/null +++ b/app/src/main/res/anim/preview_enter.xml @@ -0,0 +1,8 @@ + + + + diff --git a/app/src/main/res/anim/preview_exit.xml b/app/src/main/res/anim/preview_exit.xml new file mode 100644 index 0000000..8b50456 --- /dev/null +++ b/app/src/main/res/anim/preview_exit.xml @@ -0,0 +1,5 @@ + + + diff --git a/app/src/main/res/animator/ui_press_scale.xml b/app/src/main/res/animator/ui_press_scale.xml new file mode 100644 index 0000000..2b3d844 --- /dev/null +++ b/app/src/main/res/animator/ui_press_scale.xml @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + diff --git a/app/src/main/res/interpolator/ui_emphasized_decelerate.xml b/app/src/main/res/interpolator/ui_emphasized_decelerate.xml new file mode 100644 index 0000000..5ef881f --- /dev/null +++ b/app/src/main/res/interpolator/ui_emphasized_decelerate.xml @@ -0,0 +1,3 @@ + diff --git a/app/src/main/res/values/styles.xml b/app/src/main/res/values/styles.xml index dbc2cb1..9b87a4e 100644 --- a/app/src/main/res/values/styles.xml +++ b/app/src/main/res/values/styles.xml @@ -14,4 +14,8 @@ + diff --git a/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java b/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java index f017eae..7037319 100644 --- a/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java +++ b/app/src/test/java/io/github/aureliomo/prismlock/ArtworkTest.java @@ -74,6 +74,17 @@ private static void awaitClear(Context app, boolean reset) throws InterruptedExc assertNull(error.get()); } + static void awaitCatalogRows(android.widget.ListView list, int expected) throws InterruptedException { + long deadline = System.nanoTime() + java.util.concurrent.TimeUnit.SECONDS.toNanos(30); + var main = org.robolectric.Shadows.shadowOf(android.os.Looper.getMainLooper()); + while (list.getAdapter().getCount() != expected && System.nanoTime() < deadline) { + main.idle(); + Thread.sleep(10); + } + main.idle(); + assertEquals(expected, list.getAdapter().getCount()); + } + private static android.view.View findDescription(android.view.View view, String name) { if (name.contentEquals(view.getContentDescription() == null ? "" : view.getContentDescription())) return view; if (view instanceof android.view.ViewGroup) { @@ -93,7 +104,7 @@ private static android.view.View findDescription(android.view.View view, String var field = CatalogScreen.class.getDeclaredField("collections"); field.setAccessible(true); android.widget.ListView[] lists = (android.widget.ListView[]) field.get(activity.catalogScreen); android.widget.ListView icons = lists[0]; - assertEquals(Catalog.tags(activity, "icons").size() + 2, icons.getAdapter().getCount()); + awaitCatalogRows(icons, Catalog.tags(activity, "icons").size() + 2); android.widget.ListAdapter adapter = icons.getAdapter(); android.view.View row = adapter.getView(1, null, icons); android.view.View recycled = adapter.getView(2, row, icons); diff --git a/app/src/test/java/io/github/aureliomo/prismlock/CatalogFamiliesTest.java b/app/src/test/java/io/github/aureliomo/prismlock/CatalogFamiliesTest.java index 610c70c..c6f6b66 100644 --- a/app/src/test/java/io/github/aureliomo/prismlock/CatalogFamiliesTest.java +++ b/app/src/test/java/io/github/aureliomo/prismlock/CatalogFamiliesTest.java @@ -75,7 +75,9 @@ public class CatalogFamiliesTest { try (var controller = Robolectric.buildActivity(MainActivity.class).setup().visible()) { MainActivity activity = controller.get(); ListView list = collection(activity, 0); - int position = Catalog.tags(app, "icons").indexOf("white") + 2; + List tags = Catalog.tags(app, "icons"); + ArtworkTest.awaitCatalogRows(list, tags.size() + 2); + int position = tags.indexOf("white") + 2; View row = list.getAdapter().getView(position, null, list); assertTrue(row.isSelected()); list.performItemClick(row, position, position);