Repository: sosauce/CuteCalc Branch: main Commit: 366abd3b2ef5 Files: 105 Total size: 238.2 KB Directory structure: gitextract_votdenm3/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── feature_request.md │ │ ├── logic-bug.md │ │ └── ui-bug.md │ └── workflows/ │ └── release_stable.yml ├── .gitignore ├── LICENSE ├── README.md ├── app/ │ ├── .gitignore │ ├── build.gradle.kts │ ├── proguard-rules.pro │ └── src/ │ └── main/ │ ├── AndroidManifest.xml │ ├── java/ │ │ └── com/ │ │ └── sosauce/ │ │ └── vanilla/ │ │ ├── MainActivity.kt │ │ ├── data/ │ │ │ ├── actions/ │ │ │ │ └── CalcAction.kt │ │ │ ├── calculator/ │ │ │ │ ├── Evaluator.kt │ │ │ │ └── Tokens.kt │ │ │ ├── datastore/ │ │ │ │ ├── DataStore.kt │ │ │ │ └── SettingsExt.kt │ │ │ └── sysui/ │ │ │ └── QSTile.kt │ │ ├── domain/ │ │ │ ├── model/ │ │ │ │ └── Calculation.kt │ │ │ └── repository/ │ │ │ ├── HistoryDao.kt │ │ │ ├── HistoryDatabase.kt │ │ │ ├── HistoryEvents.kt │ │ │ └── HistoryState.kt │ │ ├── ui/ │ │ │ ├── navigation/ │ │ │ │ ├── Navigation.kt │ │ │ │ └── Screens.kt │ │ │ ├── screens/ │ │ │ │ ├── calculator/ │ │ │ │ │ ├── CalculatorScreen.kt │ │ │ │ │ ├── CalculatorScreenLandscape.kt │ │ │ │ │ ├── CalculatorViewModel.kt │ │ │ │ │ └── components/ │ │ │ │ │ ├── CalcButton.kt │ │ │ │ │ ├── CalculationDisplay.kt │ │ │ │ │ ├── CuteButton.kt │ │ │ │ │ └── DisableSoftKeyboard.kt │ │ │ │ ├── history/ │ │ │ │ │ ├── HistoryScreen.kt │ │ │ │ │ ├── HistoryViewModel.kt │ │ │ │ │ └── components/ │ │ │ │ │ ├── DeletionConfirmationDialog.kt │ │ │ │ │ └── HistoryActionButtons.kt │ │ │ │ └── settings/ │ │ │ │ ├── SettingsFormatting.kt │ │ │ │ ├── SettingsHistory.kt │ │ │ │ ├── SettingsLookAndFeel.kt │ │ │ │ ├── SettingsMisc.kt │ │ │ │ ├── SettingsScreen.kt │ │ │ │ └── components/ │ │ │ │ ├── AboutCard.kt │ │ │ │ ├── FontSelector.kt │ │ │ │ ├── LazyRowWithScrollButton.kt │ │ │ │ ├── SettingsCategoryCard.kt │ │ │ │ ├── SettingsSwitch.kt │ │ │ │ ├── SettingsWithTitle.kt │ │ │ │ └── ThemeSelector.kt │ │ │ ├── shared_components/ │ │ │ │ └── AnimatedFab.kt │ │ │ └── theme/ │ │ │ └── Theme.kt │ │ └── utils/ │ │ ├── Constants.kt │ │ ├── Extensions.kt │ │ └── ViewModelFactories.kt │ └── res/ │ ├── drawable/ │ │ ├── amoled.xml │ │ ├── arrow_right.xml │ │ ├── arrow_up.xml │ │ ├── back_arrow.xml │ │ ├── backspace_filled.xml │ │ ├── backspace_rounded.xml │ │ ├── calculator.xml │ │ ├── check.xml │ │ ├── close.xml │ │ ├── copy.xml │ │ ├── dark_mode.xml │ │ ├── delete.xml │ │ ├── favorite_filled.xml │ │ ├── formatting.xml │ │ ├── github.xml │ │ ├── history_rounded.xml │ │ ├── ic_launcher_foreground.xml │ │ ├── icon_splash.xml │ │ ├── light_mode.xml │ │ ├── more_horiz.xml │ │ ├── more_vert.xml │ │ ├── palette.xml │ │ ├── parentheses.xml │ │ ├── settings_filled.xml │ │ ├── sort_rounded.xml │ │ ├── system_theme.xml │ │ ├── trash_rounded.xml │ │ └── undo.xml │ ├── mipmap-anydpi-v26/ │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ ├── values/ │ │ ├── colors.xml │ │ ├── ic_launcher_background.xml │ │ ├── strings.xml │ │ └── themes.xml │ ├── values-es/ │ │ └── strings.xml │ ├── values-fr-rFR/ │ │ └── strings.xml │ ├── values-v31/ │ │ └── colors.xml │ └── values-zh-rCN/ │ └── strings.xml ├── build.gradle.kts ├── fastlane/ │ └── metadata/ │ └── android/ │ ├── de/ │ │ ├── full_description.txt │ │ └── short_description.txt │ └── en-US/ │ ├── full_description.txt │ └── short_description.txt ├── font_licence.txt ├── gradle/ │ ├── libs.versions.toml │ └── wrapper/ │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradle.properties ├── gradlew ├── gradlew.bat └── settings.gradle.kts ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] patreon: # Replace with a single Patreon username open_collective: # Replace with a single Open Collective username ko_fi: sosauce tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry liberapay: # Replace with a single Liberapay username issuehunt: # Replace with a single IssueHunt username otechie: # Replace with a single Otechie username lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry buy_me_a_coffee: sosauce custom: https://bit.ly/sosaucePayPal ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest a feature title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/ISSUE_TEMPLATE/logic-bug.md ================================================ --- name: Logic Bug about: Use this to report a logic bug title: Logic Bug labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Indicate the steps to reproduce. **Expected behavior** What behavior did you expect ? **Screenshots** If applicable, add screenshots to help explain your problem. **Smartphone (please complete the following information):** - Device: - OS: - Version: **Additional context** Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/ui-bug.md ================================================ --- name: UI Bug about: Use this to report an UI bug title: UI Bug labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Screenshots** If applicable, add screenshots to help explain your problem. **Smartphone (please complete the following information):** - Device: - OS: - Version: **Additional context** Add any other context about the problem here. ================================================ FILE: .github/workflows/release_stable.yml ================================================ name: Release Stable CI on: workflow_dispatch jobs: build: runs-on: ubuntu-latest outputs: versionName: ${{ steps.versionname.outputs.versionName }} steps: - uses: actions/checkout@v4 - name: set up JDK 17 uses: actions/setup-java@v4 with: java-version: '17' distribution: 'temurin' cache: gradle - name: Get versionName id: versionname run: echo "versionName=$(grep 'versionName' app/build.gradle.kts | head -1 | awk -F\" '{ print $2 }')" >> $GITHUB_OUTPUT - name: Grant execute permission for gradlew run: chmod +x gradlew - name: Decode Keystore id: decode_keystore uses: timheuer/base64-to-file@v1 with: fileName: 'release_key.jks' fileDir: 'app/' encodedString: ${{ secrets.SIGNING_KEY }} - name: Build Release APK run: ./gradlew assembleRelease env: SIGNING_KEY_ALIAS: ${{ secrets.KEY_ALIAS }} SIGNING_KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }} SIGNING_STORE_PASSWORD: ${{ secrets.KEYSTORE_PASSWORD }} - uses: actions/upload-artifact@v4 with: name: CuteCalc Release path: app/build/**/*.apk - name: Generate Changelog Content id: generate_changelog uses: release-drafter/release-drafter@v5 with: disable-prerelease: true publish: false - name: Write Changelog to File run: echo "${{ steps.generate_changelog.outputs.body }}" > ${{ needs.build.outputs.versionName }}-changelog.txt release: needs: [build] runs-on: ubuntu-latest steps: - uses: actions/download-artifact@v4 with: name: CuteCalc Release - name: Create Release id: create_release uses: softprops/action-gh-release@v2 with: name: Vesion ${{ needs.build.outputs.versionName }} body_path: ${{ needs.build.outputs.versionName }}-changelog.txt prerelease: false tag_name: v${{ needs.build.outputs.versionName }} files: | ./**/*.apk env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .gitignore ================================================ # Gradle files .gradle/ build/ # Local configuration file (sdk path, etc) local.properties # Log/OS Files *.log # Android Studio generated files and folders captures/ .externalNativeBuild/ .cxx/ *.apk output.json # IntelliJ *.iml .idea/ misc.xml deploymentTargetDropDown.xml render.experimental.xml # Keystore files *.jks *.keystore # Google Services (e.g. APIs or Firebase) google-services.json # Android Profiling *.hprof .DS_Store .kotlin/sessions/kotlin-compiler-9804472835993706459.salive ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================

Vanilla

Vanilla (formerly CuteCalc) is a cute and elegant calculator app for Android !

---

👀 Overview

- Material 3 Expressive design! - Very lightweight! (~5Mb app size) - No permissions needed! - Very fast and feature-rich! ---

🤔 Why ?

I am 15 y/o and have been into computers ever since I was ~10, growing up, I always thought about how software could do anything someone could dream of, so I started learning multiple languages until stepping upon Kotlin. Since then, I've learnt and started to build Android apps, and CuteCalc is my first project upon, I hope, alot more.

---

💬 Contact Me

[Discord server](https://discord.gg/c6aCu4yjbu)
[Email](sosauce_dev@protonmail.com) ---

❤️ Support

If you wish to support me, you can see how to do so on [my website](https://sosauce.github.io/support/) ---

⚠️ Copyright

Copyright (c)2026 sosauce This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. The above copyright notice, this permission notice, and its license shall be included in all copies or substantial portions of the Software. You can find a copy of the GNU General Public License v3 [here](https://www.gnu.org/licenses/)

--- #### You can find the SHA-256 [here](https://sosauce.github.io/projects/) ================================================ FILE: app/.gitignore ================================================ /build /release ================================================ FILE: app/build.gradle.kts ================================================ import com.android.build.api.variant.VariantOutputConfiguration import org.jetbrains.kotlin.gradle.dsl.JvmTarget plugins { alias(libs.plugins.androidApplication) alias(libs.plugins.compose.compiler) alias(libs.plugins.ksp) } androidComponents { onVariants(selector().withBuildType("release")) { variant -> val mainOutput = variant.outputs.single { it.outputType == VariantOutputConfiguration.OutputType.SINGLE } @Suppress("UnstableApiUsage") mainOutput.outputFileName = "Vanilla_${mainOutput.versionName.get()}.apk" } } kotlin { compilerOptions { jvmTarget = JvmTarget.JVM_17 } } android { namespace = "com.sosauce.vanilla" compileSdk = 37 defaultConfig { applicationId = "com.sosauce.cutecalc" minSdk = 23 targetSdk = 37 versionCode = 50002 versionName = "4.0.2" ndk { //noinspection ChromeOsAbiSupport abiFilters += arrayOf("arm64-v8a", "armeabi-v7a") } } buildTypes { release { isMinifyEnabled = true isShrinkResources = true proguardFiles( getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro" ) } } compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } buildFeatures { compose = true aidl = false shaders = false buildConfig = false resValues = false viewBinding = false } dependenciesInfo { includeInApk = false includeInBundle = false } } dependencies { implementation(platform(libs.androidx.compose.bom)) implementation(libs.androidx.activity.compose) implementation(libs.androidx.lifecycle.viewmodel.compose) implementation(libs.androidx.core.splashscreen) implementation(libs.androidx.material3) implementation(libs.androidx.ui) implementation(libs.androidx.datastore.preferences) implementation(libs.keval) implementation(libs.androidx.room.ktx) implementation(libs.squircle.shape) ksp(libs.androidx.room.compiler) } ================================================ FILE: app/proguard-rules.pro ================================================ # Add project specific ProGuard rules here. # You can control the set of applied configuration files using the # proguardFiles setting in build.gradle. # # For more details, see # http://developer.android.com/guide/developing/tools/proguard.html # If your project uses WebView with JS, uncomment the following # and specify the fully qualified class name to the JavaScript interface # class: #-keepclassmembers class fqcn.of.javascript.interface.for.webview { # public *; #} # Uncomment this to preserve the line number information for # debugging stack traces. #-keepattributes SourceFile,LineNumberTable # If you keep the line number information, uncomment this to # hide the original source file name. #-renamesourcefileattribute SourceFile ================================================ FILE: app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: app/src/main/java/com/sosauce/vanilla/MainActivity.kt ================================================ package com.sosauce.vanilla import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.getValue import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.core.view.WindowCompat import com.sosauce.vanilla.data.datastore.rememberAppTheme import com.sosauce.vanilla.data.datastore.rememberShowOnLockScreen import com.sosauce.vanilla.ui.navigation.Nav import com.sosauce.vanilla.ui.theme.CuteCalcTheme import com.sosauce.vanilla.utils.CuteTheme import com.sosauce.vanilla.utils.showOnLockScreen class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) installSplashScreen() enableEdgeToEdge() setContent { val isSystemInDarkTheme = isSystemInDarkTheme() val theme by rememberAppTheme() val showOnLockScreen by rememberShowOnLockScreen() showOnLockScreen(showOnLockScreen) CuteCalcTheme { WindowCompat .getInsetsController(window, window.decorView) .apply { val isLight = if (theme == CuteTheme.SYSTEM) !isSystemInDarkTheme else theme == CuteTheme.LIGHT isAppearanceLightStatusBars = isLight isAppearanceLightNavigationBars = isLight } Nav() } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/data/actions/CalcAction.kt ================================================ package com.sosauce.vanilla.data.actions sealed interface CalcAction { data object GetResult : CalcAction data object ResetField : CalcAction data object Backspace : CalcAction data class AddToField( val char: Char ) : CalcAction data class AddExpressionToField( val expression: String ) : CalcAction } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/data/calculator/Evaluator.kt ================================================ package com.sosauce.vanilla.data.calculator import com.notkamui.keval.Keval import com.notkamui.keval.KevalInvalidArgumentException import com.notkamui.keval.KevalInvalidExpressionException import com.notkamui.keval.KevalZeroDivisionException import java.math.RoundingMode import kotlin.math.floor import kotlin.math.pow import kotlin.math.sqrt class NegativeSquareRootException : RuntimeException("Be for real 3:<") class ValueTooLargeException : RuntimeException("Value too large") object Evaluator { private val KEVAL = Keval.create { binaryOperator { symbol = Tokens.ADD precedence = 2 isLeftAssociative = true implementation = { a, b -> a + b } } unaryOperator { symbol = Tokens.ADD isPrefix = true implementation = { it } } binaryOperator { symbol = Tokens.SUBTRACT precedence = 2 isLeftAssociative = true implementation = { a, b -> a - b } } unaryOperator { symbol = Tokens.SUBTRACT isPrefix = true implementation = { -it } } binaryOperator { symbol = Tokens.MULTIPLY precedence = 3 isLeftAssociative = true implementation = { a, b -> a * b } } binaryOperator { symbol = Tokens.DIVIDE precedence = 3 isLeftAssociative = true implementation = { a, b -> if (b == 0.0) throw KevalZeroDivisionException() a / b } } binaryOperator { symbol = Tokens.POWER precedence = 4 isLeftAssociative = false implementation = { a, b -> a.pow(b) } } unaryOperator { symbol = Tokens.FACTORIAL isPrefix = false implementation = { if (it < 0) throw KevalInvalidArgumentException("Factorial of a negative number") if (floor(it) != it) throw KevalInvalidArgumentException("Factorial of a non-integer") (1..it.toInt()).fold(1.0) { acc, i -> acc * i } } } unaryOperator { symbol = Tokens.SQUARE_ROOT isPrefix = true implementation = { arg -> if (arg < 0) throw NegativeSquareRootException() else sqrt(arg) } } unaryOperator { symbol = Tokens.MODULO isPrefix = false implementation = { arg -> arg / 100 } } constant { name = "PI" value = Math.PI } } private var prevResult: String = "" @JvmStatic fun eval( formula: String, precision: Int ): String = try { val result = KEVAL .eval(formula.replace(Tokens.PI.toString(), "PI").handleRelativePercentage()) val formattedResult = if (result > Double.MAX_VALUE) { throw ValueTooLargeException() } else { result .toBigDecimal() .setScale(precision, RoundingMode.HALF_UP) .stripTrailingZeros() .toPlainString() } prevResult = formattedResult formattedResult } catch (e: KevalInvalidExpressionException) { prevResult } catch (e: Exception) { e.message ?: "Undetermined error" } // We don't call "handleRelativePercentage" here to avoid recursive call @JvmStatic private fun evalParenthesis(formula: String): String { val result = KEVAL.eval(formula) return if (result > Double.MAX_VALUE) { throw ValueTooLargeException() } else { result.toBigDecimal().stripTrailingZeros().toPlainString() } } private fun String.handleRelativePercentage(): String { return relativePercentageRegex.replace(this.processParenthesisExpression()) { match -> val firstOperand = match.groupValues[1].toDouble() val operator = match.groupValues[2] val percentage = match.groupValues[3].toDouble() when (operator) { "+" -> "$firstOperand + ($firstOperand * $percentage / 100)" "-" -> "$firstOperand - ($firstOperand * $percentage / 100)" "*" -> "$firstOperand * ($percentage / 100)" else -> "$firstOperand" } } } private fun String.processParenthesisExpression(): String { var expression = this parenthesisRegex.findAll(this).forEach { matchResult -> val calculated = evalParenthesis(matchResult.value) val replaceWith = if (this.contains("%")) calculated else "($calculated)" expression = expression.replace(matchResult.value, replaceWith) } return expression } private val parenthesisRegex = Regex("""\(([^()]+)\)""") private val relativePercentageRegex = Regex("""(\d+(?:\.\d+)?)\s*([+\-*])\s*(\d+(?:\.\d+)?)%""") } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/data/calculator/Tokens.kt ================================================ package com.sosauce.vanilla.data.calculator object Tokens { const val ONE = '1' const val TWO = '2' const val THREE = '3' const val FOUR = '4' const val FIVE = '5' const val SIX = '6' const val SEVEN = '7' const val EIGHT = '8' const val NINE = '9' const val ZERO = '0' const val FACTORIAL = '!' const val SQUARE_ROOT = '√' const val PI = 'π' const val MODULO = '%' const val OPEN_PARENTHESIS = '(' const val CLOSED_PARENTHESIS = ')' const val POWER = '^' const val DIVIDE = '/' const val ADD = '+' const val SUBTRACT = '-' const val MULTIPLY = '×' const val DECIMAL = '.' } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/data/datastore/DataStore.kt ================================================ package com.sosauce.vanilla.data.datastore import android.content.Context import androidx.compose.runtime.Composable import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.longPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import com.sosauce.vanilla.utils.CuteTheme val Context.dataStore: DataStore by preferencesDataStore(name = "settings") data object PreferencesKeys { val THEME = stringPreferencesKey("theme") val BUTTON_VIBRATION_ENABLED = booleanPreferencesKey("button_vibration_enabled") val DECIMAL_FORMATTING = booleanPreferencesKey("decimal_formatting") val ENABLE_HISTORY = booleanPreferencesKey("enable_history") val HISTORY_MAX_ITEMS = longPreferencesKey("HISTORY_MAX_ITEMS") val SAVE_ERRORS_TO_HISTORY = booleanPreferencesKey("SAVE_ERRORS_TO_HISTORY") val USE_BUTTONS_ANIMATIONS = booleanPreferencesKey("use_buttons_animation") val USE_SYSTEM_FONT = booleanPreferencesKey("use_system_font") val SHOW_CLEAR_BUTTON = booleanPreferencesKey("show_clear_button") val DECIMAL_PRECISION = intPreferencesKey("DECIMAL_PRECISION") val SHOW_ON_LOCKSCREEN = booleanPreferencesKey("SHOW_ON_LOCKSCREEN") val HISTORY_NEWEST_FIRST = booleanPreferencesKey("HISTORY_NEWEST_FIRST") val COLORED_OPERATORS = booleanPreferencesKey("COLORED_OPERATORS") val SWAP_ZERO_AND_DECIMAL = booleanPreferencesKey("SWAP_ZERO_AND_DECIMAL") } @Composable fun rememberVibration() = rememberPreference( key = PreferencesKeys.BUTTON_VIBRATION_ENABLED, defaultValue = false ) @Composable fun rememberAppTheme() = rememberPreference( key = PreferencesKeys.THEME, defaultValue = CuteTheme.SYSTEM ) @Composable fun rememberDecimal() = rememberPreference( key = PreferencesKeys.DECIMAL_FORMATTING, defaultValue = false ) @Composable fun rememberUseHistory() = rememberPreference( key = PreferencesKeys.ENABLE_HISTORY, defaultValue = true ) @Composable fun rememberUseButtonsAnimation() = rememberPreference( key = PreferencesKeys.USE_BUTTONS_ANIMATIONS, defaultValue = true ) @Composable fun rememberUseSystemFont() = rememberPreference( key = PreferencesKeys.USE_SYSTEM_FONT, defaultValue = false ) @Composable fun rememberShowClearButton() = rememberPreference( key = PreferencesKeys.SHOW_CLEAR_BUTTON, defaultValue = true ) @Composable fun rememberHistoryMaxItems() = rememberPreference( key = PreferencesKeys.HISTORY_MAX_ITEMS, defaultValue = Long.MAX_VALUE ) @Composable fun rememberSaveErrorsToHistory() = rememberPreference( key = PreferencesKeys.SAVE_ERRORS_TO_HISTORY, defaultValue = false ) @Composable fun rememberDecimalPrecision() = rememberPreference( key = PreferencesKeys.DECIMAL_PRECISION, defaultValue = 100 ) @Composable fun rememberShowOnLockScreen() = rememberPreference( key = PreferencesKeys.SHOW_ON_LOCKSCREEN, defaultValue = false ) @Composable fun rememberHistoryNewestFirst() = rememberPreference( key = PreferencesKeys.HISTORY_NEWEST_FIRST, defaultValue = true ) @Composable fun rememberColoredOperators() = rememberPreference( key = PreferencesKeys.COLORED_OPERATORS, defaultValue = true ) @Composable fun rememberSwapZeroAndDecimal() = rememberPreference( key = PreferencesKeys.SWAP_ZERO_AND_DECIMAL, defaultValue = false ) fun getDecimalPrecision(context: Context) = getPreference( key = PreferencesKeys.DECIMAL_PRECISION, defaultValue = 1000, context = context ) ================================================ FILE: app/src/main/java/com/sosauce/vanilla/data/datastore/SettingsExt.kt ================================================ package com.sosauce.vanilla.data.datastore import android.content.Context import android.content.res.Configuration import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.platform.LocalContext import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.edit import androidx.lifecycle.compose.collectAsStateWithLifecycle import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch @Composable fun rememberPreference( key: Preferences.Key, defaultValue: T, ): MutableState { val coroutineScope = rememberCoroutineScope() val context = LocalContext.current val state by remember { context.dataStore.data .map { it[key] ?: defaultValue } }.collectAsStateWithLifecycle(initialValue = defaultValue) return remember(state) { object : MutableState { override var value: T get() = state set(value) { coroutineScope.launch { context.dataStore.edit { it[key] = value } } } override fun component1() = value override fun component2(): (T) -> Unit = { value = it } } } } fun getPreference( key: Preferences.Key, defaultValue: T, context: Context ): Flow = context.dataStore.data .map { preference -> preference[key] ?: defaultValue } @Composable fun rememberIsLandscape(): Boolean { val config = LocalConfiguration.current return remember(config.orientation) { config.orientation == Configuration.ORIENTATION_LANDSCAPE } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/data/sysui/QSTile.kt ================================================ package com.sosauce.vanilla.data.sysui import android.app.PendingIntent import android.content.Intent import android.os.Build import android.service.quicksettings.TileService import androidx.annotation.RequiresApi import com.sosauce.vanilla.MainActivity @RequiresApi(Build.VERSION_CODES.N) class QSTile : TileService() { override fun onClick() { super.onClick() val intent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT ) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { startActivityAndCollapse(pendingIntent) } else { val newIntent = Intent(intent).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) startActivity(newIntent) } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/domain/model/Calculation.kt ================================================ package com.sosauce.vanilla.domain.model import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Calculation( val operation: String, val result: String, @PrimaryKey(autoGenerate = true) val id: Int = 0 ) ================================================ FILE: app/src/main/java/com/sosauce/vanilla/domain/repository/HistoryDao.kt ================================================ package com.sosauce.vanilla.domain.repository import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.Query import com.sosauce.vanilla.domain.model.Calculation import kotlinx.coroutines.flow.Flow @Dao interface HistoryDao { @Insert suspend fun insertCalculation(calculation: Calculation) @Delete suspend fun deleteCalculation(calculation: Calculation) @Query("DELETE FROM calculation") suspend fun deleteAllCalculations() @Query("SELECT * FROM calculation ORDER BY id ASC") fun getAllCalculations(): Flow> } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/domain/repository/HistoryDatabase.kt ================================================ package com.sosauce.vanilla.domain.repository import androidx.room.Database import androidx.room.RoomDatabase import com.sosauce.vanilla.domain.model.Calculation @Database( entities = [Calculation::class], version = 1 ) abstract class HistoryDatabase : RoomDatabase() { abstract val dao: HistoryDao } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/domain/repository/HistoryEvents.kt ================================================ package com.sosauce.vanilla.domain.repository import com.sosauce.vanilla.domain.model.Calculation sealed interface HistoryEvents { data class DeleteCalculation(val calculation: Calculation) : HistoryEvents data object DeleteAllCalculation : HistoryEvents data class AddCalculation( val operation: String, val result: String, val maxHistoryItems: Long, val saveErrors: Boolean ) : HistoryEvents } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/domain/repository/HistoryState.kt ================================================ package com.sosauce.vanilla.domain.repository import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import com.sosauce.vanilla.domain.model.Calculation data class HistoryState( val calculations: List = emptyList(), val operation: MutableState = mutableStateOf(""), val result: MutableState = mutableStateOf("") ) ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/navigation/Navigation.kt ================================================ package com.sosauce.vanilla.ui.navigation import androidx.activity.compose.BackHandler import androidx.activity.compose.LocalActivity import androidx.compose.animation.AnimatedContent import androidx.compose.animation.core.Animatable import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.togetherWith import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.retain.retain import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.platform.LocalWindowInfo import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewmodel.compose.viewModel import com.sosauce.vanilla.data.actions.CalcAction import com.sosauce.vanilla.data.datastore.rememberIsLandscape import com.sosauce.vanilla.ui.screens.calculator.CalculatorScreen import com.sosauce.vanilla.ui.screens.calculator.CalculatorScreenLandscape import com.sosauce.vanilla.ui.screens.calculator.CalculatorViewModel import com.sosauce.vanilla.ui.screens.history.HistoryScreen import com.sosauce.vanilla.ui.screens.history.HistoryViewModel import com.sosauce.vanilla.ui.screens.settings.SettingsScreen import com.sosauce.vanilla.utils.CalculatorViewModelFactory import com.sosauce.vanilla.utils.HistoryViewModelFactory import com.sosauce.vanilla.utils.bouncySpec import com.sosauce.vanilla.utils.navigationBouncySpec import kotlinx.coroutines.launch import kotlin.math.roundToInt @Composable fun Nav() { val activity = LocalActivity.current!! val isLandscape = rememberIsLandscape() val viewModel = viewModel(factory = CalculatorViewModelFactory(activity.application)) val historyViewModel = viewModel(factory = HistoryViewModelFactory(activity.application)) var screenToDisplay by rememberSaveable { mutableStateOf(Screens.MAIN) } val windowInfo = LocalWindowInfo.current // Mimic back behavior from navigation BackHandler { if (screenToDisplay != Screens.MAIN) { screenToDisplay = Screens.MAIN } else { activity.moveTaskToBack(true) } } AnimatedContent( targetState = screenToDisplay, transitionSpec = { slideInHorizontally(navigationBouncySpec) { -it } + fadeIn() togetherWith fadeOut() }, modifier = Modifier.background(MaterialTheme.colorScheme.background) ) { screen -> when (screen) { Screens.MAIN -> { // survive config changes without needing a saver val yTranslation = retain { Animatable(0f) } val scope = rememberCoroutineScope() Box( modifier = Modifier.clip(RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)), ) { val calculations by historyViewModel.allCalculations.collectAsStateWithLifecycle() HistoryScreen( calculations = calculations, onEvents = historyViewModel::onEvent, onPutBackToField = { expression -> viewModel.handleAction(CalcAction.AddExpressionToField(expression)) }, onGotoMain = { scope.launch { yTranslation.animateTo(0f, bouncySpec()) } } ) if (isLandscape) { CalculatorScreenLandscape( modifier = Modifier .graphicsLayer { translationY = yTranslation.value }, viewModel = viewModel, historyViewModel = historyViewModel, onNavigate = { screenToDisplay = it }, onGotoHistory = { scope.launch { yTranslation.animateTo(windowInfo.containerSize.height.toFloat(), bouncySpec()) } } ) } else { CalculatorScreen( modifier = Modifier .graphicsLayer { translationY = yTranslation.value }, viewModel = viewModel, onNavigate = { screenToDisplay = it }, historyViewModel = historyViewModel, onUpdateDragAmount = { dragAmount -> val value = (yTranslation.value + dragAmount).coerceAtLeast(0f) // always keep the value positive or else it's a shithole to manage scope.launch { yTranslation.snapTo(value) } }, onDragStopped = { if (yTranslation.value.roundToInt() >= windowInfo.containerSize.height / 2) { yTranslation.animateTo(windowInfo.containerSize.height.toFloat(), bouncySpec()) } else { yTranslation.animateTo(0f, bouncySpec()) } } ) } } } Screens.SETTINGS -> { SettingsScreen( onNavigate = { screenToDisplay = it } ) } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/navigation/Screens.kt ================================================ package com.sosauce.vanilla.ui.navigation enum class Screens { MAIN, SETTINGS } enum class SettingsScreen { SETTINGS, LOOK_AND_FEEL, HISTORY, FORMATTING, MISC } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/calculator/CalculatorScreen.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) package com.sosauce.vanilla.ui.screens.calculator import androidx.compose.foundation.gestures.Orientation import androidx.compose.foundation.gestures.draggable import androidx.compose.foundation.gestures.rememberDraggableState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.BottomSheetDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.runtime.remember import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEach import com.sosauce.vanilla.R import com.sosauce.vanilla.data.actions.CalcAction import com.sosauce.vanilla.data.calculator.Tokens import com.sosauce.vanilla.data.datastore.rememberHistoryMaxItems import com.sosauce.vanilla.data.datastore.rememberSaveErrorsToHistory import com.sosauce.vanilla.data.datastore.rememberShowClearButton import com.sosauce.vanilla.data.datastore.rememberSwapZeroAndDecimal import com.sosauce.vanilla.data.datastore.rememberUseHistory import com.sosauce.vanilla.domain.repository.HistoryEvents import com.sosauce.vanilla.ui.navigation.Screens import com.sosauce.vanilla.ui.screens.calculator.components.ButtonType import com.sosauce.vanilla.ui.screens.calculator.components.CalcButton import com.sosauce.vanilla.ui.screens.calculator.components.CalculationDisplay import com.sosauce.vanilla.ui.screens.calculator.components.CuteButton import com.sosauce.vanilla.ui.screens.history.HistoryViewModel import com.sosauce.vanilla.utils.BACKSPACE import com.sosauce.vanilla.utils.PARENTHESES import com.sosauce.vanilla.utils.whichParenthesis import kotlinx.coroutines.CoroutineScope import java.text.DecimalFormatSymbols @Composable fun CalculatorScreen( modifier: Modifier = Modifier, viewModel: CalculatorViewModel, historyViewModel: HistoryViewModel, onNavigate: (Screens) -> Unit, onUpdateDragAmount: (Float) -> Unit, onDragStopped: suspend CoroutineScope.(Float) -> Unit ) { val localeDecimalChar = remember { DecimalFormatSymbols.getInstance().decimalSeparator.toString() } val showClearButton by rememberShowClearButton() val saveErrorsToHistory by rememberSaveErrorsToHistory() val maxItemsToHistory by rememberHistoryMaxItems() val saveToHistory by rememberUseHistory() val swapZeroAndDecimal by rememberSwapZeroAndDecimal() val row1 = listOf( CalcButton( text = "!", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.FACTORIAL)) }, rectangle = true, type = ButtonType.SPECIAL ), CalcButton( text = "%", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.MODULO)) }, rectangle = true, type = ButtonType.SPECIAL ), CalcButton( text = "√", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SQUARE_ROOT)) }, rectangle = true, type = ButtonType.SPECIAL ), CalcButton( text = "π", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.PI)) }, rectangle = true, type = ButtonType.SPECIAL ) ) val row2 = listOf( if (showClearButton) { CalcButton( text = "C", onClick = { viewModel.handleAction(CalcAction.ResetField) }, type = ButtonType.ACTION ) } else { CalcButton( text = "(", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.OPEN_PARENTHESIS)) }, type = ButtonType.OPERATOR ) }, if (showClearButton) { CalcButton( text = PARENTHESES, onClick = { viewModel.handleAction( CalcAction.AddToField( viewModel.textFieldState.text.toString().whichParenthesis() ) ) }, type = ButtonType.OPERATOR ) } else { CalcButton( text = ")", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.CLOSED_PARENTHESIS)) }, type = ButtonType.OPERATOR ) }, CalcButton( text = "^", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.POWER)) }, type = ButtonType.OPERATOR ), CalcButton( text = "/", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.DIVIDE)) }, type = ButtonType.OPERATOR ) ) val row3 = listOf( CalcButton( text = "7", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SEVEN)) }, type = ButtonType.OTHER ), CalcButton( text = "8", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.EIGHT)) }, type = ButtonType.OTHER ), CalcButton( text = "9", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.NINE)) }, type = ButtonType.OTHER ), CalcButton( text = "×", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.MULTIPLY)) }, type = ButtonType.OPERATOR ) ) val row4 = listOf( CalcButton( text = "4", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.FOUR)) }, type = ButtonType.OTHER ), CalcButton( text = "5", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.FIVE)) }, type = ButtonType.OTHER ), CalcButton( text = "6", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SIX)) }, type = ButtonType.OTHER ), CalcButton( text = "-", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SUBTRACT)) }, type = ButtonType.OPERATOR ) ) val row5 = listOf( CalcButton( text = "1", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.ONE)) }, type = ButtonType.OTHER ), CalcButton( text = "2", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.TWO)) }, type = ButtonType.OTHER ), CalcButton( text = "3", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.THREE)) }, type = ButtonType.OTHER ), CalcButton( text = "+", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.ADD)) }, type = ButtonType.OPERATOR ) ) val row6 = listOf( if (!swapZeroAndDecimal) { CalcButton( text = "0", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.ZERO)) }, type = ButtonType.OTHER ) } else { CalcButton( text = localeDecimalChar, onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.DECIMAL)) }, type = ButtonType.OTHER ) }, if (swapZeroAndDecimal) { CalcButton( text = "0", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.ZERO)) }, type = ButtonType.OTHER ) } else { CalcButton( text = localeDecimalChar, onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.DECIMAL)) }, type = ButtonType.OTHER ) }, CalcButton( text = BACKSPACE, onClick = { viewModel.handleAction(CalcAction.Backspace) }, onLongClick = { viewModel.handleAction(CalcAction.ResetField) }, type = ButtonType.OTHER ), CalcButton( text = "=", onClick = { val operation = viewModel.textFieldState.text.toString() viewModel.handleAction(CalcAction.GetResult) val result = viewModel.evaluatedCalculation if (saveToHistory && operation != result) { historyViewModel.onEvent( HistoryEvents.AddCalculation( operation = operation, result = result, maxHistoryItems = maxItemsToHistory, saveErrors = saveErrorsToHistory ) ) } }, type = ButtonType.ACTION ) ) val dragState = rememberDraggableState { dragAmount -> onUpdateDragAmount(dragAmount) } Scaffold( modifier = modifier, topBar = { CenterAlignedTopAppBar( modifier = Modifier.clip(RoundedCornerShape(topStart = 50.dp, topEnd = 50.dp)), title = { BottomSheetDefaults.DragHandle( color = MaterialTheme.colorScheme.secondary, modifier = Modifier .draggable( state = dragState, orientation = Orientation.Vertical, onDragStopped = onDragStopped ) ) }, actions = { // IconButton( // onClick = {}, // shapes = IconButtonDefaults.shapes() // ) { // Icon( // painter = painterResource(R.drawable.history_rounded), // contentDescription = stringResource(R.string.history), // tint = MaterialTheme.colorScheme.onBackground // ) // } IconButton( onClick = { onNavigate(Screens.SETTINGS) }, shapes = IconButtonDefaults.shapes() ) { Icon( painter = painterResource(R.drawable.settings_filled), contentDescription = stringResource(R.string.settings) ) } } ) } ) { pv -> Column( modifier = Modifier .padding(horizontal = 10.dp) .fillMaxSize() .padding(pv), verticalArrangement = Arrangement.Bottom ) { CalculationDisplay( modifier = Modifier.weight(1f), viewModel = viewModel, onNavigate = onNavigate ) Spacer(Modifier.height(5.dp)) Column( modifier = Modifier .fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(9.dp), ) { val rows = listOf(row1, row2, row3, row4, row5, row6) rows.forEach { row -> Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(9.dp) ) { row.fastForEach { button -> key(button.text) { CuteButton( modifier = Modifier.weight(1f), text = button.text, onClick = button.onClick, onLongClick = button.onLongClick, rectangle = button.rectangle, buttonType = button.type ) } } } } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/calculator/CalculatorScreenLandscape.kt ================================================ @file:OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.calculator import android.annotation.SuppressLint import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.WindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawing import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEach import androidx.compose.ui.zIndex import com.sosauce.vanilla.R import com.sosauce.vanilla.data.actions.CalcAction import com.sosauce.vanilla.data.calculator.Tokens import com.sosauce.vanilla.data.datastore.rememberHistoryMaxItems import com.sosauce.vanilla.data.datastore.rememberSaveErrorsToHistory import com.sosauce.vanilla.data.datastore.rememberShowClearButton import com.sosauce.vanilla.data.datastore.rememberUseHistory import com.sosauce.vanilla.domain.repository.HistoryEvents import com.sosauce.vanilla.ui.navigation.Screens import com.sosauce.vanilla.ui.screens.calculator.components.ButtonType import com.sosauce.vanilla.ui.screens.calculator.components.CalcButton import com.sosauce.vanilla.ui.screens.calculator.components.CalculationDisplay import com.sosauce.vanilla.ui.screens.calculator.components.CuteButton import com.sosauce.vanilla.ui.screens.history.HistoryViewModel import com.sosauce.vanilla.utils.BACKSPACE import com.sosauce.vanilla.utils.PARENTHESES import com.sosauce.vanilla.utils.whichParenthesis import java.text.DecimalFormatSymbols @SuppressLint("UnusedMaterial3ScaffoldPaddingParameter") @Composable fun CalculatorScreenLandscape( modifier: Modifier = Modifier, viewModel: CalculatorViewModel, historyViewModel: HistoryViewModel, onNavigate: (Screens) -> Unit, onGotoHistory: () -> Unit ) { val showClearButton by rememberShowClearButton() val localeDecimalChar = remember { DecimalFormatSymbols.getInstance().decimalSeparator.toString() } val saveErrorsToHistory by rememberSaveErrorsToHistory() val maxItemsToHistory by rememberHistoryMaxItems() val saveToHistory by rememberUseHistory() val row1 = listOf( CalcButton( text = "√", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SQUARE_ROOT)) }, type = ButtonType.OTHER ), CalcButton( text = "π", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.PI)) }, type = ButtonType.OTHER ), CalcButton( text = "9", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.NINE)) }, type = ButtonType.OTHER ), CalcButton( text = "8", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.EIGHT)) }, type = ButtonType.OTHER ), CalcButton( text = "7", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SEVEN)) }, type = ButtonType.OTHER ), CalcButton( text = "^", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.POWER)) }, type = ButtonType.OPERATOR ), if (showClearButton) { CalcButton( text = PARENTHESES, onClick = { viewModel.handleAction( CalcAction.AddToField( viewModel.textFieldState.text.whichParenthesis() ) ) }, type = ButtonType.OPERATOR ) } else { CalcButton( text = "(", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.OPEN_PARENTHESIS)) }, type = ButtonType.OPERATOR ) }, if (showClearButton) { CalcButton( text = "C", onClick = { viewModel.handleAction(CalcAction.ResetField) }, type = ButtonType.ACTION ) } else { CalcButton( text = ")", onClick = { viewModel.handleAction( CalcAction.AddToField(Tokens.CLOSED_PARENTHESIS) ) }, type = ButtonType.OPERATOR ) } ) val row2 = listOf( CalcButton( text = "%", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.MODULO)) }, type = ButtonType.OTHER ), CalcButton( text = "3", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.THREE)) }, type = ButtonType.OTHER ), CalcButton( text = "4", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.FOUR)) }, type = ButtonType.OTHER ), CalcButton( text = "5", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.FIVE)) }, type = ButtonType.OTHER ), CalcButton( text = "6", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SIX)) }, type = ButtonType.OTHER ), CalcButton( text = "+", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.ADD)) }, type = ButtonType.OPERATOR ), CalcButton( text = "-", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.SUBTRACT)) }, type = ButtonType.OPERATOR ), CalcButton( text = BACKSPACE, onClick = { viewModel.handleAction(CalcAction.Backspace) }, onLongClick = { viewModel.handleAction(CalcAction.ResetField) }, type = ButtonType.ACTION ) ) val row3 = listOf( CalcButton( text = "!", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.FACTORIAL)) }, type = ButtonType.OTHER ), CalcButton( text = "2", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.TWO)) }, type = ButtonType.OTHER ), CalcButton( text = "1", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.ONE)) }, type = ButtonType.OTHER ), CalcButton( text = "0", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.ZERO)) }, type = ButtonType.OTHER ), CalcButton( text = localeDecimalChar, onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.DECIMAL)) }, type = ButtonType.OTHER ), CalcButton( text = "×", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.MULTIPLY)) }, type = ButtonType.OPERATOR ), CalcButton( text = "/", onClick = { viewModel.handleAction(CalcAction.AddToField(Tokens.DIVIDE)) }, type = ButtonType.OPERATOR ), CalcButton( text = "=", onClick = { val operation = viewModel.textFieldState.text.toString() viewModel.handleAction(CalcAction.GetResult) val result = viewModel.evaluatedCalculation if (saveToHistory && operation != result) { historyViewModel.onEvent( HistoryEvents.AddCalculation( operation = operation, result = result, maxHistoryItems = maxItemsToHistory, saveErrors = saveErrorsToHistory ) ) } }, type = ButtonType.ACTION ) ) Scaffold( modifier = modifier, contentWindowInsets = WindowInsets.safeDrawing ) { pv -> Box( modifier = Modifier .fillMaxSize() .padding(pv), contentAlignment = Alignment.BottomCenter ) { Column( modifier = Modifier .align(Alignment.TopStart) .zIndex(1f) //history doesnt click otherwise ? ) { IconButton( onClick = { onNavigate(Screens.SETTINGS) }, shapes = IconButtonDefaults.shapes() ) { Icon( painter = painterResource(R.drawable.settings_filled), contentDescription = stringResource(R.string.settings) ) } IconButton( onClick = onGotoHistory, shapes = IconButtonDefaults.shapes() ) { Icon( painter = painterResource(R.drawable.history_rounded), contentDescription = stringResource(R.string.history) ) } } Column { CalculationDisplay( viewModel = viewModel, onNavigate = onNavigate ) Column( modifier = Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(9.dp), ) { val rows = listOf(row1, row2, row3) rows.forEach { row -> Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(9.dp) ) { row.fastForEach { button -> CuteButton( text = button.text, onClick = button.onClick, onLongClick = button.onLongClick, rectangle = true, buttonType = button.type ) } } } } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/calculator/CalculatorViewModel.kt ================================================ package com.sosauce.vanilla.ui.screens.calculator import android.app.Application import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.clearText import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.sosauce.vanilla.data.actions.CalcAction import com.sosauce.vanilla.data.calculator.Evaluator import com.sosauce.vanilla.data.datastore.getDecimalPrecision import com.sosauce.vanilla.utils.backspace import com.sosauce.vanilla.utils.insertText import com.sosauce.vanilla.utils.isErrorMessage import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class CalculatorViewModel( private val application: Application ) : AndroidViewModel(application) { val textFieldState = TextFieldState() var evaluatedCalculation by mutableStateOf("") private set private val _previewShowErrors = MutableStateFlow(false) val previewShowErrors = _previewShowErrors.asStateFlow() init { viewModelScope.launch { snapshotFlow { textFieldState.text.toString() } .collectLatest { text -> val decimalPrecision = getDecimalPrecision(application.applicationContext).first() evaluatedCalculation = if (textFieldState.text.isEmpty()) { // there's currently a bug that will keep the preview to the last result even if this is empty, my head hurts too much to search a real fix atm "" } else { Evaluator.eval(text, decimalPrecision) } } } } fun handleAction(action: CalcAction) { _previewShowErrors.update { false } when (action) { is CalcAction.GetResult -> { if (evaluatedCalculation.isErrorMessage()) { _previewShowErrors.update { true } } else { textFieldState.setTextAndPlaceCursorAtEnd(evaluatedCalculation) } } is CalcAction.AddToField -> textFieldState.insertText(action.char) is CalcAction.ResetField -> textFieldState.clearText() is CalcAction.Backspace -> textFieldState.backspace() is CalcAction.AddExpressionToField -> textFieldState.setTextAndPlaceCursorAtEnd(action.expression) } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/calculator/components/CalcButton.kt ================================================ package com.sosauce.vanilla.ui.screens.calculator.components data class CalcButton( val text: String, val onClick: () -> Unit, val onLongClick: (() -> Unit)? = null, val type: ButtonType = ButtonType.OTHER, val rectangle: Boolean = false ) ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/calculator/components/CalculationDisplay.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.calculator.components import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.input.OutputTransformation import androidx.compose.foundation.text.input.TextFieldBuffer import androidx.compose.foundation.text.input.TextFieldLineLimits import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.sosauce.vanilla.data.calculator.Tokens import com.sosauce.vanilla.data.datastore.rememberColoredOperators import com.sosauce.vanilla.data.datastore.rememberDecimal import com.sosauce.vanilla.data.datastore.rememberUseSystemFont import com.sosauce.vanilla.ui.navigation.Screens import com.sosauce.vanilla.ui.screens.calculator.CalculatorViewModel import com.sosauce.vanilla.ui.theme.nunitoFontFamily import com.sosauce.vanilla.utils.formatNumber import com.sosauce.vanilla.utils.isErrorMessage @Composable fun CalculationDisplay( modifier: Modifier = Modifier, viewModel: CalculatorViewModel, onNavigate: (Screens) -> Unit ) { val useSystemFont by rememberUseSystemFont() val shouldFormat by rememberDecimal() val scrollState = rememberScrollState() val previewScrollState = rememberScrollState() val previewCanShowErrors by viewModel.previewShowErrors.collectAsStateWithLifecycle() val coloredOperators by rememberColoredOperators() LaunchedEffect(viewModel.textFieldState.text) { scrollState.animateScrollTo(scrollState.maxValue) previewScrollState.animateScrollTo(previewScrollState.maxValue) } Column( modifier = modifier.padding(5.dp), verticalArrangement = Arrangement.Bottom ) { Text( text = viewModel.evaluatedCalculation .formatNumber(shouldFormat) .takeIf { !it.isErrorMessage() || previewCanShowErrors } ?: "", modifier = Modifier .fillMaxWidth() .horizontalScroll(previewScrollState), style = MaterialTheme.typography.displayMediumEmphasized.copy( textAlign = TextAlign.End, fontWeight = FontWeight.ExtraBold, color = if (!viewModel.evaluatedCalculation.isErrorMessage()) { MaterialTheme.colorScheme.tertiary } else MaterialTheme.colorScheme.error ) ) DisableSoftKeyboard { BasicTextField( state = viewModel.textFieldState, lineLimits = TextFieldLineLimits.SingleLine, textStyle = MaterialTheme.typography.displayMediumEmphasized.copy( textAlign = TextAlign.End, color = MaterialTheme.colorScheme.onSurface, fontFamily = if (!useSystemFont) nunitoFontFamily else null, fontWeight = FontWeight.ExtraBold ), modifier = Modifier.fillMaxWidth(), cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), scrollState = scrollState, outputTransformation = CalculatorOutputTransform( format = shouldFormat, coloredOperators = coloredOperators, operatorColor = MaterialTheme.colorScheme.primary ) ) } } } class CalculatorOutputTransform( private val format: Boolean, private val coloredOperators: Boolean, private val operatorColor: Color ) : OutputTransformation { override fun TextFieldBuffer.transformOutput() { if (format) { val expression = originalText.toString() if (expression.isEmpty()) return var shift = 0 NUMBERS_REGEX.findAll(expression).forEach { match -> val start = match.range.first + shift val end = match.range.last + 1 + shift val number = match.value val formatted = number.formatNumber(true) replace(start, end, formatted) shift += formatted.length - number.length } } if (coloredOperators) { val operators = setOf(Tokens.ADD, Tokens.SUBTRACT, Tokens.MULTIPLY, Tokens.DIVIDE, Tokens.POWER) asCharSequence().forEachIndexed { index, char -> if (char in operators) { addStyle(SpanStyle(color = operatorColor), index, index + 1) } } } } companion object { val NUMBERS_REGEX = "[\\d.]+".toRegex() } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/calculator/components/CuteButton.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.calculator.components import androidx.compose.animation.core.animateIntAsState import androidx.compose.foundation.background import androidx.compose.foundation.combinedClickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.contentColorFor import androidx.compose.material3.ripple import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.hapticfeedback.HapticFeedbackType import androidx.compose.ui.platform.LocalHapticFeedback import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberIsLandscape import com.sosauce.vanilla.data.datastore.rememberUseButtonsAnimation import com.sosauce.vanilla.data.datastore.rememberVibration import com.sosauce.vanilla.utils.BACKSPACE import com.sosauce.vanilla.utils.PARENTHESES @Composable fun CuteButton( modifier: Modifier = Modifier, text: String, buttonType: ButtonType = ButtonType.OTHER, onClick: () -> Unit, onLongClick: (() -> Unit)? = null, interactionSource: MutableInteractionSource = remember { MutableInteractionSource() }, rectangle: Boolean ) { val haptic = LocalHapticFeedback.current val shouldVibrate by rememberVibration() val useButtonsAnimation by rememberUseButtonsAnimation() val isPressed by interactionSource.collectIsPressedAsState() val cornerRadius by animateIntAsState( targetValue = if (isPressed && useButtonsAnimation) 24 else 50 ) val isLandscape = rememberIsLandscape() val backgroundColor = when (buttonType) { ButtonType.OPERATOR -> MaterialTheme.colorScheme.primary ButtonType.OTHER -> MaterialTheme.colorScheme.surfaceContainer ButtonType.ACTION -> MaterialTheme.colorScheme.tertiary ButtonType.SPECIAL -> Color.Transparent } Box( modifier = modifier .semantics { role = Role.Button } .clip(RoundedCornerShape(cornerRadius)) .combinedClickable( interactionSource = interactionSource, indication = ripple(), onClick = { onClick() if (shouldVibrate) haptic.performHapticFeedback(HapticFeedbackType.Confirm) }, onLongClick = onLongClick ) .defaultMinSize( minWidth = ButtonDefaults.MinWidth, minHeight = ButtonDefaults.MinHeight ) .background(backgroundColor) .let { if (!isLandscape && !rectangle) it.aspectRatio(1f) else it }, contentAlignment = Alignment.Center ) { when (text) { BACKSPACE -> { Icon( painter = painterResource(R.drawable.backspace_filled), contentDescription = stringResource(R.string.back), tint = MaterialTheme.colorScheme.contentColorFor(backgroundColor), modifier = Modifier.size(45.dp) ) } PARENTHESES -> { Icon( painter = painterResource(R.drawable.parentheses), contentDescription = null, tint = MaterialTheme.colorScheme.contentColorFor(backgroundColor), modifier = Modifier.size(45.dp) ) } else -> { Text( text = text, color = contentColorFor(backgroundColor), style = MaterialTheme.typography.displaySmallEmphasized ) } } } } enum class ButtonType { OPERATOR, SPECIAL, ACTION, OTHER } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/calculator/components/DisableSoftKeyboard.kt ================================================ package com.sosauce.vanilla.ui.screens.calculator.components import androidx.compose.runtime.Composable import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.platform.InterceptPlatformTextInput import kotlinx.coroutines.awaitCancellation // https://stackoverflow.com/a/78720287 @OptIn(ExperimentalComposeUiApi::class) @Composable fun DisableSoftKeyboard( content: @Composable () -> Unit ) { InterceptPlatformTextInput( interceptor = { _, _ -> awaitCancellation() }, content = content ) } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/history/HistoryScreen.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.history import android.content.ClipData import androidx.compose.foundation.basicMarquee import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DropdownMenuGroup import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuPopup import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.LocalContentColor import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MenuDefaults import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.buildAnnotatedString import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEachIndexed import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberColoredOperators import com.sosauce.vanilla.data.datastore.rememberDecimal import com.sosauce.vanilla.data.datastore.rememberHistoryNewestFirst import com.sosauce.vanilla.data.datastore.rememberUseHistory import com.sosauce.vanilla.domain.model.Calculation import com.sosauce.vanilla.domain.repository.HistoryEvents import com.sosauce.vanilla.ui.screens.history.components.DeletionConfirmationDialog import com.sosauce.vanilla.ui.screens.history.components.HistoryActionButtons import com.sosauce.vanilla.ui.shared_components.AnimatedFab import com.sosauce.vanilla.utils.formatExpression import com.sosauce.vanilla.utils.formatNumber import com.sosauce.vanilla.utils.isErrorMessage import com.sosauce.vanilla.utils.isOperator import com.sosauce.vanilla.utils.sort @Composable fun HistoryScreen( calculations: List, onEvents: (HistoryEvents) -> Unit, onPutBackToField: (String) -> Unit, onGotoMain: () -> Unit ) { val lazyState = rememberLazyListState() var isHistoryEnable by rememberUseHistory() val newestFirst by rememberHistoryNewestFirst() var showDeleteConfirmation by remember { mutableStateOf(false) } if (showDeleteConfirmation) { DeletionConfirmationDialog( onDismissRequest = { showDeleteConfirmation = false }, onDelete = { onEvents(HistoryEvents.DeleteAllCalculation) } ) } Scaffold( bottomBar = { Row( modifier = Modifier .padding(horizontal = 15.dp) .fillMaxWidth() .navigationBarsPadding(), horizontalArrangement = Arrangement.SpaceBetween ) { AnimatedFab( onClick = onGotoMain, icon = R.drawable.arrow_up, containerColor = MaterialTheme.colorScheme.surfaceContainer ) HistoryActionButtons { showDeleteConfirmation = true } } } ) { pv -> if (!isHistoryEnable) { Column( modifier = Modifier .fillMaxSize(), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Text(stringResource(R.string.history_not_enabled)) Spacer(Modifier.height(10.dp)) Button( onClick = { isHistoryEnable = !isHistoryEnable }, shapes = ButtonDefaults.shapes() ) { Text(stringResource(R.string.enable_history)) } } } else { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = pv, state = lazyState ) { if (calculations.isEmpty()) { item { Column( horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.fillMaxWidth() ) { Icon( painter = painterResource(R.drawable.history_rounded), contentDescription = null, modifier = Modifier.size(70.dp) ) Spacer(Modifier.height(10.dp)) Text( text = stringResource(R.string.no_calc_found), style = MaterialTheme.typography.headlineMediumEmphasized, fontWeight = FontWeight.Black ) Text( text = stringResource(R.string.calc_empty), style = MaterialTheme.typography.bodyMediumEmphasized, color = MaterialTheme.colorScheme.onSurfaceVariant ) } } } else { itemsIndexed( items = calculations.sort(newestFirst), key = { _, item -> item.id } ) { index, item -> CalculationItem( calculation = item, onEvents = onEvents, onPutBackToField = onPutBackToField, topDp = if (index == 0) 24.dp else 4.dp, bottomDp = if (index == calculations.lastIndex) 24.dp else 4.dp, modifier = Modifier.animateItem() ) } } } } } } @Composable private fun CalculationItem( calculation: Calculation, onEvents: (HistoryEvents) -> Unit, onPutBackToField: (String) -> Unit, topDp: Dp, bottomDp: Dp, modifier: Modifier = Modifier ) { val clipboardManager = LocalClipboard.current val localContentColor = LocalContentColor.current val shouldFormat by rememberDecimal() val coloredOperators by rememberColoredOperators() var actionsExpanded by remember { mutableStateOf(false) } val actions = listOf( HistoryAction( onClick = { onPutBackToField(calculation.operation) }, icon = R.drawable.undo, text = R.string.put_field ), HistoryAction( onClick = { clipboardManager.nativeClipboard.setPrimaryClip( ClipData.newPlainText( "", "${calculation.operation} = ${calculation.result}" ) ) }, icon = R.drawable.copy, text = R.string.copy ), HistoryAction( onClick = { onEvents(HistoryEvents.DeleteCalculation(calculation)) }, icon = R.drawable.delete, text = R.string.delete, tint = MaterialTheme.colorScheme.error ) ) Card( onClick = { onPutBackToField(calculation.operation) }, modifier = modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 2.dp), colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.surfaceContainer ), shape = RoundedCornerShape( topStart = topDp, topEnd = topDp, bottomEnd = bottomDp, bottomStart = bottomDp ) ) { Row( modifier = Modifier .fillMaxWidth() .padding(15.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Column( modifier = Modifier .weight(1f), horizontalAlignment = Alignment.Start ) { Text( text = buildAnnotatedString { calculation.operation.formatExpression(shouldFormat).forEach { char -> if (coloredOperators && char.isOperator()) { withStyle(SpanStyle(MaterialTheme.colorScheme.primary)) { append(char) } } else append(char) } }, style = MaterialTheme.typography.titleLargeEmphasized, modifier = Modifier.basicMarquee() ) Text( text = calculation.result.formatNumber(shouldFormat), style = MaterialTheme.typography.titleLargeEmphasized.copy( color = if (calculation.result.isErrorMessage()) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.tertiary ), modifier = Modifier.basicMarquee() ) } IconButton( onClick = { actionsExpanded = true }, shapes = IconButtonDefaults.shapes() ) { Icon( painter = painterResource(R.drawable.more_vert), contentDescription = stringResource(R.string.more_actions) ) DropdownMenuPopup( expanded = actionsExpanded, onDismissRequest = { actionsExpanded = false } ) { DropdownMenuGroup( shapes = MenuDefaults.groupShapes() ) { actions.fastForEachIndexed { index, action -> DropdownMenuItem( onClick = { action.onClick() actionsExpanded = false }, text = { Text( text = stringResource(action.text), color = action.tint ?: localContentColor ) }, leadingIcon = { Icon( painter = painterResource(action.icon), contentDescription = null, tint = action.tint ?: localContentColor ) }, shape = when (index) { 0 -> MenuDefaults.leadingItemShape actions.lastIndex -> MenuDefaults.trailingItemShape else -> MenuDefaults.middleItemShape } ) } } } } } } } private data class HistoryAction( val onClick: () -> Unit, val icon: Int, val text: Int, val tint: Color? = null ) ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/history/HistoryViewModel.kt ================================================ package com.sosauce.vanilla.ui.screens.history import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.sosauce.vanilla.domain.model.Calculation import com.sosauce.vanilla.domain.repository.HistoryDao import com.sosauce.vanilla.domain.repository.HistoryEvents import com.sosauce.vanilla.utils.isErrorMessage import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch class HistoryViewModel( private val dao: HistoryDao, ) : ViewModel() { val allCalculations = dao.getAllCalculations() .stateIn( viewModelScope, SharingStarted.WhileSubscribed(5000), emptyList() ) fun onEvent(event: HistoryEvents) { when (event) { is HistoryEvents.AddCalculation -> { val calculation = Calculation( operation = event.operation, result = event.result ) if (event.saveErrors || !event.result.isErrorMessage()) { viewModelScope.launch { if (allCalculations.value.size.toLong() == event.maxHistoryItems) { dao.deleteCalculation(allCalculations.value.first()) } dao.insertCalculation(calculation) } } else { return } } is HistoryEvents.DeleteCalculation -> { viewModelScope.launch { dao.deleteCalculation(event.calculation) } } is HistoryEvents.DeleteAllCalculation -> { viewModelScope.launch { dao.deleteAllCalculations() } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/history/components/DeletionConfirmationDialog.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.history.components import androidx.compose.material3.AlertDialog import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import com.sosauce.vanilla.R @Composable fun DeletionConfirmationDialog( onDismissRequest: () -> Unit, onDelete: () -> Unit ) { AlertDialog( onDismissRequest = onDismissRequest, title = { Text(stringResource(R.string.clear_history)) }, text = { Text(stringResource(R.string.cant_be_undone)) }, confirmButton = { TextButton( onClick = { onDelete() onDismissRequest() }, shapes = ButtonDefaults.shapes() ) { Text(stringResource(R.string.delete)) } }, dismissButton = { TextButton( onClick = onDismissRequest, shapes = ButtonDefaults.shapes() ) { Text(stringResource(R.string.cancel)) } }, icon = { Icon( painter = painterResource(R.drawable.delete), contentDescription = null ) } ) } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/history/components/HistoryActionButtons.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.history.components import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.layout.Row import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.DropdownMenuGroup import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.DropdownMenuPopup import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MenuDefaults import androidx.compose.material3.SmallFloatingActionButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberHistoryNewestFirst @Composable fun HistoryActionButtons( modifier: Modifier = Modifier, onDeleteHistory: () -> Unit ) { var dropDownExpanded by remember { mutableStateOf(false) } var newestFirst by rememberHistoryNewestFirst() SmallFloatingActionButton( onClick = {}, modifier = modifier, shape = RoundedCornerShape(14.dp), containerColor = MaterialTheme.colorScheme.surfaceContainer ) { Row { IconButton( onClick = { dropDownExpanded = true } ) { AnimatedContent( targetState = !dropDownExpanded ) { Icon( painter = if (it) painterResource(R.drawable.sort_rounded) else painterResource( R.drawable.close ), contentDescription = stringResource(R.string.sort) ) } } IconButton( onClick = onDeleteHistory ) { Icon( painter = painterResource(R.drawable.trash_rounded), contentDescription = stringResource(R.string.delete), tint = MaterialTheme.colorScheme.error ) } DropdownMenuPopup( expanded = dropDownExpanded, onDismissRequest = { dropDownExpanded = false } ) { DropdownMenuGroup( shapes = MenuDefaults.groupShapes() ) { DropdownMenuItem( selected = newestFirst, onClick = { newestFirst = true }, text = { Text(stringResource(R.string.newest_first)) }, trailingIcon = { if (newestFirst) { Icon( painter = painterResource(R.drawable.check), contentDescription = null ) } }, shapes = MenuDefaults.itemShapes() ) DropdownMenuItem( selected = !newestFirst, onClick = { newestFirst = false }, text = { Text(stringResource(R.string.oldest_first)) }, trailingIcon = { if (!newestFirst) { Icon( painter = painterResource(R.drawable.check), contentDescription = null ) } }, shapes = MenuDefaults.itemShapes() ) } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/SettingsFormatting.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.settings import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MenuDefaults import androidx.compose.material3.RadioButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEachIndexed import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberDecimal import com.sosauce.vanilla.data.datastore.rememberDecimalPrecision import com.sosauce.vanilla.ui.screens.settings.components.SettingsDropdownMenu import com.sosauce.vanilla.ui.screens.settings.components.SettingsSwitch import com.sosauce.vanilla.ui.screens.settings.components.SettingsWithTitle import com.sosauce.vanilla.ui.shared_components.AnimatedFab import com.sosauce.vanilla.utils.formatNumber import com.sosauce.vanilla.utils.selfAlignHorizontally @Composable fun SettingsFormatting() { var shouldFormat by rememberDecimal() var decimalPrecision by rememberDecimalPrecision() val decimalPrecisionOptions = MutableList(16) { it }.apply { add(1000) } Column { SettingsWithTitle( title = R.string.formatting ) { SettingsSwitch( checked = shouldFormat, onCheckedChange = { shouldFormat = !shouldFormat }, topDp = 24.dp, bottomDp = 4.dp, text = R.string.decimal_formatting ) SettingsDropdownMenu( value = decimalPrecision.toLong(), topDp = 4.dp, bottomDp = 24.dp, text = R.string.decimal_precision, optionalDescription = R.string.decimal_precision_desc ) { decimalPrecisionOptions.fastForEachIndexed { index, number -> val selected = number == decimalPrecision DropdownMenuItem( onClick = { decimalPrecision = number }, selected = selected, text = { Text(number.toString().formatNumber(shouldFormat)) }, shapes = MenuDefaults.itemShape(index, decimalPrecisionOptions.count()), trailingIcon = { if (selected) { Icon( painter = painterResource(R.drawable.check), contentDescription = null ) } } ) } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/SettingsHistory.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.settings import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MenuDefaults import androidx.compose.material3.RadioButton import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEachIndexed import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberHistoryMaxItems import com.sosauce.vanilla.data.datastore.rememberSaveErrorsToHistory import com.sosauce.vanilla.data.datastore.rememberUseHistory import com.sosauce.vanilla.ui.screens.settings.components.SettingsDropdownMenu import com.sosauce.vanilla.ui.screens.settings.components.SettingsSwitch import com.sosauce.vanilla.ui.screens.settings.components.SettingsWithTitle import com.sosauce.vanilla.ui.shared_components.AnimatedFab import com.sosauce.vanilla.utils.selfAlignHorizontally @Composable fun SettingsHistory() { var useHistory by rememberUseHistory() var historyMaxItems by rememberHistoryMaxItems() var saveErrorsToHistory by rememberSaveErrorsToHistory() val historyItemsChoice = listOf( 10, 20, 50, 100, 200, 500, 1000, 10000, Long.MAX_VALUE ) Column { SettingsWithTitle( title = R.string.history ) { SettingsSwitch( checked = useHistory, onCheckedChange = { useHistory = !useHistory }, topDp = 24.dp, bottomDp = 4.dp, text = R.string.enable_history ) SettingsSwitch( checked = saveErrorsToHistory, onCheckedChange = { saveErrorsToHistory = !saveErrorsToHistory }, topDp = 4.dp, bottomDp = 4.dp, text = R.string.save_errors ) SettingsDropdownMenu( value = historyMaxItems, topDp = 4.dp, bottomDp = 24.dp, text = R.string.max_history_items ) { historyItemsChoice.fastForEachIndexed { index, number -> val selected = number == historyMaxItems DropdownMenuItem( onClick = { historyMaxItems = number }, selected = selected, text = { Text(if (number == Long.MAX_VALUE) stringResource(R.string.no_limit) else number.toString()) }, trailingIcon = { if (selected) { Icon( painter = painterResource(R.drawable.check), contentDescription = null ) } }, shapes = MenuDefaults.itemShape(index, historyItemsChoice.count()) ) } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/SettingsLookAndFeel.kt ================================================ package com.sosauce.vanilla.ui.screens.settings import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberAppTheme import com.sosauce.vanilla.data.datastore.rememberColoredOperators import com.sosauce.vanilla.data.datastore.rememberShowClearButton import com.sosauce.vanilla.data.datastore.rememberSwapZeroAndDecimal import com.sosauce.vanilla.data.datastore.rememberUseButtonsAnimation import com.sosauce.vanilla.data.datastore.rememberUseSystemFont import com.sosauce.vanilla.data.datastore.rememberVibration import com.sosauce.vanilla.ui.screens.settings.components.FontSelector import com.sosauce.vanilla.ui.screens.settings.components.LazyRowWithScrollButton import com.sosauce.vanilla.ui.screens.settings.components.SettingsSwitch import com.sosauce.vanilla.ui.screens.settings.components.SettingsWithTitle import com.sosauce.vanilla.ui.screens.settings.components.ThemeItem import com.sosauce.vanilla.ui.screens.settings.components.ThemeSelector import com.sosauce.vanilla.ui.shared_components.AnimatedFab import com.sosauce.vanilla.ui.theme.nunitoFontFamily import com.sosauce.vanilla.utils.CuteTheme import com.sosauce.vanilla.utils.anyDarkColorScheme import com.sosauce.vanilla.utils.anyLightColorScheme import com.sosauce.vanilla.utils.selfAlignHorizontally @Composable fun SettingsLookAndFeel() { var theme by rememberAppTheme() var useSystemFont by rememberUseSystemFont() var useButtonsAnimation by rememberUseButtonsAnimation() var useHapticFeedback by rememberVibration() var showClearButton by rememberShowClearButton() var coloredOperators by rememberColoredOperators() var swapZeroAndDecimal by rememberSwapZeroAndDecimal() val themeItems = listOf( ThemeItem( onClick = { theme = CuteTheme.SYSTEM }, backgroundColor = if (isSystemInDarkTheme()) anyDarkColorScheme().background else anyLightColorScheme().background, text = stringResource(R.string.follow_sys), isSelected = theme == CuteTheme.SYSTEM, iconAndTint = Pair( painterResource(R.drawable.system_theme), if (isSystemInDarkTheme()) anyDarkColorScheme().onBackground else anyLightColorScheme().onBackground ) ), ThemeItem( onClick = { theme = CuteTheme.DARK }, backgroundColor = anyDarkColorScheme().background, text = stringResource(R.string.dark_mode), isSelected = theme == CuteTheme.DARK, iconAndTint = Pair( painterResource(R.drawable.dark_mode), anyDarkColorScheme().onBackground ) ), ThemeItem( onClick = { theme = CuteTheme.LIGHT }, backgroundColor = anyLightColorScheme().background, text = stringResource(R.string.light_mode), isSelected = theme == CuteTheme.LIGHT, iconAndTint = Pair( painterResource(R.drawable.light_mode), anyLightColorScheme().onBackground ) ), ThemeItem( onClick = { theme = CuteTheme.AMOLED }, backgroundColor = Color.Black, text = stringResource(R.string.amoled_mode), isSelected = theme == CuteTheme.AMOLED, iconAndTint = Pair(painterResource(R.drawable.amoled), Color.White) ) ) val fontItems = listOf( FontItem( onClick = { useSystemFont = false }, fontStyle = FontStyle.DEFAULT, borderColor = if (!useSystemFont) MaterialTheme.colorScheme.primary else Color.Transparent, text = { Text( text = "Tt", fontFamily = nunitoFontFamily ) }, ), FontItem( onClick = { useSystemFont = true }, fontStyle = FontStyle.SYSTEM, borderColor = if (useSystemFont) MaterialTheme.colorScheme.primary else Color.Transparent, text = { Text( text = "Tt", fontFamily = FontFamily.Default ) } ) ) Column { SettingsWithTitle( title = R.string.theme ) { Card( colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surfaceContainer), modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 2.dp) ) { LazyRowWithScrollButton( items = themeItems ) { item -> ThemeSelector( onClick = item.onClick, backgroundColor = item.backgroundColor, text = item.text, isThemeSelected = item.isSelected, icon = { Icon( painter = item.iconAndTint.first, contentDescription = null, tint = item.iconAndTint.second, ) } ) } } } SettingsWithTitle( title = R.string.font ) { Card( colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surfaceContainer), modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 2.dp) ) { LazyRowWithScrollButton( items = fontItems ) { item -> FontSelector( item ) } } } SettingsWithTitle( title = R.string.ui ) { SettingsSwitch( checked = useButtonsAnimation, onCheckedChange = { useButtonsAnimation = !useButtonsAnimation }, topDp = 24.dp, bottomDp = 4.dp, text = R.string.buttons_anim ) SettingsSwitch( checked = coloredOperators, onCheckedChange = { coloredOperators = !coloredOperators }, topDp = 4.dp, bottomDp = 4.dp, text = R.string.colored_operatos ) SettingsSwitch( checked = swapZeroAndDecimal, onCheckedChange = { swapZeroAndDecimal = !swapZeroAndDecimal }, topDp = 4.dp, bottomDp = 4.dp, text = R.string.swap_zero_and_decimal ) SettingsSwitch( checked = useHapticFeedback, onCheckedChange = { useHapticFeedback = !useHapticFeedback }, topDp = 4.dp, bottomDp = 4.dp, text = R.string.haptic_feedback ) SettingsSwitch( checked = showClearButton, onCheckedChange = { showClearButton = !showClearButton }, topDp = 4.dp, bottomDp = 24.dp, text = R.string.show_clear_button, optionalDescription = R.string.clear_button_desc ) } } } @Immutable data class FontItem( val onClick: () -> Unit, val fontStyle: FontStyle, val borderColor: Color, val text: @Composable () -> Unit ) enum class FontStyle { DEFAULT, SYSTEM } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/SettingsMisc.kt ================================================ package com.sosauce.vanilla.ui.screens.settings import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberShowOnLockScreen import com.sosauce.vanilla.ui.screens.settings.components.SettingsSwitch import com.sosauce.vanilla.ui.screens.settings.components.SettingsWithTitle import com.sosauce.vanilla.ui.shared_components.AnimatedFab import com.sosauce.vanilla.utils.selfAlignHorizontally @Composable fun SettingsMisc() { var showOnLockScreen by rememberShowOnLockScreen() Column { SettingsWithTitle( title = R.string.misc ) { SettingsSwitch( checked = showOnLockScreen, onCheckedChange = { showOnLockScreen = !showOnLockScreen }, topDp = 24.dp, bottomDp = 24.dp, text = R.string.show_ls, optionalDescription = R.string.show_ls_desc ) } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/SettingsScreen.kt ================================================ @file:OptIn(ExperimentalUuidApi::class) package com.sosauce.vanilla.ui.screens.settings import androidx.activity.compose.BackHandler import androidx.compose.animation.AnimatedContent import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.togetherWith import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import androidx.compose.ui.util.fastForEachIndexed import com.sosauce.vanilla.R import com.sosauce.vanilla.ui.navigation.Screens import com.sosauce.vanilla.ui.navigation.SettingsScreen import com.sosauce.vanilla.ui.screens.settings.components.AboutCard import com.sosauce.vanilla.ui.screens.settings.components.SettingsCategoryCard import com.sosauce.vanilla.ui.shared_components.AnimatedFab import com.sosauce.vanilla.utils.bouncySpec import com.sosauce.vanilla.utils.navigationBouncySpec import com.sosauce.vanilla.utils.selfAlignHorizontally import kotlin.uuid.ExperimentalUuidApi import kotlin.uuid.Uuid @Composable fun SettingsScreen( onNavigate: (Screens) -> Unit ) { var screenToDisplay by rememberSaveable { mutableStateOf(SettingsScreen.SETTINGS) } // Mimic back behavior from navigation BackHandler { if (screenToDisplay != SettingsScreen.SETTINGS) { screenToDisplay = SettingsScreen.SETTINGS } else { onNavigate(Screens.MAIN) } } Scaffold( bottomBar = { AnimatedFab( onClick = { if (screenToDisplay == SettingsScreen.SETTINGS) { onNavigate(Screens.MAIN) } else { screenToDisplay = SettingsScreen.SETTINGS } }, modifier = Modifier .padding(start = 15.dp) .navigationBarsPadding() .selfAlignHorizontally(Alignment.Start), icon = R.drawable.back_arrow, containerColor = MaterialTheme.colorScheme.surfaceContainer ) } ) { paddingValues -> AnimatedContent( targetState = screenToDisplay, modifier = Modifier .verticalScroll(rememberScrollState()) .padding(paddingValues) .background(MaterialTheme.colorScheme.background), transitionSpec = { slideInHorizontally(navigationBouncySpec) { -it } + fadeIn() togetherWith fadeOut() } ) { screen -> when (screen) { SettingsScreen.SETTINGS -> { SettingsPage( onNavigateSettings = { screenToDisplay = it } ) } SettingsScreen.LOOK_AND_FEEL -> { SettingsLookAndFeel() } SettingsScreen.HISTORY -> { SettingsHistory() } SettingsScreen.FORMATTING -> { SettingsFormatting() } SettingsScreen.MISC -> { SettingsMisc() } } } } } @Composable private fun SettingsPage( onNavigateSettings: (SettingsScreen) -> Unit ) { val settingsCategories = listOf( SettingsCategory( name = R.string.look_and_feel, description = R.string.look_and_feel_desc, icon = R.drawable.palette, onNavigate = { onNavigateSettings(SettingsScreen.LOOK_AND_FEEL) } ), SettingsCategory( name = R.string.history, description = R.string.history_desc, icon = R.drawable.history_rounded, onNavigate = { onNavigateSettings(SettingsScreen.HISTORY) } ), SettingsCategory( name = R.string.formatting, description = R.string.formatting_desc, icon = R.drawable.formatting, onNavigate = { onNavigateSettings(SettingsScreen.FORMATTING) } ), SettingsCategory( name = R.string.misc, description = R.string.misc_desc, icon = R.drawable.more_horiz, onNavigate = { onNavigateSettings(SettingsScreen.MISC) } ) ) Column { AboutCard() Spacer(Modifier.height(20.dp)) settingsCategories.fastForEachIndexed { index, category -> SettingsCategoryCard( icon = category.icon, name = category.name, description = category.description, topDp = if (index == 0) 24.dp else 4.dp, bottomDp = if (index == settingsCategories.lastIndex) 24.dp else 4.dp, onNavigate = category.onNavigate ) } } } @Immutable private data class SettingsCategory( val id: String = Uuid.random().toString(), val name: Int, val description: Int, val icon: Int, val onNavigate: () -> Unit ) ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/components/AboutCard.kt ================================================ package com.sosauce.vanilla.ui.screens.settings.components import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.FilledIconButton import androidx.compose.material3.Icon import androidx.compose.material3.IconButtonDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalUriHandler import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.sosauce.vanilla.R import com.sosauce.vanilla.utils.GITHUB_RELEASES import com.sosauce.vanilla.utils.SUPPORT_PAGE import com.sosauce.vanilla.utils.appVersion import sv.lib.squircleshape.CornerSmoothing import sv.lib.squircleshape.SquircleShape @Composable fun AboutCard() { val context = LocalContext.current val uriHandler = LocalUriHandler.current Card( colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surfaceContainer), modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 2.dp), shape = RoundedCornerShape(24.dp) ) { Row( verticalAlignment = Alignment.CenterVertically ) { Box( modifier = Modifier .size(100.dp) .padding(15.dp) .background( shape = SquircleShape(smoothing = CornerSmoothing.Full), color = Color(0xFFf4a7bd) ), contentAlignment = Alignment.Center ) { Icon( painter = painterResource(R.drawable.calculator), contentDescription = null, modifier = Modifier.size(50.dp), tint = Color(0xFFfdd9dc) ) } Column { Text("Vanilla") Text( text = "${stringResource(id = R.string.version)} ${context.appVersion}", style = MaterialTheme.typography.bodyMediumEmphasized.copy( color = MaterialTheme.colorScheme.onSurfaceVariant ) ) } Spacer(Modifier.weight(1f)) Row( verticalAlignment = Alignment.Top, modifier = Modifier.padding(end = 15.dp) ) { FilledIconButton( onClick = { uriHandler.openUri(GITHUB_RELEASES) }, shapes = IconButtonDefaults.shapes() ) { Icon( painter = painterResource(R.drawable.github), contentDescription = null ) } FilledIconButton( onClick = { uriHandler.openUri(SUPPORT_PAGE) }, shapes = IconButtonDefaults.shapes() ) { Icon( painter = painterResource(R.drawable.favorite_filled), contentDescription = null ) } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/components/FontSelector.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.settings.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialShapes import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.toShape import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.sosauce.vanilla.R import com.sosauce.vanilla.ui.screens.settings.FontStyle @Composable fun FontSelector( item: com.sosauce.vanilla.ui.screens.settings.FontItem ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .padding(10.dp) .height(100.dp) .clip(RoundedCornerShape(12.dp)) .clickable { item.onClick() } ) { Box( modifier = Modifier .padding(10.dp) .size(50.dp) .clip(MaterialShapes.Cookie9Sided.toShape()) .border( width = 2.dp, color = item.borderColor, shape = MaterialShapes.Cookie9Sided.toShape() ) .background(MaterialTheme.colorScheme.surfaceContainerHighest), contentAlignment = Alignment.Center ) { item.text() } Spacer(Modifier.weight(1f)) Text( text = if (item.fontStyle == FontStyle.SYSTEM) stringResource(R.string.system) else "Default" ) } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/components/LazyRowWithScrollButton.kt ================================================ package com.sosauce.vanilla.ui.screens.settings.components import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.layout.Box import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import com.sosauce.vanilla.R import kotlinx.coroutines.launch @Composable fun LazyRowWithScrollButton( items: List, content: @Composable (T) -> Unit ) { val state = rememberLazyListState() val scope = rememberCoroutineScope() Box { LazyRow( state = state ) { items( items = items ) { type -> content(type) } } androidx.compose.animation.AnimatedVisibility( visible = state.canScrollForward, modifier = Modifier.align(Alignment.CenterEnd), enter = slideInHorizontally { it }, exit = slideOutHorizontally { it } ) { IconButton( onClick = { scope.launch { state.animateScrollToItem(items.lastIndex) } } ) { Icon( painter = painterResource(R.drawable.arrow_right), contentDescription = null ) } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/components/SettingsCategoryCard.kt ================================================ package com.sosauce.vanilla.ui.screens.settings.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp @Composable fun SettingsCategoryCard( icon: Int, name: Int, description: Int, topDp: Dp, bottomDp: Dp, onNavigate: () -> Unit ) { Card( onClick = onNavigate, colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surfaceContainer), modifier = Modifier .fillMaxWidth() .padding(horizontal = 16.dp, vertical = 2.dp), shape = RoundedCornerShape( topStart = topDp, topEnd = topDp, bottomStart = bottomDp, bottomEnd = bottomDp ) ) { Row( modifier = Modifier .padding(16.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( painter = painterResource(icon), contentDescription = null ) Spacer(Modifier.width(15.dp)) Column { Text(stringResource(name)) Text( text = stringResource(description), color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium ) } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/components/SettingsSwitch.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.settings.components import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DropdownMenuGroup import androidx.compose.material3.DropdownMenuPopup import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialTheme import androidx.compose.material3.MenuDefaults import androidx.compose.material3.Switch import androidx.compose.material3.SwitchDefaults import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.sosauce.vanilla.R @Composable fun SettingsSwitch( checked: Boolean, onCheckedChange: () -> Unit, topDp: Dp, bottomDp: Dp, text: Int, optionalDescription: Int? = null ) { Card( colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surfaceContainer), modifier = Modifier .padding(horizontal = 16.dp, vertical = 2.dp), shape = RoundedCornerShape( topStart = topDp, topEnd = topDp, bottomStart = bottomDp, bottomEnd = bottomDp ) ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .padding(15.dp) ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .weight(1f) ) { Column { Text(stringResource(text)) optionalDescription?.let { Text( text = stringResource(it), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp ) } } } Switch( checked = checked, onCheckedChange = { onCheckedChange() }, colors = SwitchDefaults.colors( uncheckedBorderColor = Color.Transparent ) ) } } } @Composable fun SettingsDropdownMenu( value: Long, topDp: Dp, bottomDp: Dp, text: Int, optionalDescription: Int? = null, dropdownContent: @Composable (ColumnScope.() -> Unit) ) { var expanded by remember { mutableStateOf(false) } Card( colors = CardDefaults.cardColors(MaterialTheme.colorScheme.surfaceContainer), modifier = Modifier .padding(horizontal = 16.dp, vertical = 2.dp), shape = RoundedCornerShape( topStart = topDp, topEnd = topDp, bottomStart = bottomDp, bottomEnd = bottomDp ) ) { Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier .padding(15.dp) ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .weight(1f) ) { Column { Text(stringResource(text)) optionalDescription?.let { Text( text = stringResource(it), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 12.sp ) } } } TextButton( onClick = { expanded = true } ) { AnimatedContent( targetState = value ) { Text( text = if (it == Long.MAX_VALUE) stringResource(R.string.no_limit) else it.toString(), color = MaterialTheme.colorScheme.onSurfaceVariant, fontSize = 15.sp ) } DropdownMenuPopup( expanded = expanded, onDismissRequest = { expanded = false } ) { DropdownMenuGroup( shapes = MenuDefaults.groupShapes() ) { dropdownContent() } } } } } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/components/SettingsWithTitle.kt ================================================ package com.sosauce.vanilla.ui.screens.settings.components import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp @Composable fun SettingsWithTitle( title: Int, content: @Composable () -> Unit ) { Column { Text( text = stringResource(id = title), color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(horizontal = 34.dp, vertical = 8.dp) ) content() } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/screens/settings/components/ThemeSelector.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.screens.settings.components import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialShapes import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.toShape import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.unit.dp @Composable fun ThemeSelector( onClick: () -> Unit, backgroundColor: Color, icon: @Composable () -> Unit, text: String, isThemeSelected: Boolean ) { Column( verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier .padding(10.dp) .height(100.dp) .clip(RoundedCornerShape(12.dp)) .clickable { onClick() } ) { Box( modifier = Modifier .padding(10.dp) .size(50.dp) .clip(MaterialShapes.Cookie9Sided.toShape()) .border( width = 2.dp, color = if (isThemeSelected) MaterialTheme.colorScheme.secondary else Color.Transparent, shape = MaterialShapes.Cookie9Sided.toShape() ) .background(backgroundColor), contentAlignment = Alignment.Center ) { icon() } Spacer(Modifier.weight(1f)) Text(text) } } @Immutable data class ThemeItem( val onClick: () -> Unit, val backgroundColor: Color, val text: String, val isSelected: Boolean, val iconAndTint: Pair ) ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/shared_components/AnimatedFab.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.shared_components import androidx.annotation.DrawableRes import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsPressedAsState import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.defaultMinSize import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.FloatingActionButtonDefaults import androidx.compose.material3.Icon import androidx.compose.material3.MaterialShapes import androidx.compose.material3.contentColorFor import androidx.compose.material3.toPath import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.draw.scale import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Matrix import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Shape import androidx.compose.ui.res.painterResource import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.graphics.shapes.Morph import com.sosauce.vanilla.utils.bouncySpec private data class FabAnimation( val rotation: Float, val scale: Float, val shape: Shape ) @Composable private fun rememberFabAnimations(isPressed: Boolean): FabAnimation { val morph = remember { Morph( MaterialShapes.Cookie9Sided, MaterialShapes.Circle ) } val animatedScale by animateFloatAsState( targetValue = if (isPressed) 0.8f else 1f, label = "scale", animationSpec = bouncySpec() ) val animatedRotation by animateFloatAsState( targetValue = if (isPressed) 180f else 0f, label = "rotation", animationSpec = bouncySpec() ) val animatedProgress by animateFloatAsState( targetValue = if (isPressed) 1f else 0f, label = "progress", animationSpec = bouncySpec() ) val shape = remember(morph, animatedProgress) { MorphPolygonShape(morph, animatedProgress) } return FabAnimation( rotation = animatedRotation, scale = animatedScale, shape = shape ) } @Composable fun AnimatedFab( onClick: () -> Unit, @DrawableRes icon: Int, modifier: Modifier = Modifier, minSize: Dp = 56.dp, containerColor: Color = FloatingActionButtonDefaults.containerColor ) { val interactionSource = remember { MutableInteractionSource() } val isPressed by interactionSource.collectIsPressedAsState() val fabAnimation = rememberFabAnimations(isPressed) Box( modifier = modifier .scale(fabAnimation.scale) .defaultMinSize(minWidth = minSize, minHeight = minSize) .clip(fabAnimation.shape) .background(containerColor) .clickable(interactionSource = interactionSource, indication = null, onClick = onClick) ) { Icon( painter = painterResource(icon), contentDescription = null, tint = contentColorFor(containerColor), modifier = Modifier .align(Alignment.Center) .rotate(fabAnimation.rotation) ) } } class MorphPolygonShape( private val morph: Morph, private val percentage: Float ) : Shape { private val matrix = Matrix() override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { matrix.scale(size.width, size.height) val path = morph.toPath(progress = percentage) path.transform(matrix) return Outline.Generic(path) } } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/ui/theme/Theme.kt ================================================ @file:OptIn(ExperimentalMaterial3ExpressiveApi::class) package com.sosauce.vanilla.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi import androidx.compose.material3.MaterialExpressiveTheme import androidx.compose.material3.Typography import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontStyle import androidx.compose.ui.text.font.FontWeight import com.sosauce.vanilla.R import com.sosauce.vanilla.data.datastore.rememberAppTheme import com.sosauce.vanilla.data.datastore.rememberUseSystemFont import com.sosauce.vanilla.utils.CuteTheme import com.sosauce.vanilla.utils.anyDarkColorScheme import com.sosauce.vanilla.utils.anyLightColorScheme @Composable fun CuteCalcTheme( content: @Composable () -> Unit ) { val isSystemInDarkTheme = isSystemInDarkTheme() val appTheme by rememberAppTheme() val useSystemFont by rememberUseSystemFont() val colorScheme = when (appTheme) { CuteTheme.AMOLED -> anyDarkColorScheme().copy( surface = Color.Black, inverseSurface = Color.White, background = Color.Black, ) CuteTheme.SYSTEM -> if (isSystemInDarkTheme) anyDarkColorScheme() else anyLightColorScheme() CuteTheme.DARK -> anyDarkColorScheme() CuteTheme.LIGHT -> anyLightColorScheme() else -> anyDarkColorScheme() } MaterialExpressiveTheme( colorScheme = colorScheme, content = content, typography = if (useSystemFont) null else NunitoTypography ) } val nunitoFontFamily = FontFamily( Font(R.font.nunito_extrabold, FontWeight.ExtraBold, FontStyle.Normal) ) val NunitoTypography = Typography().run { copy( displayLarge = displayLarge.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), displayMedium = displayMedium.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), displaySmall = displaySmall.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), headlineLarge = headlineLarge.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), headlineMedium = headlineMedium.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), headlineSmall = headlineSmall.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), titleLarge = titleLarge.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), titleMedium = titleMedium.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), titleSmall = titleSmall.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), bodyLarge = bodyLarge.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), bodyMedium = bodyMedium.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), bodySmall = bodySmall.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), labelLarge = labelLarge.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), labelMedium = labelMedium.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), labelSmall = labelSmall.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), displayLargeEmphasized = displayLargeEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), displayMediumEmphasized = displayMediumEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), displaySmallEmphasized = displaySmallEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), headlineLargeEmphasized = headlineLargeEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), headlineMediumEmphasized = headlineMediumEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), headlineSmallEmphasized = headlineSmallEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), titleLargeEmphasized = titleLargeEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), titleMediumEmphasized = titleMediumEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), titleSmallEmphasized = titleSmallEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), bodyLargeEmphasized = bodyLargeEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), bodyMediumEmphasized = bodyMediumEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), bodySmallEmphasized = bodySmallEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), labelLargeEmphasized = labelLargeEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), labelMediumEmphasized = labelMediumEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ), labelSmallEmphasized = labelSmallEmphasized.copy( fontFamily = nunitoFontFamily, fontWeight = FontWeight.ExtraBold ) ) } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/utils/Constants.kt ================================================ package com.sosauce.vanilla.utils const val CUTE_MUSIC = "com.sosauce.cutemusic" const val GITHUB_RELEASES = "https://github.com/sosauce/CuteCalc/releases" const val SUPPORT_PAGE = "https://sosauce.github.io/support/" const val BACKSPACE = "backspace" const val PARENTHESES = "parentheses" object CuteTheme { const val SYSTEM = "SYSTEM" const val DARK = "DARK" const val LIGHT = "LIGHT" const val AMOLED = "AMOLED" } ================================================ FILE: app/src/main/java/com/sosauce/vanilla/utils/Extensions.kt ================================================ package com.sosauce.vanilla.utils import android.app.Activity import android.content.Context import android.os.Build import android.view.WindowManager import androidx.compose.animation.core.Spring import androidx.compose.animation.core.spring import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.foundation.text.input.delete import androidx.compose.foundation.text.input.insert import androidx.compose.material3.ColorScheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.IntOffset import com.sosauce.vanilla.data.calculator.Tokens import com.sosauce.vanilla.domain.model.Calculation import java.text.DecimalFormatSymbols fun Modifier.thenIf( condition: Boolean, modifier: Modifier.() -> Modifier ): Modifier { return if (condition) { this.then(modifier()) } else this } fun List.sort( newestFirst: Boolean ): List { return if (newestFirst) { this.sortedByDescending { it.id } } else { this } } @Composable fun anyLightColorScheme(): ColorScheme { val context = LocalContext.current return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { dynamicLightColorScheme(context) } else { lightColorScheme() } } @Composable fun anyDarkColorScheme(): ColorScheme { val context = LocalContext.current return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { dynamicDarkColorScheme(context) } else { darkColorScheme() } } fun TextFieldState.insertText(char: Char) { val expression = this.text val cursorPosition = selection.start val charInfrontCursor = expression.getOrNull(cursorPosition - 1) ?: ' ' val charBehindCursor = expression.getOrNull(cursorPosition) ?: ' ' when (char) { Tokens.ZERO, Tokens.ONE, Tokens.TWO, Tokens.THREE, Tokens.FOUR, Tokens.FIVE, Tokens.SIX, Tokens.SEVEN, Tokens.EIGHT, Tokens.NINE, Tokens.PI, Tokens.OPEN_PARENTHESIS, Tokens.CLOSED_PARENTHESIS, Tokens.SQUARE_ROOT, Tokens.MODULO, Tokens.FACTORIAL -> { edit { insert(cursorPosition, char.toString()) } } Tokens.DECIMAL -> { val toInsert = if (!charInfrontCursor.isDigit()) { "${Tokens.ZERO}${Tokens.DECIMAL}" } else Tokens.DECIMAL.toString() edit { insert(cursorPosition, toInsert) } } Tokens.SUBTRACT -> { if (charInfrontCursor.isOperator()) { edit { insert(cursorPosition, "${Tokens.OPEN_PARENTHESIS}${Tokens.SUBTRACT}") } } else if (charBehindCursor.isOperator()) { edit { replace(cursorPosition, cursorPosition + 1, char.toString()) } } else { edit { insert(cursorPosition, char.toString()) } } } Tokens.ADD, Tokens.DIVIDE, Tokens.MULTIPLY, Tokens.POWER -> { if (charInfrontCursor.isOperator()) { edit { replace(cursorPosition - 1, cursorPosition, char.toString()) } } else if (charBehindCursor.isOperator()) { edit { replace(cursorPosition, cursorPosition + 1, char.toString()) } } else { edit { insert(cursorPosition, char.toString()) } } } } } fun TextFieldState.backspace() { val cursorPosition = selection.start if (selection.collapsed && cursorPosition > 0) { edit { delete(cursorPosition - 1, cursorPosition) } } } fun Char.isOperator(): Boolean { val operators = listOf(Tokens.ADD, Tokens.SUBTRACT, Tokens.DIVIDE, Tokens.MULTIPLY, Tokens.POWER) return this in operators } fun String.isErrorMessage(): Boolean { return any { char -> char.isLetter() } } fun CharSequence.whichParenthesis(): Char { return if (count { it == Tokens.OPEN_PARENTHESIS } > count { it == Tokens.CLOSED_PARENTHESIS }) { Tokens.CLOSED_PARENTHESIS } else { Tokens.OPEN_PARENTHESIS } } /** * Formats a number not an expression !! */ fun String.formatNumber(shouldFormat: Boolean): String { val number = this val localSymbols = DecimalFormatSymbols.getInstance() if (number.any { it.isLetter() } || !shouldFormat) return number val integer = number.takeWhile { it != '.' } val decimal = number.removePrefix(integer).replace('.', localSymbols.decimalSeparator) // 1234 val formattedInteger = integer .reversed() // 4321 .chunked(3) // [432, 1] .joinToString(localSymbols.groupingSeparator.toString()) // 432,1 .reversed() // 1,234 return "${formattedInteger}${decimal}" } fun String.formatExpression(shouldFormat: Boolean): String { if (!shouldFormat) return this var expression = this val numberRegex = Regex("[\\d.]+") numberRegex.findAll(expression).forEach { result -> expression = expression.replace(result.value, result.value.formatNumber(true)) } return expression } fun Activity.showOnLockScreen(show: Boolean) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) { setShowWhenLocked(show) } else { if (show) { window.addFlags( WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON ) } } } fun Modifier.selfAlignHorizontally(align: Alignment.Horizontal = Alignment.CenterHorizontally): Modifier { return this.then( Modifier .fillMaxWidth() .wrapContentWidth(align) ) } fun bouncySpec() = spring( dampingRatio = Spring.DampingRatioMediumBouncy, stiffness = Spring.StiffnessLow ) val navigationBouncySpec = spring(Spring.DampingRatioLowBouncy, Spring.StiffnessLow) val Context.appVersion get() = packageManager.getPackageInfo(packageName, 0).versionName ================================================ FILE: app/src/main/java/com/sosauce/vanilla/utils/ViewModelFactories.kt ================================================ package com.sosauce.vanilla.utils import android.app.Application import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.room.Room import com.sosauce.vanilla.domain.repository.HistoryDatabase import com.sosauce.vanilla.ui.screens.calculator.CalculatorViewModel import com.sosauce.vanilla.ui.screens.history.HistoryViewModel class HistoryViewModelFactory(val application: Application) : ViewModelProvider.Factory { private val historyDb by lazy { Room.databaseBuilder( context = application, klass = HistoryDatabase::class.java, name = "history.db" ).build() } override fun create(modelClass: Class): T { return HistoryViewModel(historyDb.dao) as T } } class CalculatorViewModelFactory(val application: Application) : ViewModelProvider.Factory { override fun create(modelClass: Class): T { return CalculatorViewModel(application) as T } } ================================================ FILE: app/src/main/res/drawable/amoled.xml ================================================ ================================================ FILE: app/src/main/res/drawable/arrow_right.xml ================================================ ================================================ FILE: app/src/main/res/drawable/arrow_up.xml ================================================ ================================================ FILE: app/src/main/res/drawable/back_arrow.xml ================================================ ================================================ FILE: app/src/main/res/drawable/backspace_filled.xml ================================================ ================================================ FILE: app/src/main/res/drawable/backspace_rounded.xml ================================================ ================================================ FILE: app/src/main/res/drawable/calculator.xml ================================================ ================================================ FILE: app/src/main/res/drawable/check.xml ================================================ ================================================ FILE: app/src/main/res/drawable/close.xml ================================================ ================================================ FILE: app/src/main/res/drawable/copy.xml ================================================ ================================================ FILE: app/src/main/res/drawable/dark_mode.xml ================================================ ================================================ FILE: app/src/main/res/drawable/delete.xml ================================================ ================================================ FILE: app/src/main/res/drawable/favorite_filled.xml ================================================ ================================================ FILE: app/src/main/res/drawable/formatting.xml ================================================ ================================================ FILE: app/src/main/res/drawable/github.xml ================================================ ================================================ FILE: app/src/main/res/drawable/history_rounded.xml ================================================ ================================================ FILE: app/src/main/res/drawable/ic_launcher_foreground.xml ================================================ ================================================ FILE: app/src/main/res/drawable/icon_splash.xml ================================================ ================================================ FILE: app/src/main/res/drawable/light_mode.xml ================================================ ================================================ FILE: app/src/main/res/drawable/more_horiz.xml ================================================ ================================================ FILE: app/src/main/res/drawable/more_vert.xml ================================================ ================================================ FILE: app/src/main/res/drawable/palette.xml ================================================ ================================================ FILE: app/src/main/res/drawable/parentheses.xml ================================================ ================================================ FILE: app/src/main/res/drawable/settings_filled.xml ================================================ ================================================ FILE: app/src/main/res/drawable/sort_rounded.xml ================================================ ================================================ FILE: app/src/main/res/drawable/system_theme.xml ================================================ ================================================ FILE: app/src/main/res/drawable/trash_rounded.xml ================================================ ================================================ FILE: app/src/main/res/drawable/undo.xml ================================================ ================================================ FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml ================================================ ================================================ FILE: app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml ================================================ ================================================ FILE: app/src/main/res/values/colors.xml ================================================ #201A1A #f0d2ce ================================================ FILE: app/src/main/res/values/ic_launcher_background.xml ================================================ #F5A6BD ================================================ FILE: app/src/main/res/values/strings.xml ================================================ Theme Settings Dark Light Amoled Version Check updates Vanilla by sosauce System Font System Buttons animation History Use history It looks like history isn\'t enabled ! Enable history Misc Haptic feedback Ascending Descending Decimal formatting Show clear button You can still long press the backspace button to clear the input field. Back Sort Delete Backspace Put back in input field Copy to clipboard More actions Look and feel Why not calculate in style ? Default UI Remember everything ! Max saved items in history No limit Other settings that didn\'t deserve their own page. Formatting Show back button Clear history Are you sure you want to do that ? This action can\'t be undone ! Cancel Save errors to history Support Decimal precision Adjust the number of decimal places. Make numbers look great ! Show app on lock screen The app will still be usable on the lock screen. This can be useful for example, in stores. Newest first Oldest first No calculation found ! Start calculating already ! Colored operators Swap zero & decimal ================================================ FILE: app/src/main/res/values/themes.xml ================================================ ================================================ FILE: app/src/main/res/values-es/strings.xml ================================================ Tema Ajustes Modo Oscuro Modo Claro Modo Amoled Versión Buscar actualizaciones Vanilla por sosauce Seguir sistema Fuente Sistema Animación de botones Historial Usar historial ¡Parece que el historial no está habilitado! Habilitar historial Varios Respuesta háptica Ascendente Descendente Formato decimal Mostrar botón de borrar Aún puedes mantener presionado el botón de retroceso para borrar el campo de entrada. Atrás Ordenar Eliminar Retroceso Poner de nuevo en el campo de entrada Copiar al portapapeles Más acciones Apariencia y estilo ¿Por qué no calcular con estilo? Predeterminada IU ¡Recordarlo todo! Máximo de elementos en el historial Sin límite Otros ajustes que no merecían su propia página. Formato Mostrar botón de retroceso Limpiar historial ¿Realmente quieres hacer eso? ¡Esta acción no se puede deshacer! Cancelar Guardar errores en el historial Apóyame Precisión decimal Ajusta el número de decimales. ¡Haz que los números se vean geniales! Mostrar app en pantalla de bloqueo La app seguirá siendo utilizable en la pantalla de bloqueo. Esto puede ser útil, por ejemplo, en tiendas. Primero los más recientes Primero los más antiguos ¡No se encontraron cálculos! ¡Empieza a calcular de una vez! Operadores coloreados ================================================ FILE: app/src/main/res/values-fr-rFR/strings.xml ================================================ Thème Paramètres Mode sombre Clair Mode amoled Version Mettre à jour Vanilla par sosauce Suivre le système Police d\'écriture Système Animation des buttons Historique Utiliser l\'historique Il semblerait que l\'historique ne soit pas activé ! Activé l\'historique Divers Vibrations Ascendant Descendant Format décimal Afficher le button effacer Vous pouvez toujours rester appuyer sur le button d\'effacement arrière pour effacer le champs de calcul. Retour Trier Supprimer Retour arrière Remettre dans le champ Copier dans le presse-papiers Plus d\'action Apparence Pourquoi pas calculer en style ? Défaut UI Souvenez-vous de tout ! Éléments max sauvegarder dans l\'historique Pas de limite Autre paramètres qui ne méritaient pas leurs pages Formattage Montrer le button arrière Vider l\'historique Êtes-vous sûr de vouloir faire ceci ? Annuler Sauvegarder les erreurs dans l\'historique Supporter Précision décimale Ajuster le nombre de chiffres après la décimale Rendez les nombres beaux ! Montrer l\'app sur l\'écran de vérouillage L\'app sera utilisable sur l\'écran de vérouillage. ================================================ FILE: app/src/main/res/values-v31/colors.xml ================================================ @android:color/system_neutral2_900 @android:color/system_accent1_100 ================================================ FILE: app/src/main/res/values-zh-rCN/strings.xml ================================================ 主题 设置 深色 浅色 Amoled 版本 检查更新 Vanilla by sosauce 系统 字体 系统 按钮动画 历史记录 使用历史记录 看起来没有启用历史记录! 启用历史记录 杂项 触觉反馈 上升 下降 小数格式 显示清除按钮 你仍然可以长按退格键来清空输入字段。 返回 排序 删除 退格 Put back in input field 复制到剪贴板 更多操作 外观和感觉 为什么不美观地计算呢? 默认 UI 记住一切! 历史记录中能保存的最大项目 无限 其他不值得单独页面的设置。 格式化 显示返回按钮 清除历史记录 你确定要这样做吗?此操作无法撤销! 取消 将错误保存到历史记录 支持 小数精度 调整小数位数。 让数字看起来更出色! 在锁屏上显示应用 该应用在锁屏状态下仍然可用。例如,这在商店里可能会很有用。 最新的在前 最早的在前 未找到计算! 快开始计算吧! ================================================ FILE: build.gradle.kts ================================================ plugins { alias(libs.plugins.androidApplication) apply false alias(libs.plugins.compose.compiler) apply false alias(libs.plugins.ksp) apply false } ================================================ FILE: fastlane/metadata/android/de/full_description.txt ================================================ Vanilla ist eine kleine, schnelle, Open-Source Android Taschenrechner-App im Material 3 Design, die keine Berechtigungen braucht. ================================================ FILE: fastlane/metadata/android/de/short_description.txt ================================================ Eine simple, kleine, Open-Source Taschenrechner-App ================================================ FILE: fastlane/metadata/android/en-US/full_description.txt ================================================ Vanilla is a cute an elegant calculator app for Android! ================================================ FILE: fastlane/metadata/android/en-US/short_description.txt ================================================ A cute and elegant calculator app for Android ================================================ FILE: font_licence.txt ================================================ Copyright 2014 The Nunito Project Authors (https://github.com/googlefonts/nunito) This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ----------------------------------------------------------- PREAMBLE The goals of the Open Font License (OFL) are to stimulate worldwide development of collaborative font projects, to support the font creation efforts of academic and linguistic communities, and to provide a free and open framework in which fonts may be shared and improved in partnership with others. The OFL allows the licensed fonts to be used, studied, modified and redistributed freely as long as they are not sold by themselves. The fonts, including any derivative works, can be bundled, embedded, redistributed and/or sold with any software provided that any reserved names are not used by derivative works. The fonts and derivatives, however, cannot be released under any other type of license. The requirement for fonts to remain under this license does not apply to any document created using the fonts or their derivatives. DEFINITIONS "Font Software" refers to the set of files released by the Copyright Holder(s) under this license and clearly marked as such. This may include source files, build scripts and documentation. "Reserved Font Name" refers to any names specified as such after the copyright statement(s). "Original Version" refers to the collection of Font Software components as distributed by the Copyright Holder(s). "Modified Version" refers to any derivative made by adding to, deleting, or substituting -- in part or in whole -- any of the components of the Original Version, by changing formats or by porting the Font Software to a new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font Software, subject to the following conditions: 1) Neither the Font Software nor any of its individual components, in Original or Modified Versions, may be sold by itself. 2) Original or Modified Versions of the Font Software may be bundled, redistributed and/or sold with any software, provided that each copy contains the above copyright notice and this license. These can be included either as stand-alone text files, human-readable headers or in the appropriate machine-readable metadata fields within text or binary files as long as those fields can be easily viewed by the user. 3) No Modified Version of the Font Software may use the Reserved Font Name(s) unless explicit written permission is granted by the corresponding Copyright Holder. This restriction only applies to the primary font name as presented to the users. 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font Software shall not be used to promote, endorse or advertise any Modified Version, except to acknowledge the contribution(s) of the Copyright Holder(s) and the Author(s) or with their explicit written permission. 5) The Font Software, modified or unmodified, in part or in whole, must be distributed entirely under this license, and must not be distributed under any other license. The requirement for fonts to remain under this license does not apply to any document created using the Font Software. TERMINATION This license becomes null and void if any of the above conditions are not met. DISCLAIMER THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. ================================================ FILE: gradle/libs.versions.toml ================================================ [versions] agp = "9.2.1" composeBom = "2026.05.00" coreSplashscreen = "1.2.0" datastorePreferences = "1.2.1" keval = "1.1.1" kotlin = "2.3.21" ksp = "2.3.4" lifecycleViewmodelCompose = "2.10.0" roomCompiler = "2.8.4" roomKtx = "2.8.4" activityCompose = "1.13.0" material3 = "1.5.0-alpha19" squircleShape = "5.2.1" [libraries] androidx-compose-bom = { module = "androidx.compose:compose-bom", version.ref = "composeBom" } androidx-core-splashscreen = { module = "androidx.core:core-splashscreen", version.ref = "coreSplashscreen" } androidx-datastore-preferences = { module = "androidx.datastore:datastore-preferences", version.ref = "datastorePreferences" } androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycleViewmodelCompose" } androidx-material3 = { module = "androidx.compose.material3:material3", version.ref = "material3" } androidx-ui = { module = "androidx.compose.ui:ui" } keval = { module = "com.notkamui.libs:keval", version.ref = "keval" } androidx-room-compiler = { module = "androidx.room:room-compiler", version.ref = "roomCompiler" } androidx-room-ktx = { module = "androidx.room:room-ktx", version.ref = "roomKtx" } androidx-activity-compose = { module = "androidx.activity:activity-compose", version.ref = "activityCompose" } squircle-shape = { module = "com.stoyanvuchev:squircle-shape", version.ref = "squircleShape" } [plugins] androidApplication = { id = "com.android.application", version.ref = "agp" } compose-compiler = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" } ksp = { id = "com.google.devtools.ksp", version.ref = "ksp" } ================================================ FILE: gradle/wrapper/gradle-wrapper.properties ================================================ #Fri Dec 15 16:55:56 CET 2023 distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists ================================================ FILE: gradle.properties ================================================ android.useAndroidX=true kotlin.code.style=official android.nonTransitiveRClass=true android.uniquePackageNames=false android.dependency.useConstraints=true android.r8.strictFullModeForKeepRules=false org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 ================================================ FILE: gradlew ================================================ #!/usr/bin/env sh # # Copyright 2015 the original author or authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## ## ## Gradle start up script for UN*X ## ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link PRG="$0" # Need this for relative symlinks. while [ -h "$PRG" ] ; do ls=`ls -ld "$PRG"` link=`expr "$ls" : '.*-> \(.*\)$'` if expr "$link" : '/.*' > /dev/null; then PRG="$link" else PRG=`dirname "$PRG"`"/$link" fi done SAVED="`pwd`" cd "`dirname \"$PRG\"`/" >/dev/null APP_HOME="`pwd -P`" cd "$SAVED" >/dev/null APP_NAME="Gradle" APP_BASE_NAME=`basename "$0"` # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD="maximum" warn () { echo "$*" } die () { echo echo "$*" echo exit 1 } # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "`uname`" in CYGWIN* ) cygwin=true ;; Darwin* ) darwin=true ;; MINGW* ) msys=true ;; NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD="$JAVA_HOME/jre/sh/java" else JAVACMD="$JAVA_HOME/bin/java" fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD="java" which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then MAX_FD_LIMIT=`ulimit -H -n` if [ $? -eq 0 ] ; then if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then MAX_FD="$MAX_FD_LIMIT" fi ulimit -n $MAX_FD if [ $? -ne 0 ] ; then warn "Could not set maximum file descriptor limit: $MAX_FD" fi else warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" fi fi # For Darwin, add options to specify how the application appears in the dock if $darwin; then GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" fi # For Cygwin or MSYS, switch paths to Windows format before running java if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then APP_HOME=`cygpath --path --mixed "$APP_HOME"` CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` JAVACMD=`cygpath --unix "$JAVACMD"` # We build the pattern for arguments to be converted via cygpath ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` SEP="" for dir in $ROOTDIRSRAW ; do ROOTDIRS="$ROOTDIRS$SEP$dir" SEP="|" done OURCYGPATTERN="(^($ROOTDIRS))" # Add a user-defined pattern to the cygpath arguments if [ "$GRADLE_CYGPATTERN" != "" ] ; then OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" fi # Now convert the arguments - kludge to limit ourselves to /bin/sh i=0 for arg in "$@" ; do CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` else eval `echo args$i`="\"$arg\"" fi i=`expr $i + 1` done case $i in 0) set -- ;; 1) set -- "$args0" ;; 2) set -- "$args0" "$args1" ;; 3) set -- "$args0" "$args1" "$args2" ;; 4) set -- "$args0" "$args1" "$args2" "$args3" ;; 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; esac fi # Escape application args save () { for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done echo " " } APP_ARGS=`save "$@"` # Collect all arguments for the java command, following the shell quoting and substitution rules eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" exec "$JAVACMD" "$@" ================================================ FILE: gradlew.bat ================================================ @rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega ================================================ FILE: settings.gradle.kts ================================================ @file:Suppress("UnstableApiUsage") pluginManagement { repositories { google() mavenCentral() gradlePluginPortal() } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() maven { url = uri("https://jitpack.io") } } } rootProject.name = "Vanilla" include(":app")