diff --git a/Android.bp b/Android.bp index 4eb4110..a439960 100644 --- a/Android.bp +++ b/Android.bp @@ -1,5 +1,5 @@ // -// Copyright (C) 2023 The Evolution X Project +// Copyright (C) 2023-2024 The Evolution X Project // SPDX-License-Identifier: Apache-2.0 // @@ -8,28 +8,20 @@ android_app { defaults: [ "SettingsLibDefaults", ], - srcs: [ - "src/**/*.java", - "src/**/*.kt", - ], + + srcs: ["src/**/*.java"], + resource_dirs: ["res"], certificate: "platform", platform_apis: true, system_ext_specific: true, privileged: true, + static_libs: [ "androidx.core_core", "androidx.preference_preference", - "particles", ], - resource_dirs: ["res"], + optimize: { proguard_flags_files: ["proguard.flags"], }, } - -java_import { - name: "particles", - jars: [ - "libs/LeonidsLib.jar", - ], -} diff --git a/AndroidManifest.xml b/AndroidManifest.xml index d46beb6..3765c9c 100644 --- a/AndroidManifest.xml +++ b/AndroidManifest.xml @@ -1,6 +1,6 @@ @@ -8,11 +8,8 @@ xmlns:tools="http://schemas.android.com/tools" android:sharedUserId="android.uid.system" package="org.evolution.pixelparts" - android:versionCode="1" - android:versionName="1.0" > - - - + android:versionCode="2" + android:versionName="2.0" > - - - - - - - - - - - - - @@ -58,87 +32,61 @@ - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + - - + + + - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - + + + + + + + + + + + diff --git a/PixelParts.png b/PixelParts.png deleted file mode 100644 index ca18f95..0000000 Binary files a/PixelParts.png and /dev/null differ diff --git a/README.md b/README.md index 12130f7..df1f405 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ -![example](https://raw.githubusercontent.com/Evolution-X-Devices/packages_apps_PixelParts/tiramisu/PixelParts.png) +![example](https://raw.githubusercontent.com/Evolution-X-Devices/packages_apps_PixelParts/udc/readme_resources/PixelParts.png) ## About the app @@ -8,15 +8,12 @@ PixelParts began as a simple High Brightness Mode (HBM) tool. Since then, it has | Category | Feature | Description | QS Tile | Required kernel changes | | --- | --- | --- | --- | --- | -| **Battery** | `Battery info` | View various battery information | N/A |N/A | -| | `Start/Stop charging` | Start/stop charging at specific percentages | N/A | N/A | -| **Display** | `High brightness mode (HBM)` | Enable peak luminance. | Yes | N/A | -| | `Automatic HBM` | Enable peak luminance based on sunlight | Yes | N/A | -| | `Saturation` | Control the saturation level of the display | N/A | N/A | -| **Leds** | `Torch strength` | Adjust the brightness of the PixelParts flashlight QS-Tile | PixelParts Flashlight QS | N/A | -| **Ui-Bench** | `Jitter` | Calculate rendering jitter. | N/A | N/A | -| **USB** | `USB 2.0 fast charge` | Enable CDP mode for faster charging on USB 2.0 ports. | Yes | [Commit 1/1](https://github.com/Evolution-X-Devices/kernel_google_gs101/commit/dcbfcd76bdc5d72e16f85fd8a48de6afa8804b61) | - +| **Battery** | `Battery information` | View various battery information | Yes |N/A | +| | `Charge control` | Start/stop charging at specific percentages | N/A | N/A | +| | `Fast charge` | Enable CDP mode for faster charging on USB 2.0 ports. | Yes | [Commit 1/1](https://github.com/Evolution-X-Devices/kernel_google_gs101/commit/dcbfcd76bdc5d72e16f85fd8a48de6afa8804b61) | +| **Display** | `Automatic high brightness mode (HBM)` | Enable peak luminance based on sunlight | Yes | N/A | +| | `Saturation` | Control the saturation level of the display | Yes | N/A | +| **Leds** | `Pixel torch` | Adjust the brightness of the PixelParts flashlight QS-Tile | PixelParts Flashlight QS | N/A | ## Including PixelParts @@ -41,7 +38,7 @@ croot && git clone https://github.com/Evolution-X-Devices/packages_apps_PixelPar include packages/apps/PixelParts/device.mk ``` -This line includes the [device.mk](https://github.com/Evolution-X-Devices/packages_apps_PixelParts/blob/tiramisu/device.mk) file from the PixelParts repository, which will add the PixelParts application, its initialization script (init.rc), and the necessary security policies (sepolicies) to your AOSP build during compilation. +This line includes the [device.mk](https://github.com/Evolution-X-Devices/packages_apps_PixelParts/blob/udc/device.mk) file from the PixelParts repository, which will add the PixelParts application, its initialization script (init.rc), and the necessary security policies (sepolicies) to your AOSP build during compilation. ## Testing changes @@ -54,19 +51,9 @@ m PixelParts ``` - This also assumes you are already running an AOSP build including PixelParts as a priv-app in /system_ext. -## Screenshots -![screenshots_1](https://raw.githubusercontent.com/Evolution-X-Devices/packages_apps_PixelParts/tiramisu/screenshots_1.png) - -![screenshots_2](https://raw.githubusercontent.com/Evolution-X-Devices/packages_apps_PixelParts/tiramisu/screenshots_2.png) - - ## Credits -| Work | Author | +| Work | Author | | ----------------------------------------------------------- | --------------------------------------------------------------------------- | -| Base preference fragment & CustomSeekBar preference | [Neobuddy89](https://forum.xda-developers.com/m/neobuddy89.3795148/) | +| CustomSeekBar preference | [Neobuddy89](https://forum.xda-developers.com/m/neobuddy89.3795148/) | | Original AutoHBMService | [Hikari no Tenshi](https://forum.xda-developers.com/m/hikari-no-tenshi.4337348/) & [maxwen](https://forum.xda-developers.com/m/maxwen.4683552/) | -| ShakeUtils | [AmeChanRain](https://github.com/AmeChanRain) | -| First launch warning dialog | [Ramyski](https://forum.xda-developers.com/m/ramyski.8538037/) | -| Leonids particle system | [Plattysoft](https://github.com/plattysoft) | -| Randomized color particle effect | [LorD ClockaN](https://forum.xda-developers.com/m/lord-clockan.1184673/) | diff --git a/device.mk b/device.mk index 0b8bd69..06475d8 100644 --- a/device.mk +++ b/device.mk @@ -1,5 +1,5 @@ # -# Copyright (C) 2023 The Evolution X Project +# Copyright (C) 2023-2024 The Evolution X Project # # SPDX-License-Identifier: Apache-2.0 # @@ -12,5 +12,8 @@ PRODUCT_PACKAGES += \ PRODUCT_PACKAGES += \ init.pixelparts.rc +# PixelParts overlays +DEVICE_PACKAGE_OVERLAYS += packages/apps/PixelParts/overlay + # PixelParts sepolicy BOARD_SEPOLICY_DIRS += packages/apps/PixelParts/sepolicy diff --git a/init/Android.bp b/init/Android.bp index 8bdc6b5..0d22498 100644 --- a/init/Android.bp +++ b/init/Android.bp @@ -1,5 +1,5 @@ // -// Copyright (C) 2023 The Evolution X Project +// Copyright (C) 2023-2024 The Evolution X Project // SPDX-License-Identifier: Apache-2.0 // diff --git a/libs/LeonidsLib.jar b/libs/LeonidsLib.jar deleted file mode 100644 index 2713755..0000000 Binary files a/libs/LeonidsLib.jar and /dev/null differ diff --git a/overlay/packages/apps/Settings/res/values/config.xml b/overlay/packages/apps/Settings/res/values/config.xml new file mode 100644 index 0000000..39d3ddc --- /dev/null +++ b/overlay/packages/apps/Settings/res/values/config.xml @@ -0,0 +1,10 @@ + + + + + false + + diff --git a/readme_resources/PixelParts.png b/readme_resources/PixelParts.png new file mode 100644 index 0000000..cbdf862 Binary files /dev/null and b/readme_resources/PixelParts.png differ diff --git a/res/drawable/easteregg.xml b/res/drawable/easteregg.xml deleted file mode 100644 index 9c6860c..0000000 --- a/res/drawable/easteregg.xml +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - diff --git a/res/drawable/ic_hbm_tile.xml b/res/drawable/ic_auto_hbm_tile.xml similarity index 95% rename from res/drawable/ic_hbm_tile.xml rename to res/drawable/ic_auto_hbm_tile.xml index 7fa0adc..bcab34d 100644 --- a/res/drawable/ic_hbm_tile.xml +++ b/res/drawable/ic_auto_hbm_tile.xml @@ -1,4 +1,4 @@ - + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/drawable/ic_usb2_fc_tile.xml b/res/drawable/ic_fast_charge_tile.xml similarity index 92% rename from res/drawable/ic_usb2_fc_tile.xml rename to res/drawable/ic_fast_charge_tile.xml index fbbc8fa..021eb7c 100644 --- a/res/drawable/ic_usb2_fc_tile.xml +++ b/res/drawable/ic_fast_charge_tile.xml @@ -1,4 +1,4 @@ - + - - diff --git a/res/drawable/ic_pixel_parts_tile.xml b/res/drawable/ic_pixel_parts_tile.xml deleted file mode 100644 index e0027df..0000000 --- a/res/drawable/ic_pixel_parts_tile.xml +++ /dev/null @@ -1,11 +0,0 @@ - - - - diff --git a/res/drawable/ic_pixeltorch_tile.xml b/res/drawable/ic_pixel_torch_tile.xml similarity index 91% rename from res/drawable/ic_pixeltorch_tile.xml rename to res/drawable/ic_pixel_torch_tile.xml index 920c9be..a30b372 100644 --- a/res/drawable/ic_pixeltorch_tile.xml +++ b/res/drawable/ic_pixel_torch_tile.xml @@ -1,4 +1,4 @@ - + - - diff --git a/res/layout/evolution_logo.xml b/res/layout/evolution_logo.xml deleted file mode 100644 index ddfa56f..0000000 --- a/res/layout/evolution_logo.xml +++ /dev/null @@ -1,21 +0,0 @@ - - - - - - - diff --git a/res/layout/rendering_jitter.xml b/res/layout/rendering_jitter.xml deleted file mode 100644 index 5ed5f3b..0000000 --- a/res/layout/rendering_jitter.xml +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - - - - - diff --git a/res/layout/saturation.xml b/res/layout/saturation.xml index 660d7d0..aa8f98a 100644 --- a/res/layout/saturation.xml +++ b/res/layout/saturation.xml @@ -1,7 +1,7 @@ - + - - diff --git a/res/menu/pixel_parts_menu.xml b/res/menu/pixel_parts_menu.xml deleted file mode 100644 index bbcf442..0000000 --- a/res/menu/pixel_parts_menu.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - diff --git a/res/values-es-rES/strings.xml b/res/values-es-rES/strings.xml deleted file mode 100644 index be1ff48..0000000 --- a/res/values-es-rES/strings.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Ajustes del Pixel - Configurar ajustes específicos del dispositivo - Advertencia - Muchas de estas características dependen de nodos específicos del kernel para funcionar. Al flashear un kernel personalizado, podrías perder algunas características. ¡Has sido advertido! - Ok - ¡El acceso al nodo Kernel falló! Por favor, asegúrese de que la ruta proporcionada al atributo sysfs o procfs es exacta, de que tiene los permisos apropiados, y de que las políticas SELinux están correctamente configuradas. - - Batería - Información de la batería - Ver información variada de la batería - actualizar información después de (segundos) - Información disponible - Tecnología - Estado - Temperatura - Capacidad ahora - Nivel de capacidad - Actual - Voltaje - Vatiaje - Salud de la batería - Ciclos de carga - Detener la carga al - Evitar que el dispositivo cargue sobre un porcentaje específico - Comenzar la carga en porcentaje específico - Reanudar la carga en un porcentaje específico - ¡Ajuste final debe estar por encima del ajuste de inicio! - ¡Ajuste de inicio debe estar por debajo del ajuste final! - - Cámara - Linterna - Intensidad de la linterna - Ajustar el brillo de la linterna del ícono de PixelParts en los ajustes rápido - - CPU - Cola de trabajo de bajo consumo energético - Ahorre energía reprogramando tareas a un núcleo que ya está activo - - Pantalla - Modo de alto brillo (HBM) - Habilitar luminancia máxima - Modo de alto brillo automático - Habilita la iluminación máxima basada en la luz del sol - umbral (lux) - activar después de (segundos) - deshabilitar después de (segundos) - El uso prolongado del modo de brillo alto puede dañar la pantalla! - - Test de interfaz de usuario - Jitter - Cálculo de renderización de Jitter - - USB - Carga rápida USB 2.0 - Activar el modo CDP para cargar rápidamente en puertos USB 2.0 - No todos los puertos USB 2.0 soportan el modo CDP, ¡tenga cuidado! - - Valor: %s - por defecto - Valor predeterminado: %s\nMantén pulsado para establecer - \"El valor predeterminado está establecido - diff --git a/res/values-fr-rFR/strings.xml b/res/values-fr-rFR/strings.xml deleted file mode 100644 index 0f712c3..0000000 --- a/res/values-fr-rFR/strings.xml +++ /dev/null @@ -1,156 +0,0 @@ - - - - - Customisation Pixel - Configurer les paramètres spécifiques à l\'appareil - Avertissement - La plupart de ces fonctions dépendent de nœuds spécifiques du noyau pour fonctionner. Lorsque vous flashez un noyau personnalisé, vous risquez de perdre l\'accès à certaines de ces fonctionnalités. Vous êtes prévenu ! - OK - L\'accès au nœud du noyau a échoué ! Veuillez vous assurer que le chemin fourni vers l\'attribut sysfs ou procfs est exact, qu\'il dispose des autorisations appropriées et que les politiques SELinux sont correctement configurées. - Activé - Désactivé - - Batterie - Informations sur la batterie - Affichage de diverses informations sur la batterie - Fréquence d\'actualisation - Définir la fréquence d\'actualisation des informations de la batterie (en secondes) - Informations disponibles - Technologie - Informations technologiques - Li-ion (Lithium-ion):\n\nLargement utilisée dans les smartphones et de nombreux appareils électroniques, les piles Li-ion offrent une densité énergétique élevée, une conception légère, et un taux d\'autodécharge relativement faible.\n\n - NiMH (Nickel Metal Hydride) :\n\nOffrant un bon équilibre entre capacité et coût, les piles NiMH sont couramment utilisées dans certains dispositifs.\n\n - Li-poly (polymère de Lithium) :\n\nSimilaires aux piles Li-ion, Les piles Li-poly ont un facteur de forme flexible et léger. Ils sont souvent utilisés dans des appareils minces où l\'espace est une préoccupation.\n\n - LiFe (Phosphate de Fer de Lithium) :\n\nOffre une durée de vie plus longue, une sécurité accrue, et une meilleure tolérance à la température, les piles LiFe sont couramment utilisées dans des applications priorisant la durabilité et la stabilité.\n\n - NiCd (Nickel Cadmium) :\n\nUne technologie plus ancienne avec une densité d\'énergie réduite et une vitesse d\'autodécharge plus élevée, De nos jours, les piles NiCd sont moins courantes en raison de préoccupations environnementales.\n\n - LiMn (Lithium Manganèse):\n\nUne variante de piles Li-ion, Les piles LiMn offrent une puissance et une stabilité élevées, ce qui les rend adaptées aux applications nécessitant un haut courant.\n\n - Sur smartphones, Les piles Li-ion sont la technologie la plus couramment utilisée en raison de leur équilibre optimal en termes de performance, de capacité et de sécurité. - - Statut - Informations sur le statut - Inconnu :\n\nLe statut de l\'appareil est actuellement inconnu.\n\n - Chargement :\n\nL\'appareil est actuellement en cours de chargement.\n\n - Déchargement :\n\nL\'appareil est actuellement en train de décharger sa batterie.\n\n - Pas en charge:\n\nL\'appareil est connecté mais ne charge pas activement sa batterie. - - Inconnu - En charge - En décharge - Pas en charge - Chargée - Type USB - Informations sur les types d\'USB - Port aval standard (SDP):\n\nC\'est la forme la plus basique de connexion USB. Il peut être utilisé pour le transfert de données et pour l\'alimentation mais il ne dispose pas de fonctionnalités spéciales pour charger les appareils plus rapidement.\n\n - Port de charge en aval (CDP):\n\nCe type de connexion USB prend également en charge le transfert de données, mais il peut fournir plus d\'énergie qu\'un port SDP. Cela signifie qu\'il peut charger des appareils plus rapidement tout en permettant le transfert de données. Des CDP ont été introduits dans la spécification de charge de la batterie USB (Révision 1.2), pour répondre au besoin de charger les piles des périphériques portables.\n\n - Port de chargement dédié (DCP) :\n\nCe type de connexion USB ne supporte pas du tout le transfert de données. Il est seulement utilisé pour charger des périphériques et peut généralement fournir encore plus de puissance qu\'un port CDP. Le DCP est utilisé quand il y a besoin de plus de puissance pour charger un périphérique, mais aucun transfert de données n\'est nécessaire. - - Non connecté ou inconnu - Port Standard en aval (SDP) - Port de charge en aval (CDP) - Port de chargement dédié (DCP) - Température - Informations sur la température - La température désigne le degré de chaleur ou de froid, mesuré en Celsius (°C) ou Fahrenheit (°F). Les températures élevées peuvent affecter les performances et la durée de vie de l’appareil. Les plages de fonctionnement recommandées pour les smartphones sont généralement entre 0°C et 35°C (32°F et 95°F). La surveillance de la température assure que les appareils restent dans la plage de sécurité et évitent la surchauffe et les dommages. - Afficher la température en Fahrenheit - Capacité actuelle - Informations sur la capacité - La capacité correspond au niveau de charge actuel de la batterie, représenté en pourcentage de sa capacité globale. Il indique le montant actuellement disponible par rapport à la capacité maximale. Surveiller le niveau de capacité en pourcentage permet d\'estimer la puissance restante de la batterie et de planifier la consommation d\'énergie en conséquence. - Niveau de capacité - Informations sur le niveau de capacité - Inconnu :\n\nLa capacité de la batterie actuelle est inconnue.\n\n - Critique :\n\nLa capacité de la batterie est critiquement faible. La charge immédiate est recommandée.\n\n - Faible :\n\nLa capacité de la batterie est faible. Pensez à charger l\'appareil.\n\n - Normal:\n\nLa capacité de la batterie est à un niveau normal.\n\n - Élevé :\n\nLa capacité de la batterie est relativement élevée. Aucune charge immédiate n\'est requise.\n\n - Plein :\n\nLa capacité de la batterie est à pleine capacité. L\'appareil est entièrement chargé. - - Inconnu - Critique - Faible - Normale - Élevé - Pleine - Actuel - Informations sur le courant - Le courant désigne le flux de charge électrique dans un circuit, mesuré en milliampères (mA). La valeur actuelle indique le montant de la charge en cours de charge ou de sortie par un appareil. Surveiller la valeur du courant permet de suivre le flux de puissance et de gérer efficacement le processus de charge ou de décharge. - Tension - Informations sur la tension - La tension désigne la différence électrique potentielle dans un circuit, mesuré en volts (V), qui détermine le comportement et la fonctionnalité des appareils électriques. La concordance de la tension requise assure un fonctionnement correct de l\'appareil, tandis que des niveaux de tension incorrects peuvent causer des dommages ou un dysfonctionnement. - Puissance - Informations sur la puissance - La puissance désigne la quantité d\'énergie électrique consommée ou produite par un appareil. Il est calculé en multipliant la tension par le courant (Puissance = Tension × Courant). Comprendre la puissance aide à déterminer les besoins en puissance, les capacités de l\'appareil et assure un fonctionnement sécuritaire des appareils électriques. - Santé - Informations sur la santé - Inconnu :\n\nL\'état de santé de la batterie est actuellement inconnu.\n\n - Bon :\n\nLa batterie est en bonne santé et fonctionne correctement.\n\n - Surchauffe :\n\nLa batterie subit une surchauffe, ce qui peut affecter ses performances et sa durée de vie.\n\n - Morte :\n\nLa batterie est morte et ne fonctionne plus. Le remplacement est nécessaire.\n\n - Surtension :\n\nLa batterie est en surtension, qui peuvent présenter un risque pour l\'appareil.\n\n - Échec non spécifié:\n\nLa batterie a rencontré une panne non spécifiée, affectant ses performances.\n\n - Froide :\n\nLa batterie connaît des conditions de température froide, qui peuvent affecter ses performances et sa capacité. - - Inconnu - Bon - Surchauffe - Morte - Surtension - Défaillance non précisée - Froide - La minuterie Watchdog expire - La minuterie de sécurité expire - Surintensité - Calibrage requis - Chaude - Froide - Chaude - Nombre de cycles - Informations sur le nombre de cycles - Le nombre de cycles indique le nombre de cycles de charge qu\'une batterie rechargeable a subi. Il indique l\'utilisation et le vieillissement de la batterie. La surveillance du nombre de cycles aide à estimer la durée de vie de la batterie et aide à déterminer si un remplacement est nécessaire. - Niveau de charge d\'arrêt - Empêcher l\'appareil de se recharger au-delà d\'un certain pourcentage - Niveau de charge de départ - Reprise de la charge à un pourcentage spécifique - Le niveau d\'arrêt doit être supérieur au niveau de départ ! - Le niveau de départ doit être inférieur au niveau d\'arrêt ! - - Appareil photo - Torche Pixel - Puissance de la torche - Régler la luminosité de la torche Pixel dans les réglages rapides - - CPU - File de puissance efficace - Économiser de l\'énergie en reprogrammant le travail sur un noyau déjà éveillé - - Affichage - Mode haute luminosité (HBM) - Activer la haute luminosité - HBM automatique - Activer la luminosité maximale en fonction de la lumière du soleil - Seuil (lux) - activer après (secondes) - désactivation après (secondes) - L\'utilisation prolongée du mode haute luminosité peut endommager l\'écran ! - Saturation - Contrôler le niveau de saturation de l\'écran - La modification du mode couleur dans les paramètres d\'affichage remplacera le niveau de saturation, ce qui nécessitera sa réapplication. - - UiBench - Jitter - Calculer l\'instabilité du rendu - - USB - Charge rapide USB 2.0 - Activer le mode CDP pour la charge rapide sur les ports USB 2.0 - Attention : Tous les ports USB 2.0 ne supportent pas le mode CDP. Pour que les changements prennent effet, déconnectez et reconnectez le périphérique après l\'activation ou la désactivation de ce mode. - - Valeur : %s - par défaut - Valeur par défaut : %s\nRester appuyer pour définir - Valeur par défaut définie - diff --git a/res/values-hu-rHU/strings.xml b/res/values-hu-rHU/strings.xml deleted file mode 100644 index 0892889..0000000 --- a/res/values-hu-rHU/strings.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Pixel-részek - A speciális, készülékfüggő beállítások változtatásai - Figyelmeztetés - Ezen funkciók legtöbbjének a helyes működéséhez meghatározott kernelbázisok szükségesek. Amennyiben Ön egyéni kernelt flessel, azt kockáztatja, hogy elveszíti a hozzáférést bizonyos funkciókhoz. Mi szóltunk előre! - OK - A kernelhez való hozzáférés nem sikerült! Győződjön meg arról, hogy a sysf vagy procfs attribútum megadott elérési útja pontos, megfelelő jogosultságokkal rendelkezik, és a SELinux-szabályok megfelelőek. - - Akkumulátor - Akkuinformáció - Megtekintheti a különféle akkuinfókat - frissítés ennyi másodperc után - Elérhető információk - Technológia - Állapot - Hőmérséklet - Jelenlegi kapacitás - Kapacitás-szint - Jelenlegi - Feszültség - Fogyasztás - Állapot - Ciklusszám - Töltésmegállítási szint - Nem engedi a készüléket egy adott szintnél tovább tölteni - Töltésinditási szint - Csak akkor tölt, ha a beállított szint alá merül - A megállási szintnek a kezdés szintje felett kell lennie! - A kezdési szintnek a leállítási szint alatt kell lennie! - - Kamera - Lámpa - A zseblámpa erőssége - Itt állíthatja be a csempék fényerősségét - - Processzor - Energiahatékony feladat-sorrendbeállítás - Energiát takarít meg azáltal, hogy átütemezi a munkát egy olyan processzormagra, amely már ébren van - - Képernyő - Magas fényerejű mód (HBM) - Csúcsfényerő-engedélyezés - Automatikus magasfényerő - A napfényhez igazodik a csúcsfényerő - küszöbérték (lux) - Ennyi másodperc múlva bekapcsol - Ennyi másodperc múlva kikapcsol - A \'Magas fényerejű mód\' hosszú idejű használata tönkreteheti a kijelzőjét! - - UiBench - Jitter - A renderelési jitter kiszámítása - - USB - USB 2.0 gyorstöltés - Az USB 2.0 portokon engedélyezi a CDP-módot a gyorstöltéshez - Vigyázva használja! Nem minden USB 2.0 port támogatja a CDP-módot! - - %s értékű - alapértelmezés szerint - Alapértelmezetten %s értékű\nNyomja meg hosszan a beállításhoz - Az alapértelmezett érték beállítva - diff --git a/res/values-pt-rBR/strings.xml b/res/values-pt-rBR/strings.xml deleted file mode 100644 index 9a172c0..0000000 --- a/res/values-pt-rBR/strings.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Pixel Parts - Configurações específicas do dispositivo - Aviso - A maioria destes recursos são atribuídas ao kernel stock. Ao instalar um kernel personalizado, você está sujeito a perder algumas funções. Você foi avisado! - OK - Falha ao acessar os componentes do kernel! Certifique-se de que o caminho fornecido para o atributo sysfs ou procfs seja preciso, que tenha as permissões apropriadas e que as políticas do SELinux estejam configuradas corretamente. - - Bateria - Informações da bateria - Ver várias informações da bateria - atualizar informação após (segundos) - Informações disponíveis - Tecnologia - Status - Temperatura - Capacidade atual - Nível de capacidade - Atual - Tensão - Potência - Saúde - Ciclos de carga - Nível para interromper o carregamento - Impedir que o dispositivo carregue acima da porcentagem definida - Nível para retomar o carregamento - Retomar a carga na porcentagem definida - O nível para interromper o carregamento deve ser maior que o nível para retomar! - O nível para retomar o carregamento deve ser menor que o nível para interromper! - - Câmera - Lanterna - Intensidade da lanterna - Ajusta a intensidade da luz pelo bloco da lanterna nas configurações rápidas - - CPU - Eficiência energética na fila de trabalho - Economize energia reprogramando o trabalho para um núcleo que já está acordado - - Tela - Modo de brilho máximo (HBM) - Ativar pico de luz - HBM automático - Ativar o pico de luz quando exposto à luz solar - limite (lux) - ativar após (segundos) - desativar após (segundos) - Usar o modo de brilho máximo por muito tempo pode danificar sua tela! - - UiBench - Jitter - Calcular jitter de renderização - - USB - Carregamento rápido USB 2.0 - Ative o modo CDP para carregar rapidamente nas portas USB 2.0 - Nem todas as portas USB 2.0 suportam o modo CDP, use com cuidado! - - Valor: %s - por padrão - Valor padrão: %s\nPressione e segure para definir - Valor padrão definido - diff --git a/res/values-ru-rRU/strings.xml b/res/values-ru-rRU/strings.xml deleted file mode 100644 index 6ff96e6..0000000 --- a/res/values-ru-rRU/strings.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Pixel Parts - Настроить специфические параметры устройства - Предупреждение - Большинство этих функций для своей работы зависят от определенных узлов ядра. При прошивке пользовательского ядра вы рискуете потерять доступ к некоторым из этих функций. Вы были предупреждены! - ОК - Не удалось получить доступ к узлу ядра! Убедитесь, что предоставленный путь к атрибуту sysfs или procfs является точным, что он имеет соответствующие разрешения, а политики SELinux правильно настроены. - - Батарея - Информация о батарее - Просмотр различной информации о батарее - обновлять информацию через (секунд) - Доступная информация - Технология - Статус - Температура - Емкость сейчас - Уровень емкости - Текущий - Напряжение - Ваттность - Здоровье - Количество циклов - Уровень прекращения зарядки - Запрет на зарядку устройства свыше определенного процента - Уровень начала зарядки - Возобновление зарядки при определенном проценте - Уровень остановки должен быть выше уровня старта! - Уровень старта должен быть ниже уровня остановки! - - Камера - Фонарик - Мощность фонарика - Регулировка яркости фонарика PixelParts QS-Tile - - Процессор - Энергоэффективная рабочая очередь - Экономит электроэнергию, перенося работу на ядро, которое уже активно - - Экран - Режим повышенной яркости (HBM) - Включить пиковую яркость - Автоматический HBM - Включение пиковой яркости на основе солнечного света - порог (люкс) - включить через (секунд) - выключить через (секунд) - Длительное использование режима повышенной яркости может привести к повреждению дисплея! - - UiBench - Дрожание - Рассчитать визуализацию дрожания - - USB - Быстрая зарядка USB 2.0 - Включить режим CDP для быстрой зарядки на портах USB 2.0 - Не все порты USB 2.0 поддерживают режим CDP, используйте с осторожностью! - - Значение: %s - по умолчанию - Значение по умолчанию: %s\nУдерживайте для установки - Установлено значение по умолчанию - diff --git a/res/values-sv-rSE/strings.xml b/res/values-sv-rSE/strings.xml deleted file mode 100644 index 717ad34..0000000 --- a/res/values-sv-rSE/strings.xml +++ /dev/null @@ -1,66 +0,0 @@ - - - - - Pixel Parts - Konfigurera enhetsspecifika inställningar - Varning - De flesta av dessa funktionerna kräver specifika kernel noder för att fungera. När du installerar en tredjeparts kernel så riskerar du att ta miste om några av dessa funktionerna. Du har blivit varnad! - Åtkomst till kernelnoderna misslyckades! Var noga med att rätt sökväg till sysfs eller procfs attributerna är rätt, att de har lämpliga rättigheter och att SELinux är inställt rätt. - - Batteriinformation - Visa diverse batteriinformation - Uppdatera infon efter (sekunder) - Tillgänglig info - Teknologi - Status - Temperatur - Nuvarande kapacitet - Kapacitetsnivå - Ström - Spänning - Watt - Hälsa - Antal cykler - Stoppladdningsnivå - Förhindra enheten från att ladda över en viss procent - Startladdningsnivå - Återuppta laddning vid procent - Stoppnivån måste vara över startnivån! - Startnivån måste vara under stoppnivå! - - Ficklampsstryka - Justera ljusstyrkan för PixelParts ficklampans QS-bricka - - CPU - Krafteffektiv arbetskö - Spara kraft genom att flytta arbetet till en kärna som redan är aktiv - - Skärm - Högt ljusstyrksläge (HBM) - Aktiveringsluminans - Automatisk HBM - Aktivera luminans baserat på solljus - tröskel (lux) - aktivera efter (sekunder) - inaktivera efter (sekunder) - Längre tids användning av HBM kan skada din skärm! - - UiBench - Jitter - Beräkna renderingsjitter - - USB - USB 2.0 snabbladdning - Aktivera CDP-läge för snabb laddning på USB 2.0-portar - Inte alla USB 2.0-portar har stöd för CDP-läge, använd varsamt! - - Värde: %s - standard - Standardvärde: %s\nLångtryck för att ställa in - Standardvärdet är satt - diff --git a/res/values-tr-rTR/strings.xml b/res/values-tr-rTR/strings.xml deleted file mode 100644 index 3bcd0b0..0000000 --- a/res/values-tr-rTR/strings.xml +++ /dev/null @@ -1,70 +0,0 @@ - - - - - Pixel Araçları - Cihaza özel seçenekleri ayarlayın - Uyarı - Bu özelliklerin çoğu özel kernel parametreleri gerektirir. Özel bir kernel yüklerseniz bazı özellikleri kaybetme riskiniz olur. Dikkatli olun! - Tamam - Kernel devresine erişim başarısız oldu! Lütfen sysfs veya procfs yolunun doğru olup olmadığını, gerekli izinlere sahip olup olmadığını ve SELinux durumunun doğru ayarlanıp ayarlanmadığını kontrol edin. - - Pil - Pil bilgisi - Çeşitli pil bilgilerini görüntüleyin - bilgiyi (saniye) sonra yenile - Mevcut bilgi - Teknoloji - Durum - Sıcaklık - Şu anki kapasite - Kapasite seviyesi - Mevcut - Voltaj - Vat miktarı - Sağlık - Döngü sayısı - Şarj etmeyi durdurma seviyesi - Cihazın özel bir yüzdeden fazla şarj olmasını engelle - Şarj etmeyi başlatma seviyesi - Özel bir yüzdeye gelince şarj etmeyi sürdür - Durdurma seviyesi başlatma seviyesinin üstünde olmalıdır! - Başlatma seviyesi durdurma seviyesinin altında olmalıdır! - - Kamera - El feneri - El feneri gücü - El fenerinin parlaklığını ayarlayın - - İşlemci - Güç verimli iş sırası - İş sırasını yeniden planlayarak zaten uyanık olan bir çekirdeğe aktararak güç tasarrufu yapın - - Ekran - Yüksek parlaklık modu (YPM) - En yüksek parlaklığı etkinleştir - Otomatik YPM - Gün ışığına bağlı olarak yüksek parlaklığı etkinleştir - eşik (lux) - (Saniye) sonra etkinleştir - (Saniye) sonra devre dışı bırak - Yüksek parlaklık modunun uzun süre kullanımı ekranınıza zarar verebilir! - - Kullanıcı arabirimi sıralaması - Seğirme - Seyirme oluşumunu ölç - - USB - USB 2.0 hızlı şarj - USB 2.0 portundan hızlı şarjı etkinleştir - Tüm USB 2.0 portları hızlı şarjı desteklemez, dikkatli olun! - - Değer: %s - varsayılan olarak - Varsayılan değer: %s\nAyarlamak için uzun dokunun - Varsayılan değer ayarlandı - diff --git a/res/values/arrays.xml b/res/values/arrays.xml new file mode 100644 index 0000000..f51a72d --- /dev/null +++ b/res/values/arrays.xml @@ -0,0 +1,13 @@ + + + + + + tangorpro + felix + + + diff --git a/res/values/strings.xml b/res/values/strings.xml index 8edb879..68a3cb4 100644 --- a/res/values/strings.xml +++ b/res/values/strings.xml @@ -1,6 +1,6 @@ @@ -8,83 +8,33 @@ Pixel Parts - Configure device specific settings - Warning - Some of these features rely on specific kernel nodes in order to function. When flashing a custom kernel, you risk the possibility of losing access to some of these features. You have been warned! - OK - About - PixelParts began as a simple High Brightness Mode (HBM) tool. Since then, it has evolved to include a detailed battery information panel, a display saturation level adjuster, charging limiter and more. The app now offers a wide range of features, transitioning from its original function as an HBM tool to a hub for device tweaks and stats on customs, with a lot more planned going forward - Various links - Credit - GitHub - Check out the GitHub repository - XDA - Check out the XDA thread - Developer - Anierin Bliss Kernel node access failed! Please ensure the provided path to the sysfs or procfs attribute is accurate, that it has appropriate permissions, and the SELinux policies are properly configured. + No string resource found for the value returned by the node. On Off + Camera in use - - Battery - Battery info - View various battery information + + Battery information + View various information pertaining to the battery Refresh info every second Launch battery usage summary - Available info Technology - Technology information - - Li-ion (Lithium-ion):\n\nWidely used in smartphones and many electronic devices, Li-ion batteries provide high energy density, lightweight design, and relatively low self-discharge rate.\n\n - NiMH (Nickel Metal Hydride):\n\nOffering a good balance between capacity and cost, NiMH batteries are commonly used in certain devices.\n\n - Li-poly (Lithium Polymer):\n\nSimilar to Li-ion batteries, Li-poly batteries have a flexible and lightweight form factor. They are often used in slim devices where space is a concern.\n\n - LiFe (Lithium Iron Phosphate):\n\nProviding a longer lifespan, enhanced safety, and better temperature tolerance, LiFe batteries are commonly used in applications prioritizing durability and stability.\n\n - NiCd (Nickel Cadmium):\n\nAn older technology with lower energy density and higher self-discharge rate, NiCd batteries are less common nowadays due to environmental concerns.\n\n - LiMn (Lithium Manganese):\n\nA variant of Li-ion batteries, LiMn batteries offer high power output and stability, making them suitable for applications requiring high current.\n\n - In smartphones, Li-ion batteries are the most commonly used technology due to their optimal balance of performance, capacity, and safety. - Status - Status information - - Unknown:\n\nThe status of the device is currently unknown.\n\n - Charging:\n\nThe device is currently being charged.\n\n - Discharging:\n\nThe device is currently discharging its battery.\n\n - Not charging:\n\nThe device is connected but not actively charging its battery. - Unknown Charging Discharging Not charging Full USB type - USB type information - - Standard Downstream Port (SDP):\n\nThis is the most basic form of USB connection. It can be used for data transfer and also to supply power, but it doesn\'t have any special features for charging devices more quickly.\n\n - Charging Downstream Port (CDP):\n\nThis type of USB connection also supports data transfer, but it can supply more power than an SDP port. This means it can charge devices more quickly while still allowing for data transfer. CDPs were introduced in the USB Battery Charging Specification (Revision 1.2), to address the need of charging batteries of portable devices.\n\n - Dedicated Charging Port (DCP):\n\nThis type of USB connection doesn\'t support data transfer at all. It\'s only used for charging devices, and it can usually supply even more power than a CDP port. DCP is used when there is a need for more power to charge a device but no data transfer is needed. - Not connected or unknown Standard Downstream Port (SDP) Charging Downstream Port (CDP) Dedicated Charging Port (DCP) Temperature - Temperature information - Temperature refers to the degree of hotness or coldness, measured in Celsius (°C) or Fahrenheit (°F). High temperatures can impact device performance and lifespan. Recommended operating ranges for smartphones are typically between 0°C and 35°C (32°F and 95°F). Monitoring temperature ensures devices stay within the safe range, preventing overheating and damage. Maintaining suitable temperatures contributes to optimal performance and longevity. Use °F for temperature Capacity now - Capacity information - Capacity refers to the current charge level of the battery, represented as a percentage of its overall capacity. It indicates how much charge is currently available compared to the maximum capacity. Monitoring the capacity level in percentage helps estimate the remaining battery power and plan power usage accordingly. Capacity level - Capacity level information - - Unknown:\n\nThe current battery capacity level is unknown.\n\n - Critical:\n\nThe battery capacity is critically low. Immediate charging is recommended.\n\n - Low:\n\nThe battery capacity is low. Consider charging the device.\n\n - Normal:\n\nThe battery capacity is at a normal level.\n\n - High:\n\nThe battery capacity is relatively high. No immediate charging is required.\n\n - Full:\n\nThe battery capacity is at full capacity. The device is fully charged. - Unknown Critical Low @@ -92,25 +42,9 @@ High Full Current - Current information - Current refers to the flow of electric charge in a circuit, measured in milliamperes (mA). It represents the rate at which electric charge is flowing. The current value indicates the amount of charge being charged or discharged by a device. Monitoring the current value helps track the flow of power and manage the charging or discharging process effectively. Voltage - Voltage information - Voltage refers to the electrical potential difference in a circuit, measured in volts (V). It determines the behavior and functionality of electrical devices. Matching the required voltage ensures proper device operation, while incorrect voltage levels can cause damage or malfunction. Wattage - Wattage information - Wattage refers to the amount of electrical power consumed or produced by a device. It is calculated by multiplying the voltage by the current (Wattage = Voltage × Current). Understanding wattage helps determine power requirements, device capabilities, and ensures safe operation of electrical devices. Health - Health information - - Unknown:\n\nThe battery health status is currently unknown.\n\n - Good:\n\nThe battery is in good health and functioning properly.\n\n - Overheat:\n\nThe battery is experiencing overheat, which may affect its performance and lifespan.\n\n - Dead:\n\nThe battery is dead and no longer functional. Replacement is necessary.\n\n - Over voltage:\n\nThe battery is experiencing over voltage, which may pose a risk to the device.\n\n - Unspecified failure:\n\nThe battery has encountered an unspecified failure, affecting its performance.\n\n - Cold:\n\nThe battery is experiencing cold temperature conditions, which may affect its performance and capacity. - Unknown Good Overheat @@ -126,25 +60,26 @@ Cool Hot Cycle count - Cycle count information - Cycle count refers to the number of charge-discharge cycles a rechargeable battery has undergone. It indicates the usage and aging of the battery. Monitoring the cycle count helps estimate battery lifespan and helps determine if a replacement is needed. + + + Charge control + Control when the device stops and starts charging + Use Charge control Stop charging level - Prevent the device from charging over a specific percentage + Stop charging when the set percentage is reached Start charging level - Resume charging at a specific percentage + Resume charging when the set percentage is reached Stop level must be above start level! Start level must be below stop level! + Charge control may interfere with adaptive charging. - - LEDs - Pixel Torch - Torch strength - Adjust the brightness of the Pixel Torch QS-Tile + + Pixel torch + Adjust the brightness of the Pixel Torch QS-Tile + Strength + The brightness level used by Pixel torch - - Display - High brightness mode (HBM) - Directly enable high brightness mode + Automatic HBM Use automatic HBM Automatically enable high brightness mode based on sunlight intensity (lux) @@ -154,25 +89,21 @@ Duration in seconds that the light threshold must be continuously met to activate HBM Disable time Duration in seconds for which HBM is deactivated if the light threshold falls below the set level + + Saturation Control the saturation level of the display Changing the color mode in display settings will override the saturation level, requiring it to be reapplied. - - UiBench - Jitter - Calculate rendering jitter - - - USB - USB 2.0 fast charge - Enable CDP mode for fast charging on USB 2.0 ports - Caution: Not all USB 2.0 ports support CDP mode. For changes to take effect, disconnect and reconnect the device after enabling or disabling this mode. + + Fast charge + Enable CDP mode for fast charging on USB 2.0 ports + Use Fast charge + Caution: Not all USB 2.0 ports support CDP mode. For changes to take effect, disconnect and reconnect the device after enabling or disabling this mode. Value: %s by default Default value: %s\nLong tap to set Default value is set - diff --git a/res/xml/about.xml b/res/xml/about.xml deleted file mode 100644 index 2651489..0000000 --- a/res/xml/about.xml +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/xml/auto_hbm.xml b/res/xml/auto_hbm.xml new file mode 100644 index 0000000..4bcaafb --- /dev/null +++ b/res/xml/auto_hbm.xml @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + diff --git a/res/xml/autohbm.xml b/res/xml/autohbm.xml deleted file mode 100644 index cb9ded7..0000000 --- a/res/xml/autohbm.xml +++ /dev/null @@ -1,51 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/res/xml/battery_info.xml b/res/xml/battery_info.xml new file mode 100644 index 0000000..6004685 --- /dev/null +++ b/res/xml/battery_info.xml @@ -0,0 +1,65 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/res/xml/batteryinfo.xml b/res/xml/batteryinfo.xml deleted file mode 100644 index 7ee83b8..0000000 --- a/res/xml/batteryinfo.xml +++ /dev/null @@ -1,69 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/xml/charge_control.xml b/res/xml/charge_control.xml new file mode 100644 index 0000000..7b11349 --- /dev/null +++ b/res/xml/charge_control.xml @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + diff --git a/res/xml/fast_charge.xml b/res/xml/fast_charge.xml new file mode 100644 index 0000000..20df167 --- /dev/null +++ b/res/xml/fast_charge.xml @@ -0,0 +1,24 @@ + + + + + + + + + + + diff --git a/res/xml/main.xml b/res/xml/main.xml deleted file mode 100644 index b8aa874..0000000 --- a/res/xml/main.xml +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/res/xml/pixel_torch.xml b/res/xml/pixel_torch.xml new file mode 100644 index 0000000..542525f --- /dev/null +++ b/res/xml/pixel_torch.xml @@ -0,0 +1,22 @@ + + + + + + + + + diff --git a/res/xml/saturation.xml b/res/xml/saturation.xml index 27ec8d7..2b10910 100644 --- a/res/xml/saturation.xml +++ b/res/xml/saturation.xml @@ -1,12 +1,14 @@ - - + + = stopLevel) { - startLevel = stopLevel - 1; - sharedPrefs.edit().putInt(Constants.KEY_START_CHARGING, startLevel).commit(); - FileUtils.writeValue(Constants.NODE_START_CHARGING, String.valueOf(startLevel)); - mStartChargingPreference.refresh(startLevel); - Toast.makeText(getContext(), R.string.stop_below_start_error, Toast.LENGTH_SHORT).show(); - } - sharedPrefs.edit().putInt(Constants.KEY_STOP_CHARGING, value).commit(); - FileUtils.writeValue(Constants.NODE_STOP_CHARGING, String.valueOf(value)); - return true; - // Start charging preference - } else if (preference == mStartChargingPreference) { - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); - int value = Integer.parseInt(newValue.toString()); - int startLevel = Integer.parseInt(newValue.toString()); - int stopLevel = sharedPrefs.getInt(Constants.KEY_STOP_CHARGING, 100); - if (stopLevel <= startLevel) { - stopLevel = startLevel + 1; - sharedPrefs.edit().putInt(Constants.KEY_STOP_CHARGING, stopLevel).commit(); - FileUtils.writeValue(Constants.NODE_STOP_CHARGING, String.valueOf(stopLevel)); - mStopChargingPreference.refresh(stopLevel); - Toast.makeText(getContext(), R.string.start_above_stop_error, Toast.LENGTH_SHORT).show(); - } - sharedPrefs.edit().putInt(Constants.KEY_START_CHARGING, value).commit(); - FileUtils.writeValue(Constants.NODE_START_CHARGING, String.valueOf(value)); - return true; - // High brightness mode switch - } else if (preference == mHBMSwitch) { - boolean enabled = (Boolean) newValue; - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); - sharedPrefs.edit().putBoolean(Constants.KEY_HBM, enabled).commit(); - FileUtils.writeValue(Constants.NODE_HBM, enabled ? "1" : "0"); - Intent hbmServiceIntent = new Intent(this.getContext(), HBMService.class); - if (enabled) { - this.getContext().startService(hbmServiceIntent); - } else { - this.getContext().stopService(hbmServiceIntent); - } - return true; - // USB 2.0 fast charge switch - } else if (preference == mUSB2FastChargeSwitch) { - boolean enabled = (Boolean) newValue; - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); - sharedPrefs.edit().putBoolean(Constants.KEY_USB2_FAST_CHARGE, enabled).commit(); - FileUtils.writeValue(Constants.NODE_USB2_FAST_CHARGE, enabled ? "1" : "0"); - return true; - } - - return false; - } - - // Stop charging preference - public static void restoreStopChargingSetting(Context context) { - if (FileUtils.isFileWritable(Constants.NODE_STOP_CHARGING)) { - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); - int value = sharedPrefs.getInt(Constants.KEY_STOP_CHARGING, - Integer.parseInt(FileUtils.getFileValue(Constants.NODE_STOP_CHARGING, Constants.DEFAULT_STOP_CHARGING))); - FileUtils.writeValue(Constants.NODE_STOP_CHARGING, String.valueOf(value)); - } - } - - // Start charging preference - public static void restoreStartChargingSetting(Context context) { - if (FileUtils.isFileWritable(Constants.NODE_START_CHARGING)) { - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); - int value = sharedPrefs.getInt(Constants.KEY_START_CHARGING, - Integer.parseInt(FileUtils.getFileValue(Constants.NODE_START_CHARGING, Constants.DEFAULT_START_CHARGING))); - FileUtils.writeValue(Constants.NODE_START_CHARGING, String.valueOf(value)); - } - } - - // High brightness mode switch - public static void restoreHBMSetting(Context context) { - if (FileUtils.isFileWritable(Constants.NODE_HBM)) { - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); - boolean value = sharedPrefs.getBoolean(Constants.KEY_HBM, false); - FileUtils.writeValue(Constants.NODE_HBM, value ? "1" : "0"); - } - } - - // USB 2.0 fast charge switch - public static void restoreUSB2FastChargeSetting(Context context) { - if (FileUtils.isFileWritable(Constants.NODE_USB2_FAST_CHARGE)) { - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); - boolean value = sharedPrefs.getBoolean(Constants.KEY_USB2_FAST_CHARGE, false); - FileUtils.writeValue(Constants.NODE_USB2_FAST_CHARGE, value ? "1" : "0"); - } - } - - // First launch warning dialog - public static class WarningDialogFragment extends DialogFragment { - @Override - public Dialog onCreateDialog(Bundle savedInstanceState) { - return new AlertDialog.Builder(getActivity()) - .setTitle(R.string.pixel_parts_warning_title) - .setMessage(R.string.pixel_parts_warning_text) - .setNegativeButton(R.string.pixel_parts_dialog, (dialog, which) -> dialog.cancel()) - .create(); - } - - @Override - public void onCancel(DialogInterface dialog) { - getActivity().getSharedPreferences("main", Activity.MODE_PRIVATE) - .edit() - .putBoolean("first_warning_shown", true) - .commit(); - } - } - - private void showWarning() { - WarningDialogFragment fragment = new WarningDialogFragment(); - fragment.show(getFragmentManager(), "warning_dialog"); - } -} diff --git a/src/org/evolution/pixelparts/PixelPartsActivity.java b/src/org/evolution/pixelparts/PixelPartsActivity.java deleted file mode 100644 index 25100b8..0000000 --- a/src/org/evolution/pixelparts/PixelPartsActivity.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright (C) 2023 The Evolution X Project - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.evolution.pixelparts; - -import android.app.Activity; -import android.app.AlertDialog; -import android.app.Dialog; -import android.app.DialogFragment; -import android.app.Fragment; -import android.content.DialogInterface; -import android.content.res.Resources; -import android.graphics.Color; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.view.Menu; -import android.view.MenuInflater; -import android.view.MenuItem; -import androidx.preference.PreferenceFragment; -import androidx.preference.PreferenceManager; - -import com.android.settingslib.collapsingtoolbar.CollapsingToolbarBaseActivity; -import com.android.settingslib.widget.R; - -import java.util.Arrays; -import java.util.Random; - -import com.plattysoft.leonids.ParticleSystem; - -import org.evolution.pixelparts.utils.ShakeUtils; - -public class PixelPartsActivity extends CollapsingToolbarBaseActivity - implements ShakeUtils.OnShakeListener { - - private static final String TAG = "PixelParts"; - - private ShakeUtils mShakeUtils; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - getFragmentManager().beginTransaction().replace(R.id.content_frame, - new PixelParts(), TAG).commit(); - - mShakeUtils = new ShakeUtils(this); - } - - @Override - protected void onResume() { - super.onResume(); - mShakeUtils.bindShakeListener(this); - } - - @Override - protected void onStop() { - super.onStop(); - mShakeUtils.unBindShakeListener(this); - } - - @Override - protected void onDestroy() { - super.onDestroy(); - mShakeUtils.unBindShakeListener(this); - } - - @Override - public void onShake(double speed) { - Random rand = new Random(); - int firstRandom = rand.nextInt(91-0); - int secondRandom = rand.nextInt(181-90)+90; - int thirdRandom = rand.nextInt(181-0); - - Drawable easteregg = getResources().getDrawable(R.drawable.easteregg,null); - int randomColor; - randomColor = Color.rgb( - Color.red(rand.nextInt(0xFFFFFF)), - Color.green(rand.nextInt(0xFFFFFF)), - Color.blue(rand.nextInt(0xFFFFFF))); - easteregg.setTint(randomColor); - - ParticleSystem ps = new ParticleSystem(this, 50, easteregg, 2000); - ps.setScaleRange(0.7f,1.3f); - ps.setSpeedRange(0.1f,0.25f); - ps.setAcceleration(0.0001f,thirdRandom); - ps.setRotationSpeedRange(firstRandom,secondRandom); - ps.setFadeOut(300); - ps.oneShot(this.findViewById(android.R.id.content),50); - } -} diff --git a/src/org/evolution/pixelparts/Startup.java b/src/org/evolution/pixelparts/Startup.java index 7a6dbe0..cf2786b 100644 --- a/src/org/evolution/pixelparts/Startup.java +++ b/src/org/evolution/pixelparts/Startup.java @@ -1,6 +1,5 @@ /* - * Copyright (C) 2018-2022 crDroid Android Project - * 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ @@ -10,33 +9,74 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; -import org.evolution.pixelparts.saturation.Saturation; -import org.evolution.pixelparts.services.PixelTorchTileService; -import org.evolution.pixelparts.utils.AutoHBMUtils; +import org.evolution.pixelparts.autohbm.AutoHbmActivity; +import org.evolution.pixelparts.autohbm.AutoHbmFragment; +import org.evolution.pixelparts.autohbm.AutoHbmTileService; +import org.evolution.pixelparts.chargecontrol.ChargeControlFragment; +import org.evolution.pixelparts.fastcharge.FastChargeActivity; +import org.evolution.pixelparts.fastcharge.FastChargeFragment; +import org.evolution.pixelparts.fastcharge.FastChargeTileService; +import org.evolution.pixelparts.pixeltorch.PixelTorchActivity; +import org.evolution.pixelparts.pixeltorch.PixelTorchFragment; +import org.evolution.pixelparts.pixeltorch.PixelTorchTileService; +import org.evolution.pixelparts.saturation.SaturationFragment; import org.evolution.pixelparts.utils.ComponentUtils; -import org.evolution.pixelparts.utils.TorchUtils; +import org.evolution.pixelparts.utils.FileUtils; public class Startup extends BroadcastReceiver { - private static final String TAG = Startup.class.getSimpleName(); - @Override public void onReceive(Context context, Intent intent) { final String action = intent.getAction(); - // PixelParts - PixelParts.restoreStopChargingSetting(context); - PixelParts.restoreStartChargingSetting(context); - PixelParts.restoreHBMSetting(context); - PixelParts.restoreUSB2FastChargeSetting(context); - AutoHBMUtils.enableAutoHBM(context); - Saturation.restoreSaturationSetting(context); + // Auto hbm + AutoHbmFragment.toggleAutoHbmService(context); - // PixelTorchTileService - ComponentUtils.setComponentEnabled( + ComponentUtils.toggleComponent( + context, + AutoHbmActivity.class, + AutoHbmFragment.isHbmSupported(context) + ); + + ComponentUtils.toggleComponent( + context, + AutoHbmTileService.class, + AutoHbmFragment.isHbmSupported(context) + ); + + // Charge control + ChargeControlFragment.restoreStartChargingSetting(context); + ChargeControlFragment.restoreStopChargingSetting(context); + + // Fast charge + FastChargeFragment.restoreFastChargeSetting(context); + + ComponentUtils.toggleComponent( + context, + FastChargeActivity.class, + FileUtils.fileExists(Constants.NODE_FAST_CHARGE) + ); + + ComponentUtils.toggleComponent( + context, + FastChargeTileService.class, + FileUtils.fileExists(Constants.NODE_FAST_CHARGE) + ); + + // PixelTorch + ComponentUtils.toggleComponent( + context, + PixelTorchActivity.class, + PixelTorchFragment.hasTorch(context) + ); + + ComponentUtils.toggleComponent( context, PixelTorchTileService.class, - TorchUtils.hasTorch(context) + PixelTorchFragment.hasTorch(context) ); + + // Saturation + SaturationFragment.restoreSaturationSetting(context); } } diff --git a/src/org/evolution/pixelparts/about/About.java b/src/org/evolution/pixelparts/about/About.java deleted file mode 100644 index 8503d94..0000000 --- a/src/org/evolution/pixelparts/about/About.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2023 The Evolution X Project - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.evolution.pixelparts.about; - -import android.app.Activity; -import android.content.Context; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.util.Log; - -import androidx.preference.PreferenceFragment; -import androidx.preference.PreferenceManager; -import androidx.preference.Preference; - -import org.evolution.pixelparts.R; - -public class About extends PreferenceFragment - implements Preference.OnPreferenceChangeListener { - private static final String TAG = About.class.getSimpleName(); - - @Override - public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.about); - SharedPreferences prefs = getActivity().getSharedPreferences("about", - Activity.MODE_PRIVATE); - - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); - Context context = getContext(); - } - - @Override - public boolean onPreferenceChange(Preference preference, Object newValue) { - return false; - } -} diff --git a/src/org/evolution/pixelparts/autohbm/AutoHBMActivity.java b/src/org/evolution/pixelparts/autohbm/AutoHbmActivity.java similarity index 67% rename from src/org/evolution/pixelparts/autohbm/AutoHBMActivity.java rename to src/org/evolution/pixelparts/autohbm/AutoHbmActivity.java index 8837cdb..a16b186 100644 --- a/src/org/evolution/pixelparts/autohbm/AutoHBMActivity.java +++ b/src/org/evolution/pixelparts/autohbm/AutoHbmActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ @@ -10,15 +10,15 @@ import android.os.Bundle; import com.android.settingslib.collapsingtoolbar.CollapsingToolbarBaseActivity; import com.android.settingslib.widget.R; -public class AutoHBMActivity extends CollapsingToolbarBaseActivity { +public class AutoHbmActivity extends CollapsingToolbarBaseActivity { - private static final String TAG = "AutoHBM"; + private static final String TAG = "AutoHbm"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(R.id.content_frame, - new AutoHBM(), TAG).commit(); + new AutoHbmFragment(), TAG).commit(); } } diff --git a/src/org/evolution/pixelparts/autohbm/AutoHBM.java b/src/org/evolution/pixelparts/autohbm/AutoHbmFragment.java similarity index 55% rename from src/org/evolution/pixelparts/autohbm/AutoHBM.java rename to src/org/evolution/pixelparts/autohbm/AutoHbmFragment.java index 47d610d..7bc79af 100644 --- a/src/org/evolution/pixelparts/autohbm/AutoHBM.java +++ b/src/org/evolution/pixelparts/autohbm/AutoHbmFragment.java @@ -1,17 +1,21 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ package org.evolution.pixelparts.autohbm; import android.content.Context; +import android.content.Intent; +import android.content.res.Resources; import android.content.SharedPreferences; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; +import android.os.Build; import android.os.Bundle; +import android.os.UserHandle; import android.widget.Switch; import androidx.preference.Preference; @@ -22,15 +26,13 @@ import com.android.settingslib.widget.MainSwitchPreference; import com.android.settingslib.widget.OnMainSwitchChangeListener; import com.android.settingslib.widget.UsageProgressBarPreference; -import org.evolution.pixelparts.misc.Constants; -import org.evolution.pixelparts.preferences.CustomSeekBarPreference; +import org.evolution.pixelparts.Constants; +import org.evolution.pixelparts.CustomSeekBarPreference; import org.evolution.pixelparts.R; -import org.evolution.pixelparts.utils.AutoHBMUtils; -public class AutoHBM extends PreferenceFragment +public class AutoHbmFragment extends PreferenceFragment implements OnMainSwitchChangeListener, SensorEventListener, Preference.OnPreferenceChangeListener { - private static final String TAG = AutoHBM.class.getSimpleName(); private static final String[] AUTO_HBM_PREFERENCES = { Constants.KEY_AUTO_HBM_THRESHOLD, Constants.KEY_AUTO_HBM_ENABLE_TIME, @@ -38,40 +40,41 @@ public class AutoHBM extends PreferenceFragment Constants.KEY_CURRENT_LUX_LEVEL }; - private CustomSeekBarPreference mAutoHBMThresholdPreference; - private MainSwitchPreference mAutoHBMSwitch; + private CustomSeekBarPreference mAutoHbmThresholdPreference; + private MainSwitchPreference mAutoHbmSwitch; private SensorManager mSensorManager; - private SharedPreferences mSharedPrefs; private Sensor mLightSensor; private UsageProgressBarPreference mCurrentLuxLevelPreference; private int mCurrentLux; + private static boolean mAutoHbmServiceEnabled = false; + @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.autohbm); + addPreferencesFromResource(R.xml.auto_hbm); Context context = getContext(); - mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); - mAutoHBMSwitch = findPreference(Constants.KEY_AUTO_HBM); - mAutoHBMSwitch.setChecked(mSharedPrefs.getBoolean(Constants.KEY_AUTO_HBM, false)); - mAutoHBMSwitch.addOnSwitchChangeListener(this); + mAutoHbmSwitch = findPreference(Constants.KEY_AUTO_HBM); + mAutoHbmSwitch.setChecked(sharedPrefs.getBoolean(Constants.KEY_AUTO_HBM, false)); + mAutoHbmSwitch.addOnSwitchChangeListener(this); - mAutoHBMThresholdPreference = findPreference(Constants.KEY_AUTO_HBM_THRESHOLD); - mAutoHBMThresholdPreference.setOnPreferenceChangeListener(this); + mAutoHbmThresholdPreference = findPreference(Constants.KEY_AUTO_HBM_THRESHOLD); + mAutoHbmThresholdPreference.setOnPreferenceChangeListener(this); mCurrentLuxLevelPreference = findPreference(Constants.KEY_CURRENT_LUX_LEVEL); mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE); mLightSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT); - toggleAutoHBMPreferencesVisibility(mAutoHBMSwitch.isChecked()); + toggleAutoHbmPreferencesVisibility(mAutoHbmSwitch.isChecked()); } @Override public void onResume() { super.onResume(); - if (mAutoHBMSwitch.isChecked()) { + if (mAutoHbmSwitch.isChecked()) { mSensorManager.registerListener(this, mLightSensor, SensorManager.SENSOR_DELAY_NORMAL); } } @@ -79,16 +82,17 @@ public class AutoHBM extends PreferenceFragment @Override public void onPause() { super.onPause(); - if (mAutoHBMSwitch.isChecked()) { + if (mAutoHbmSwitch.isChecked()) { mSensorManager.unregisterListener(this); } } @Override public void onSwitchChanged(Switch switchView, boolean isChecked) { - mSharedPrefs.edit().putBoolean(Constants.KEY_AUTO_HBM, isChecked).apply(); - AutoHBMUtils.enableAutoHBM(getContext()); - toggleAutoHBMPreferencesVisibility(isChecked); + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); + sharedPrefs.edit().putBoolean(Constants.KEY_AUTO_HBM, isChecked).apply(); + toggleAutoHbmService(getContext()); + toggleAutoHbmPreferencesVisibility(isChecked); if (isChecked) { mSensorManager.registerListener(this, mLightSensor, SensorManager.SENSOR_DELAY_NORMAL); @@ -99,9 +103,9 @@ public class AutoHBM extends PreferenceFragment @Override public boolean onPreferenceChange(Preference preference, Object newValue) { - if (preference == mAutoHBMThresholdPreference && mCurrentLuxLevelPreference != null) { + if (preference == mAutoHbmThresholdPreference && mCurrentLuxLevelPreference != null) { int threshold = (int) newValue; - updateCurrentLuxLevelPreference(mCurrentLux, threshold); + updateCurrentLuxLevelPreference(mCurrentLux, threshold); return true; } return false; @@ -109,10 +113,11 @@ public class AutoHBM extends PreferenceFragment @Override public void onSensorChanged(SensorEvent event) { + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); if (event.sensor.getType() == Sensor.TYPE_LIGHT && mCurrentLuxLevelPreference != null) { float luxValue = event.values[0]; mCurrentLux = (int) luxValue; - int threshold = mSharedPrefs.getInt(Constants.KEY_AUTO_HBM_THRESHOLD, 20000); + int threshold = sharedPrefs.getInt(Constants.KEY_AUTO_HBM_THRESHOLD, 20000); updateCurrentLuxLevelPreference(mCurrentLux, threshold); } } @@ -135,7 +140,7 @@ public class AutoHBM extends PreferenceFragment } } - private void toggleAutoHBMPreferencesVisibility(boolean show) { + private void toggleAutoHbmPreferencesVisibility(boolean show) { for (String prefKey : AUTO_HBM_PREFERENCES) { Preference pref = findPreference(prefKey); if (pref != null) { @@ -144,7 +149,40 @@ public class AutoHBM extends PreferenceFragment } } - public static boolean isAutoHBMEnabled(Context context) { - return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(Constants.KEY_AUTO_HBM, false); + public static void toggleAutoHbmService(Context context) { + if (isHbmSupported(context)) { + boolean isAutoHbmEnabled = PreferenceManager.getDefaultSharedPreferences(context) + .getBoolean(Constants.KEY_AUTO_HBM, false); + + if (isAutoHbmEnabled && !mAutoHbmServiceEnabled) { + startAutoHbmService(context); + } else if (!isAutoHbmEnabled && mAutoHbmServiceEnabled) { + stopAutoHbmService(context); + } + } + } + + private static void startAutoHbmService(Context context) { + context.startServiceAsUser(new Intent(context, AutoHbmService.class), + UserHandle.CURRENT); + mAutoHbmServiceEnabled = true; + } + + private static void stopAutoHbmService(Context context) { + mAutoHbmServiceEnabled = false; + context.stopServiceAsUser(new Intent(context, AutoHbmService.class), + UserHandle.CURRENT); + } + + public static boolean isHbmSupported(Context context) { + String[] UnsupportedHbmDevicesArray = context.getResources().getStringArray(R.array.unsupported_hbm_devices); + String deviceCodename = Build.PRODUCT; + + for (String device : UnsupportedHbmDevicesArray) { + if (deviceCodename.equals(device)) { + return false; + } + } + return true; } } diff --git a/src/org/evolution/pixelparts/services/AutoHBMService.java b/src/org/evolution/pixelparts/autohbm/AutoHbmService.java similarity index 87% rename from src/org/evolution/pixelparts/services/AutoHBMService.java rename to src/org/evolution/pixelparts/autohbm/AutoHbmService.java index 8ff6cae..1bacd99 100644 --- a/src/org/evolution/pixelparts/services/AutoHBMService.java +++ b/src/org/evolution/pixelparts/autohbm/AutoHbmService.java @@ -1,4 +1,4 @@ -package org.evolution.pixelparts.services; +package org.evolution.pixelparts.autohbm; import android.app.KeyguardManager; import android.app.Service; @@ -19,12 +19,12 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import org.evolution.pixelparts.misc.Constants; +import org.evolution.pixelparts.Constants; import org.evolution.pixelparts.utils.FileUtils; -public class AutoHBMService extends Service { +public class AutoHbmService extends Service { - private static boolean mAutoHBMActive = false; + private static boolean mAutoHbmActive = false; private ExecutorService mExecutorService; private SensorManager mSensorManager; @@ -43,12 +43,12 @@ public class AutoHBMService extends Service { public void deactivateLightSensorRead() { submit(() -> { mSensorManager.unregisterListener(mSensorEventListener); - mAutoHBMActive = false; - enableHBM(false); + mAutoHbmActive = false; + enableHbm(false); }); } - private void enableHBM(boolean enable) { + private void enableHbm(boolean enable) { if (enable) { FileUtils.writeValue(Constants.NODE_HBM, "1"); } else { @@ -73,8 +73,8 @@ public class AutoHBMService extends Service { (KeyguardManager) getSystemService(getApplicationContext().KEYGUARD_SERVICE); boolean keyguardShowing = km.inKeyguardRestrictedInputMode(); int luxThreshold = mSharedPrefs.getInt(Constants.KEY_AUTO_HBM_THRESHOLD, 20000); - int timeToEnableHBM = mSharedPrefs.getInt(Constants.KEY_AUTO_HBM_ENABLE_TIME, 0); - int timeToDisableHBM = mSharedPrefs.getInt(Constants.KEY_AUTO_HBM_DISABLE_TIME, 1); + int timeToEnableHbm = mSharedPrefs.getInt(Constants.KEY_AUTO_HBM_ENABLE_TIME, 0); + int timeToDisableHbm = mSharedPrefs.getInt(Constants.KEY_AUTO_HBM_DISABLE_TIME, 1); if (lux > luxThreshold) { if (!mCrossedThreshold) { @@ -82,20 +82,20 @@ public class AutoHBMService extends Service { mCrossedThresholdTime = System.currentTimeMillis(); } else { long currentTime = System.currentTimeMillis(); - if (currentTime - mCrossedThresholdTime >= timeToEnableHBM * 1000 && (!mAutoHBMActive || !isCurrentlyEnabled()) && !keyguardShowing) { - mAutoHBMActive = true; - enableHBM(true); + if (currentTime - mCrossedThresholdTime >= timeToEnableHbm * 1000 && (!mAutoHbmActive || !isCurrentlyEnabled()) && !keyguardShowing) { + mAutoHbmActive = true; + enableHbm(true); mLastTriggerTime = currentTime; } } } else { mCrossedThreshold = false; - if (mAutoHBMActive) { + if (mAutoHbmActive) { long currentTime = System.currentTimeMillis(); - if (currentTime - mLastTriggerTime >= timeToDisableHBM * 1000) { - mAutoHBMActive = false; - enableHBM(false); + if (currentTime - mLastTriggerTime >= timeToDisableHbm * 1000) { + mAutoHbmActive = false; + enableHbm(false); } } } diff --git a/src/org/evolution/pixelparts/services/AutoHBMTileService.java b/src/org/evolution/pixelparts/autohbm/AutoHbmTileService.java similarity index 63% rename from src/org/evolution/pixelparts/services/AutoHBMTileService.java rename to src/org/evolution/pixelparts/autohbm/AutoHbmTileService.java index 1a6ffc0..e1e80d7 100644 --- a/src/org/evolution/pixelparts/services/AutoHBMTileService.java +++ b/src/org/evolution/pixelparts/autohbm/AutoHbmTileService.java @@ -1,34 +1,20 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ -package org.evolution.pixelparts.services; +package org.evolution.pixelparts.autohbm; import android.content.SharedPreferences; import android.service.quicksettings.Tile; import android.service.quicksettings.TileService; import androidx.preference.PreferenceManager; -import org.evolution.pixelparts.misc.Constants; +import org.evolution.pixelparts.Constants; import org.evolution.pixelparts.R; -import org.evolution.pixelparts.utils.AutoHBMUtils; import org.evolution.pixelparts.utils.FileUtils; -public class AutoHBMTileService extends TileService { - - private void updateTile(boolean enabled) { - final Tile tile = getQsTile(); - if (FileUtils.isFileWritable(Constants.NODE_HBM)) { - tile.setState(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); - String subtitle = enabled ? getString(R.string.tile_on) : getString(R.string.tile_off); - tile.setSubtitle(subtitle); - tile.updateTile(); - } else { - tile.setState(Tile.STATE_UNAVAILABLE); - } - tile.updateTile(); - } +public class AutoHbmTileService extends TileService { @Override public void onStartListening() { @@ -48,7 +34,15 @@ public class AutoHBMTileService extends TileService { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); final boolean enabled = !(sharedPrefs.getBoolean(Constants.KEY_AUTO_HBM, false)); sharedPrefs.edit().putBoolean(Constants.KEY_AUTO_HBM, enabled).commit(); - AutoHBMUtils.enableAutoHBM(this); + AutoHbmFragment.toggleAutoHbmService(this); updateTile(enabled); } + + private void updateTile(boolean enabled) { + final Tile tile = getQsTile(); + tile.setState(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); + String subtitle = enabled ? getString(R.string.tile_on) : getString(R.string.tile_off); + tile.setSubtitle(subtitle); + tile.updateTile(); + } } diff --git a/src/org/evolution/pixelparts/batteryinfo/BatteryInfoActivity.java b/src/org/evolution/pixelparts/batteryinfo/BatteryInfoActivity.java index 8b23a68..cd28ace 100644 --- a/src/org/evolution/pixelparts/batteryinfo/BatteryInfoActivity.java +++ b/src/org/evolution/pixelparts/batteryinfo/BatteryInfoActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ @@ -19,6 +19,6 @@ public class BatteryInfoActivity extends CollapsingToolbarBaseActivity { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(R.id.content_frame, - new BatteryInfo(), TAG).commit(); + new BatteryInfoFragment(), TAG).commit(); } } diff --git a/src/org/evolution/pixelparts/batteryinfo/BatteryInfo.java b/src/org/evolution/pixelparts/batteryinfo/BatteryInfoFragment.java similarity index 64% rename from src/org/evolution/pixelparts/batteryinfo/BatteryInfo.java rename to src/org/evolution/pixelparts/batteryinfo/BatteryInfoFragment.java index 6dc4a42..341b6f4 100644 --- a/src/org/evolution/pixelparts/batteryinfo/BatteryInfo.java +++ b/src/org/evolution/pixelparts/batteryinfo/BatteryInfoFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ @@ -7,7 +7,6 @@ package org.evolution.pixelparts.batteryinfo; import android.app.Activity; import android.content.Context; -import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; @@ -15,20 +14,18 @@ import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; -import androidx.appcompat.app.AlertDialog; -import androidx.preference.Preference.OnPreferenceClickListener; + import androidx.preference.PreferenceFragment; import androidx.preference.PreferenceManager; import androidx.preference.Preference; import androidx.preference.SwitchPreference; -import org.evolution.pixelparts.misc.Constants; +import org.evolution.pixelparts.Constants; import org.evolution.pixelparts.R; import org.evolution.pixelparts.utils.FileUtils; -public class BatteryInfo extends PreferenceFragment +public class BatteryInfoFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { - private static final String TAG = BatteryInfo.class.getSimpleName(); private Handler mHandler; private Runnable mUpdateRunnable; @@ -49,9 +46,7 @@ public class BatteryInfo extends PreferenceFragment @Override public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { - addPreferencesFromResource(R.xml.batteryinfo); - SharedPreferences prefs = getActivity().getSharedPreferences("batteryinfo", - Activity.MODE_PRIVATE); + addPreferencesFromResource(R.xml.battery_info); mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); Context context = getContext(); @@ -107,7 +102,7 @@ public class BatteryInfo extends PreferenceFragment @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { - inflater.inflate(R.menu.batteryinfo_menu, menu); + inflater.inflate(R.menu.battery_info_menu, menu); menu.findItem(R.id.temperature_unit).setChecked(mSharedPrefs.getBoolean(Constants.KEY_TEMPERATURE_UNIT, false)); menu.findItem(R.id.battery_info_refresh).setChecked(mSharedPrefs.getBoolean(Constants.KEY_BATTERY_INFO_REFRESH, false)); } @@ -116,17 +111,12 @@ public class BatteryInfo extends PreferenceFragment public boolean onOptionsItemSelected(MenuItem item) { boolean isChecked = !item.isChecked(); item.setChecked(isChecked); - if (item.getItemId() == R.id.temperature_unit) { mSharedPrefs.edit().putBoolean(Constants.KEY_TEMPERATURE_UNIT, isChecked).apply(); return true; } else if (item.getItemId() == R.id.battery_info_refresh) { mSharedPrefs.edit().putBoolean(Constants.KEY_BATTERY_INFO_REFRESH, isChecked).apply(); return true; - } else if (item.getItemId() == R.id.launch_battery_usage) { - Intent intent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY); - startActivity(intent); - return true; } else { return super.onOptionsItemSelected(item); } @@ -137,19 +127,6 @@ public class BatteryInfo extends PreferenceFragment if (FileUtils.isFileReadable(Constants.NODE_TECHNOLOGY)) { String fileValue = FileUtils.getFileValue(Constants.NODE_TECHNOLOGY, null); mTechnologyPreference.setSummary(fileValue); - - mTechnologyPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.technology_info_title)) - .setMessage(getString(R.string.technology_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mTechnologyPreference.setSummary(getString(R.string.kernel_node_access_error)); mTechnologyPreference.setEnabled(false); @@ -160,19 +137,6 @@ public class BatteryInfo extends PreferenceFragment String fileValue = FileUtils.getFileValue(Constants.NODE_STATUS, null); int statusStringResourceId = getStatusStringResourceId(fileValue); mStatusPreference.setSummary(getString(statusStringResourceId)); - - mStatusPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.status_info_title)) - .setMessage(getString(R.string.status_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mStatusPreference.setSummary(getString(R.string.kernel_node_access_error)); mStatusPreference.setEnabled(false); @@ -183,19 +147,6 @@ public class BatteryInfo extends PreferenceFragment String fileValue = FileUtils.getFileValue(Constants.NODE_USB_TYPE, null); int usbTypeStringResourceId = getUSBTypeStringResourceId(fileValue); mUSBTypePreference.setSummary(getString(usbTypeStringResourceId)); - - mUSBTypePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.usb_type_info_title)) - .setMessage(getString(R.string.usb_type_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mUSBTypePreference.setSummary(getString(R.string.kernel_node_access_error)); mUSBTypePreference.setEnabled(false); @@ -214,19 +165,6 @@ public class BatteryInfo extends PreferenceFragment float roundedTemperatureCelsius = Math.round(temperatureCelsius * 10) / 10.0f; mTemperaturePreference.setSummary(roundedTemperatureCelsius + "°C"); } - - mTemperaturePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.temperature_info_title)) - .setMessage(getString(R.string.temperature_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mTemperaturePreference.setSummary(getString(R.string.kernel_node_access_error)); mTemperaturePreference.setEnabled(false); @@ -236,19 +174,6 @@ public class BatteryInfo extends PreferenceFragment if (FileUtils.isFileReadable(Constants.NODE_CAPACITY)) { String fileValue = FileUtils.getFileValue(Constants.NODE_CAPACITY, null); mCapacityPreference.setSummary(fileValue + "%"); - - mCapacityPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.capacity_info_title)) - .setMessage(getString(R.string.capacity_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mCapacityPreference.setSummary(getString(R.string.kernel_node_access_error)); mCapacityPreference.setEnabled(false); @@ -259,19 +184,6 @@ public class BatteryInfo extends PreferenceFragment String fileValue = FileUtils.getFileValue(Constants.NODE_CAPACITY_LEVEL, null); int capacityLevelStringResourceId = geCapacityLevelStringResourceId(fileValue); mCapacityLevelPreference.setSummary(getString(capacityLevelStringResourceId)); - - mCapacityLevelPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.capacity_level_info_title)) - .setMessage(getString(R.string.capacity_level_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mCapacityLevelPreference.setSummary(getString(R.string.kernel_node_access_error)); mCapacityLevelPreference.setEnabled(false); @@ -284,19 +196,6 @@ public class BatteryInfo extends PreferenceFragment int absoluteChargingCurrent = Math.abs(chargingCurrent); String formattedChargingCurrent = (absoluteChargingCurrent / 1000) + "mA"; mCurrentPreference.setSummary(formattedChargingCurrent); - - mCurrentPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.current_info_title)) - .setMessage(getString(R.string.current_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mCurrentPreference.setSummary(getString(R.string.kernel_node_access_error)); mCurrentPreference.setEnabled(false); @@ -308,19 +207,6 @@ public class BatteryInfo extends PreferenceFragment float chargingVoltage = Float.parseFloat(fileValue); String formattedChargingVoltage = String.format("%.1f", (chargingVoltage / 1000000)) + "V"; mVoltagePreference.setSummary(formattedChargingVoltage); - - mVoltagePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.voltage_info_title)) - .setMessage(getString(R.string.voltage_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mVoltagePreference.setSummary(getString(R.string.kernel_node_access_error)); mVoltagePreference.setEnabled(false); @@ -336,19 +222,6 @@ public class BatteryInfo extends PreferenceFragment float absoluteWattage = Math.abs(wattage); String formattedWattage = String.format("%.1f", absoluteWattage) + "W"; mWattagePreference.setSummary(formattedWattage); - - mWattagePreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.wattage_info_title)) - .setMessage(getString(R.string.wattage_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mWattagePreference.setSummary(getString(R.string.kernel_node_access_error)); mWattagePreference.setEnabled(false); @@ -359,19 +232,6 @@ public class BatteryInfo extends PreferenceFragment String fileValue = FileUtils.getFileValue(Constants.NODE_HEALTH, null); int healthStringResourceId = getHealthStringResourceId(fileValue); mHealthPreference.setSummary(getString(healthStringResourceId)); - - mHealthPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.health_info_title)) - .setMessage(getString(R.string.health_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mHealthPreference.setSummary(getString(R.string.kernel_node_access_error)); mHealthPreference.setEnabled(false); @@ -381,19 +241,6 @@ public class BatteryInfo extends PreferenceFragment if (FileUtils.isFileReadable(Constants.NODE_CYCLE_COUNT)) { String fileValue = FileUtils.getFileValue(Constants.NODE_CYCLE_COUNT, null); mCycleCountPreference.setSummary(fileValue); - - mCycleCountPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() { - @Override - public boolean onPreferenceClick(Preference preference) { - new AlertDialog.Builder(getContext()) - .setTitle(getString(R.string.cycle_count_title)) - .setMessage(getString(R.string.cycle_count_info_message)) - .setPositiveButton(android.R.string.ok, null) - .show(); - return true; - } - }); - } else { mCycleCountPreference.setSummary(getString(R.string.kernel_node_access_error)); mCycleCountPreference.setEnabled(false); @@ -414,7 +261,7 @@ public class BatteryInfo extends PreferenceFragment case "Full": return R.string.status_full; default: - return R.string.kernel_node_access_error; + return R.string.kernel_node_returned_value_unknown; } } @@ -429,7 +276,7 @@ public class BatteryInfo extends PreferenceFragment } else if (usbType.contains("[DCP]")) { return R.string.usb_type_dedicated_charging_port; } else { - return R.string.kernel_node_access_error; + return R.string.kernel_node_returned_value_unknown; } } @@ -449,7 +296,7 @@ public class BatteryInfo extends PreferenceFragment case "Full": return R.string.capacity_level_full; default: - return R.string.kernel_node_access_error; + return R.string.kernel_node_returned_value_unknown; } } @@ -485,7 +332,7 @@ public class BatteryInfo extends PreferenceFragment case "Hot": return R.string.health_hot; default: - return R.string.kernel_node_access_error; + return R.string.kernel_node_returned_value_unknown; } } diff --git a/src/org/evolution/pixelparts/services/BatteryInfoTileService.java b/src/org/evolution/pixelparts/batteryinfo/BatteryInfoTileService.java similarity index 85% rename from src/org/evolution/pixelparts/services/BatteryInfoTileService.java rename to src/org/evolution/pixelparts/batteryinfo/BatteryInfoTileService.java index b75fe04..84d03b0 100644 --- a/src/org/evolution/pixelparts/services/BatteryInfoTileService.java +++ b/src/org/evolution/pixelparts/batteryinfo/BatteryInfoTileService.java @@ -1,25 +1,17 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ -package org.evolution.pixelparts.services; +package org.evolution.pixelparts.batteryinfo; import android.app.PendingIntent; import android.content.Intent; import android.service.quicksettings.Tile; import android.service.quicksettings.TileService; -import org.evolution.pixelparts.batteryinfo.BatteryInfoActivity; - public class BatteryInfoTileService extends TileService { - private void updateTile() { - final Tile tile = getQsTile(); - tile.setState(Tile.STATE_ACTIVE); - tile.updateTile(); - } - @Override public void onStartListening() { super.onStartListening(); @@ -39,4 +31,10 @@ public class BatteryInfoTileService extends TileService { ); startActivityAndCollapse(pendingIntent); } + + private void updateTile() { + final Tile tile = getQsTile(); + tile.setState(Tile.STATE_ACTIVE); + tile.updateTile(); + } } diff --git a/src/org/evolution/pixelparts/chargecontrol/ChargeControlActivity.java b/src/org/evolution/pixelparts/chargecontrol/ChargeControlActivity.java new file mode 100644 index 0000000..73769f8 --- /dev/null +++ b/src/org/evolution/pixelparts/chargecontrol/ChargeControlActivity.java @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2023-2024 The Evolution X Project + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.evolution.pixelparts.chargecontrol; + +import android.os.Bundle; + +import com.android.settingslib.collapsingtoolbar.CollapsingToolbarBaseActivity; +import com.android.settingslib.widget.R; + +public class ChargeControlActivity extends CollapsingToolbarBaseActivity { + + private static final String TAG = "ChargeControl"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + getFragmentManager().beginTransaction().replace(R.id.content_frame, + new ChargeControlFragment(), TAG).commit(); + } +} diff --git a/src/org/evolution/pixelparts/chargecontrol/ChargeControlFragment.java b/src/org/evolution/pixelparts/chargecontrol/ChargeControlFragment.java new file mode 100644 index 0000000..d937f09 --- /dev/null +++ b/src/org/evolution/pixelparts/chargecontrol/ChargeControlFragment.java @@ -0,0 +1,160 @@ +/* + * Copyright (C) 2023-2024 The Evolution X Project + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.evolution.pixelparts.chargecontrol; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.widget.Switch; +import android.widget.Toast; + +import androidx.preference.Preference; +import androidx.preference.PreferenceFragment; +import androidx.preference.PreferenceManager; + +import com.android.settingslib.widget.MainSwitchPreference; +import com.android.settingslib.widget.OnMainSwitchChangeListener; + +import org.evolution.pixelparts.Constants; +import org.evolution.pixelparts.CustomSeekBarPreference; +import org.evolution.pixelparts.R; +import org.evolution.pixelparts.utils.FileUtils; + +public class ChargeControlFragment extends PreferenceFragment + implements OnMainSwitchChangeListener, Preference.OnPreferenceChangeListener { + + // Charge control preference + private MainSwitchPreference mChargeControlSwitch; + + // Stop/Start preferences + private CustomSeekBarPreference mStopChargingPreference; + private CustomSeekBarPreference mStartChargingPreference; + + @Override + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + addPreferencesFromResource(R.xml.charge_control); + + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); + + // Charge control preference + mChargeControlSwitch = findPreference(Constants.KEY_CHARGE_CONTROL); + mChargeControlSwitch.setChecked(sharedPrefs.getBoolean(Constants.KEY_CHARGE_CONTROL, false)); + mChargeControlSwitch.addOnSwitchChangeListener(this); + + // Stop preference + mStopChargingPreference = findPreference(Constants.KEY_STOP_CHARGING); + if (FileUtils.isFileWritable(Constants.NODE_STOP_CHARGING)) { + mStopChargingPreference.setValue(sharedPrefs.getInt(Constants.KEY_STOP_CHARGING, + Integer.parseInt(FileUtils.getFileValue(Constants.NODE_STOP_CHARGING, Constants.DEFAULT_STOP_CHARGING)))); + mStopChargingPreference.setOnPreferenceChangeListener(this); + } else { + mStopChargingPreference.setSummary(getString(R.string.kernel_node_access_error)); + mStopChargingPreference.setEnabled(false); + } + mStopChargingPreference.setVisible(mChargeControlSwitch.isChecked()); + + // Start preference + mStartChargingPreference = findPreference(Constants.KEY_START_CHARGING); + if (FileUtils.isFileWritable(Constants.NODE_START_CHARGING)) { + mStartChargingPreference.setValue(sharedPrefs.getInt(Constants.KEY_START_CHARGING, + Integer.parseInt(FileUtils.getFileValue(Constants.NODE_START_CHARGING, Constants.DEFAULT_START_CHARGING)))); + mStartChargingPreference.setOnPreferenceChangeListener(this); + } else { + mStartChargingPreference.setSummary(getString(R.string.kernel_node_access_error)); + mStartChargingPreference.setEnabled(false); + } + mStartChargingPreference.setVisible(mChargeControlSwitch.isChecked()); + } + + @Override + public void onSwitchChanged(Switch switchView, boolean isChecked) { + SharedPreferences.Editor prefChange = PreferenceManager.getDefaultSharedPreferences(getContext()).edit(); + + prefChange.putBoolean(Constants.KEY_CHARGE_CONTROL, isChecked).apply(); + + mStopChargingPreference.setVisible(isChecked); + mStartChargingPreference.setVisible(isChecked); + + if (!isChecked) { + // Stop preference + int defaultStopCharging = 100; + prefChange.putInt(Constants.KEY_STOP_CHARGING, defaultStopCharging).apply(); + FileUtils.writeValue(Constants.NODE_STOP_CHARGING, Integer.toString(defaultStopCharging)); + mStopChargingPreference.refresh(defaultStopCharging); + + // Start preference + int defaultStartCharging = 0; + prefChange.putInt(Constants.KEY_START_CHARGING, defaultStartCharging).apply(); + FileUtils.writeValue(Constants.NODE_START_CHARGING, Integer.toString(defaultStartCharging)); + mStartChargingPreference.refresh(defaultStartCharging); + } + } + + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + // Stop preference + if (preference == mStopChargingPreference) { + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); + int value = Integer.parseInt(newValue.toString()); + int stopLevel = Integer.parseInt(newValue.toString()); + int startLevel = sharedPrefs.getInt(Constants.KEY_START_CHARGING, 0); + if (startLevel >= stopLevel) { + startLevel = stopLevel - 1; + sharedPrefs.edit().putInt(Constants.KEY_START_CHARGING, startLevel).apply(); + FileUtils.writeValue(Constants.NODE_START_CHARGING, String.valueOf(startLevel)); + mStartChargingPreference.refresh(startLevel); + Toast.makeText(getContext(), R.string.stop_below_start_error, Toast.LENGTH_SHORT).show(); + + } + sharedPrefs.edit().putInt(Constants.KEY_STOP_CHARGING, value).apply(); + FileUtils.writeValue(Constants.NODE_STOP_CHARGING, String.valueOf(value)); + return true; + } + // Start preference + else if (preference == mStartChargingPreference) { + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); + int value = Integer.parseInt(newValue.toString()); + int startLevel = Integer.parseInt(newValue.toString()); + int stopLevel = sharedPrefs.getInt(Constants.KEY_STOP_CHARGING, 100); + if (stopLevel <= startLevel) { + stopLevel = startLevel + 1; + sharedPrefs.edit().putInt(Constants.KEY_STOP_CHARGING, stopLevel).apply(); + FileUtils.writeValue(Constants.NODE_STOP_CHARGING, String.valueOf(stopLevel)); + mStopChargingPreference.refresh(stopLevel); + Toast.makeText(getContext(), R.string.start_above_stop_error, Toast.LENGTH_SHORT).show(); + } + sharedPrefs.edit().putInt(Constants.KEY_START_CHARGING, value).apply(); + FileUtils.writeValue(Constants.NODE_START_CHARGING, String.valueOf(value)); + return true; + } + + return false; + } + + // Stop preference + public static void restoreStopChargingSetting(Context context) { + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); + boolean chargeControlEnabled = sharedPrefs.getBoolean(Constants.KEY_CHARGE_CONTROL, true); + + if (chargeControlEnabled && FileUtils.isFileWritable(Constants.NODE_STOP_CHARGING)) { + int value = sharedPrefs.getInt(Constants.KEY_STOP_CHARGING, + Integer.parseInt(FileUtils.getFileValue(Constants.NODE_STOP_CHARGING, Constants.DEFAULT_STOP_CHARGING))); + FileUtils.writeValue(Constants.NODE_STOP_CHARGING, String.valueOf(value)); + } + } + + // Start preference + public static void restoreStartChargingSetting(Context context) { + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); + boolean chargeControlEnabled = sharedPrefs.getBoolean(Constants.KEY_CHARGE_CONTROL, true); + + if (chargeControlEnabled && FileUtils.isFileWritable(Constants.NODE_START_CHARGING)) { + int value = sharedPrefs.getInt(Constants.KEY_START_CHARGING, + Integer.parseInt(FileUtils.getFileValue(Constants.NODE_START_CHARGING, Constants.DEFAULT_START_CHARGING))); + FileUtils.writeValue(Constants.NODE_START_CHARGING, String.valueOf(value)); + } + } +} diff --git a/src/org/evolution/pixelparts/about/AboutActivity.java b/src/org/evolution/pixelparts/fastcharge/FastChargeActivity.java similarity index 59% rename from src/org/evolution/pixelparts/about/AboutActivity.java rename to src/org/evolution/pixelparts/fastcharge/FastChargeActivity.java index a2760a2..7126ae7 100644 --- a/src/org/evolution/pixelparts/about/AboutActivity.java +++ b/src/org/evolution/pixelparts/fastcharge/FastChargeActivity.java @@ -1,24 +1,24 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ -package org.evolution.pixelparts.about; +package org.evolution.pixelparts.fastcharge; import android.os.Bundle; import com.android.settingslib.collapsingtoolbar.CollapsingToolbarBaseActivity; import com.android.settingslib.widget.R; -public class AboutActivity extends CollapsingToolbarBaseActivity { +public class FastChargeActivity extends CollapsingToolbarBaseActivity { - private static final String TAG = "About"; + private static final String TAG = "FastCharge"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getFragmentManager().beginTransaction().replace(R.id.content_frame, - new About(), TAG).commit(); + new FastChargeFragment(), TAG).commit(); } } diff --git a/src/org/evolution/pixelparts/fastcharge/FastChargeFragment.java b/src/org/evolution/pixelparts/fastcharge/FastChargeFragment.java new file mode 100644 index 0000000..8ff2faa --- /dev/null +++ b/src/org/evolution/pixelparts/fastcharge/FastChargeFragment.java @@ -0,0 +1,56 @@ +/* + * Copyright (C) 2023-2024 The Evolution X Project + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.evolution.pixelparts.fastcharge; + +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.widget.Switch; + +import androidx.preference.Preference; +import androidx.preference.PreferenceFragment; +import androidx.preference.PreferenceManager; + +import com.android.settingslib.widget.MainSwitchPreference; +import com.android.settingslib.widget.OnMainSwitchChangeListener; + +import org.evolution.pixelparts.Constants; +import org.evolution.pixelparts.R; +import org.evolution.pixelparts.utils.FileUtils; + +public class FastChargeFragment extends PreferenceFragment + implements OnMainSwitchChangeListener { + + private MainSwitchPreference mFastChargeSwitch; + + @Override + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + addPreferencesFromResource(R.xml.fast_charge); + + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext()); + + mFastChargeSwitch = findPreference(Constants.KEY_FAST_CHARGE); + mFastChargeSwitch.setChecked(sharedPrefs.getBoolean(Constants.KEY_FAST_CHARGE, false)); + mFastChargeSwitch.addOnSwitchChangeListener(this); + } + + @Override + public void onSwitchChanged(Switch switchView, boolean isChecked) { + SharedPreferences.Editor prefChange = PreferenceManager.getDefaultSharedPreferences(getContext()).edit(); + prefChange.putBoolean(Constants.KEY_FAST_CHARGE, isChecked).apply(); + if (FileUtils.isFileWritable(Constants.NODE_FAST_CHARGE)) { + FileUtils.writeValue(Constants.NODE_FAST_CHARGE, isChecked ? "1" : "0"); + } + } + + public static void restoreFastChargeSetting(Context context) { + if (FileUtils.isFileWritable(Constants.NODE_FAST_CHARGE)) { + SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); + boolean value = sharedPrefs.getBoolean(Constants.KEY_FAST_CHARGE, false); + FileUtils.writeValue(Constants.NODE_FAST_CHARGE, value ? "1" : "0"); + } + } +} diff --git a/src/org/evolution/pixelparts/services/USB2FCTileService.java b/src/org/evolution/pixelparts/fastcharge/FastChargeTileService.java similarity index 52% rename from src/org/evolution/pixelparts/services/USB2FCTileService.java rename to src/org/evolution/pixelparts/fastcharge/FastChargeTileService.java index 5250090..ec0ad4d 100644 --- a/src/org/evolution/pixelparts/services/USB2FCTileService.java +++ b/src/org/evolution/pixelparts/fastcharge/FastChargeTileService.java @@ -1,39 +1,26 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ -package org.evolution.pixelparts.services; +package org.evolution.pixelparts.fastcharge; import android.content.SharedPreferences; import android.service.quicksettings.Tile; import android.service.quicksettings.TileService; import androidx.preference.PreferenceManager; -import org.evolution.pixelparts.misc.Constants; +import org.evolution.pixelparts.Constants; import org.evolution.pixelparts.R; import org.evolution.pixelparts.utils.FileUtils; -public class USB2FCTileService extends TileService { - - private void updateTile(boolean enabled) { - final Tile tile = getQsTile(); - if (FileUtils.isFileWritable(Constants.NODE_USB2_FAST_CHARGE)) { - tile.setState(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); - String subtitle = enabled ? getString(R.string.tile_on) : getString(R.string.tile_off); - tile.setSubtitle(subtitle); - tile.updateTile(); - } else { - tile.setState(Tile.STATE_UNAVAILABLE); - } - tile.updateTile(); - } +public class FastChargeTileService extends TileService { @Override public void onStartListening() { super.onStartListening(); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - updateTile(sharedPrefs.getBoolean(Constants.KEY_USB2_FAST_CHARGE, false)); + updateTile(sharedPrefs.getBoolean(Constants.KEY_FAST_CHARGE, false)); } @Override @@ -45,9 +32,17 @@ public class USB2FCTileService extends TileService { public void onClick() { super.onClick(); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - final boolean enabled = !(sharedPrefs.getBoolean(Constants.KEY_USB2_FAST_CHARGE, false)); - FileUtils.writeValue(Constants.NODE_USB2_FAST_CHARGE, enabled ? "1" : "0"); - sharedPrefs.edit().putBoolean(Constants.KEY_USB2_FAST_CHARGE, enabled).commit(); + final boolean enabled = !(sharedPrefs.getBoolean(Constants.KEY_FAST_CHARGE, false)); + FileUtils.writeValue(Constants.NODE_FAST_CHARGE, enabled ? "1" : "0"); + sharedPrefs.edit().putBoolean(Constants.KEY_FAST_CHARGE, enabled).commit(); updateTile(enabled); } + + private void updateTile(boolean enabled) { + final Tile tile = getQsTile(); + tile.setState(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); + String subtitle = enabled ? getString(R.string.tile_on) : getString(R.string.tile_off); + tile.setSubtitle(subtitle); + tile.updateTile(); + } } diff --git a/src/org/evolution/pixelparts/pixeltorch/PixelTorchActivity.java b/src/org/evolution/pixelparts/pixeltorch/PixelTorchActivity.java new file mode 100644 index 0000000..35b49f7 --- /dev/null +++ b/src/org/evolution/pixelparts/pixeltorch/PixelTorchActivity.java @@ -0,0 +1,24 @@ +/* + * Copyright (C) 2023-2024 The Evolution X Project + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.evolution.pixelparts.pixeltorch; + +import android.os.Bundle; + +import com.android.settingslib.collapsingtoolbar.CollapsingToolbarBaseActivity; +import com.android.settingslib.widget.R; + +public class PixelTorchActivity extends CollapsingToolbarBaseActivity { + + private static final String TAG = "PixelTorch"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + getFragmentManager().beginTransaction().replace(R.id.content_frame, + new PixelTorchFragment(), TAG).commit(); + } +} diff --git a/src/org/evolution/pixelparts/pixeltorch/PixelTorchFragment.java b/src/org/evolution/pixelparts/pixeltorch/PixelTorchFragment.java new file mode 100644 index 0000000..b6a2575 --- /dev/null +++ b/src/org/evolution/pixelparts/pixeltorch/PixelTorchFragment.java @@ -0,0 +1,36 @@ +/* + * Copyright (C) 2023-2024 The Evolution X Project + * SPDX-License-Identifier: Apache-2.0 + */ + +package org.evolution.pixelparts.pixeltorch; + +import android.content.Context; +import android.content.pm.PackageManager; +import android.content.SharedPreferences; +import android.os.Bundle; + +import androidx.preference.Preference; +import androidx.preference.PreferenceFragment; +import androidx.preference.PreferenceManager; + +import org.evolution.pixelparts.R; + +public class PixelTorchFragment extends PreferenceFragment + implements Preference.OnPreferenceChangeListener { + + @Override + public void onCreatePreferences(Bundle savedInstanceState, String rootKey) { + addPreferencesFromResource(R.xml.pixel_torch); + } + + @Override + public boolean onPreferenceChange(Preference preference, Object newValue) { + return true; + } + + public static boolean hasTorch(Context context) { + PackageManager packageManager = context.getPackageManager(); + return packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); + } +} diff --git a/src/org/evolution/pixelparts/services/PixelTorchTileService.java b/src/org/evolution/pixelparts/pixeltorch/PixelTorchTileService.java similarity index 77% rename from src/org/evolution/pixelparts/services/PixelTorchTileService.java rename to src/org/evolution/pixelparts/pixeltorch/PixelTorchTileService.java index 89adaa5..d4fda3d 100644 --- a/src/org/evolution/pixelparts/services/PixelTorchTileService.java +++ b/src/org/evolution/pixelparts/pixeltorch/PixelTorchTileService.java @@ -1,19 +1,20 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ -package org.evolution.pixelparts.services; +package org.evolution.pixelparts.pixeltorch; import android.content.Context; import android.content.SharedPreferences; import android.hardware.camera2.CameraAccessException; import android.hardware.camera2.CameraManager; -import android.preference.PreferenceManager; import android.service.quicksettings.Tile; import android.service.quicksettings.TileService; -import org.evolution.pixelparts.misc.Constants; +import androidx.preference.PreferenceManager; + +import org.evolution.pixelparts.Constants; import org.evolution.pixelparts.R; public class PixelTorchTileService extends TileService { @@ -27,7 +28,6 @@ public class PixelTorchTileService extends TileService { sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); cameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE); registerTorchCallback(); - updateTile(Tile.STATE_INACTIVE); } @Override @@ -41,6 +41,23 @@ public class PixelTorchTileService extends TileService { toggleTorch(); } + private void registerTorchCallback() { + torchCallback = new CameraManager.TorchCallback() { + @Override + public void onTorchModeChanged(String cameraId, boolean enabled) { + super.onTorchModeChanged(cameraId, enabled); + updateTile(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); + } + + @Override + public void onTorchModeUnavailable(String cameraId) { + super.onTorchModeUnavailable(cameraId); + updateTile(Tile.STATE_UNAVAILABLE); + } + }; + cameraManager.registerTorchCallback(torchCallback, null); + } + private void toggleTorch() { try { String outCameraId = cameraManager.getCameraIdList()[0]; @@ -66,7 +83,7 @@ public class PixelTorchTileService extends TileService { private void turnOnTorch(String outCameraId) { try { - int torchStrength = sharedPrefs.getInt(Constants.KEY_TORCH_STRENGTH, 45); + int torchStrength = sharedPrefs.getInt(Constants.KEY_PIXEL_TORCH_STRENGTH, 45); if (torchStrength != 0) { cameraManager.turnOnTorchWithStrengthLevel(outCameraId, torchStrength); } @@ -76,25 +93,18 @@ public class PixelTorchTileService extends TileService { updateTile(Tile.STATE_ACTIVE); } - private void registerTorchCallback() { - torchCallback = new CameraManager.TorchCallback() { - @Override - public void onTorchModeChanged(String cameraId, boolean enabled) { - super.onTorchModeChanged(cameraId, enabled); - updateTile(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); - } - }; - cameraManager.registerTorchCallback(torchCallback, null); - } - private void updateTile(int state) { Tile qsTile = getQsTile(); if (qsTile != null) { + if (state == Tile.STATE_UNAVAILABLE) { + qsTile.setSubtitle(getString(R.string.tile_camera_in_use)); + } else { + String subtitle = state == Tile.STATE_ACTIVE ? + getString(R.string.tile_on) : + getString(R.string.tile_off); + qsTile.setSubtitle(subtitle); + } qsTile.setState(state); - String subtitle = state == Tile.STATE_ACTIVE ? - getString(R.string.tile_on) : - getString(R.string.tile_off); - qsTile.setSubtitle(subtitle); qsTile.updateTile(); } } diff --git a/src/org/evolution/pixelparts/saturation/SaturationActivity.java b/src/org/evolution/pixelparts/saturation/SaturationActivity.java index 2bc139e..eb7dc83 100644 --- a/src/org/evolution/pixelparts/saturation/SaturationActivity.java +++ b/src/org/evolution/pixelparts/saturation/SaturationActivity.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * 2018 Havoc-OS * SPDX-License-Identifier: Apache-2.0 */ @@ -27,8 +27,6 @@ public class SaturationActivity extends CollapsingToolbarBaseActivity { private LinearLayout mSliderDotsPanel; private ImageView[] mDots; - private Saturation mSaturationFragment; - @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -36,15 +34,8 @@ public class SaturationActivity extends CollapsingToolbarBaseActivity { setupImageSlider(); - Fragment fragment = getFragmentManager().findFragmentById(R.id.saturation); - if (fragment == null) { - mSaturationFragment = new Saturation(); - getFragmentManager().beginTransaction() - .add(R.id.saturation, mSaturationFragment) - .commit(); - } else { - mSaturationFragment = (Saturation) fragment; - } + getFragmentManager().beginTransaction().replace(R.id.saturation, + new SaturationFragment(), TAG).commit(); } private void setupImageSlider() { diff --git a/src/org/evolution/pixelparts/saturation/Saturation.java b/src/org/evolution/pixelparts/saturation/SaturationFragment.java similarity index 88% rename from src/org/evolution/pixelparts/saturation/Saturation.java rename to src/org/evolution/pixelparts/saturation/SaturationFragment.java index 9ba8596..7bb8c68 100644 --- a/src/org/evolution/pixelparts/saturation/Saturation.java +++ b/src/org/evolution/pixelparts/saturation/SaturationFragment.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ @@ -15,13 +15,12 @@ import androidx.preference.PreferenceManager; import java.io.IOException; -import org.evolution.pixelparts.misc.Constants; -import org.evolution.pixelparts.preferences.CustomSeekBarPreference; +import org.evolution.pixelparts.Constants; +import org.evolution.pixelparts.CustomSeekBarPreference; import org.evolution.pixelparts.R; -public class Saturation extends PreferenceFragment +public class SaturationFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener { - private static final String TAG = Saturation.class.getSimpleName(); // Saturation preference private CustomSeekBarPreference mSaturationPreference; diff --git a/src/org/evolution/pixelparts/services/SaturationTileService.java b/src/org/evolution/pixelparts/saturation/SaturationTileService.java similarity index 86% rename from src/org/evolution/pixelparts/services/SaturationTileService.java rename to src/org/evolution/pixelparts/saturation/SaturationTileService.java index 44b2a18..d60db11 100644 --- a/src/org/evolution/pixelparts/services/SaturationTileService.java +++ b/src/org/evolution/pixelparts/saturation/SaturationTileService.java @@ -1,25 +1,17 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ -package org.evolution.pixelparts.services; +package org.evolution.pixelparts.saturation; import android.app.PendingIntent; import android.content.Intent; import android.service.quicksettings.Tile; import android.service.quicksettings.TileService; -import org.evolution.pixelparts.saturation.SaturationActivity; - public class SaturationTileService extends TileService { - private void updateTile() { - final Tile tile = getQsTile(); - tile.setState(Tile.STATE_ACTIVE); - tile.updateTile(); - } - @Override public void onStartListening() { super.onStartListening(); @@ -39,4 +31,10 @@ public class SaturationTileService extends TileService { ); startActivityAndCollapse(pendingIntent); } + + private void updateTile() { + final Tile tile = getQsTile(); + tile.setState(Tile.STATE_ACTIVE); + tile.updateTile(); + } } diff --git a/src/org/evolution/pixelparts/saturation/ViewPagerAdapter.java b/src/org/evolution/pixelparts/saturation/ViewPagerAdapter.java index 4d7bff0..a2ed396 100644 --- a/src/org/evolution/pixelparts/saturation/ViewPagerAdapter.java +++ b/src/org/evolution/pixelparts/saturation/ViewPagerAdapter.java @@ -1,6 +1,6 @@ /* * Copyright (C) 2018 Havoc-OS - * 2023 The Evolution X Project + * 2023-2024 The Evolution X Project * SPDX-License-Identifier: GPL-2.0-or-later */ diff --git a/src/org/evolution/pixelparts/services/HBMService.java b/src/org/evolution/pixelparts/services/HBMService.java deleted file mode 100644 index 56241ee..0000000 --- a/src/org/evolution/pixelparts/services/HBMService.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2023 The Evolution X Project - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.evolution.pixelparts.services; - -import android.app.Service; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.os.IBinder; -import android.preference.PreferenceManager; - -import org.evolution.pixelparts.misc.Constants; - -public class HBMService extends Service { - - private BroadcastReceiver mReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - String action = intent.getAction(); - if (action.equals(Intent.ACTION_SCREEN_OFF)) { - SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); - SharedPreferences.Editor editor = preferences.edit(); - editor.putBoolean(Constants.KEY_HBM, false); - editor.commit(); - stopSelf(); - } - } - }; - - @Override - public int onStartCommand(Intent intent, int flags, int startId) { - IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SCREEN_OFF); - registerReceiver(mReceiver, intentFilter); - return START_REDELIVER_INTENT; - } - - @Override - public IBinder onBind(Intent intent) { - return null; - } - - @Override - public void onDestroy() { - unregisterReceiver(mReceiver); - super.onDestroy(); - } -} diff --git a/src/org/evolution/pixelparts/services/HBMTileService.java b/src/org/evolution/pixelparts/services/HBMTileService.java deleted file mode 100644 index 27c1f1b..0000000 --- a/src/org/evolution/pixelparts/services/HBMTileService.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2023 The Evolution X Project - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.evolution.pixelparts.services; - -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.content.SharedPreferences; -import android.content.BroadcastReceiver; -import android.service.quicksettings.Tile; -import android.service.quicksettings.TileService; -import androidx.preference.PreferenceManager; - -import org.evolution.pixelparts.misc.Constants; -import org.evolution.pixelparts.R; -import org.evolution.pixelparts.utils.FileUtils; - -public class HBMTileService extends TileService { - - private BroadcastReceiver screenStateReceiver = new BroadcastReceiver() { - @Override - public void onReceive(Context context, Intent intent) { - if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); - sharedPrefs.edit().putBoolean(Constants.KEY_HBM, false).commit(); - updateTile(false); - } - } - }; - - private void updateTile(boolean enabled) { - final Tile tile = getQsTile(); - if (FileUtils.isFileWritable(Constants.NODE_HBM)) { - tile.setState(enabled ? Tile.STATE_ACTIVE : Tile.STATE_INACTIVE); - String subtitle = enabled ? getString(R.string.tile_on) : getString(R.string.tile_off); - tile.setSubtitle(subtitle); - tile.updateTile(); - } else { - tile.setState(Tile.STATE_UNAVAILABLE); - } - tile.updateTile(); - } - - @Override - public void onCreate() { - super.onCreate(); - IntentFilter filter = new IntentFilter(); - filter.addAction(Intent.ACTION_SCREEN_OFF); - registerReceiver(screenStateReceiver, filter); - } - - @Override - public void onDestroy() { - super.onDestroy(); - unregisterReceiver(screenStateReceiver); - } - - @Override - public void onStartListening() { - super.onStartListening(); - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - updateTile(sharedPrefs.getBoolean(Constants.KEY_HBM, false)); - } - - @Override - public void onStopListening() { - super.onStopListening(); - } - - @Override - public void onClick() { - super.onClick(); - SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); - final boolean enabled = !(sharedPrefs.getBoolean(Constants.KEY_HBM, false)); - FileUtils.writeValue(Constants.NODE_HBM, enabled ? "1" : "0"); - sharedPrefs.edit().putBoolean(Constants.KEY_HBM, enabled).commit(); - updateTile(enabled); - } -} diff --git a/src/org/evolution/pixelparts/services/PixelPartsTileService.java b/src/org/evolution/pixelparts/services/PixelPartsTileService.java deleted file mode 100644 index de6f7d8..0000000 --- a/src/org/evolution/pixelparts/services/PixelPartsTileService.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2023 The Evolution X Project - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.evolution.pixelparts.services; - -import android.app.PendingIntent; -import android.content.Intent; -import android.service.quicksettings.Tile; -import android.service.quicksettings.TileService; - -import org.evolution.pixelparts.PixelPartsActivity; - -public class PixelPartsTileService extends TileService { - - private void updateTile() { - final Tile tile = getQsTile(); - tile.setState(Tile.STATE_ACTIVE); - tile.updateTile(); - } - - @Override - public void onStartListening() { - super.onStartListening(); - updateTile(); - } - - @Override - public void onClick() { - super.onClick(); - Intent intent = new Intent(this, PixelPartsActivity.class); - intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); - PendingIntent pendingIntent = PendingIntent.getActivity( - this, - 0, - intent, - PendingIntent.FLAG_IMMUTABLE - ); - startActivityAndCollapse(pendingIntent); - } -} diff --git a/src/org/evolution/pixelparts/uibench/JitterTestActivity.java b/src/org/evolution/pixelparts/uibench/JitterTestActivity.java deleted file mode 100644 index 676dbaf..0000000 --- a/src/org/evolution/pixelparts/uibench/JitterTestActivity.java +++ /dev/null @@ -1,357 +0,0 @@ -/* - * Copyright (C) 2016 The Android Open Source Project - * SPDX-License-Identifier: GPL-2.0-or-later - */ - -package org.evolution.pixelparts.uibench; - -import android.app.Activity; -import android.content.Context; -import android.graphics.Canvas; -import android.graphics.Color; -import android.graphics.ColorFilter; -import android.graphics.Paint; -import android.graphics.PixelFormat; -import android.graphics.Rect; -import android.graphics.drawable.Drawable; -import android.os.Bundle; -import android.os.Handler; -import android.os.HandlerThread; -import android.os.Message; -import android.util.AttributeSet; -import android.view.FrameMetrics; -import android.view.View; -import android.view.Window; -import android.view.Window.OnFrameMetricsAvailableListener; -import android.view.animation.AnimationUtils; -import android.widget.TextView; - -import org.evolution.pixelparts.R; - -public class JitterTestActivity extends Activity { - private TextView mJitterReport; - private TextView mUiFrameTimeReport; - private TextView mRenderThreadTimeReport; - private TextView mTotalFrameTimeReport; - private TextView mMostlyTotalFrameTimeReport; - private PointGraphView mGraph; - - private static Handler sMetricsHandler; - static { - HandlerThread thread = new HandlerThread("frameMetricsListener"); - thread.start(); - sMetricsHandler = new Handler(thread.getLooper()); - } - - private Handler mUpdateHandler = new Handler() { - @Override - public void handleMessage(Message msg) { - switch (msg.what) { - case R.id.jitter_mma: - mJitterReport.setText((CharSequence) msg.obj); - break; - case R.id.totalish_mma: - mMostlyTotalFrameTimeReport.setText((CharSequence) msg.obj); - break; - case R.id.ui_frametime_mma: - mUiFrameTimeReport.setText((CharSequence) msg.obj); - break; - case R.id.rt_frametime_mma: - mRenderThreadTimeReport.setText((CharSequence) msg.obj); - break; - case R.id.total_mma: - mTotalFrameTimeReport.setText((CharSequence) msg.obj); - break; - case R.id.graph: - mGraph.addJitterSample(msg.arg1, msg.arg2); - break; - } - } - }; - - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - setContentView(R.layout.rendering_jitter); - View content = findViewById(android.R.id.content); - content.setBackground(new AnimatedBackgroundDrawable()); - content.setKeepScreenOn(true); - mJitterReport = findViewById(R.id.jitter_mma); - mMostlyTotalFrameTimeReport = findViewById(R.id.totalish_mma); - mUiFrameTimeReport = findViewById(R.id.ui_frametime_mma); - mRenderThreadTimeReport = findViewById(R.id.rt_frametime_mma); - mTotalFrameTimeReport = findViewById(R.id.total_mma); - mGraph = findViewById(R.id.graph); - mJitterReport.setText("abcdefghijklmnopqrstuvwxyz"); - mMostlyTotalFrameTimeReport.setText("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - mUiFrameTimeReport.setText("0123456789"); - mRenderThreadTimeReport.setText(",.!()[]{};"); - getWindow().addOnFrameMetricsAvailableListener(mMetricsListener, sMetricsHandler); - } - - public static final class PointGraphView extends View { - private static final float[] JITTER_LINES_MS = { - .5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 5.0f - }; - private static final String[] JITTER_LINES_LABELS = makeLabels(JITTER_LINES_MS); - private static final int[] JITTER_LINES_COLORS = new int[] { - 0xFF00E676, 0xFFFFF176, 0xFFFDD835, 0xFFFBC02D, 0xFFF9A825, - 0xFFF57F17, 0xFFDD2C00 - }; - private Paint mPaint = new Paint(); - private float[] mJitterYs = new float[JITTER_LINES_MS.length]; - private float mLabelWidth; - private float mLabelHeight; - private float mDensity; - private float mGraphScale; - private float mGraphMaxMs; - - private float[] mJitterPoints; - private float[] mJitterAvgPoints; - - public PointGraphView(Context context, AttributeSet attrs) { - super(context, attrs); - setWillNotDraw(false); - mDensity = context.getResources().getDisplayMetrics().density; - mPaint.setTextSize(dp(10)); - Rect textBounds = new Rect(); - mPaint.getTextBounds("8.8", 0, 3, textBounds); - mLabelWidth = textBounds.width() + dp(2); - mLabelHeight = textBounds.height(); - } - - public void addJitterSample(int jitterUs, int jitterUsAvg) { - for (int i = 1; i < mJitterPoints.length - 2; i += 2) { - mJitterPoints[i] = mJitterPoints[i + 2]; - mJitterAvgPoints[i] = mJitterAvgPoints[i + 2]; - } - mJitterPoints[mJitterPoints.length - 1] = - getHeight() - mGraphScale * (jitterUs / 1000.0f); - mJitterAvgPoints[mJitterAvgPoints.length - 1] = - getHeight() - mGraphScale * (jitterUsAvg / 1000.0f); - invalidate(); - } - - private float dp(float dp) { - return mDensity * dp; - } - - @Override - protected void onDraw(Canvas canvas) { - canvas.drawColor(0x90000000); - int h = getHeight(); - int w = getWidth(); - mPaint.setColor(Color.WHITE); - mPaint.setStrokeWidth(dp(1)); - canvas.drawLine(mLabelWidth, 0, mLabelWidth, h, mPaint); - for (int i = 0; i < JITTER_LINES_LABELS.length; i++) { - canvas.drawText(JITTER_LINES_LABELS[i], - 0, (float) Math.floor(mJitterYs[i] + mLabelHeight * .5f), mPaint); - } - for (int i = 0; i < JITTER_LINES_LABELS.length; i++) { - mPaint.setColor(JITTER_LINES_COLORS[i]); - canvas.drawLine(mLabelWidth, mJitterYs[i], w, mJitterYs[i], mPaint); - } - mPaint.setStrokeWidth(dp(2)); - mPaint.setColor(Color.WHITE); - canvas.drawPoints(mJitterPoints, mPaint); - mPaint.setColor(0xFF2196F3); - canvas.drawPoints(mJitterAvgPoints, mPaint); - } - - @Override - protected void onSizeChanged(int w, int h, int oldw, int oldh) { - super.onSizeChanged(w, h, oldw, oldh); - int graphWidth = (int) ((w - mLabelWidth - dp(1)) / mDensity); - float[] oldJitterPoints = mJitterPoints; - float[] oldJitterAvgPoints = mJitterAvgPoints; - mJitterPoints = new float[graphWidth * 2]; - mJitterAvgPoints = new float[graphWidth * 2]; - for (int i = 0; i < mJitterPoints.length; i += 2) { - mJitterPoints[i] = mLabelWidth + (i / 2 + 1) * mDensity; - mJitterAvgPoints[i] = mJitterPoints[i]; - } - if (oldJitterPoints != null) { - int newIndexShift = Math.max(mJitterPoints.length - oldJitterPoints.length, 0); - int oldIndexShift = oldJitterPoints.length - mJitterPoints.length; - for (int i = 1 + newIndexShift; i < mJitterPoints.length; i += 2) { - mJitterPoints[i] = oldJitterPoints[i + oldIndexShift]; - mJitterAvgPoints[i] = oldJitterAvgPoints[i + oldIndexShift]; - } - } - mGraphMaxMs = JITTER_LINES_MS[JITTER_LINES_MS.length - 1] + .5f; - mGraphScale = (h / mGraphMaxMs); - for (int i = 0; i < JITTER_LINES_MS.length; i++) { - mJitterYs[i] = (float) Math.floor(h - mGraphScale * JITTER_LINES_MS[i]); - } - } - - private static String[] makeLabels(float[] divisions) { - String[] ret = new String[divisions.length]; - for (int i = 0; i < divisions.length; i++) { - ret[i] = Float.toString(divisions[i]); - } - return ret; - } - } - - private final OnFrameMetricsAvailableListener mMetricsListener = new OnFrameMetricsAvailableListener() { - private final static double WEIGHT = 40; - private long mPreviousFrameTotal; - private double mJitterMma; - private double mUiFrametimeMma; - private double mRtFrametimeMma; - private double mTotalFrametimeMma; - private double mMostlyTotalFrametimeMma; - private boolean mNeedsFirstValues = true; - - @Override - public void onFrameMetricsAvailable(Window window, FrameMetrics frameMetrics, - int dropCountSinceLastInvocation) { - if (frameMetrics.getMetric(FrameMetrics.FIRST_DRAW_FRAME) == 1) { - return; - } - - long uiDuration = frameMetrics.getMetric(FrameMetrics.INPUT_HANDLING_DURATION) - + frameMetrics.getMetric(FrameMetrics.ANIMATION_DURATION) - + frameMetrics.getMetric(FrameMetrics.LAYOUT_MEASURE_DURATION) - + frameMetrics.getMetric(FrameMetrics.DRAW_DURATION); - long rtDuration = frameMetrics.getMetric(FrameMetrics.SYNC_DURATION) - + frameMetrics.getMetric(FrameMetrics.COMMAND_ISSUE_DURATION); - long totalDuration = frameMetrics.getMetric(FrameMetrics.TOTAL_DURATION); - long jitter = Math.abs(totalDuration - mPreviousFrameTotal); - if (mNeedsFirstValues) { - mJitterMma = 0; - mUiFrametimeMma = uiDuration; - mRtFrametimeMma = rtDuration; - mTotalFrametimeMma = totalDuration; - mMostlyTotalFrametimeMma = uiDuration + rtDuration; - mNeedsFirstValues = false; - } else { - mJitterMma = add(mJitterMma, jitter); - mUiFrametimeMma = add(mUiFrametimeMma, uiDuration); - mRtFrametimeMma = add(mRtFrametimeMma, rtDuration); - mTotalFrametimeMma = add(mTotalFrametimeMma, totalDuration); - mMostlyTotalFrametimeMma = add(mMostlyTotalFrametimeMma, uiDuration + rtDuration); - } - mPreviousFrameTotal = totalDuration; - mUpdateHandler.obtainMessage(R.id.jitter_mma, - String.format("Jitter: %.3fms", toMs(mJitterMma))).sendToTarget(); - mUpdateHandler.obtainMessage(R.id.totalish_mma, - String.format("CPU-total duration: %.3fms", toMs(mMostlyTotalFrametimeMma))).sendToTarget(); - mUpdateHandler.obtainMessage(R.id.ui_frametime_mma, - String.format("UI duration: %.3fms", toMs(mUiFrametimeMma))).sendToTarget(); - mUpdateHandler.obtainMessage(R.id.rt_frametime_mma, - String.format("RT duration: %.3fms", toMs(mRtFrametimeMma))).sendToTarget(); - mUpdateHandler.obtainMessage(R.id.total_mma, - String.format("Total duration: %.3fms", toMs(mTotalFrametimeMma))).sendToTarget(); - mUpdateHandler.obtainMessage(R.id.graph, (int) (jitter / 1000), - (int) (mJitterMma / 1000)).sendToTarget(); - } - - double add(double previous, double today) { - return (((WEIGHT - 1) * previous) + today) / WEIGHT; - } - - double toMs(double val) { - return val / 1000000; - } - }; - - private static final class AnimatedBackgroundDrawable extends Drawable { - private static final int FROM_COLOR = 0xFF18FFFF; - private static final int TO_COLOR = 0xFF40C4FF; - private static final int DURATION = 1400; - - private final Paint mPaint; - private boolean mReverse; - private long mStartTime; - private int mColor; - - private boolean mReverseX; - private boolean mReverseY; - private float mX; - private float mY; - private float mRadius; - private float mMoveStep = 10.0f; - - public AnimatedBackgroundDrawable() { - mPaint = new Paint(); - mPaint.setColor(0xFFFFFF00); - mPaint.setAntiAlias(true); - } - - @Override - public void draw(Canvas canvas) { - stepColor(); - canvas.drawColor(mColor); - - mX += (mReverseX ? -mMoveStep : mMoveStep); - mY += (mReverseY ? -mMoveStep : mMoveStep); - clampXY(); - canvas.drawCircle(mX, mY, mRadius, mPaint); - - invalidateSelf(); - } - - private void clampXY() { - if (mX <= mRadius) { - mReverseX = false; - mX = mRadius; - } - if (mY <= mRadius) { - mReverseY = false; - mY = mRadius; - } - float maxX = getBounds().width() - mRadius; - if (mX >= maxX) { - mReverseX = true; - mX = maxX; - } - float maxY = getBounds().height() - mRadius; - if (mY >= maxY) { - mReverseY = true; - mY = maxY; - } - } - - @Override - protected void onBoundsChange(Rect bounds) { - super.onBoundsChange(bounds); - mMoveStep = Math.min(bounds.width(), bounds.height()) / 130.0f; - mRadius = Math.min(bounds.width(), bounds.height()) / 20.0f; - } - - @Override - public void setAlpha(int alpha) { - } - - @Override - public void setColorFilter(ColorFilter colorFilter) { - } - - @Override - public int getOpacity() { - return PixelFormat.OPAQUE; - } - - private void stepColor() { - if (mStartTime == 0) { - mStartTime = AnimationUtils.currentAnimationTimeMillis(); - } - float frac = (AnimationUtils.currentAnimationTimeMillis() - mStartTime) - / (float) DURATION; - if (frac > 1.0f) frac = 1.0f; - int dest = mReverse ? FROM_COLOR : TO_COLOR; - int src = mReverse ? TO_COLOR : FROM_COLOR; - int r = (int) (Color.red(src) + (Color.red(dest) - Color.red(src)) * frac); - int g = (int) (Color.green(src) + (Color.green(dest) - Color.green(src)) * frac); - int b = (int) (Color.blue(src) + (Color.blue(dest) - Color.blue(src)) * frac); - mColor = Color.rgb(r, g, b); - if (frac == 1.0f) { - mStartTime = 0; - mReverse = !mReverse; - } - } - } -} diff --git a/src/org/evolution/pixelparts/utils/AutoHBMUtils.java b/src/org/evolution/pixelparts/utils/AutoHBMUtils.java deleted file mode 100644 index 32f84e9..0000000 --- a/src/org/evolution/pixelparts/utils/AutoHBMUtils.java +++ /dev/null @@ -1,33 +0,0 @@ -package org.evolution.pixelparts.utils; - -import android.content.Context; -import android.content.Intent; -import android.os.UserHandle; - -import org.evolution.pixelparts.autohbm.AutoHBM; -import org.evolution.pixelparts.services.AutoHBMService; - -public class AutoHBMUtils { - - private static boolean mAutoHBMEnabled = false; - - private static void startAutoHBM(Context context) { - context.startServiceAsUser(new Intent(context, AutoHBMService.class), - UserHandle.CURRENT); - mAutoHBMEnabled = true; - } - - private static void stopAutoHBM(Context context) { - mAutoHBMEnabled = false; - context.stopServiceAsUser(new Intent(context, AutoHBMService.class), - UserHandle.CURRENT); - } - - public static void enableAutoHBM(Context context) { - if (AutoHBM.isAutoHBMEnabled(context) && !mAutoHBMEnabled) { - startAutoHBM(context); - } else if (!AutoHBM.isAutoHBMEnabled(context) && mAutoHBMEnabled) { - stopAutoHBM(context); - } - } -} diff --git a/src/org/evolution/pixelparts/utils/ComponentUtils.java b/src/org/evolution/pixelparts/utils/ComponentUtils.java index 05cfde2..5e80efb 100644 --- a/src/org/evolution/pixelparts/utils/ComponentUtils.java +++ b/src/org/evolution/pixelparts/utils/ComponentUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2023 The Evolution X Project + * Copyright (C) 2023-2024 The Evolution X Project * SPDX-License-Identifier: Apache-2.0 */ @@ -18,7 +18,7 @@ public class ComponentUtils { * @param componentClass The class of the component to be enabled or disabled. * @param enable If true, the component will be enabled; if false, it will be disabled. */ - public static void setComponentEnabled(Context context, Class componentClass, boolean enable) { + public static void toggleComponent(Context context, Class componentClass, boolean enable) { ComponentName componentName = new ComponentName(context, componentClass); PackageManager packageManager = context.getPackageManager(); int currentState = packageManager.getComponentEnabledSetting(componentName); diff --git a/src/org/evolution/pixelparts/utils/ShakeUtils.kt b/src/org/evolution/pixelparts/utils/ShakeUtils.kt deleted file mode 100644 index cab78f8..0000000 --- a/src/org/evolution/pixelparts/utils/ShakeUtils.kt +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2021-2022 Miku UI - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.evolution.pixelparts.utils; - -import android.content.Context -import android.hardware.Sensor -import android.hardware.SensorEvent -import android.hardware.SensorEventListener -import android.hardware.SensorManager -import kotlin.math.sqrt - -class ShakeUtils(context: Context) : SensorEventListener { - private var mOnShakeListeners: ArrayList? = null - - // Last time we triggered shake - private var mLastShakeTime = 0L - private var mLastUpdateTime = 0L - - // Last position we triggered shake - private var mLastX = 0f - private var mLastY = 0f - private var mLastZ = 0f - - interface OnShakeListener { - fun onShake(speed: Double) - } - - fun bindShakeListener(listener: OnShakeListener?) { - if (listener != null) { - mOnShakeListeners?.add(listener) - } - } - - fun unBindShakeListener(listener: OnShakeListener) { - mOnShakeListeners?.remove(listener) - } - - override fun onSensorChanged(event: SensorEvent) { - if (event == null) { - return - } - val curUpdateTime = System.currentTimeMillis() - // Times between two shakes - val timeInterval = curUpdateTime - mLastUpdateTime - if (timeInterval < SHAKE_INTERVAL_MILLISECOND) { - return - } - if (event.values.size < 3) { - return - } - mLastUpdateTime = curUpdateTime - val x = event.values[0] - val y = event.values[1] - val z = event.values[2] - val deltaX = x - mLastX - val deltaY = y - mLastY - val deltaZ = z - mLastZ - mLastX = x - mLastY = y - mLastZ = z - val speed = - sqrt((deltaX * deltaX + deltaY * deltaY + deltaZ * deltaZ).toDouble()) * 1000.0 / timeInterval - if (speed >= SPEED_SHAKE_MILLISECONDS) { - startShake(speed) - } - } - - private fun startShake(speed: Double) { - val curShakeTime = System.currentTimeMillis() - if (curShakeTime - mLastShakeTime < MIN_SHAKE_INTERVAL) { - return - } - mLastShakeTime = curShakeTime - mOnShakeListeners?.let { - for (i in it.indices) { - it[i].onShake(speed) - } - } - } - - override fun onAccuracyChanged(sensor: Sensor, accuracy: Int) {} - - companion object { - - // Minimal time interval of position changes - private const val MIN_SHAKE_INTERVAL = 1024 - - // Minimal shake speed - private const val SPEED_SHAKE_MILLISECONDS = 400 - - // Minimal time interval between two shakes - private const val SHAKE_INTERVAL_MILLISECOND = 55 - } - - init { - val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager - val sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) - mSensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI) - mOnShakeListeners = ArrayList() - } -} diff --git a/src/org/evolution/pixelparts/utils/TorchUtils.java b/src/org/evolution/pixelparts/utils/TorchUtils.java deleted file mode 100644 index 4788b49..0000000 --- a/src/org/evolution/pixelparts/utils/TorchUtils.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2023 The Evolution X Project - * SPDX-License-Identifier: Apache-2.0 - */ - -package org.evolution.pixelparts.utils; - -import android.content.Context; -import android.content.pm.PackageManager; - -public class TorchUtils { - - /** - * Checks if the device has torch hardware. - * - * @param context The context used to access the package manager. - * @return True if the device has torch hardware, false otherwise. - */ - public static boolean hasTorch(Context context) { - PackageManager packageManager = context.getPackageManager(); - return packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH); - } -}