diff --git a/.gitmodules b/.gitmodules index 23a31e91..795cf7f0 100644 --- a/.gitmodules +++ b/.gitmodules @@ -6,7 +6,3 @@ path = Source/Horizon-OC-Monitor/lib/libultrahand url = https://github.com/ppkantorski/libultrahand branch = main -[submodule "Source/sys-clk/overlay/lib/libultrahand"] - path = Source/sys-clk/overlay/lib/libultrahand - url = https://github.com/ppkantorski/libultrahand - branch = main diff --git a/Source/hoc-clk/common/include/sysclk/board.h b/Source/hoc-clk/common/include/sysclk/board.h index 467ba192..f34ed47e 100644 --- a/Source/hoc-clk/common/include/sysclk/board.h +++ b/Source/hoc-clk/common/include/sysclk/board.h @@ -218,7 +218,7 @@ static inline const char* sysclkFormatThermalSensor(SysClkThermalSensor thermSen return pretty ? "GPU" : "gpu"; case HorizonOCThermalSensor_MEM: return pretty ? "MEM" : "mem"; - case HorizonOCThermalSensor_PLLX: + case HorizonOCThermalSensor_PLLX: return pretty ? "PLLX" : "pllx"; default: return NULL; diff --git a/Source/hoc-clk/overlay/lib/libultrahand/.github/FUNDING.yml b/Source/hoc-clk/overlay/lib/libultrahand/.github/FUNDING.yml new file mode 100644 index 00000000..57fdec3d --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: ppkantorski +ko_fi: ppkantorski diff --git a/Source/hoc-clk/overlay/lib/libultrahand/.gitmodules b/Source/hoc-clk/overlay/lib/libultrahand/.gitmodules new file mode 100644 index 00000000..e69de29b diff --git a/Source/hoc-clk/overlay/lib/libultrahand/.pics/libultrahand.png b/Source/hoc-clk/overlay/lib/libultrahand/.pics/libultrahand.png new file mode 100644 index 00000000..7165fb92 Binary files /dev/null and b/Source/hoc-clk/overlay/lib/libultrahand/.pics/libultrahand.png differ diff --git a/Source/hoc-clk/overlay/lib/libultrahand/LICENSE b/Source/hoc-clk/overlay/lib/libultrahand/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/Source/hoc-clk/overlay/lib/libultrahand/README.md b/Source/hoc-clk/overlay/lib/libultrahand/README.md new file mode 100644 index 00000000..a2b45be0 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/README.md @@ -0,0 +1,211 @@ +# ☆ libultrahand +[![platform](https://img.shields.io/badge/platform-Switch-898c8c?logo=C++.svg)](https://gbatemp.net/forums/nintendo-switch.283/?prefix_id=44) +[![language](https://img.shields.io/badge/language-C++-ba1632?logo=C++.svg)](https://github.com/topics/cpp) +[![GPLv2 License](https://img.shields.io/badge/license-GPLv2-189c11.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html) +[![Latest Version](https://img.shields.io/github/v/release/ppkantorski/libultrahand?label=latest&color=blue)](https://github.com/ppkantorski/libultrahand/releases/latest) +[![Downloads](https://img.shields.io/github/downloads/ppkantorski/libultrahand/total?color=6f42c1)](https://github.com/ppkantorski/libultrahand/graphs/traffic) +[![GitHub issues](https://img.shields.io/github/issues/ppkantorski/libultrahand?color=222222)](https://github.com/ppkantorski/libultrahand/issues) +[![GitHub stars](https://img.shields.io/github/stars/ppkantorski/libultrahand)](https://github.com/ppkantorski/libultrahand/stargazers) + + +Expanded [**libtesla**](https://github.com/WerWolv/libtesla) (originally by [WerWolv](https://github.com/WerWolv)) + **libultra** libraries for overlay development on the Nintendo Switch + +![libultrahand Logo](.pics/libultrahand.png) + +## Compiling + +### Necessary Libraries and Imports +For easy importing and inclusion, try using `ultrahand.mk`. These lines must go after your projects `SOURCES` and `INCLUDES` definitions. +```sh +include $(TOPDIR)/lib/libultrahand/ultrahand.mk +``` +This location should reflect where you place the `libultrahand` directory (`lib` can vary between projects). + +## + +Otherwise developers should include the following `SOURCES` and `INCLUDES` lines. +```sh +SOURCES += lib/libultrahand/common lib/libultrahand/libultra/source +INCLUDES += lib/libultrahand/common lib/libultrahand/libultra/include lib/libultrahand/libtesla/include +``` +## + +Including the following libraries are also essential for compilation. +```sh +LIBS := -lcurl -lz -lminizip -lmbedtls -lmbedx509 -lmbedcrypto -lnx +``` + +### Active Services +Service conflictions can occur, so if you are already using the following libnx services, you may want to remove them from your project. +```cpp +i2cInitialize(); +fsdevMountSdmc(); +splInitialize(); +spsmInitialize(); +ASSERT_FATAL(socketInitializeDefault()); +ASSERT_FATAL(nifmInitialize(NifmServiceType_User)); +ASSERT_FATAL(smInitialize()); // needed to prevent issues with powering device into sleep +``` +Service `i2cInitialize` however is only utilized in accordance with `USING_WIDGET_DIRECTIVE`. + +### Optional Compilation Flags +``` +-ffunction-sections -fdata-sections +``` +These options are present in both CFLAGS and CXXFLAGS. They instruct the compiler to place each function and data item in its own section, which allows the linker to more easily identify and remove unused code. + +``` +-Wl,--gc-sections +``` +Included in LDFLAGS. This linker flag instructs the linker to remove unused sections that were created by -ffunction-sections and -fdata-sections. This ensures that functions or data that are not used are removed from the final executable. + +``` +-flto (Link Time Optimization) +``` +Present in CFLAGS, CXXFLAGS, and LDFLAGS. It enables link-time optimization, allowing the compiler to optimize across different translation units and remove any unused code during the linking phase. You also use -flto=6 to control the number of threads for parallel LTO, which helps speed up the process. + +``` +-fuse-linker-plugin +``` +This flag allows the compiler and linker to better collaborate when using LTO, which further helps in optimizing and eliminating unused code. +Together, these flags (-ffunction-sections, -fdata-sections, -Wl,--gc-sections, and -flto) ensure that any unused functions or data are stripped out during the build process, leading to a smaller and more optimized final binary. + + +## Build Examples +- [Ultrahand Overlay](https://github.com/ppkantorski/Ultrahand-Overlay) + +- [Tetris Overlay](https://github.com/ppkantorski/Tetris-Overlay) + +- [Status Monitor Overlay](https://github.com/ppkantorski/Status-Monitor-Overlay) + +- [Edizon Overlay](https://github.com/proferabg/EdiZon-Overlay) + +- [Sysmodules](https://github.com/ppkantorski/ovl-sysmodules) + +- [sys-clk](https://github.com/ppkantorski/sys-clk) + +- [FPSLocker](https://github.com/ppkantorski/FPSLocker) + +- [ReverseNX-RT](https://github.com/ppkantorski/ReverseNX-RT) + +- [QuickNTP](https://github.com/ppkantorski/QuickNTP) + +- [SysDVR Overlay](https://github.com/ppkantorski/sysdvr-overlay) + +- [Fizeau](https://github.com/ppkantorski/Fizeau) + +- [NX-FanControl](https://github.com/ppkantorski/NX-FanControl) + +- [DNS-MITM_Manager](https://github.com/ppkantorski/DNS-MITM_Manager) + + +## Features + +### Overriding Themes and Wallpapers + +To customize theme, wallpaper and / or allow direct language translations for your overlay, you can override the default settings by adding the following lines to your `Makefile`: + +``` +# Enable appearance overriding +UI_OVERRIDE_PATH := /config// +CFLAGS += -DUI_OVERRIDE_PATH="\"$(UI_OVERRIDE_PATH)\"" +``` + +Replace `` with the desired name of your overlay config directory. + +Users can specify custom Ultrahand `theme.ini` and `wallpaper.rgba` files for the overlay to use located in your SD card's `/config//` or `{UI_OVERRIDE_PATH}` directory. + +#### **Troubleshooting** +**Notice:** Makefile directives also must be added to `CXXFLAGS`. +You can do this by adding the directives before `CXXFLAGS := $(CFLAGS)` gets defined, or include `CXXFLAGS += ...`. + + +There are rare occurences where the theme and wallpaper are still not being loaded. This may have to do with how the GUI class is used in some projects. For a work around, you can try adding the `INITIALIZE_IN_GUI_DIRECTIVE` directive. + +``` +# For theme / wallpaper loading in GUI class method (add to project if theme does not appear) +INITIALIZE_IN_GUI_DIRECTIVE := 1 +CFLAGS += -DINITIALIZE_IN_GUI_DIRECTIVE=$(INITIALIZE_IN_GUI_DIRECTIVE) +``` + +This fix will work for many projects, but other projects may not like this directive or may not need it at all so use with that in mind. + +--- + +### Overriding Languages +For language translation, `UI_OVERRIDE_PATH` must be defined. Translations are performed direction on the rederer's `drawString` method. Direct strings can be added to a json located in `/config//lang/` or `{UI_OVERRIDE_PATH}/lang/`. + +Jsons will need to be named ISO 639-1 format (en, de, fr, es, etc...) and will only be used in accordance with the current language set in the Ultrahand Overlay `/config/ultrahand/config.ini`. + +The format for language jsons is as follows. +```json +{ + "English String": "Translated String", + "Another String": "Another Translation", + ... +} +``` + +--- + +### Ultrahand Overlay Widget + +To add the Ultrahand Overlay widget to your `OverlayFrame`'s, add the following directive to your `Makefile`: + +``` +# Enable Widget +USING_WIDGET_DIRECTIVE := 1 +CFLAGS += -DUSING_WIDGET_DIRECTIVE=$(USING_WIDGET_DIRECTIVE) +``` + +--- + +### Forcing use of `` instead of `` (unnecessary) + +To compile utilizing `fstream`, add the following directive to your `Makefile`: + +``` +# Enable fstream +USING_FSTREAM_DIRECTIVE := 1 +CFLAGS += -DUSING_FSTREAM_DIRECTIVE=$(USING_FSTREAM_DIRECTIVE) +``` + +--- + +### Initializing Settings + +Ultrahand Overlay theme variables and settings for your overlay are read automatically upon initialization. Themes loading implementation is currently set within `OverlayFrame` and `HeaderOverlayFrame`. + +However if you are breaking your project up into individual parts that only import `tesla.hpp` and modify elements, you may need to declare `/libultrahand/libultra/include` at the start of your `INCLUDES` in your make file. + +If that still is not working, then you may need to add this line somewhere for the theme to be applied to that element. + +```cpp +tsl::initializeThemeVars(); // Initialize variables for ultrahand themes +``` + +### Download Methods + +To utilize the `libultra` download methods in your project, you will need to add the following line to your `initServices` function: +```cpp +initializeCurl(); +``` +As well as the following line to your `exetServices` function: +```cpp +cleanupCurl(); +``` + +These lines will ensure `curl` functions properly within the overlay. + + +## Contributing + +Contributions are welcome! If you have any ideas, suggestions, or bug reports, please raise an [issue](https://github.com/ppkantorski/libultrahand/issues/new/choose), submit a [pull request](https://github.com/ppkantorski/libultrahand/compare) or reach out to me directly on [GBATemp](https://gbatemp.net/threads/ultrahand-overlay-the-fully-craft-able-overlay-executor.633560/). + +[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/X8X3VR194) + +## License + +This project is licensed and distributed under [GPLv2](LICENSE) with a [custom library](libultra) utilizing [CC-BY-4.0](SUB_LICENSE). + +Copyright (c) 2023-2026 ppkantorski diff --git a/Source/hoc-clk/overlay/lib/libultrahand/SUB_LICENSE b/Source/hoc-clk/overlay/lib/libultrahand/SUB_LICENSE new file mode 100644 index 00000000..2f244ac8 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/SUB_LICENSE @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/Source/hoc-clk/overlay/lib/libultrahand/common/cJSON.c b/Source/hoc-clk/overlay/lib/libultrahand/common/cJSON.c new file mode 100644 index 00000000..ca824f0e --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/common/cJSON.c @@ -0,0 +1,3191 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 18) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + item->string = NULL; + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char *number_c_string; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + size_t number_string_length = 0; + cJSON_bool has_decimal_point = false; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_string_length++; + break; + + case '.': + number_string_length++; + has_decimal_point = true; + break; + + default: + goto loop_end; + } + } +loop_end: + /* malloc for temporary buffer, add 1 for '\0' */ + number_c_string = (unsigned char *) input_buffer->hooks.allocate(number_string_length + 1); + if (number_c_string == NULL) + { + return false; /* allocation failure */ + } + + memcpy(number_c_string, buffer_at_offset(input_buffer), number_string_length); + number_c_string[number_string_length] = '\0'; + + if (has_decimal_point) + { + for (i = 0; i < number_string_length; i++) + { + if (number_c_string[i] == '.') + { + /* replace '.' with the decimal point of the current locale (for strtod) */ + number_c_string[i] = decimal_point; + } + } + } + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + size_t v1_len; + size_t v2_len; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted or valuestring is NULL */ + if (object->valuestring == NULL || valuestring == NULL) + { + return NULL; + } + + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); + + if (v1_len <= v2_len) + { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ + if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) + { + return NULL; + } + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + output = NULL; + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + if (printed != NULL) + { + hooks->deallocate(printed); + printed = NULL; + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + p.buffer = NULL; + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + if (cannot_access_at_index(input_buffer, 1)) + { + goto fail; /* nothing comes after the comma */ + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && after_inserted->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); + +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + return cJSON_Duplicate_rec(item, 0, recurse ); +} + +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + if(depth >= CJSON_CIRCULAR_LIMIT) { + goto fail; + } + newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); + object = NULL; +} diff --git a/Source/hoc-clk/overlay/lib/libultrahand/common/cJSON.h b/Source/hoc-clk/overlay/lib/libultrahand/common/cJSON.h new file mode 100644 index 00000000..37520bbc --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/common/cJSON.h @@ -0,0 +1,306 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 18 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* Limits the length of circular references can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_CIRCULAR_LIMIT +#define CJSON_CIRCULAR_LIMIT 10000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libtesla/LICENSE b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libtesla/README.md b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/README.md new file mode 100644 index 00000000..5782d161 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/README.md @@ -0,0 +1,32 @@ +# libtesla + +

+ +

+ +libtesla is the interface between the Tesla overlay loader and user-made Overlays. It handles all layer creation, UI creation, drawing and input management. +It's main goal is to make sure all overlays look and feel similar and don't differenciate themselves from the switch's native overlays. + +## Screenshots + +
+ + +
+ +`Overlays do NOT show up on Screenshots. These pictures were taken using a capture card` + +## Example + +An example for how to use libtesla can be found here: https://github.com/WerWolv/libtesla/tree/master/example +To create your own Overlay, please consider creating a new repository using the official Tesla overlay template: https://github.com/WerWolv/Tesla-Template + +**Please Note:** While it is possible to create overlays without libtesla, it's highly recommended to not do so. libtesla handles showing and hiding of overlays, button combo detection, layer creation and a lot more. Not using it will lead to an inconsistent user experience when using multiple different overlays ultimately making it worse for the end user. If something's missing, please consider opening a PR here. + +## Credits + +- **switchbrew** for nx-hbloader which is used as basis for overlay loading +- **kardch** for the amazing icon +- **All the devs on AtlasNX, RetroNX and Switchbrew** for their feedback +- **All overlay devs** for making something awesome out of this :) + diff --git a/Source/sys-clk/overlay/Makefile b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/example/Makefile similarity index 61% rename from Source/sys-clk/overlay/Makefile rename to Source/hoc-clk/overlay/lib/libultrahand/libtesla/example/Makefile index 09339ff1..cdb011ae 100644 --- a/Source/sys-clk/overlay/Makefile +++ b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/example/Makefile @@ -15,61 +15,56 @@ include $(DEVKITPRO)/libnx/switch_rules # SOURCES is a list of directories containing source code # DATA is a list of directories containing data files # INCLUDES is a list of directories containing header files -# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm". +# ROMFS is the directory containing data to be added to RomFS, relative to the Makefile (Optional) +# +# NO_ICON: if set to anything, do not use icon. +# NO_NACP: if set to anything, no .nacp file is generated. +# APP_TITLE is the name of the app stored in the .nacp file (Optional) +# APP_AUTHOR is the author of the app stored in the .nacp file (Optional) +# APP_VERSION is the version of the app stored in the .nacp file (Optional) +# APP_TITLEID is the titleID of the app stored in the .nacp file (Optional) +# ICON is the filename of the icon (.jpg), relative to the project folder. +# If not set, it attempts to use one of the following (in this order): +# - .jpg +# - icon.jpg +# - /default_icon.jpg +# +# CONFIG_JSON is the filename of the NPDM config file (.json), relative to the project folder. +# If not set, it attempts to use one of the following (in this order): +# - .json +# - config.json +# If a JSON file is provided or autodetected, an ExeFS PFS0 (.nsp) is built instead +# of a homebrew executable (.nro). This is intended to be used for sysmodules. +# NACP building is skipped as well. #--------------------------------------------------------------------------------- -TARGET := horizon-oc-overlay + +APP_TITLE := Tesla Example +APP_VERSION := 1.3.0 + +TARGET := $(notdir $(CURDIR)) BUILD := build -OUTDIR := out -RESOURCES := res -SOURCES := src src/ui/gui src/ui/elements ../common/src ../common/src/client +SOURCES := source DATA := data -INCLUDES := ../common/include -EXEFS_SRC := exefs_src -IS_MINIMAL := 0 +INCLUDES := ../include -APP_TITLE := Horizon OC Zeus -NO_ICON := 1 - - -# This location should reflect where you place the libultrahand directory (lib can vary between projects). -include ${TOPDIR}/lib/libultrahand/ultrahand.mk - - -#--------------------------------------------------------------------------------- -# version control constants -#--------------------------------------------------------------------------------- -#TARGET_VERSION := $(shell git describe --dirty --always --tags) -APP_VERSION := 1.2.0 -TARGET_VERSION := $(APP_VERSION) +NO_ICON := 1 #--------------------------------------------------------------------------------- # options for code generation #--------------------------------------------------------------------------------- -DEFINES := -DDISABLE_IPC -DTARGET="\"$(TARGET)\"" -DTARGET_VERSION="\"$(TARGET_VERSION)\"" -DIS_MINIMAL=$(IS_MINIMAL) - ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE -CFLAGS := -O2 -Wall -flto -fdata-sections -ffunction-sections -fno-rtti -fno-common \ +CFLAGS := -g -Wall -O2 -ffunction-sections \ $(ARCH) $(DEFINES) CFLAGS += $(INCLUDE) -D__SWITCH__ -# Enable appearance overriding -export MSYS2_ARG_CONV_EXCL := -DUI_OVERRIDE_PATH -UI_OVERRIDE_PATH := /config/horizon-oc/ -CFLAGS += -DUI_OVERRIDE_PATH="\"$(UI_OVERRIDE_PATH)\"" - -# Disable fstream -#NO_FSTREAM_DIRECTIVE := 1 -#CFLAGS += -DNO_FSTREAM_DIRECTIVE=$(NO_FSTREAM_DIRECTIVE) - - -CXXFLAGS := $(CFLAGS) -fno-exceptions -std=gnu++20 +CXXFLAGS := $(CFLAGS) -fno-exceptions -std=c++20 ASFLAGS := -g $(ARCH) LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) -LIBS := -lcurl -lz -lzzip -lmbedtls -lmbedx509 -lmbedcrypto -ljansson -lnx +LIBS := -lnx #--------------------------------------------------------------------------------- # list of directories containing libraries, this must be the top level containing @@ -77,6 +72,7 @@ LIBS := -lcurl -lz -lzzip -lmbedtls -lmbedx509 -lmbedcrypto -ljansson -lnx #--------------------------------------------------------------------------------- LIBDIRS := $(PORTLIBS) $(LIBNX) + #--------------------------------------------------------------------------------- # no real need to edit anything past this point unless you need to add additional # rules for different file extensions @@ -84,7 +80,7 @@ LIBDIRS := $(PORTLIBS) $(LIBNX) ifneq ($(BUILD),$(notdir $(CURDIR))) #--------------------------------------------------------------------------------- -export OUTPUT := $(CURDIR)/$(OUTDIR)/$(TARGET) +export OUTPUT := $(CURDIR)/$(TARGET) export TOPDIR := $(CURDIR) export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ @@ -111,8 +107,10 @@ else endif #--------------------------------------------------------------------------------- -export OFILES := $(addsuffix .o,$(BINFILES)) \ - $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) +export OFILES_BIN := $(addsuffix .o,$(BINFILES)) +export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) +export OFILES := $(OFILES_BIN) $(OFILES_SRC) +export HFILES_BIN := $(addsuffix .h,$(subst .,_,$(BINFILES))) export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ @@ -120,48 +118,86 @@ export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) -export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC) +ifeq ($(strip $(CONFIG_JSON)),) + jsons := $(wildcard *.json) + ifneq (,$(findstring $(TARGET).json,$(jsons))) + export APP_JSON := $(TOPDIR)/$(TARGET).json + else + ifneq (,$(findstring config.json,$(jsons))) + export APP_JSON := $(TOPDIR)/config.json + endif + endif +else + export APP_JSON := $(TOPDIR)/$(CONFIG_JSON) +endif + +ifeq ($(strip $(ICON)),) + icons := $(wildcard *.jpg) + ifneq (,$(findstring $(TARGET).jpg,$(icons))) + export APP_ICON := $(TOPDIR)/$(TARGET).jpg + else + ifneq (,$(findstring icon.jpg,$(icons))) + export APP_ICON := $(TOPDIR)/icon.jpg + endif + endif +else + export APP_ICON := $(TOPDIR)/$(ICON) +endif + +ifeq ($(strip $(NO_ICON)),) + export NROFLAGS += --icon=$(APP_ICON) +endif + +ifeq ($(strip $(NO_NACP)),) + export NROFLAGS += --nacp=$(CURDIR)/$(TARGET).nacp +endif + +ifneq ($(APP_TITLEID),) + export NACPFLAGS += --titleid=$(APP_TITLEID) +endif + +ifneq ($(ROMFS),) + export NROFLAGS += --romfsdir=$(CURDIR)/$(ROMFS) +endif .PHONY: $(BUILD) clean all #--------------------------------------------------------------------------------- all: $(BUILD) + $(BUILD): @[ -d $@ ] || mkdir -p $@ - @[ -d $(OUTDIR) ] || mkdir -p $(OUTDIR) @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile #--------------------------------------------------------------------------------- clean: - @echo clean ... - @rm -fr $(BUILD) $(TARGET).ovl $(TARGET).nacp $(TARGET).nso $(TARGET).elf $(OUTDIR) + @rm -fr $(BUILD) $(TARGET).ovl $(TARGET).nro $(TARGET).nacp $(TARGET).elf #--------------------------------------------------------------------------------- else .PHONY: all -DEPENDS := $(OFILES:.o=.d) +DEPENDS := $(OFILES:.o=.d) #--------------------------------------------------------------------------------- # main targets #--------------------------------------------------------------------------------- +all : $(OUTPUT).ovl -all: $(OUTPUT).ovl - -$(OUTPUT).ovl: $(OUTPUT).elf $(OUTPUT).nacp - @elf2nro $< $@ --nacp=$(OUTPUT).nacp +$(OUTPUT).ovl : $(OUTPUT).elf $(OUTPUT).nacp + @elf2nro $< $@ $(NROFLAGS) @echo "built ... $(notdir $(OUTPUT).ovl)" - @printf 'ULTR' >> $@ - @printf "Ultrahand signature has been added.\n" -$(OUTPUT).elf: $(OFILES) +$(OUTPUT).elf : $(OFILES) + +$(OFILES_SRC) : $(HFILES_BIN) #--------------------------------------------------------------------------------- # you need a rule like this for each extension you use as binary data #--------------------------------------------------------------------------------- -%.bin.o : %.bin +%.bin.o %_bin.h : %.bin #--------------------------------------------------------------------------------- @echo $(notdir $<) @$(bin2o) diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp new file mode 100644 index 00000000..bf4c2522 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp @@ -0,0 +1,100 @@ +#define TESLA_INIT_IMPL // If you have more than one file using the tesla header, only define this in the main one +#include // The Tesla Header + + +class GuiSecondary : public tsl::Gui { +public: + GuiSecondary() {} + + virtual tsl::elm::Element* createUI() override { + auto *rootFrame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2 - Secondary Gui"); + + rootFrame->setContent(new tsl::elm::DebugRectangle(tsl::Color{ 0x8, 0x3, 0x8, 0xF })); + + return rootFrame; + } +}; + +class GuiTest : public tsl::Gui { +public: + GuiTest(u8 arg1, u8 arg2, bool arg3) { } + + // Called when this Gui gets loaded to create the UI + // Allocate all elements on the heap. libtesla will make sure to clean them up when not needed anymore + virtual tsl::elm::Element* createUI() override { + // A OverlayFrame is the base element every overlay consists of. This will draw the default Title and Subtitle. + // If you need more information in the header or want to change it's look, use a HeaderOverlayFrame. + auto frame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2"); + + // A list that can contain sub elements and handles scrolling + auto list = new tsl::elm::List(); + + // List Items + list->addItem(new tsl::elm::CategoryHeader("List items")); + + auto *clickableListItem = new tsl::elm::ListItem("Clickable List Item", "..."); + clickableListItem->setClickListener([](u64 keys) { + if (keys & HidNpadButton_A) { + tsl::changeTo(); + return true; + } + + return false; + }); + + list->addItem(clickableListItem); + list->addItem(new tsl::elm::ListItem("Default List Item")); + list->addItem(new tsl::elm::ListItem("Default List Item with an extra long name to trigger truncation and scrolling")); + list->addItem(new tsl::elm::ToggleListItem("Toggle List Item", true)); + + // Custom Drawer, a element that gives direct access to the renderer + list->addItem(new tsl::elm::CategoryHeader("Custom Drawer", true)); + list->addItem(new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) { + renderer->drawCircle(x + 40, y + 40, 20, true, renderer->a(0xF00F)); + renderer->drawCircle(x + 50, y + 50, 20, true, renderer->a(0xF0F0)); + renderer->drawRect(x + 130, y + 30, 60, 40, renderer->a(0xFF00)); + renderer->drawString("Hello :)", false, x + 250, y + 70, 20, renderer->a(0xFF0F)); + renderer->drawRect(x + 40, y + 90, 300, 10, renderer->a(0xF0FF)); + }), 100); + + // Track bars + list->addItem(new tsl::elm::CategoryHeader("Track bars")); + list->addItem(new tsl::elm::TrackBar("\u2600")); + list->addItem(new tsl::elm::StepTrackBar("\uE13C", 20)); + list->addItem(new tsl::elm::NamedStepTrackBar("\uE132", { "Selection 1", "Selection 2", "Selection 3" })); + + // Add the list to the frame for it to be drawn + frame->setContent(list); + + // Return the frame to have it become the top level element of this Gui + return frame; + } + + // Called once every frame to update values + virtual void update() override { + + } + + // Called once every frame to handle inputs not handled by other UI elements + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) override { + return false; // Return true here to signal the inputs have been consumed + } +}; + +class OverlayTest : public tsl::Overlay { +public: + // libtesla already initialized fs, hid, pl, pmdmnt, hid:sys and set:sys + virtual void initServices() override {} // Called at the start to initialize all services necessary for this Overlay + virtual void exitServices() override {} // Called at the end to clean up all services previously initialized + + virtual void onShow() override {} // Called before overlay wants to change from invisible to visible state + virtual void onHide() override {} // Called before overlay wants to change from visible to invisible state + + virtual std::unique_ptr loadInitialGui() override { + return initially(1, 2, true); // Initial Gui to load. It's possible to pass arguments to it's constructor like this + } +}; + +int main(int argc, char **argv) { + return tsl::loop(argc, argv); +} diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h new file mode 100644 index 00000000..04c154f5 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h @@ -0,0 +1,5210 @@ +// stb_truetype.h - v1.26 - public domain +// authored from 2009-2021 by Sean Barrett / RAD Game Tools +// +// ======================================================================= +// +// NO SECURITY GUARANTEE -- DO NOT USE THIS ON UNTRUSTED FONT FILES +// +// This library does no range checking of the offsets found in the file, +// meaning an attacker can use it to read arbitrary memory. +// +// ======================================================================= +// +// This library processes TrueType files: +// parse files +// extract glyph metrics +// extract glyph shapes +// render glyphs to one-channel bitmaps with antialiasing (box filter) +// render glyphs to one-channel SDF bitmaps (signed-distance field/function) +// +// Todo: +// non-MS cmaps +// crashproof on bad data +// hinting? (no longer patented) +// cleartype-style AA? +// optimize: use simple memory allocator for intermediates +// optimize: build edge-list directly from curves +// optimize: rasterize directly from curves? +// +// ADDITIONAL CONTRIBUTORS +// +// Mikko Mononen: compound shape support, more cmap formats +// Tor Andersson: kerning, subpixel rendering +// Dougall Johnson: OpenType / Type 2 font handling +// Daniel Ribeiro Maciel: basic GPOS-based kerning +// +// Misc other: +// Ryan Gordon +// Simon Glass +// github:IntellectualKitty +// Imanol Celaya +// Daniel Ribeiro Maciel +// +// Bug/warning reports/fixes: +// "Zer" on mollyrocket Fabian "ryg" Giesen github:NiLuJe +// Cass Everitt Martins Mozeiko github:aloucks +// stoiko (Haemimont Games) Cap Petschulat github:oyvindjam +// Brian Hook Omar Cornut github:vassvik +// Walter van Niftrik Ryan Griege +// David Gow Peter LaValle +// David Given Sergey Popov +// Ivan-Assen Ivanov Giumo X. Clanjor +// Anthony Pesch Higor Euripedes +// Johan Duparc Thomas Fields +// Hou Qiming Derek Vinyard +// Rob Loach Cort Stratton +// Kenney Phillis Jr. Brian Costabile +// Ken Voskuil (kaesve) Yakov Galka +// +// VERSION HISTORY +// +// 1.26 (2021-08-28) fix broken rasterizer +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) GPOS kerning, STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) user-defined fabs(); rare memory leak; remove duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use allocation userdata properly +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// variant PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// +// Full history can be found at the end of this file. +// +// LICENSE +// +// See end of file for license information. +// +// USAGE +// +// Include this file in whatever places need to refer to it. In ONE C/C++ +// file, write: +// #define STB_TRUETYPE_IMPLEMENTATION +// before the #include of this file. This expands out the actual +// implementation into that C/C++ file. +// +// To make the implementation private to the file that generates the implementation, +// #define STBTT_STATIC +// +// Simple 3D API (don't ship this, but it's fine for tools and quick start) +// stbtt_BakeFontBitmap() -- bake a font to a bitmap for use as texture +// stbtt_GetBakedQuad() -- compute quad to draw for a given char +// +// Improved 3D API (more shippable): +// #include "stb_rect_pack.h" -- optional, but you really want it +// stbtt_PackBegin() +// stbtt_PackSetOversampling() -- for improved quality on small fonts +// stbtt_PackFontRanges() -- pack and renders +// stbtt_PackEnd() +// stbtt_GetPackedQuad() +// +// "Load" a font file from a memory buffer (you have to keep the buffer loaded) +// stbtt_InitFont() +// stbtt_GetFontOffsetForIndex() -- indexing for TTC font collections +// stbtt_GetNumberOfFonts() -- number of fonts for TTC font collections +// +// Render a unicode codepoint to a bitmap +// stbtt_GetCodepointBitmap() -- allocates and returns a bitmap +// stbtt_MakeCodepointBitmap() -- renders into bitmap you provide +// stbtt_GetCodepointBitmapBox() -- how big the bitmap must be +// +// Character advance/positioning +// stbtt_GetCodepointHMetrics() +// stbtt_GetFontVMetrics() +// stbtt_GetFontVMetricsOS2() +// stbtt_GetCodepointKernAdvance() +// +// Starting with version 1.06, the rasterizer was replaced with a new, +// faster and generally-more-precise rasterizer. The new rasterizer more +// accurately measures pixel coverage for anti-aliasing, except in the case +// where multiple shapes overlap, in which case it overestimates the AA pixel +// coverage. Thus, anti-aliasing of intersecting shapes may look wrong. If +// this turns out to be a problem, you can re-enable the old rasterizer with +// #define STBTT_RASTERIZER_VERSION 1 +// which will incur about a 15% speed hit. +// +// ADDITIONAL DOCUMENTATION +// +// Immediately after this block comment are a series of sample programs. +// +// After the sample programs is the "header file" section. This section +// includes documentation for each API function. +// +// Some important concepts to understand to use this library: +// +// Codepoint +// Characters are defined by unicode codepoints, e.g. 65 is +// uppercase A, 231 is lowercase c with a cedilla, 0x7e30 is +// the hiragana for "ma". +// +// Glyph +// A visual character shape (every codepoint is rendered as +// some glyph) +// +// Glyph index +// A font-specific integer ID representing a glyph +// +// Baseline +// Glyph shapes are defined relative to a baseline, which is the +// bottom of uppercase characters. Characters extend both above +// and below the baseline. +// +// Current Point +// As you draw text to the screen, you keep track of a "current point" +// which is the origin of each character. The current point's vertical +// position is the baseline. Even "baked fonts" use this model. +// +// Vertical Font Metrics +// The vertical qualities of the font, used to vertically position +// and space the characters. See docs for stbtt_GetFontVMetrics. +// +// Font Size in Pixels or Points +// The preferred interface for specifying font sizes in stb_truetype +// is to specify how tall the font's vertical extent should be in pixels. +// If that sounds good enough, skip the next paragraph. +// +// Most font APIs instead use "points", which are a common typographic +// measurement for describing font size, defined as 72 points per inch. +// stb_truetype provides a point API for compatibility. However, true +// "per inch" conventions don't make much sense on computer displays +// since different monitors have different number of pixels per +// inch. For example, Windows traditionally uses a convention that +// there are 96 pixels per inch, thus making 'inch' measurements have +// nothing to do with inches, and thus effectively defining a point to +// be 1.333 pixels. Additionally, the TrueType font data provides +// an explicit scale factor to scale a given font's glyphs to points, +// but the author has observed that this scale factor is often wrong +// for non-commercial fonts, thus making fonts scaled in points +// according to the TrueType spec incoherently sized in practice. +// +// DETAILED USAGE: +// +// Scale: +// Select how high you want the font to be, in points or pixels. +// Call ScaleForPixelHeight or ScaleForMappingEmToPixels to compute +// a scale factor SF that will be used by all other functions. +// +// Baseline: +// You need to select a y-coordinate that is the baseline of where +// your text will appear. Call GetFontBoundingBox to get the baseline-relative +// bounding box for all characters. SF*-y0 will be the distance in pixels +// that the worst-case character could extend above the baseline, so if +// you want the top edge of characters to appear at the top of the +// screen where y=0, then you would set the baseline to SF*-y0. +// +// Current point: +// Set the current point where the first character will appear. The +// first character could extend left of the current point; this is font +// dependent. You can either choose a current point that is the leftmost +// point and hope, or add some padding, or check the bounding box or +// left-side-bearing of the first character to be displayed and set +// the current point based on that. +// +// Displaying a character: +// Compute the bounding box of the character. It will contain signed values +// relative to . I.e. if it returns x0,y0,x1,y1, +// then the character should be displayed in the rectangle from +// to = 32 && *text < 128) { + stbtt_aligned_quad q; + stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9 + glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y0); + glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y0); + glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y1); + glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y1); + } + ++text; + } + glEnd(); +} +#endif +// +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program (this compiles): get a single bitmap, print as ASCII art +// +#if 0 +#include +#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation +#include "stb_truetype.h" + +char ttf_buffer[1<<25]; + +int main(int argc, char **argv) +{ + stbtt_fontinfo font; + unsigned char *bitmap; + int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20); + + fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb")); + + stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0)); + bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0); + + for (j=0; j < h; ++j) { + for (i=0; i < w; ++i) + putchar(" .:ioVM@"[bitmap[j*w+i]>>5]); + putchar('\n'); + } + return 0; +} +#endif +// +// Output: +// +// .ii. +// @@@@@@. +// V@Mio@@o +// :i. V@V +// :oM@@M +// :@@@MM@M +// @@o o@M +// :@@. M@M +// @@@o@@@@ +// :M@@V:@@. +// +////////////////////////////////////////////////////////////////////////////// +// +// Complete program: print "Hello World!" banner, with bugs +// +#if 0 +char buffer[24<<20]; +unsigned char screen[20][79]; + +int main(int arg, char **argv) +{ + stbtt_fontinfo font; + int i,j,ascent,baseline,ch=0; + float scale, xpos=2; // leave a little padding in case the character extends left + char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness + + fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb")); + stbtt_InitFont(&font, buffer, 0); + + scale = stbtt_ScaleForPixelHeight(&font, 15); + stbtt_GetFontVMetrics(&font, &ascent,0,0); + baseline = (int) (ascent*scale); + + while (text[ch]) { + int advance,lsb,x0,y0,x1,y1; + float x_shift = xpos - (float) floor(xpos); + stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb); + stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1); + stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]); + // note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong + // because this API is really for baking character bitmaps into textures. if you want to render + // a sequence of characters, you really need to render each bitmap to a temp buffer, then + // "alpha blend" that into the working buffer + xpos += (advance * scale); + if (text[ch+1]) + xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]); + ++ch; + } + + for (j=0; j < 20; ++j) { + for (i=0; i < 78; ++i) + putchar(" .:ioVM@"[screen[j][i]>>5]); + putchar('\n'); + } + + return 0; +} +#endif + + +////////////////////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////////////////// +//// +//// INTEGRATION WITH YOUR CODEBASE +//// +//// The following sections allow you to supply alternate definitions +//// of C library functions used by stb_truetype, e.g. if you don't +//// link with the C runtime library. + +#ifdef STB_TRUETYPE_IMPLEMENTATION + // #define your own (u)stbtt_int8/16/32 before including to override this + #ifndef stbtt_uint8 + typedef unsigned char stbtt_uint8; + typedef signed char stbtt_int8; + typedef unsigned short stbtt_uint16; + typedef signed short stbtt_int16; + typedef unsigned int stbtt_uint32; + typedef signed int stbtt_int32; + #endif + + typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1]; + typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1]; + + // e.g. #define your own STBTT_ifloor/STBTT_iceil() to avoid math.h + #ifndef STBTT_ifloor + #include + #define STBTT_ifloor(x) ((int) floor(x)) + #define STBTT_iceil(x) ((int) ceil(x)) + #endif + + #ifndef STBTT_sqrt + #include + #define STBTT_sqrt(x) sqrt(x) + #define STBTT_pow(x,y) pow(x,y) + #endif + + #ifndef STBTT_fmod + #include + #define STBTT_fmod(x,y) fmod(x,y) + #endif + + #ifndef STBTT_cos + #include + #define STBTT_cos(x) cos(x) + #define STBTT_acos(x) acos(x) + #endif + + #ifndef STBTT_fabs + #include + #define STBTT_fabs(x) fabs(x) + #endif + + // #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h + #ifndef STBTT_malloc + #include + #define STBTT_malloc(x,u) ((void)(u),malloc(x)) + #define STBTT_free(x,u) ((void)(u),free(x)) + #endif + + //ifndef STBTT_assert + //include + //define STBTT_assert(x) assert(x) + //endif + + #ifndef STBTT_strlen + #include + #define STBTT_strlen(x) strlen(x) + #endif + + #ifndef STBTT_memcpy + #include + #define STBTT_memcpy memcpy + #define STBTT_memset memset + #endif +#endif + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// INTERFACE +//// +//// + +#ifndef __STB_INCLUDE_STB_TRUETYPE_H__ +#define __STB_INCLUDE_STB_TRUETYPE_H__ + +#ifdef STBTT_STATIC +#define STBTT_DEF static +#else +#define STBTT_DEF extern +#endif + +#ifdef __cplusplus +extern "C" { +#endif + +// private structure +typedef struct +{ + unsigned char *data; + int cursor; + int size; +} stbtt__buf; + +////////////////////////////////////////////////////////////////////////////// +// +// TEXTURE BAKING API +// +// If you use this API, you only have to call two functions ever. +// + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; +} stbtt_bakedchar; + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata); // you allocate this, it's num_chars long +// if return is positive, the first unused row of the bitmap +// if return is negative, returns the negative of the number of characters that fit +// if return is 0, no characters fit and no rows were used +// This uses a very crappy packing. + +typedef struct +{ + float x0,y0,s0,t0; // top-left + float x1,y1,s1,t1; // bottom-right +} stbtt_aligned_quad; + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier +// Call GetBakedQuad with char_index = 'character - first_char', and it +// creates the quad you need to draw and advances the current position. +// +// The coordinate system used assumes y increases downwards. +// +// Characters will extend both above and below the current position; +// see discussion of "BASELINE" above. +// +// It's inefficient; you might want to c&p it and optimize it. + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap); +// Query the font vertical metrics without having to create a font first. + + +////////////////////////////////////////////////////////////////////////////// +// +// NEW TEXTURE BAKING API +// +// This provides options for packing multiple fonts into one atlas, not +// perfectly but better than nothing. + +typedef struct +{ + unsigned short x0,y0,x1,y1; // coordinates of bbox in bitmap + float xoff,yoff,xadvance; + float xoff2,yoff2; +} stbtt_packedchar; + +typedef struct stbtt_pack_context stbtt_pack_context; +typedef struct stbtt_fontinfo stbtt_fontinfo; +#ifndef STB_RECT_PACK_VERSION +typedef struct stbrp_rect stbrp_rect; +#endif + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context); +// Initializes a packing context stored in the passed-in stbtt_pack_context. +// Future calls using this context will pack characters into the bitmap passed +// in here: a 1-channel bitmap that is width * height. stride_in_bytes is +// the distance from one row to the next (or 0 to mean they are packed tightly +// together). "padding" is the amount of padding to leave between each +// character (normally you want '1' for bitmaps you'll use as textures with +// bilinear filtering). +// +// Returns 0 on failure, 1 on success. + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc); +// Cleans up the packing context and frees all memory. + +#define STBTT_POINT_SIZE(x) (-(x)) + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range); +// Creates character bitmaps from the font_index'th font found in fontdata (use +// font_index=0 if you don't know what that is). It creates num_chars_in_range +// bitmaps for characters with unicode values starting at first_unicode_char_in_range +// and increasing. Data for how to render them is stored in chardata_for_range; +// pass these to stbtt_GetPackedQuad to get back renderable quads. +// +// font_size is the full height of the character from ascender to descender, +// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed +// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE() +// and pass that result as 'font_size': +// ..., 20 , ... // font max minus min y is 20 pixels tall +// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall + +typedef struct +{ + float font_size; + int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint + int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints + int num_chars; + stbtt_packedchar *chardata_for_range; // output + unsigned char h_oversample, v_oversample; // don't set these, they're used internally +} stbtt_pack_range; + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges); +// Creates character bitmaps from multiple ranges of characters stored in +// ranges. This will usually create a better-packed bitmap than multiple +// calls to stbtt_PackFontRange. Note that you can call this multiple +// times within a single PackBegin/PackEnd. + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample); +// Oversampling a font increases the quality by allowing higher-quality subpixel +// positioning, and is especially valuable at smaller text sizes. +// +// This function sets the amount of oversampling for all following calls to +// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given +// pack context. The default (no oversampling) is achieved by h_oversample=1 +// and v_oversample=1. The total number of pixels required is +// h_oversample*v_oversample larger than the default; for example, 2x2 +// oversampling requires 4x the storage of 1x1. For best results, render +// oversampled textures with bilinear filtering. Look at the readme in +// stb/tests/oversample for information about oversampled fonts +// +// To use with PackFontRangesGather etc., you must set it before calls +// call to PackFontRangesGatherRects. + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip); +// If skip != 0, this tells stb_truetype to skip any codepoints for which +// there is no corresponding glyph. If skip=0, which is the default, then +// codepoints without a glyph recived the font's "missing character" glyph, +// typically an empty box by convention. + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, // same data as above + int char_index, // character to display + float *xpos, float *ypos, // pointers to current position in screen pixel space + stbtt_aligned_quad *q, // output: quad to draw + int align_to_integer); + +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects); +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects); +// Calling these functions in sequence is roughly equivalent to calling +// stbtt_PackFontRanges(). If you more control over the packing of multiple +// fonts, or if you want to pack custom data into a font texture, take a look +// at the source to of stbtt_PackFontRanges() and create a custom version +// using these functions, e.g. call GatherRects multiple times, +// building up a single array of rects, then call PackRects once, +// then call RenderIntoRects repeatedly. This may result in a +// better packing than calling PackFontRanges multiple times +// (or it may not). + +// this is an opaque structure that you shouldn't mess with which holds +// all the context needed from PackBegin to PackEnd. +struct stbtt_pack_context { + void *user_allocator_context; + void *pack_info; + int width; + int height; + int stride_in_bytes; + int padding; + int skip_missing; + unsigned int h_oversample, v_oversample; + unsigned char *pixels; + void *nodes; +}; + +////////////////////////////////////////////////////////////////////////////// +// +// FONT LOADING +// +// + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data); +// This function will determine the number of fonts in a font file. TrueType +// collection (.ttc) files may contain multiple fonts, while TrueType font +// (.ttf) files only contain one font. The number of fonts can be used for +// indexing with the previous function where the index is between zero and one +// less than the total fonts. If an error occurs, -1 is returned. + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index); +// Each .ttf/.ttc file may have more than one font. Each font has a sequential +// index number starting from 0. Call this function to get the font offset for +// a given index; it returns -1 if the index is out of range. A regular .ttf +// file will only define one font and it always be at offset 0, so it will +// return '0' for index 0, and -1 for all other indices. + +// The following structure is defined publicly so you can declare one on +// the stack or as a global or etc, but you should treat it as opaque. +struct stbtt_fontinfo +{ + void * userdata; + unsigned char * data; // pointer to .ttf file + int fontstart; // offset of start of font + + int numGlyphs; // number of glyphs, needed for range checking + + int loca,head,glyf,hhea,hmtx,kern,gpos,svg; // table locations as offset from start of .ttf + int index_map; // a cmap mapping for our chosen character encoding + int indexToLocFormat; // format needed to map from glyph index to glyph + + stbtt__buf cff; // cff font data + stbtt__buf charstrings; // the charstring index + stbtt__buf gsubrs; // global charstring subroutines index + stbtt__buf subrs; // private charstring subroutines index + stbtt__buf fontdicts; // array of font dicts + stbtt__buf fdselect; // map from glyph to fontdict +}; + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset); +// Given an offset into the file that defines a font, this function builds +// the necessary cached info for the rest of the system. You must allocate +// the stbtt_fontinfo yourself, and stbtt_InitFont will fill it out. You don't +// need to do anything special to free it, because the contents are pure +// value data with no additional data structures. Returns 0 on failure. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER TO GLYPH-INDEX CONVERSIOn + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint); +// If you're going to perform multiple operations on the same character +// and you want a speed-up, call this function with the character you're +// going to process, then use glyph-based functions instead of the +// codepoint-based functions. +// Returns 0 if the character codepoint is not defined in the font. + + +////////////////////////////////////////////////////////////////////////////// +// +// CHARACTER PROPERTIES +// + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose "height" is 'pixels' tall. +// Height is measured as the distance from the highest ascender to the lowest +// descender; in other words, it's equivalent to calling stbtt_GetFontVMetrics +// and computing: +// scale = pixels / (ascent - descent) +// so if you prefer to measure height by the ascent only, use a similar calculation. + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels); +// computes a scale factor to produce a font whose EM size is mapped to +// 'pixels' tall. This is probably what traditional APIs compute, but +// I'm not positive. + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap); +// ascent is the coordinate above the baseline the font extends; descent +// is the coordinate below the baseline the font extends (i.e. it is typically negative) +// lineGap is the spacing between one row's descent and the next row's ascent... +// so you should advance the vertical position by "*ascent - *descent + *lineGap" +// these are expressed in unscaled coordinates, so you must multiply by +// the scale factor for a given size + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap); +// analogous to GetFontVMetrics, but returns the "typographic" values from the OS/2 +// table (specific to MS/Windows TTF files). +// +// Returns 1 on success (table present), 0 on failure. + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1); +// the bounding box around all possible characters + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing); +// leftSideBearing is the offset from the current horizontal position to the left edge of the character +// advanceWidth is the offset from the current horizontal position to the next horizontal position +// these are expressed in unscaled coordinates + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2); +// an additional amount to add to the 'advance' value between ch1 and ch2 + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1); +// Gets the bounding box of the visible part of the glyph, in unscaled coordinates + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing); +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2); +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); +// as above, but takes one or more glyph indices for greater efficiency + +typedef struct stbtt_kerningentry +{ + int glyph1; // use stbtt_FindGlyphIndex + int glyph2; + int advance; +} stbtt_kerningentry; + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info); +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length); +// Retrieves a complete list of all of the kerning pairs provided by the font +// stbtt_GetKerningTable never writes more than table_length entries and returns how many entries it did write. +// The table will be sorted by (a.glyph1 == b.glyph1)?(a.glyph2 < b.glyph2):(a.glyph1 < b.glyph1) + +////////////////////////////////////////////////////////////////////////////// +// +// GLYPH SHAPES (you probably don't need these, but they have to go before +// the bitmaps for C declaration-order reasons) +// + +#ifndef STBTT_vmove // you can predefine these to use different values (but why?) + enum { + STBTT_vmove=1, + STBTT_vline, + STBTT_vcurve, + STBTT_vcubic + }; +#endif + +#ifndef stbtt_vertex // you can predefine this to use different values + // (we share this with other code at RAD) + #define stbtt_vertex_type short // can't use stbtt_int16 because that's not visible in the header file + typedef struct + { + stbtt_vertex_type x,y,cx,cy,cx1,cy1; + unsigned char type,padding; + } stbtt_vertex; +#endif + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index); +// returns non-zero if nothing is drawn for this glyph + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices); +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **vertices); +// returns # of vertices and fills *vertices with the pointer to them +// these are expressed in "unscaled" coordinates +// +// The shape is a series of contours. Each one starts with +// a STBTT_moveto, then consists of a series of mixed +// STBTT_lineto and STBTT_curveto segments. A lineto +// draws a line from previous endpoint to its x,y; a curveto +// draws a quadratic bezier from previous endpoint to +// its x,y, using cx,cy as the bezier control point. + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *vertices); +// frees the data allocated above + +STBTT_DEF unsigned char *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl); +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg); +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg); +// fills svg with the character's SVG data. +// returns data size or 0 if SVG not found. + +////////////////////////////////////////////////////////////////////////////// +// +// BITMAP RENDERING +// + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata); +// frees the bitmap allocated below + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// allocates a large-enough single-channel 8bpp bitmap and renders the +// specified character/glyph at the specified scale into it, with +// antialiasing. 0 is no coverage (transparent), 255 is fully covered (opaque). +// *width & *height are filled out with the width & height of the bitmap, +// which is stored left-to-right, top-to-bottom. +// +// xoff/yoff are the offset it pixel space from the glyph origin to the top-left of the bitmap + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff); +// the same as stbtt_GetCodepoitnBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint); +// the same as stbtt_GetCodepointBitmap, but you pass in storage for the bitmap +// in the form of 'output', with row spacing of 'out_stride' bytes. the bitmap +// is clipped to out_w/out_h bytes. Call stbtt_GetCodepointBitmapBox to get the +// width and height and positioning info for it first. + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint); +// same as stbtt_MakeCodepointBitmap, but you can specify a subpixel +// shift for the character + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint); +// same as stbtt_MakeCodepointBitmapSubpixel, but prefiltering +// is performed (see stbtt_PackSetOversampling) + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +// get the bbox of the bitmap centered around the glyph origin; so the +// bitmap width is ix1-ix0, height is iy1-iy0, and location to place +// the bitmap top left is (leftSideBearing*scale,iy0). +// (Note that the bitmap uses y-increases-down, but the shape uses +// y-increases-up, so CodepointBitmapBox and CodepointBox are inverted.) + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); +// same as stbtt_GetCodepointBitmapBox, but you can specify a subpixel +// shift for the character + +// the following functions are equivalent to the above functions, but operate +// on glyph indices instead of Unicode codepoints (for efficiency) +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph); +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int glyph); +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1); +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1); + + +// @TODO: don't expose this structure +typedef struct +{ + int w,h,stride; + unsigned char *pixels; +} stbtt__bitmap; + +// rasterize a shape with quadratic beziers into a bitmap +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, // 1-channel bitmap to draw into + float flatness_in_pixels, // allowable error of curve in pixels + stbtt_vertex *vertices, // array of vertices defining shape + int num_verts, // number of vertices in above array + float scale_x, float scale_y, // scale applied to input vertices + float shift_x, float shift_y, // translation applied to input vertices + int x_off, int y_off, // another translation applied to input + int invert, // if non-zero, vertically flip shape + void *userdata); // context for to STBTT_MALLOC + +////////////////////////////////////////////////////////////////////////////// +// +// Signed Distance Function (or Field) rendering + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata); +// frees the SDF bitmap allocated below + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff); +// These functions compute a discretized SDF field for a single character, suitable for storing +// in a single-channel texture, sampling with bilinear filtering, and testing against +// larger than some threshold to produce scalable fonts. +// info -- the font +// scale -- controls the size of the resulting SDF bitmap, same as it would be creating a regular bitmap +// glyph/codepoint -- the character to generate the SDF for +// padding -- extra "pixels" around the character which are filled with the distance to the character (not 0), +// which allows effects like bit outlines +// onedge_value -- value 0-255 to test the SDF against to reconstruct the character (i.e. the isocontour of the character) +// pixel_dist_scale -- what value the SDF should increase by when moving one SDF "pixel" away from the edge (on the 0..255 scale) +// if positive, > onedge_value is inside; if negative, < onedge_value is inside +// width,height -- output height & width of the SDF bitmap (including padding) +// xoff,yoff -- output origin of the character +// return value -- a 2D array of bytes 0..255, width*height in size +// +// pixel_dist_scale & onedge_value are a scale & bias that allows you to make +// optimal use of the limited 0..255 for your application, trading off precision +// and special effects. SDF values outside the range 0..255 are clamped to 0..255. +// +// Example: +// scale = stbtt_ScaleForPixelHeight(22) +// padding = 5 +// onedge_value = 180 +// pixel_dist_scale = 180/5.0 = 36.0 +// +// This will create an SDF bitmap in which the character is about 22 pixels +// high but the whole bitmap is about 22+5+5=32 pixels high. To produce a filled +// shape, sample the SDF at each pixel and fill the pixel if the SDF value +// is greater than or equal to 180/255. (You'll actually want to antialias, +// which is beyond the scope of this example.) Additionally, you can compute +// offset outlines (e.g. to stroke the character border inside & outside, +// or only outside). For example, to fill outside the character up to 3 SDF +// pixels, you would compare against (180-36.0*3)/255 = 72/255. The above +// choice of variables maps a range from 5 pixels outside the shape to +// 2 pixels inside the shape to 0..255; this is intended primarily for apply +// outside effects only (the interior range is needed to allow proper +// antialiasing of the font at *smaller* sizes) +// +// The function computes the SDF analytically at each SDF pixel, not by e.g. +// building a higher-res bitmap and approximating it. In theory the quality +// should be as high as possible for an SDF of this size & representation, but +// unclear if this is true in practice (perhaps building a higher-res bitmap +// and computing from that can allow drop-out prevention). +// +// The algorithm has not been optimized at all, so expect it to be slow +// if computing lots of characters or very large sizes. + + + +////////////////////////////////////////////////////////////////////////////// +// +// Finding the right font... +// +// You should really just solve this offline, keep your own tables +// of what font is what, and don't try to get it out of the .ttf file. +// That's because getting it out of the .ttf file is really hard, because +// the names in the file can appear in many possible encodings, in many +// possible languages, and e.g. if you need a case-insensitive comparison, +// the details of that depend on the encoding & language in a complex way +// (actually underspecified in truetype, but also gigantic). +// +// But you can use the provided functions in two possible ways: +// stbtt_FindMatchingFont() will use *case-sensitive* comparisons on +// unicode-encoded names to try to find the font you want; +// you can run this before calling stbtt_InitFont() +// +// stbtt_GetFontNameString() lets you get any of the various strings +// from the file yourself and do your own comparisons on them. +// You have to have called stbtt_InitFont() first. + + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags); +// returns the offset (not index) of the font that matches, or -1 if none +// if you use STBTT_MACSTYLE_DONTCARE, use a font name like "Arial Bold". +// if you use any other flag, use a font name like "Arial"; this checks +// the 'macStyle' header field; i don't know if fonts set this consistently +#define STBTT_MACSTYLE_DONTCARE 0 +#define STBTT_MACSTYLE_BOLD 1 +#define STBTT_MACSTYLE_ITALIC 2 +#define STBTT_MACSTYLE_UNDERSCORE 4 +#define STBTT_MACSTYLE_NONE 8 // <= not same as 0, this makes us check the bitfield is 0 + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2); +// returns 1/0 whether the first string interpreted as utf8 is identical to +// the second string interpreted as big-endian utf16... useful for strings from next func + +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID); +// returns the string (which may be big-endian double byte, e.g. for unicode) +// and puts the length in bytes in *length. +// +// some of the values for the IDs are below; for more see the truetype spec: +// http://developer.apple.com/textfonts/TTRefMan/RM06/Chap6name.html +// http://www.microsoft.com/typography/otspec/name.htm + +enum { // platformID + STBTT_PLATFORM_ID_UNICODE =0, + STBTT_PLATFORM_ID_MAC =1, + STBTT_PLATFORM_ID_ISO =2, + STBTT_PLATFORM_ID_MICROSOFT =3 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_UNICODE + STBTT_UNICODE_EID_UNICODE_1_0 =0, + STBTT_UNICODE_EID_UNICODE_1_1 =1, + STBTT_UNICODE_EID_ISO_10646 =2, + STBTT_UNICODE_EID_UNICODE_2_0_BMP=3, + STBTT_UNICODE_EID_UNICODE_2_0_FULL=4 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MICROSOFT + STBTT_MS_EID_SYMBOL =0, + STBTT_MS_EID_UNICODE_BMP =1, + STBTT_MS_EID_SHIFTJIS =2, + STBTT_MS_EID_UNICODE_FULL =10 +}; + +enum { // encodingID for STBTT_PLATFORM_ID_MAC; same as Script Manager codes + STBTT_MAC_EID_ROMAN =0, STBTT_MAC_EID_ARABIC =4, + STBTT_MAC_EID_JAPANESE =1, STBTT_MAC_EID_HEBREW =5, + STBTT_MAC_EID_CHINESE_TRAD =2, STBTT_MAC_EID_GREEK =6, + STBTT_MAC_EID_KOREAN =3, STBTT_MAC_EID_RUSSIAN =7 +}; + +enum { // languageID for STBTT_PLATFORM_ID_MICROSOFT; same as LCID... + // problematic because there are e.g. 16 english LCIDs and 16 arabic LCIDs + STBTT_MS_LANG_ENGLISH =0x0409, STBTT_MS_LANG_ITALIAN =0x0410, + STBTT_MS_LANG_CHINESE =0x0804, STBTT_MS_LANG_JAPANESE =0x0411, + STBTT_MS_LANG_DUTCH =0x0413, STBTT_MS_LANG_KOREAN =0x0412, + STBTT_MS_LANG_FRENCH =0x040c, STBTT_MS_LANG_RUSSIAN =0x0419, + STBTT_MS_LANG_GERMAN =0x0407, STBTT_MS_LANG_SPANISH =0x0409, + STBTT_MS_LANG_HEBREW =0x040d, STBTT_MS_LANG_SWEDISH =0x041D +}; + +enum { // languageID for STBTT_PLATFORM_ID_MAC + STBTT_MAC_LANG_ENGLISH =0 , STBTT_MAC_LANG_JAPANESE =11, + STBTT_MAC_LANG_ARABIC =12, STBTT_MAC_LANG_KOREAN =23, + STBTT_MAC_LANG_DUTCH =4 , STBTT_MAC_LANG_RUSSIAN =32, + STBTT_MAC_LANG_FRENCH =1 , STBTT_MAC_LANG_SPANISH =6 , + STBTT_MAC_LANG_GERMAN =2 , STBTT_MAC_LANG_SWEDISH =5 , + STBTT_MAC_LANG_HEBREW =10, STBTT_MAC_LANG_CHINESE_SIMPLIFIED =33, + STBTT_MAC_LANG_ITALIAN =3 , STBTT_MAC_LANG_CHINESE_TRAD =19 +}; + +#ifdef __cplusplus +} +#endif + +#endif // __STB_INCLUDE_STB_TRUETYPE_H__ + +/////////////////////////////////////////////////////////////////////////////// +/////////////////////////////////////////////////////////////////////////////// +//// +//// IMPLEMENTATION +//// +//// + +#ifdef STB_TRUETYPE_IMPLEMENTATION + +#ifndef STBTT_MAX_OVERSAMPLE +#define STBTT_MAX_OVERSAMPLE 8 +#endif + +#if STBTT_MAX_OVERSAMPLE > 255 +#error "STBTT_MAX_OVERSAMPLE cannot be > 255" +#endif + +typedef int stbtt__test_oversample_pow2[(STBTT_MAX_OVERSAMPLE & (STBTT_MAX_OVERSAMPLE-1)) == 0 ? 1 : -1]; + +#ifndef STBTT_RASTERIZER_VERSION +#define STBTT_RASTERIZER_VERSION 2 +#endif + +#ifdef _MSC_VER +#define STBTT__NOTUSED(v) (void)(v) +#else +#define STBTT__NOTUSED(v) (void)sizeof(v) +#endif + +////////////////////////////////////////////////////////////////////////// +// +// stbtt__buf helpers to parse data from file +// + +static stbtt_uint8 stbtt__buf_get8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor++]; +} + +static stbtt_uint8 stbtt__buf_peek8(stbtt__buf *b) +{ + if (b->cursor >= b->size) + return 0; + return b->data[b->cursor]; +} + +static void stbtt__buf_seek(stbtt__buf *b, int o) +{ + //STBTT_assert(!(o > b->size || o < 0)); + b->cursor = (o > b->size || o < 0) ? b->size : o; +} + +static void stbtt__buf_skip(stbtt__buf *b, int o) +{ + stbtt__buf_seek(b, b->cursor + o); +} + +static stbtt_uint32 stbtt__buf_get(stbtt__buf *b, int n) +{ + stbtt_uint32 v = 0; + int i; + //STBTT_assert(n >= 1 && n <= 4); + for (i = 0; i < n; i++) + v = (v << 8) | stbtt__buf_get8(b); + return v; +} + +static stbtt__buf stbtt__new_buf(const void *p, size_t size) +{ + stbtt__buf r; + //STBTT_assert(size < 0x40000000); + r.data = (stbtt_uint8*) p; + r.size = (int) size; + r.cursor = 0; + return r; +} + +#define stbtt__buf_get16(b) stbtt__buf_get((b), 2) +#define stbtt__buf_get32(b) stbtt__buf_get((b), 4) + +static stbtt__buf stbtt__buf_range(const stbtt__buf *b, int o, int s) +{ + stbtt__buf r = stbtt__new_buf(NULL, 0); + if (o < 0 || s < 0 || o > b->size || s > b->size - o) return r; + r.data = b->data + o; + r.size = s; + return r; +} + +static stbtt__buf stbtt__cff_get_index(stbtt__buf *b) +{ + int count, start, offsize; + start = b->cursor; + count = stbtt__buf_get16(b); + if (count) { + offsize = stbtt__buf_get8(b); + //STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(b, offsize * count); + stbtt__buf_skip(b, stbtt__buf_get(b, offsize) - 1); + } + return stbtt__buf_range(b, start, b->cursor - start); +} + +static stbtt_uint32 stbtt__cff_int(stbtt__buf *b) +{ + int b0 = stbtt__buf_get8(b); + if (b0 >= 32 && b0 <= 246) return b0 - 139; + else if (b0 >= 247 && b0 <= 250) return (b0 - 247)*256 + stbtt__buf_get8(b) + 108; + else if (b0 >= 251 && b0 <= 254) return -(b0 - 251)*256 - stbtt__buf_get8(b) - 108; + else if (b0 == 28) return stbtt__buf_get16(b); + else if (b0 == 29) return stbtt__buf_get32(b); + //STBTT_assert(0); + return 0; +} + +static void stbtt__cff_skip_operand(stbtt__buf *b) { + if (stbtt__buf_peek8(b) == 30) { + ++b->cursor; // Direct increment instead of skip + int v; + do { + v = stbtt__buf_get8(b); + } while ((v & 0xF) != 0xF && (v >> 4) != 0xF && b->cursor < b->size); + } else { + stbtt__cff_int(b); + } +} + +static stbtt__buf stbtt__dict_get(stbtt__buf *b, int key) { + // Variables moved outside the loop for better performance + int start; + int end; + int op; + + b->cursor = 0; // Direct assignment instead of seek + + while (b->cursor < b->size) { + start = b->cursor; + + while (stbtt__buf_peek8(b) >= 28) + stbtt__cff_skip_operand(b); + + end = b->cursor; // Capture end BEFORE reading operator + op = stbtt__buf_get8(b); + if (op == 12) op = stbtt__buf_get8(b) | 0x100; + if (op == key) return stbtt__buf_range(b, start, end - start); + } + + // Return empty range + stbtt__buf empty = {b->data, 0, 0}; + return empty; +} + +static void stbtt__dict_get_ints(stbtt__buf *b, int key, int outcount, stbtt_uint32 *out) { + stbtt__buf operands = stbtt__dict_get(b, key); + + // Unroll small common cases + switch (outcount) { + case 1: + if (operands.cursor < operands.size) out[0] = stbtt__cff_int(&operands); + break; + case 2: + if (operands.cursor < operands.size) out[0] = stbtt__cff_int(&operands); + if (operands.cursor < operands.size) out[1] = stbtt__cff_int(&operands); + break; + default: + for (int i = 0; i < outcount && operands.cursor < operands.size; i++) + out[i] = stbtt__cff_int(&operands); + } +} + +static int stbtt__cff_index_count(stbtt__buf *b) +{ + stbtt__buf_seek(b, 0); + return stbtt__buf_get16(b); +} + +static stbtt__buf stbtt__cff_index_get(stbtt__buf b, int i) +{ + int count, offsize, start, end; + stbtt__buf_seek(&b, 0); + count = stbtt__buf_get16(&b); + offsize = stbtt__buf_get8(&b); + //STBTT_assert(i >= 0 && i < count); + //STBTT_assert(offsize >= 1 && offsize <= 4); + stbtt__buf_skip(&b, i*offsize); + start = stbtt__buf_get(&b, offsize); + end = stbtt__buf_get(&b, offsize); + return stbtt__buf_range(&b, 2+(count+1)*offsize+start, end - start); +} + +////////////////////////////////////////////////////////////////////////// +// +// accessors to parse data from file +// + +// on platforms that don't allow misaligned reads, if we want to allow +// truetype fonts that aren't padded to alignment, define ALLOW_UNALIGNED_TRUETYPE + +#define ttBYTE(p) (* (stbtt_uint8 *) (p)) +#define ttCHAR(p) (* (stbtt_int8 *) (p)) +#define ttFixed(p) ttLONG(p) + +static stbtt_uint16 ttUSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_int16 ttSHORT(stbtt_uint8 *p) { return p[0]*256 + p[1]; } +static stbtt_uint32 ttULONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } +static stbtt_int32 ttLONG(stbtt_uint8 *p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } + +#define stbtt_tag4(p,c0,c1,c2,c3) ((p)[0] == (c0) && (p)[1] == (c1) && (p)[2] == (c2) && (p)[3] == (c3)) +#define stbtt_tag(p,str) stbtt_tag4(p,str[0],str[1],str[2],str[3]) + +static int stbtt__isfont(stbtt_uint8 *font) +{ + // check the version number + if (stbtt_tag4(font, '1',0,0,0)) return 1; // TrueType 1 + if (stbtt_tag(font, "typ1")) return 1; // TrueType with type 1 font -- we don't support this! + if (stbtt_tag(font, "OTTO")) return 1; // OpenType with CFF + if (stbtt_tag4(font, 0,1,0,0)) return 1; // OpenType 1.0 + if (stbtt_tag(font, "true")) return 1; // Apple specification for TrueType fonts + return 0; +} + +// @OPTIMIZE: binary search +static stbtt_uint32 stbtt__find_table(stbtt_uint8 *data, stbtt_uint32 fontstart, const char *tag) +{ + stbtt_int32 num_tables = ttUSHORT(data+fontstart+4); + stbtt_uint32 tabledir = fontstart + 12; + stbtt_int32 i; + stbtt_uint32 loc; + for (i=0; i < num_tables; ++i) { + loc = tabledir + 16*i; + if (stbtt_tag(data+loc+0, tag)) + return ttULONG(data+loc+8); + } + return 0; +} + +static int stbtt_GetFontOffsetForIndex_internal(unsigned char *font_collection, int index) +{ + // if it's just a font, there's only one valid index + if (stbtt__isfont(font_collection)) + return index == 0 ? 0 : -1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + stbtt_int32 n = ttLONG(font_collection+8); + if (index >= n) + return -1; + return ttULONG(font_collection+12+index*4); + } + } + return -1; +} + +static int stbtt_GetNumberOfFonts_internal(unsigned char *font_collection) +{ + // if it's just a font, there's only one valid font + if (stbtt__isfont(font_collection)) + return 1; + + // check if it's a TTC + if (stbtt_tag(font_collection, "ttcf")) { + // version 1? + if (ttULONG(font_collection+4) == 0x00010000 || ttULONG(font_collection+4) == 0x00020000) { + return ttLONG(font_collection+8); + } + } + return 0; +} + +static stbtt__buf stbtt__get_subrs(stbtt__buf cff, stbtt__buf fontdict) +{ + stbtt_uint32 subrsoff = 0, private_loc[2] = { 0, 0 }; + stbtt__buf pdict; + stbtt__dict_get_ints(&fontdict, 18, 2, private_loc); + if (!private_loc[1] || !private_loc[0]) return stbtt__new_buf(NULL, 0); + pdict = stbtt__buf_range(&cff, private_loc[1], private_loc[0]); + stbtt__dict_get_ints(&pdict, 19, 1, &subrsoff); + if (!subrsoff) return stbtt__new_buf(NULL, 0); + stbtt__buf_seek(&cff, private_loc[1]+subrsoff); + return stbtt__cff_get_index(&cff); +} + +// since most people won't use this, find this table the first time it's needed +static int stbtt__get_svg(stbtt_fontinfo *info) +{ + stbtt_uint32 t; + if (info->svg < 0) { + t = stbtt__find_table(info->data, info->fontstart, "SVG "); + if (t) { + stbtt_uint32 offset = ttULONG(info->data + t + 2); + info->svg = t + offset; + } else { + info->svg = 0; + } + } + return info->svg; +} + +static int stbtt_InitFont_internal(stbtt_fontinfo *info, unsigned char *data, int fontstart) +{ + stbtt_uint32 cmap, t; + stbtt_int32 i,numTables; + + info->data = data; + info->fontstart = fontstart; + info->cff = stbtt__new_buf(NULL, 0); + + cmap = stbtt__find_table(data, fontstart, "cmap"); // required + info->loca = stbtt__find_table(data, fontstart, "loca"); // required + info->head = stbtt__find_table(data, fontstart, "head"); // required + info->glyf = stbtt__find_table(data, fontstart, "glyf"); // required + info->hhea = stbtt__find_table(data, fontstart, "hhea"); // required + info->hmtx = stbtt__find_table(data, fontstart, "hmtx"); // required + info->kern = stbtt__find_table(data, fontstart, "kern"); // not required + info->gpos = stbtt__find_table(data, fontstart, "GPOS"); // not required + + if (!cmap || !info->head || !info->hhea || !info->hmtx) + return 0; + if (info->glyf) { + // required for truetype + if (!info->loca) return 0; + } else { + // initialization for CFF / Type2 fonts (OTF) + stbtt__buf b, topdict, topdictidx; + stbtt_uint32 cstype = 2, charstrings = 0, fdarrayoff = 0, fdselectoff = 0; + stbtt_uint32 cff; + + cff = stbtt__find_table(data, fontstart, "CFF "); + if (!cff) return 0; + + info->fontdicts = stbtt__new_buf(NULL, 0); + info->fdselect = stbtt__new_buf(NULL, 0); + + // @TODO this should use size from table (not 512MB) + info->cff = stbtt__new_buf(data+cff, 512*1024*1024); + b = info->cff; + + // read the header + stbtt__buf_skip(&b, 2); + stbtt__buf_seek(&b, stbtt__buf_get8(&b)); // hdrsize + + // @TODO the name INDEX could list multiple fonts, + // but we just use the first one. + stbtt__cff_get_index(&b); // name INDEX + topdictidx = stbtt__cff_get_index(&b); + topdict = stbtt__cff_index_get(topdictidx, 0); + stbtt__cff_get_index(&b); // string INDEX + info->gsubrs = stbtt__cff_get_index(&b); + + stbtt__dict_get_ints(&topdict, 17, 1, &charstrings); + stbtt__dict_get_ints(&topdict, 0x100 | 6, 1, &cstype); + stbtt__dict_get_ints(&topdict, 0x100 | 36, 1, &fdarrayoff); + stbtt__dict_get_ints(&topdict, 0x100 | 37, 1, &fdselectoff); + info->subrs = stbtt__get_subrs(b, topdict); + + // we only support Type 2 charstrings + if (cstype != 2) return 0; + if (charstrings == 0) return 0; + + if (fdarrayoff) { + // looks like a CID font + if (!fdselectoff) return 0; + stbtt__buf_seek(&b, fdarrayoff); + info->fontdicts = stbtt__cff_get_index(&b); + info->fdselect = stbtt__buf_range(&b, fdselectoff, b.size-fdselectoff); + } + + stbtt__buf_seek(&b, charstrings); + info->charstrings = stbtt__cff_get_index(&b); + } + + t = stbtt__find_table(data, fontstart, "maxp"); + if (t) + info->numGlyphs = ttUSHORT(data+t+4); + else + info->numGlyphs = 0xffff; + + info->svg = -1; + + // find a cmap encoding table we understand *now* to avoid searching + // later. (todo: could make this installable) + // the same regardless of glyph. + numTables = ttUSHORT(data + cmap + 2); + info->index_map = 0; + stbtt_uint32 encoding_record; + for (i=0; i < numTables; ++i) { + encoding_record = cmap + 4 + 8 * i; + // find an encoding we understand: + switch(ttUSHORT(data+encoding_record)) { + case STBTT_PLATFORM_ID_MICROSOFT: + switch (ttUSHORT(data+encoding_record+2)) { + case STBTT_MS_EID_UNICODE_BMP: + case STBTT_MS_EID_UNICODE_FULL: + // MS/Unicode + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + break; + case STBTT_PLATFORM_ID_UNICODE: + // Mac/iOS has these + // all the encodingIDs are unicode, so we don't bother to check it + info->index_map = cmap + ttULONG(data+encoding_record+4); + break; + } + } + if (info->index_map == 0) + return 0; + + info->indexToLocFormat = ttUSHORT(data+info->head + 50); + return 1; +} + +// Inline helper functions for better performance - avoid function call overhead +#define FAST_USHORT(p) (((stbtt_uint16)(p)[0] << 8) | (p)[1]) +#define FAST_ULONG(p) (((stbtt_uint32)(p)[0] << 24) | ((stbtt_uint32)(p)[1] << 16) | ((stbtt_uint32)(p)[2] << 8) | (p)[3]) +#define FAST_SHORT(p) ((stbtt_int16)FAST_USHORT(p)) + +// Force inline for maximum performance +static inline int stbtt_FindGlyphIndex_impl(stbtt_uint8 *data, stbtt_uint32 index_map, int unicode_codepoint) +{ + stbtt_uint16 format = FAST_USHORT(data + index_map); + stbtt_uint32 uc = (stbtt_uint32)unicode_codepoint; + + switch (format) { + case 4: { + if (uc > 0xffff) return 0; + + stbtt_uint8 *header = data + index_map; + stbtt_uint16 segcount = FAST_USHORT(header + 6) >> 1; + stbtt_uint16 rangeShift = FAST_USHORT(header + 12) >> 1; + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + if (uc >= (stbtt_uint16)FAST_USHORT(data + search + (rangeShift << 1))) + search += rangeShift << 1; + + search -= 2; + stbtt_uint16 entrySelector = FAST_USHORT(header + 10); + stbtt_uint16 searchRange = FAST_USHORT(header + 8) >> 1; + + while (entrySelector) { + searchRange >>= 1; + stbtt_uint32 test_pos = search + (searchRange << 1); + if (uc > (stbtt_uint16)FAST_USHORT(data + test_pos)) + search = test_pos; + --entrySelector; + } + + search += 2; + stbtt_uint16 item = (stbtt_uint16)((search - endCount) >> 1); + stbtt_uint32 base = index_map + 14; + + stbtt_uint16 start = FAST_USHORT(data + base + (segcount << 1) + 2 + (item << 1)); + stbtt_uint16 end = FAST_USHORT(data + endCount + (item << 1)); + + if ((stbtt_uint32)(uc - start) > (stbtt_uint32)(end - start)) + return 0; + + stbtt_uint16 offset = FAST_USHORT(data + base + (segcount * 6) + 2 + (item << 1)); + if (offset == 0) + return (stbtt_uint16)(uc + FAST_SHORT(data + base + (segcount << 2) + 2 + (item << 1))); + + return FAST_USHORT(data + offset + ((uc - start) << 1) + base + (segcount * 6) + 2 + (item << 1)); + } + + case 12: + case 13: { + stbtt_uint32 low = 0, high = FAST_ULONG(data + index_map + 12); + stbtt_uint8 *groups_base = data + index_map + 16; + + while (low < high) { + stbtt_uint32 mid = (low + high) >> 1; + stbtt_uint8 *group = groups_base + (mid * 12); + stbtt_uint32 start_char = FAST_ULONG(group); + + if (uc < start_char) { + high = mid; + } else if (uc <= FAST_ULONG(group + 4)) { + stbtt_uint32 start_glyph = FAST_ULONG(group + 8); + return (format == 12) ? (start_glyph + uc - start_char) : start_glyph; + } else { + low = mid + 1; + } + } + return 0; + } + + case 0: + return (uc < (stbtt_uint32)(FAST_USHORT(data + index_map + 2) - 6)) ? + data[index_map + 6 + uc] : 0; + + case 6: { + stbtt_uint32 offset = uc - FAST_USHORT(data + index_map + 6); + return (offset < (stbtt_uint32)FAST_USHORT(data + index_map + 8)) ? + FAST_USHORT(data + index_map + 10 + (offset << 1)) : 0; + } + + default: + return 0; + } +} + + +STBTT_DEF int stbtt_FindGlyphIndex(const stbtt_fontinfo *info, int unicode_codepoint) +{ + // Early negative check before function call + if (unicode_codepoint < 0) return 0; + + return stbtt_FindGlyphIndex_impl(info->data, info->index_map, unicode_codepoint); +} + + +STBTT_DEF int stbtt_GetCodepointShape(const stbtt_fontinfo *info, int unicode_codepoint, stbtt_vertex **vertices) +{ + return stbtt_GetGlyphShape(info, stbtt_FindGlyphIndex(info, unicode_codepoint), vertices); +} + +static void stbtt_setvertex(stbtt_vertex *v, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy) +{ + v->type = type; + v->x = (stbtt_int16) x; + v->y = (stbtt_int16) y; + v->cx = (stbtt_int16) cx; + v->cy = (stbtt_int16) cy; +} + +static int stbtt__GetGlyfOffset(const stbtt_fontinfo *info, int glyph_index) +{ + int g1,g2; + + //STBTT_assert(!info->cff.size); + + if (glyph_index >= info->numGlyphs) return -1; // glyph index out of range + if (info->indexToLocFormat >= 2) return -1; // unknown index->glyph map format + + if (info->indexToLocFormat == 0) { + g1 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2) * 2; + g2 = info->glyf + ttUSHORT(info->data + info->loca + glyph_index * 2 + 2) * 2; + } else { + g1 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4); + g2 = info->glyf + ttULONG (info->data + info->loca + glyph_index * 4 + 4); + } + + return g1==g2 ? -1 : g1; // if length is 0, return -1 +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1); + +STBTT_DEF int stbtt_GetGlyphBox(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + if (info->cff.size) { + stbtt__GetGlyphInfoT2(info, glyph_index, x0, y0, x1, y1); + } else { + int g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 0; + + if (x0) *x0 = ttSHORT(info->data + g + 2); + if (y0) *y0 = ttSHORT(info->data + g + 4); + if (x1) *x1 = ttSHORT(info->data + g + 6); + if (y1) *y1 = ttSHORT(info->data + g + 8); + } + return 1; +} + +STBTT_DEF int stbtt_GetCodepointBox(const stbtt_fontinfo *info, int codepoint, int *x0, int *y0, int *x1, int *y1) +{ + return stbtt_GetGlyphBox(info, stbtt_FindGlyphIndex(info,codepoint), x0,y0,x1,y1); +} + +STBTT_DEF int stbtt_IsGlyphEmpty(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt_int16 numberOfContours; + int g; + if (info->cff.size) + return stbtt__GetGlyphInfoT2(info, glyph_index, NULL, NULL, NULL, NULL) == 0; + g = stbtt__GetGlyfOffset(info, glyph_index); + if (g < 0) return 1; + numberOfContours = ttSHORT(info->data + g); + return numberOfContours == 0; +} + +static int stbtt__close_shape(stbtt_vertex *vertices, int num_vertices, int was_off, int start_off, + stbtt_int32 sx, stbtt_int32 sy, stbtt_int32 scx, stbtt_int32 scy, stbtt_int32 cx, stbtt_int32 cy) +{ + if (start_off) { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+scx)>>1, (cy+scy)>>1, cx,cy); + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, sx,sy,scx,scy); + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve,sx,sy,cx,cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline,sx,sy,0,0); + } + return num_vertices; +} + +static int stbtt__GetGlyphShapeTT(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + stbtt_int16 numberOfContours; + stbtt_uint8 *endPtsOfContours; + stbtt_uint8 *data = info->data; + stbtt_vertex *vertices=0; + int num_vertices=0; + int g = stbtt__GetGlyfOffset(info, glyph_index); + + *pvertices = NULL; + + if (g < 0) return 0; + + numberOfContours = ttSHORT(data + g); + + if (numberOfContours > 0) { + // Variables moved outside loops for simple contours processing + stbtt_uint8 flags=0,flagcount; + stbtt_int32 ins, i,j=0,m,n, next_move, was_off=0, off, start_off=0; + stbtt_int32 x,y,cx,cy,sx,sy, scx,scy; + stbtt_uint8 *points; + stbtt_int16 dx, dy; // Moved outside x/y coordinate loading loops + + endPtsOfContours = (data + g + 10); + ins = ttUSHORT(data + g + 10 + numberOfContours * 2); + points = data + g + 10 + numberOfContours * 2 + 2 + ins; + + n = 1+ttUSHORT(endPtsOfContours + numberOfContours*2-2); + + m = n + 2*numberOfContours; // a loose bound on how many vertices we might need + vertices = (stbtt_vertex *) STBTT_malloc(m * sizeof(vertices[0]), info->userdata); + if (vertices == 0) + return 0; + + next_move = 0; + flagcount=0; + + // in first pass, we load uninterpreted data into the allocated array + // above, shifted to the end of the array so we won't overwrite it when + // we create our final data starting from the front + + off = m - n; // starting offset for uninterpreted data, regardless of how m ends up being calculated + + // first load flags + + for (i=0; i < n; ++i) { + if (flagcount == 0) { + flags = *points++; + if (flags & 8) + flagcount = *points++; + } else + --flagcount; + vertices[off+i].type = flags; + } + + // now load x coordinates + x=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 2) { + dx = *points++; + x += (flags & 16) ? dx : -dx; // ??? + } else { + if (!(flags & 16)) { + x = x + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].x = (stbtt_int16) x; + } + + // now load y coordinates + y=0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + if (flags & 4) { + dy = *points++; + y += (flags & 32) ? dy : -dy; // ??? + } else { + if (!(flags & 32)) { + y = y + (stbtt_int16) (points[0]*256 + points[1]); + points += 2; + } + } + vertices[off+i].y = (stbtt_int16) y; + } + + // now convert them to our format + num_vertices=0; + sx = sy = cx = cy = scx = scy = 0; + for (i=0; i < n; ++i) { + flags = vertices[off+i].type; + x = (stbtt_int16) vertices[off+i].x; + y = (stbtt_int16) vertices[off+i].y; + + if (next_move == i) { + if (i != 0) + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + + // now start the new one + start_off = !(flags & 1); + if (start_off) { + // if we start off with an off-curve point, then when we need to find a point on the curve + // where we can start, and we need to save some state for when we wraparound. + scx = x; + scy = y; + if (!(vertices[off+i+1].type & 1)) { + // next point is also a curve point, so interpolate an on-point curve + sx = (x + (stbtt_int32) vertices[off+i+1].x) >> 1; + sy = (y + (stbtt_int32) vertices[off+i+1].y) >> 1; + } else { + // otherwise just use the next point as our start point + sx = (stbtt_int32) vertices[off+i+1].x; + sy = (stbtt_int32) vertices[off+i+1].y; + ++i; // we're using point i+1 as the starting point, so skip it + } + } else { + sx = x; + sy = y; + } + stbtt_setvertex(&vertices[num_vertices++], STBTT_vmove,sx,sy,0,0); + was_off = 0; + next_move = 1 + ttUSHORT(endPtsOfContours+j*2); + ++j; + } else { + if (!(flags & 1)) { // if it's a curve + if (was_off) // two off-curve control points in a row means interpolate an on-curve midpoint + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, (cx+x)>>1, (cy+y)>>1, cx, cy); + cx = x; + cy = y; + was_off = 1; + } else { + if (was_off) + stbtt_setvertex(&vertices[num_vertices++], STBTT_vcurve, x,y, cx, cy); + else + stbtt_setvertex(&vertices[num_vertices++], STBTT_vline, x,y,0,0); + was_off = 0; + } + } + } + num_vertices = stbtt__close_shape(vertices, num_vertices, was_off, start_off, sx,sy,scx,scy,cx,cy); + } else if (numberOfContours < 0) { + // Compound shapes. + // Variables moved outside the while loop for compound shape processing + int more = 1; + stbtt_uint8 *comp = data + g + 10; + stbtt_uint16 flags, gidx; + int comp_num_verts = 0, i; + stbtt_vertex *comp_verts = 0, *tmp = 0; + float mtx[6] = {1,0,0,1,0,0}, m, n; + stbtt_vertex* v; + stbtt_vertex_type vx, vy; // Temporary variables for vertex transformation + + num_vertices = 0; + vertices = 0; + while (more) { + flags = ttSHORT(comp); comp+=2; + gidx = ttSHORT(comp); comp+=2; + + // Reset matrix to identity + mtx[0] = mtx[3] = 1; mtx[1] = mtx[2] = mtx[4] = mtx[5] = 0; + + if (flags & 2) { // XY values + if (flags & 1) { // shorts + mtx[4] = ttSHORT(comp); comp+=2; + mtx[5] = ttSHORT(comp); comp+=2; + } else { + mtx[4] = ttCHAR(comp); comp+=1; + mtx[5] = ttCHAR(comp); comp+=1; + } + } + else { + // @TODO handle matching point + //STBTT_assert(0); + } + if (flags & (1<<3)) { // WE_HAVE_A_SCALE + mtx[0] = mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + } else if (flags & (1<<6)) { // WE_HAVE_AN_X_AND_YSCALE + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = mtx[2] = 0; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } else if (flags & (1<<7)) { // WE_HAVE_A_TWO_BY_TWO + mtx[0] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[1] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[2] = ttSHORT(comp)/16384.0f; comp+=2; + mtx[3] = ttSHORT(comp)/16384.0f; comp+=2; + } + + // Find transformation scales. + m = (float) STBTT_sqrt(mtx[0]*mtx[0] + mtx[1]*mtx[1]); + n = (float) STBTT_sqrt(mtx[2]*mtx[2] + mtx[3]*mtx[3]); + + // Get indexed glyph. + comp_num_verts = stbtt_GetGlyphShape(info, gidx, &comp_verts); + if (comp_num_verts > 0) { + // Transform vertices. + for (i = 0; i < comp_num_verts; ++i) { + v = &comp_verts[i]; + vx=v->x; vy=v->y; + v->x = (stbtt_vertex_type)(m * (mtx[0]*vx + mtx[2]*vy + mtx[4])); + v->y = (stbtt_vertex_type)(n * (mtx[1]*vx + mtx[3]*vy + mtx[5])); + vx=v->cx; vy=v->cy; + v->cx = (stbtt_vertex_type)(m * (mtx[0]*vx + mtx[2]*vy + mtx[4])); + v->cy = (stbtt_vertex_type)(n * (mtx[1]*vx + mtx[3]*vy + mtx[5])); + } + // Append vertices. + tmp = (stbtt_vertex*)STBTT_malloc((num_vertices+comp_num_verts)*sizeof(stbtt_vertex), info->userdata); + if (!tmp) { + if (vertices) STBTT_free(vertices, info->userdata); + if (comp_verts) STBTT_free(comp_verts, info->userdata); + return 0; + } + if (num_vertices > 0 && vertices) STBTT_memcpy(tmp, vertices, num_vertices*sizeof(stbtt_vertex)); + STBTT_memcpy(tmp+num_vertices, comp_verts, comp_num_verts*sizeof(stbtt_vertex)); + if (vertices) STBTT_free(vertices, info->userdata); + vertices = tmp; + STBTT_free(comp_verts, info->userdata); + num_vertices += comp_num_verts; + } + // More components ? + more = flags & (1<<5); + } + } else { + // numberOfCounters == 0, do nothing + } + + *pvertices = vertices; + return num_vertices; +} + +typedef struct +{ + int bounds; + int started; + float first_x, first_y; + float x, y; + stbtt_int32 min_x, max_x, min_y, max_y; + + stbtt_vertex *pvertices; + int num_vertices; +} stbtt__csctx; + +#define STBTT__CSCTX_INIT(bounds) {bounds,0, 0,0, 0,0, 0,0,0,0, NULL, 0} + +static void stbtt__track_vertex(stbtt__csctx *c, stbtt_int32 x, stbtt_int32 y) +{ + if (x > c->max_x || !c->started) c->max_x = x; + if (y > c->max_y || !c->started) c->max_y = y; + if (x < c->min_x || !c->started) c->min_x = x; + if (y < c->min_y || !c->started) c->min_y = y; + c->started = 1; +} + +static void stbtt__csctx_v(stbtt__csctx *c, stbtt_uint8 type, stbtt_int32 x, stbtt_int32 y, stbtt_int32 cx, stbtt_int32 cy, stbtt_int32 cx1, stbtt_int32 cy1) +{ + if (c->bounds) { + stbtt__track_vertex(c, x, y); + if (type == STBTT_vcubic) { + stbtt__track_vertex(c, cx, cy); + stbtt__track_vertex(c, cx1, cy1); + } + } else { + stbtt_setvertex(&c->pvertices[c->num_vertices], type, x, y, cx, cy); + c->pvertices[c->num_vertices].cx1 = (stbtt_int16) cx1; + c->pvertices[c->num_vertices].cy1 = (stbtt_int16) cy1; + } + c->num_vertices++; +} + +static void stbtt__csctx_close_shape(stbtt__csctx *ctx) +{ + if (ctx->first_x != ctx->x || ctx->first_y != ctx->y) + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->first_x, (int)ctx->first_y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rmove_to(stbtt__csctx *ctx, float dx, float dy) +{ + stbtt__csctx_close_shape(ctx); + ctx->first_x = ctx->x = ctx->x + dx; + ctx->first_y = ctx->y = ctx->y + dy; + stbtt__csctx_v(ctx, STBTT_vmove, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rline_to(stbtt__csctx *ctx, float dx, float dy) +{ + ctx->x += dx; + ctx->y += dy; + stbtt__csctx_v(ctx, STBTT_vline, (int)ctx->x, (int)ctx->y, 0, 0, 0, 0); +} + +static void stbtt__csctx_rccurve_to(stbtt__csctx *ctx, float dx1, float dy1, float dx2, float dy2, float dx3, float dy3) +{ + float cx1 = ctx->x + dx1; + float cy1 = ctx->y + dy1; + float cx2 = cx1 + dx2; + float cy2 = cy1 + dy2; + ctx->x = cx2 + dx3; + ctx->y = cy2 + dy3; + stbtt__csctx_v(ctx, STBTT_vcubic, (int)ctx->x, (int)ctx->y, (int)cx1, (int)cy1, (int)cx2, (int)cy2); +} + +static stbtt__buf stbtt__get_subr(stbtt__buf idx, int n) +{ + int count = stbtt__cff_index_count(&idx); + int bias = 107; + if (count >= 33900) + bias = 32768; + else if (count >= 1240) + bias = 1131; + n += bias; + if (n < 0 || n >= count) + return stbtt__new_buf(NULL, 0); + return stbtt__cff_index_get(idx, n); +} + +static stbtt__buf stbtt__cid_get_glyph_subrs(const stbtt_fontinfo *info, int glyph_index) +{ + stbtt__buf fdselect = info->fdselect; + int nranges, start, end, v, fmt, fdselector = -1, i; + + stbtt__buf_seek(&fdselect, 0); + fmt = stbtt__buf_get8(&fdselect); + if (fmt == 0) { + // untested + stbtt__buf_skip(&fdselect, glyph_index); + fdselector = stbtt__buf_get8(&fdselect); + } else if (fmt == 3) { + nranges = stbtt__buf_get16(&fdselect); + start = stbtt__buf_get16(&fdselect); + for (i = 0; i < nranges; i++) { + v = stbtt__buf_get8(&fdselect); + end = stbtt__buf_get16(&fdselect); + if (glyph_index >= start && glyph_index < end) { + fdselector = v; + break; + } + start = end; + } + } + if (fdselector == -1) stbtt__new_buf(NULL, 0); + return stbtt__get_subrs(info->cff, stbtt__cff_index_get(info->fontdicts, fdselector)); +} + +static int stbtt__run_charstring(const stbtt_fontinfo *info, int glyph_index, stbtt__csctx *c) +{ + int in_header = 1, maskbits = 0, subr_stack_height = 0, sp = 0, v, i, b0; + int has_subrs = 0, clear_stack; + float s[48]; + stbtt__buf subr_stack[10], subrs = info->subrs, b; + float f; + +#define STBTT__CSERR(s) (0) + + // this currently ignores the initial width value, which isn't needed if we have hmtx + b = stbtt__cff_index_get(info->charstrings, glyph_index); + while (b.cursor < b.size) { + i = 0; + clear_stack = 1; + b0 = stbtt__buf_get8(&b); + switch (b0) { + // @TODO implement hinting + case 0x13: // hintmask + case 0x14: // cntrmask + if (in_header) + maskbits += (sp / 2); // implicit "vstem" + in_header = 0; + stbtt__buf_skip(&b, (maskbits + 7) / 8); + break; + + case 0x01: // hstem + case 0x03: // vstem + case 0x12: // hstemhm + case 0x17: // vstemhm + maskbits += (sp / 2); + break; + + case 0x15: // rmoveto + in_header = 0; + if (sp < 2) return STBTT__CSERR("rmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-2], s[sp-1]); + break; + case 0x04: // vmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("vmoveto stack"); + stbtt__csctx_rmove_to(c, 0, s[sp-1]); + break; + case 0x16: // hmoveto + in_header = 0; + if (sp < 1) return STBTT__CSERR("hmoveto stack"); + stbtt__csctx_rmove_to(c, s[sp-1], 0); + break; + + case 0x05: // rlineto + if (sp < 2) return STBTT__CSERR("rlineto stack"); + for (; i + 1 < sp; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + // hlineto/vlineto and vhcurveto/hvcurveto alternate horizontal and vertical + // starting from a different place. + + case 0x07: // vlineto + if (sp < 1) return STBTT__CSERR("vlineto stack"); + goto vlineto; + case 0x06: // hlineto + if (sp < 1) return STBTT__CSERR("hlineto stack"); + for (;;) { + if (i >= sp) break; + stbtt__csctx_rline_to(c, s[i], 0); + i++; + vlineto: + if (i >= sp) break; + stbtt__csctx_rline_to(c, 0, s[i]); + i++; + } + break; + + case 0x1F: // hvcurveto + if (sp < 4) return STBTT__CSERR("hvcurveto stack"); + goto hvcurveto; + case 0x1E: // vhcurveto + if (sp < 4) return STBTT__CSERR("vhcurveto stack"); + for (;;) { + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, 0, s[i], s[i+1], s[i+2], s[i+3], (sp - i == 5) ? s[i + 4] : 0.0f); + i += 4; + hvcurveto: + if (i + 3 >= sp) break; + stbtt__csctx_rccurve_to(c, s[i], 0, s[i+1], s[i+2], (sp - i == 5) ? s[i+4] : 0.0f, s[i+3]); + i += 4; + } + break; + + case 0x08: // rrcurveto + if (sp < 6) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x18: // rcurveline + if (sp < 8) return STBTT__CSERR("rcurveline stack"); + for (; i + 5 < sp - 2; i += 6) + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + if (i + 1 >= sp) return STBTT__CSERR("rcurveline stack"); + stbtt__csctx_rline_to(c, s[i], s[i+1]); + break; + + case 0x19: // rlinecurve + if (sp < 8) return STBTT__CSERR("rlinecurve stack"); + for (; i + 1 < sp - 6; i += 2) + stbtt__csctx_rline_to(c, s[i], s[i+1]); + if (i + 5 >= sp) return STBTT__CSERR("rlinecurve stack"); + stbtt__csctx_rccurve_to(c, s[i], s[i+1], s[i+2], s[i+3], s[i+4], s[i+5]); + break; + + case 0x1A: // vvcurveto + case 0x1B: // hhcurveto + if (sp < 4) return STBTT__CSERR("(vv|hh)curveto stack"); + f = 0.0; + if (sp & 1) { f = s[i]; i++; } + for (; i + 3 < sp; i += 4) { + if (b0 == 0x1B) + stbtt__csctx_rccurve_to(c, s[i], f, s[i+1], s[i+2], s[i+3], 0.0); + else + stbtt__csctx_rccurve_to(c, f, s[i], s[i+1], s[i+2], 0.0, s[i+3]); + f = 0.0; + } + break; + + case 0x0A: // callsubr + if (!has_subrs) { + if (info->fdselect.size) + subrs = stbtt__cid_get_glyph_subrs(info, glyph_index); + has_subrs = 1; + } + // FALLTHROUGH + case 0x1D: // callgsubr + if (sp < 1) return STBTT__CSERR("call(g|)subr stack"); + v = (int) s[--sp]; + if (subr_stack_height >= 10) return STBTT__CSERR("recursion limit"); + subr_stack[subr_stack_height++] = b; + b = stbtt__get_subr(b0 == 0x0A ? subrs : info->gsubrs, v); + if (b.size == 0) return STBTT__CSERR("subr not found"); + b.cursor = 0; + clear_stack = 0; + break; + + case 0x0B: // return + if (subr_stack_height <= 0) return STBTT__CSERR("return outside subr"); + b = subr_stack[--subr_stack_height]; + clear_stack = 0; + break; + + case 0x0E: // endchar + stbtt__csctx_close_shape(c); + return 1; + + case 0x0C: { // two-byte escape + float dx1, dx2, dx3, dx4, dx5, dx6, dy1, dy2, dy3, dy4, dy5, dy6; + float dx, dy; + int b1 = stbtt__buf_get8(&b); + switch (b1) { + // @TODO These "flex" implementations ignore the flex-depth and resolution, + // and always draw beziers. + case 0x22: // hflex + if (sp < 7) return STBTT__CSERR("hflex stack"); + dx1 = s[0]; + dx2 = s[1]; + dy2 = s[2]; + dx3 = s[3]; + dx4 = s[4]; + dx5 = s[5]; + dx6 = s[6]; + stbtt__csctx_rccurve_to(c, dx1, 0, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, -dy2, dx6, 0); + break; + + case 0x23: // flex + if (sp < 13) return STBTT__CSERR("flex stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = s[10]; + dy6 = s[11]; + //fd is s[12] + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + case 0x24: // hflex1 + if (sp < 9) return STBTT__CSERR("hflex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dx4 = s[5]; + dx5 = s[6]; + dy5 = s[7]; + dx6 = s[8]; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, 0); + stbtt__csctx_rccurve_to(c, dx4, 0, dx5, dy5, dx6, -(dy1+dy2+dy5)); + break; + + case 0x25: // flex1 + if (sp < 11) return STBTT__CSERR("flex1 stack"); + dx1 = s[0]; + dy1 = s[1]; + dx2 = s[2]; + dy2 = s[3]; + dx3 = s[4]; + dy3 = s[5]; + dx4 = s[6]; + dy4 = s[7]; + dx5 = s[8]; + dy5 = s[9]; + dx6 = dy6 = s[10]; + dx = dx1+dx2+dx3+dx4+dx5; + dy = dy1+dy2+dy3+dy4+dy5; + if (STBTT_fabs(dx) > STBTT_fabs(dy)) + dy6 = -dy; + else + dx6 = -dx; + stbtt__csctx_rccurve_to(c, dx1, dy1, dx2, dy2, dx3, dy3); + stbtt__csctx_rccurve_to(c, dx4, dy4, dx5, dy5, dx6, dy6); + break; + + default: + return STBTT__CSERR("unimplemented"); + } + } break; + + default: + if (b0 != 255 && b0 != 28 && b0 < 32) + return STBTT__CSERR("reserved operator"); + + // push immediate + if (b0 == 255) { + f = (float)(stbtt_int32)stbtt__buf_get32(&b) / 0x10000; + } else { + stbtt__buf_skip(&b, -1); + f = (float)(stbtt_int16)stbtt__cff_int(&b); + } + if (sp >= 48) return STBTT__CSERR("push stack overflow"); + s[sp++] = f; + clear_stack = 0; + break; + } + if (clear_stack) sp = 0; + } + return STBTT__CSERR("no endchar"); + +#undef STBTT__CSERR +} + +static int stbtt__GetGlyphShapeT2(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + // runs the charstring twice, once to count and once to output (to avoid realloc) + stbtt__csctx count_ctx = STBTT__CSCTX_INIT(1); + stbtt__csctx output_ctx = STBTT__CSCTX_INIT(0); + if (stbtt__run_charstring(info, glyph_index, &count_ctx)) { + *pvertices = (stbtt_vertex*)STBTT_malloc(count_ctx.num_vertices*sizeof(stbtt_vertex), info->userdata); + output_ctx.pvertices = *pvertices; + if (stbtt__run_charstring(info, glyph_index, &output_ctx)) { + //STBTT_assert(output_ctx.num_vertices == count_ctx.num_vertices); + return output_ctx.num_vertices; + } + } + *pvertices = NULL; + return 0; +} + +static int stbtt__GetGlyphInfoT2(const stbtt_fontinfo *info, int glyph_index, int *x0, int *y0, int *x1, int *y1) +{ + stbtt__csctx c = STBTT__CSCTX_INIT(1); + int r = stbtt__run_charstring(info, glyph_index, &c); + if (x0) *x0 = r ? c.min_x : 0; + if (y0) *y0 = r ? c.min_y : 0; + if (x1) *x1 = r ? c.max_x : 0; + if (y1) *y1 = r ? c.max_y : 0; + return r ? c.num_vertices : 0; +} + +STBTT_DEF int stbtt_GetGlyphShape(const stbtt_fontinfo *info, int glyph_index, stbtt_vertex **pvertices) +{ + if (!info->cff.size) + return stbtt__GetGlyphShapeTT(info, glyph_index, pvertices); + else + return stbtt__GetGlyphShapeT2(info, glyph_index, pvertices); +} + +STBTT_DEF void stbtt_GetGlyphHMetrics(const stbtt_fontinfo *info, int glyph_index, int *advanceWidth, int *leftSideBearing) +{ + stbtt_uint16 numOfLongHorMetrics = ttUSHORT(info->data+info->hhea + 34); + if (glyph_index < numOfLongHorMetrics) { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*glyph_index); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*glyph_index + 2); + } else { + if (advanceWidth) *advanceWidth = ttSHORT(info->data + info->hmtx + 4*(numOfLongHorMetrics-1)); + if (leftSideBearing) *leftSideBearing = ttSHORT(info->data + info->hmtx + 4*numOfLongHorMetrics + 2*(glyph_index - numOfLongHorMetrics)); + } +} + +STBTT_DEF int stbtt_GetKerningTableLength(const stbtt_fontinfo *info) +{ + stbtt_uint8 *data = info->data + info->kern; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + return ttUSHORT(data+10); +} + +STBTT_DEF int stbtt_GetKerningTable(const stbtt_fontinfo *info, stbtt_kerningentry* table, int table_length) +{ + stbtt_uint8 *data = info->data + info->kern; + int k, length; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + length = ttUSHORT(data+10); + if (table_length < length) + length = table_length; + + for (k = 0; k < length; k++) + { + table[k].glyph1 = ttUSHORT(data+18+(k*6)); + table[k].glyph2 = ttUSHORT(data+20+(k*6)); + table[k].advance = ttSHORT(data+22+(k*6)); + } + + return length; +} + +static int stbtt__GetGlyphKernInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint8 *data = info->data + info->kern; + stbtt_uint32 needle, straw; + int l, r, m; + + // we only look at the first table. it must be 'horizontal' and format 0. + if (!info->kern) + return 0; + if (ttUSHORT(data+2) < 1) // number of tables, need at least 1 + return 0; + if (ttUSHORT(data+8) != 1) // horizontal flag must be set in format + return 0; + + l = 0; + r = ttUSHORT(data+10) - 1; + needle = glyph1 << 16 | glyph2; + while (l <= r) { + m = (l + r) >> 1; + straw = ttULONG(data+18+(m*6)); // note: unaligned read + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else + return ttSHORT(data+22+(m*6)); + } + return 0; +} + +static stbtt_int32 stbtt__GetCoverageIndex(stbtt_uint8 *coverageTable, int glyph) +{ + stbtt_uint16 coverageFormat = ttUSHORT(coverageTable); + switch (coverageFormat) { + case 1: { + stbtt_uint16 glyphCount = ttUSHORT(coverageTable + 2); + + // Binary search. + stbtt_int32 l=0, r=glyphCount-1, m; + int straw, needle=glyph; + while (l <= r) { + stbtt_uint8 *glyphArray = coverageTable + 4; + stbtt_uint16 glyphID; + m = (l + r) >> 1; + glyphID = ttUSHORT(glyphArray + 2 * m); + straw = glyphID; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + return m; + } + } + break; + } + + case 2: { + stbtt_uint16 rangeCount = ttUSHORT(coverageTable + 2); + stbtt_uint8 *rangeArray = coverageTable + 4; + + // Binary search. + stbtt_int32 l=0, r=rangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *rangeRecord; + m = (l + r) >> 1; + rangeRecord = rangeArray + 6 * m; + strawStart = ttUSHORT(rangeRecord); + strawEnd = ttUSHORT(rangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else { + stbtt_uint16 startCoverageIndex = ttUSHORT(rangeRecord + 4); + return startCoverageIndex + glyph - strawStart; + } + } + break; + } + + default: return -1; // unsupported + } + + return -1; +} + +static stbtt_int32 stbtt__GetGlyphClass(stbtt_uint8 *classDefTable, int glyph) +{ + stbtt_uint16 classDefFormat = ttUSHORT(classDefTable); + switch (classDefFormat) + { + case 1: { + stbtt_uint16 startGlyphID = ttUSHORT(classDefTable + 2); + stbtt_uint16 glyphCount = ttUSHORT(classDefTable + 4); + stbtt_uint8 *classDef1ValueArray = classDefTable + 6; + + if (glyph >= startGlyphID && glyph < startGlyphID + glyphCount) + return (stbtt_int32)ttUSHORT(classDef1ValueArray + 2 * (glyph - startGlyphID)); + break; + } + + case 2: { + stbtt_uint16 classRangeCount = ttUSHORT(classDefTable + 2); + stbtt_uint8 *classRangeRecords = classDefTable + 4; + + // Binary search. + stbtt_int32 l=0, r=classRangeCount-1, m; + int strawStart, strawEnd, needle=glyph; + while (l <= r) { + stbtt_uint8 *classRangeRecord; + m = (l + r) >> 1; + classRangeRecord = classRangeRecords + 6 * m; + strawStart = ttUSHORT(classRangeRecord); + strawEnd = ttUSHORT(classRangeRecord + 2); + if (needle < strawStart) + r = m - 1; + else if (needle > strawEnd) + l = m + 1; + else + return (stbtt_int32)ttUSHORT(classRangeRecord + 4); + } + break; + } + + default: + return -1; // Unsupported definition type, return an error. + } + + // "All glyphs not assigned to a class fall into class 0". (OpenType spec) + return 0; +} + +// Define to STBTT_assert(x) if you want to break on unimplemented formats. +#define STBTT_GPOS_TODO_assert(x) + +static stbtt_int32 stbtt__GetGlyphGPOSInfoAdvance(const stbtt_fontinfo *info, int glyph1, int glyph2) +{ + stbtt_uint16 lookupListOffset; + stbtt_uint8 *lookupList; + stbtt_uint16 lookupCount; + stbtt_uint8 *data; + stbtt_int32 i, sti; + + // Variables moved outside loops for better performance + stbtt_uint16 lookupOffset; + stbtt_uint8 *lookupTable; + stbtt_uint16 lookupType; + stbtt_uint16 subTableCount; + stbtt_uint8 *subTableOffsets; + stbtt_uint16 subtableOffset; + stbtt_uint8 *table; + stbtt_uint16 posFormat; + stbtt_uint16 coverageOffset; + stbtt_int32 coverageIndex; + + // Case 1 variables + stbtt_int32 l, r, m; + int straw, needle; + stbtt_uint16 valueFormat1, valueFormat2; + stbtt_int32 valueRecordPairSizeInBytes; + stbtt_uint16 pairSetCount; + stbtt_uint16 pairPosOffset; + stbtt_uint8 *pairValueTable; + stbtt_uint16 pairValueCount; + stbtt_uint8 *pairValueArray; + stbtt_uint16 secondGlyph; + stbtt_uint8 *pairValue; + stbtt_int16 xAdvance; + + // Case 2 variables + stbtt_uint16 classDef1Offset, classDef2Offset; + int glyph1class, glyph2class; + stbtt_uint16 class1Count, class2Count; + stbtt_uint8 *class1Records, *class2Records; + + if (!info->gpos) return 0; + + data = info->data + info->gpos; + + if (ttUSHORT(data+0) != 1) return 0; // Major version 1 + if (ttUSHORT(data+2) != 0) return 0; // Minor version 0 + + lookupListOffset = ttUSHORT(data+8); + lookupList = data + lookupListOffset; + lookupCount = ttUSHORT(lookupList); + + for (i=0; i= pairSetCount) return 0; + + needle=glyph2; + r=pairValueCount-1; + l=0; + + // Binary search. + while (l <= r) { + m = (l + r) >> 1; + pairValue = pairValueArray + (2 + valueRecordPairSizeInBytes) * m; + secondGlyph = ttUSHORT(pairValue); + straw = secondGlyph; + if (needle < straw) + r = m - 1; + else if (needle > straw) + l = m + 1; + else { + xAdvance = ttSHORT(pairValue + 2); + return xAdvance; + } + } + } else + return 0; + break; + } + + case 2: { + valueFormat1 = ttUSHORT(table + 4); + valueFormat2 = ttUSHORT(table + 6); + if (valueFormat1 == 4 && valueFormat2 == 0) { // Support more formats? + classDef1Offset = ttUSHORT(table + 8); + classDef2Offset = ttUSHORT(table + 10); + glyph1class = stbtt__GetGlyphClass(table + classDef1Offset, glyph1); + glyph2class = stbtt__GetGlyphClass(table + classDef2Offset, glyph2); + + class1Count = ttUSHORT(table + 12); + class2Count = ttUSHORT(table + 14); + + if (glyph1class < 0 || glyph1class >= class1Count) return 0; // malformed + if (glyph2class < 0 || glyph2class >= class2Count) return 0; // malformed + + class1Records = table + 16; + class2Records = class1Records + 2 * (glyph1class * class2Count); + xAdvance = ttSHORT(class2Records + 2 * glyph2class); + return xAdvance; + } else + return 0; + break; + } + + default: + return 0; // Unsupported position format + } + } + } + + return 0; +} + +STBTT_DEF int stbtt_GetGlyphKernAdvance(const stbtt_fontinfo *info, int g1, int g2) +{ + int xAdvance = 0; + + if (info->gpos) + xAdvance += stbtt__GetGlyphGPOSInfoAdvance(info, g1, g2); + else if (info->kern) + xAdvance += stbtt__GetGlyphKernInfoAdvance(info, g1, g2); + + return xAdvance; +} + +STBTT_DEF int stbtt_GetCodepointKernAdvance(const stbtt_fontinfo *info, int ch1, int ch2) +{ + if (!info->kern && !info->gpos) // if no kerning table, don't waste time looking up both codepoint->glyphs + return 0; + return stbtt_GetGlyphKernAdvance(info, stbtt_FindGlyphIndex(info,ch1), stbtt_FindGlyphIndex(info,ch2)); +} + +STBTT_DEF void stbtt_GetCodepointHMetrics(const stbtt_fontinfo *info, int codepoint, int *advanceWidth, int *leftSideBearing) +{ + stbtt_GetGlyphHMetrics(info, stbtt_FindGlyphIndex(info,codepoint), advanceWidth, leftSideBearing); +} + +STBTT_DEF void stbtt_GetFontVMetrics(const stbtt_fontinfo *info, int *ascent, int *descent, int *lineGap) +{ + if (ascent ) *ascent = ttSHORT(info->data+info->hhea + 4); + if (descent) *descent = ttSHORT(info->data+info->hhea + 6); + if (lineGap) *lineGap = ttSHORT(info->data+info->hhea + 8); +} + +STBTT_DEF int stbtt_GetFontVMetricsOS2(const stbtt_fontinfo *info, int *typoAscent, int *typoDescent, int *typoLineGap) +{ + int tab = stbtt__find_table(info->data, info->fontstart, "OS/2"); + if (!tab) + return 0; + if (typoAscent ) *typoAscent = ttSHORT(info->data+tab + 68); + if (typoDescent) *typoDescent = ttSHORT(info->data+tab + 70); + if (typoLineGap) *typoLineGap = ttSHORT(info->data+tab + 72); + return 1; +} + +STBTT_DEF void stbtt_GetFontBoundingBox(const stbtt_fontinfo *info, int *x0, int *y0, int *x1, int *y1) +{ + *x0 = ttSHORT(info->data + info->head + 36); + *y0 = ttSHORT(info->data + info->head + 38); + *x1 = ttSHORT(info->data + info->head + 40); + *y1 = ttSHORT(info->data + info->head + 42); +} + +STBTT_DEF float stbtt_ScaleForPixelHeight(const stbtt_fontinfo *info, float height) +{ + int fheight = ttSHORT(info->data + info->hhea + 4) - ttSHORT(info->data + info->hhea + 6); + return (float) height / fheight; +} + +STBTT_DEF float stbtt_ScaleForMappingEmToPixels(const stbtt_fontinfo *info, float pixels) +{ + int unitsPerEm = ttUSHORT(info->data + info->head + 18); + return pixels / unitsPerEm; +} + +STBTT_DEF void stbtt_FreeShape(const stbtt_fontinfo *info, stbtt_vertex *v) +{ + STBTT_free(v, info->userdata); +} + +STBTT_DEF stbtt_uint8 *stbtt_FindSVGDoc(const stbtt_fontinfo *info, int gl) +{ + int i; + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc_list = data + stbtt__get_svg((stbtt_fontinfo *) info); + + int numEntries = ttUSHORT(svg_doc_list); + stbtt_uint8 *svg_docs = svg_doc_list + 2; + + for(i=0; i= ttUSHORT(svg_doc)) && (gl <= ttUSHORT(svg_doc + 2))) + return svg_doc; + } + return 0; +} + +STBTT_DEF int stbtt_GetGlyphSVG(const stbtt_fontinfo *info, int gl, const char **svg) +{ + stbtt_uint8 *data = info->data; + stbtt_uint8 *svg_doc; + + if (info->svg == 0) + return 0; + + svg_doc = stbtt_FindSVGDoc(info, gl); + if (svg_doc != NULL) { + *svg = (char *) data + info->svg + ttULONG(svg_doc + 4); + return ttULONG(svg_doc + 8); + } else { + return 0; + } +} + +STBTT_DEF int stbtt_GetCodepointSVG(const stbtt_fontinfo *info, int unicode_codepoint, const char **svg) +{ + return stbtt_GetGlyphSVG(info, stbtt_FindGlyphIndex(info, unicode_codepoint), svg); +} + +////////////////////////////////////////////////////////////////////////////// +// +// antialiasing software rasterizer +// + +STBTT_DEF void stbtt_GetGlyphBitmapBoxSubpixel(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y,float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + int x0=0,y0=0,x1,y1; // =0 suppresses compiler warning + if (!stbtt_GetGlyphBox(font, glyph, &x0,&y0,&x1,&y1)) { + // e.g. space character + if (ix0) *ix0 = 0; + if (iy0) *iy0 = 0; + if (ix1) *ix1 = 0; + if (iy1) *iy1 = 0; + } else { + // move to integral bboxes (treating pixels as little squares, what pixels get touched)? + if (ix0) *ix0 = STBTT_ifloor( x0 * scale_x + shift_x); + if (iy0) *iy0 = STBTT_ifloor(-y1 * scale_y + shift_y); + if (ix1) *ix1 = STBTT_iceil ( x1 * scale_x + shift_x); + if (iy1) *iy1 = STBTT_iceil (-y0 * scale_y + shift_y); + } +} + +STBTT_DEF void stbtt_GetGlyphBitmapBox(const stbtt_fontinfo *font, int glyph, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, glyph, scale_x, scale_y,0.0f,0.0f, ix0, iy0, ix1, iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBoxSubpixel(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, float shift_x, float shift_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetGlyphBitmapBoxSubpixel(font, stbtt_FindGlyphIndex(font,codepoint), scale_x, scale_y,shift_x,shift_y, ix0,iy0,ix1,iy1); +} + +STBTT_DEF void stbtt_GetCodepointBitmapBox(const stbtt_fontinfo *font, int codepoint, float scale_x, float scale_y, int *ix0, int *iy0, int *ix1, int *iy1) +{ + stbtt_GetCodepointBitmapBoxSubpixel(font, codepoint, scale_x, scale_y,0.0f,0.0f, ix0,iy0,ix1,iy1); +} + +////////////////////////////////////////////////////////////////////////////// +// +// Rasterizer + +typedef struct stbtt__hheap_chunk +{ + struct stbtt__hheap_chunk *next; +} stbtt__hheap_chunk; + +typedef struct stbtt__hheap +{ + struct stbtt__hheap_chunk *head; + void *first_free; + int num_remaining_in_head_chunk; +} stbtt__hheap; + +static void *stbtt__hheap_alloc(stbtt__hheap *hh, size_t size, void *userdata) +{ + if (hh->first_free) { + void *p = hh->first_free; + hh->first_free = * (void **) p; + return p; + } else { + if (hh->num_remaining_in_head_chunk == 0) { + int count = (size < 32 ? 2000 : size < 128 ? 800 : 100); + stbtt__hheap_chunk *c = (stbtt__hheap_chunk *) STBTT_malloc(sizeof(stbtt__hheap_chunk) + size * count, userdata); + if (c == NULL) + return NULL; + c->next = hh->head; + hh->head = c; + hh->num_remaining_in_head_chunk = count; + } + --hh->num_remaining_in_head_chunk; + return (char *) (hh->head) + sizeof(stbtt__hheap_chunk) + size * hh->num_remaining_in_head_chunk; + } +} + +static void stbtt__hheap_free(stbtt__hheap *hh, void *p) +{ + *(void **) p = hh->first_free; + hh->first_free = p; +} + +static void stbtt__hheap_cleanup(stbtt__hheap *hh, void *userdata) +{ + stbtt__hheap_chunk *c = hh->head; + while (c) { + stbtt__hheap_chunk *n = c->next; + STBTT_free(c, userdata); + c = n; + } +} + +typedef struct stbtt__edge { + float x0,y0, x1,y1; + int invert; +} stbtt__edge; + + +typedef struct stbtt__active_edge +{ + struct stbtt__active_edge *next; + #if STBTT_RASTERIZER_VERSION==1 + int x,dx; + float ey; + int direction; + #elif STBTT_RASTERIZER_VERSION==2 + float fx,fdx,fdy; + float direction; + float sy; + float ey; + #else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" + #endif +} stbtt__active_edge; + +#if STBTT_RASTERIZER_VERSION == 1 +#define STBTT_FIXSHIFT 10 +#define STBTT_FIX (1 << STBTT_FIXSHIFT) +#define STBTT_FIXMASK (STBTT_FIX-1) + +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + const float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + //STBTT_assert(z != NULL); + if (!z) return z; + + // round dx down to avoid overshooting + if (dxdy < 0) + z->dx = -STBTT_ifloor(STBTT_FIX * -dxdy); + else + z->dx = STBTT_ifloor(STBTT_FIX * dxdy); + + z->x = STBTT_ifloor(STBTT_FIX * e->x0 + z->dx * (start_point - e->y0)); // use z->dx so when we offset later it's by the same amount + z->x -= off_x * STBTT_FIX; + + z->ey = e->y1; + z->next = 0; + z->direction = e->invert ? 1 : -1; + return z; +} +#elif STBTT_RASTERIZER_VERSION == 2 +static stbtt__active_edge *stbtt__new_active(stbtt__hheap *hh, stbtt__edge *e, int off_x, float start_point, void *userdata) +{ + stbtt__active_edge *z = (stbtt__active_edge *) stbtt__hheap_alloc(hh, sizeof(*z), userdata); + const float dxdy = (e->x1 - e->x0) / (e->y1 - e->y0); + //STBTT_assert(z != NULL); + //STBTT_assert(e->y0 <= start_point); + if (!z) return z; + z->fdx = dxdy; + z->fdy = dxdy != 0.0f ? (1.0f/dxdy) : 0.0f; + z->fx = e->x0 + dxdy * (start_point - e->y0); + z->fx -= off_x; + z->direction = e->invert ? 1.0f : -1.0f; + z->sy = e->y0; + z->ey = e->y1; + z->next = 0; + return z; +} +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#if STBTT_RASTERIZER_VERSION == 1 +// note: this routine clips fills that extend off the edges... ideally this +// wouldn't happen, but it could happen if the truetype glyph bounding boxes +// are wrong, or if the user supplies a too-small bitmap +static void stbtt__fill_active_edges(unsigned char *scanline, int len, stbtt__active_edge *e, int max_weight) +{ + // non-zero winding fill + int x0=0, w=0; + + // Variables moved outside loop for better performance + int x1; + int i, j; + + while (e) { + if (w == 0) { + // if we're currently at zero, we need to record the edge start point + x0 = e->x; w += e->direction; + } else { + x1 = e->x; w += e->direction; + // if we went to zero, we need to draw + if (w == 0) { + i = x0 >> STBTT_FIXSHIFT; + j = x1 >> STBTT_FIXSHIFT; + + if (i < len && j >= 0) { + if (i == j) { + // x0,x1 are the same pixel, so compute combined coverage + scanline[i] = scanline[i] + (stbtt_uint8) ((x1 - x0) * max_weight >> STBTT_FIXSHIFT); + } else { + if (i >= 0) // add antialiasing for x0 + scanline[i] = scanline[i] + (stbtt_uint8) (((STBTT_FIX - (x0 & STBTT_FIXMASK)) * max_weight) >> STBTT_FIXSHIFT); + else + i = -1; // clip + + if (j < len) // add antialiasing for x1 + scanline[j] = scanline[j] + (stbtt_uint8) (((x1 & STBTT_FIXMASK) * max_weight) >> STBTT_FIXSHIFT); + else + j = len; // clip + + for (++i; i < j; ++i) // fill pixels between x0 and x1 + scanline[i] = scanline[i] + (stbtt_uint8) max_weight; + } + } + } + } + + e = e->next; + } +} + +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0; + int max_weight = (255 / vsubsample); // weight per vertical scanline + int s; // vertical subsample index + unsigned char scanline_data[512], *scanline; + + // Variables moved outside loops for better performance + float scan_y; + stbtt__active_edge **step; + stbtt__active_edge *z; + int changed; + stbtt__active_edge *t, *q; + stbtt__active_edge *p; + + if (result->w > 512) + scanline = (unsigned char *) STBTT_malloc(result->w, userdata); + else + scanline = scanline_data; + + y = off_y * vsubsample; + e[n].y0 = (off_y + result->h) * (float) vsubsample + 1; + + while (j < result->h) { + STBTT_memset(scanline, 0, result->w); + for (s=0; s < vsubsample; ++s) { + // find center of pixel for this scanline + scan_y = y + 0.5f; + step = &active; + + // update all active edges; + // remove all active edges that terminate before the center of this scanline + while (*step) { + z = *step; + if (z->ey <= scan_y) { + *step = z->next; // delete from list + //STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + z->x += z->dx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + } + + // resort the list if needed + for(;;) { + changed=0; + step = &active; + while (*step && (*step)->next) { + if ((*step)->x > (*step)->next->x) { + t = *step; + q = t->next; + + t->next = q->next; + q->next = t; + *step = q; + changed = 1; + } + step = &(*step)->next; + } + if (!changed) break; + } + + // insert all edges that start before the center of this scanline -- omit ones that also end on this scanline + while (e->y0 <= scan_y) { + if (e->y1 > scan_y) { + z = stbtt__new_active(&hh, e, off_x, scan_y, userdata); + if (z != NULL) { + // find insertion point + if (active == NULL) + active = z; + else if (z->x < active->x) { + // insert at front + z->next = active; + active = z; + } else { + // find thing to insert AFTER + p = active; + while (p->next && p->next->x < z->x) + p = p->next; + // at this point, p->next->x is NOT < z->x + z->next = p->next; + p->next = z; + } + } + } + ++e; + } + + // now process all active edges in XOR fashion + if (active) + stbtt__fill_active_edges(scanline, result->w, active, max_weight); + + ++y; + } + STBTT_memcpy(result->pixels + j * result->stride, scanline, result->w); + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#elif STBTT_RASTERIZER_VERSION == 2 + +// the edge passed in here does not cross the vertical line at x or the vertical line at x+1 +// (i.e. it has already been clipped to those) +static void stbtt__handle_clipped_edge(float *scanline, int x, stbtt__active_edge *e, float x0, float y0, float x1, float y1) +{ + if (y0 == y1) return; + //STBTT_assert(y0 < y1); + //STBTT_assert(e->sy <= e->ey); + if (y0 > e->ey) return; + if (y1 < e->sy) return; + if (y0 < e->sy) { + x0 += (x1-x0) * (e->sy - y0) / (y1-y0); + y0 = e->sy; + } + if (y1 > e->ey) { + x1 += (x1-x0) * (e->ey - y1) / (y1-y0); + y1 = e->ey; + } + + //if (x0 == x) + // //STBTT_assert(x1 <= x+1); + //else if (x0 == x+1) + // //STBTT_assert(x1 >= x); + //else if (x0 <= x) + // //STBTT_assert(x1 <= x); + //else if (x0 >= x+1) + // //STBTT_assert(x1 >= x+1); + //else + // //STBTT_assert(x1 >= x && x1 <= x+1); + + if (x0 <= x && x1 <= x) + scanline[x] += e->direction * (y1-y0); + else if (x0 >= x+1 && x1 >= x+1) + ; + else { + //STBTT_assert(x0 >= x && x0 <= x+1 && x1 >= x && x1 <= x+1); + scanline[x] += e->direction * (y1-y0) * (1-((x0-x)+(x1-x))/2); // coverage = 1 - average x position + } +} + +static float stbtt__sized_trapezoid_area(float height, float top_width, float bottom_width) +{ + //STBTT_assert(top_width >= 0); + //STBTT_assert(bottom_width >= 0); + return (top_width + bottom_width) / 2.0f * height; +} + +static float stbtt__position_trapezoid_area(float height, float tx0, float tx1, float bx0, float bx1) +{ + return stbtt__sized_trapezoid_area(height, tx1 - tx0, bx1 - bx0); +} + +static float stbtt__sized_triangle_area(float height, float width) +{ + return height * width / 2; +} + +static void stbtt__fill_active_edges_new(float *scanline, float *scanline_fill, int len, stbtt__active_edge *e, float y_top) +{ + float y_bottom = y_top+1; + + // Variables moved outside loops for better performance + float x0, dx, xb, x_top, x_bottom; + float sy0, sy1, dy; + float height; + int x, x1, x2; + float y_crossing, y_final, step, sign, area; + float t; + float y0, y1, y2, y3; + + float x1_clip; + float x2_clip; + float x3; + + while (e) { + // brute force every pixel + + // compute intersection points with top & bottom + //STBTT_assert(e->ey >= y_top); + + if (e->fdx == 0) { + x0 = e->fx; + if (x0 < len) { + if (x0 >= 0) { + stbtt__handle_clipped_edge(scanline,(int) x0,e, x0,y_top, x0,y_bottom); + stbtt__handle_clipped_edge(scanline_fill-1,(int) x0+1,e, x0,y_top, x0,y_bottom); + } else { + stbtt__handle_clipped_edge(scanline_fill-1,0,e, x0,y_top, x0,y_bottom); + } + } + } else { + x0 = e->fx; + dx = e->fdx; + xb = x0 + dx; + dy = e->fdy; + //STBTT_assert(e->sy <= y_bottom && e->ey >= y_top); + + // compute endpoints of line segment clipped to this scanline (if the + // line segment starts on this scanline. x0 is the intersection of the + // line with y_top, but that may be off the line segment. + if (e->sy > y_top) { + x_top = x0 + dx * (e->sy - y_top); + sy0 = e->sy; + } else { + x_top = x0; + sy0 = y_top; + } + if (e->ey < y_bottom) { + x_bottom = x0 + dx * (e->ey - y_top); + sy1 = e->ey; + } else { + x_bottom = xb; + sy1 = y_bottom; + } + + if (x_top >= 0 && x_bottom >= 0 && x_top < len && x_bottom < len) { + // from here on, we don't have to range check x values + + if ((int) x_top == (int) x_bottom) { + // simple case, only spans one pixel + x = (int) x_top; + height = (sy1 - sy0) * e->direction; + //STBTT_assert(x >= 0 && x < len); + scanline[x] += stbtt__position_trapezoid_area(height, x_top, x+1.0f, x_bottom, x+1.0f); + scanline_fill[x] += height; // everything right of this pixel is filled + } else { + // covers 2+ pixels + if (x_top > x_bottom) { + // flip scanline vertically; signed area is the same + sy0 = y_bottom - (sy0 - y_top); + sy1 = y_bottom - (sy1 - y_top); + t = sy0; sy0 = sy1; sy1 = t; + t = x_bottom; x_bottom = x_top; x_top = t; + dx = -dx; + dy = -dy; + t = x0; x0 = xb; xb = t; + } + //STBTT_assert(dy >= 0); + //STBTT_assert(dx >= 0); + + x1 = (int) x_top; + x2 = (int) x_bottom; + // compute intersection with y axis at x1+1 + y_crossing = y_top + dy * (x1+1 - x0); + + // compute intersection with y axis at x2 + y_final = y_top + dy * (x2 - x0); + + // x1 x_top x2 x_bottom + // y_top +------|-----+------------+------------+--------|---+------------+ + // | | | | | | + // | | | | | | + // sy0 | Txxxxx|............|............|............|............| + // y_crossing | *xxxxx.......|............|............|............| + // | | xxxxx..|............|............|............| + // | | /- xx*xxxx........|............|............| + // | | dy < | xxxxxx..|............|............| + // y_final | | \- | xx*xxx.........|............| + // sy1 | | | | xxxxxB...|............| + // | | | | | | + // | | | | | | + // y_bottom +------------+------------+------------+------------+------------+ + // + // goal is to measure the area covered by '.' in each pixel + + // if x2 is right at the right edge of x1, y_crossing can blow up, github #1057 + // @TODO: maybe test against sy1 rather than y_bottom? + if (y_crossing > y_bottom) + y_crossing = y_bottom; + + sign = e->direction; + + // area of the rectangle covered from sy0..y_crossing + area = sign * (y_crossing-sy0); + + // area of the triangle (x_top,sy0), (x1+1,sy0), (x1+1,y_crossing) + scanline[x1] += stbtt__sized_triangle_area(area, x1+1 - x_top); + + // check if final y_crossing is blown up; no test case for this + if (y_final > y_bottom) { + y_final = y_bottom; + dy = (y_final - y_crossing ) / (x2 - (x1+1)); // if denom=0, y_final = y_crossing, so y_final <= y_bottom + } + + // in second pixel, area covered by line segment found in first pixel + // is always a rectangle 1 wide * the height of that line segment; this + // is exactly what the variable 'area' stores. it also gets a contribution + // from the line segment within it. the THIRD pixel will get the first + // pixel's rectangle contribution, the second pixel's rectangle contribution, + // and its own contribution. the 'own contribution' is the same in every pixel except + // the leftmost and rightmost, a trapezoid that slides down in each pixel. + // the second pixel's contribution to the third pixel will be the + // rectangle 1 wide times the height change in the second pixel, which is dy. + + step = sign * dy * 1; // dy is dy/dx, change in y for every 1 change in x, + // which multiplied by 1-pixel-width is how much pixel area changes for each step in x + // so the area advances by 'step' every time + + for (x = x1+1; x < x2; ++x) { + scanline[x] += area + step/2; // area of trapezoid is 1*step/2 + area += step; + } + //STBTT_assert(STBTT_fabs(area) <= 1.01f); // accumulated error from area += step unless we round step down + //STBTT_assert(sy1 > y_final-0.01f); + + // area covered in the last pixel is the rectangle from all the pixels to the left, + // plus the trapezoid filled by the line segment in this pixel all the way to the right edge + scanline[x2] += area + sign * stbtt__position_trapezoid_area(sy1-y_final, (float) x2, x2+1.0f, x_bottom, x2+1.0f); + + // the rest of the line is filled based on the total height of the line segment in this pixel + scanline_fill[x2] += sign * (sy1-sy0); + } + } else { + // if edge goes outside of box we're drawing, we require + // clipping logic. since this does not match the intended use + // of this library, we use a different, very slow brute + // force implementation + // note though that this does happen some of the time because + // x_top and x_bottom can be extrapolated at the top & bottom of + // the shape and actually lie outside the bounding box + for (x=0; x < len; ++x) { + // cases: + // + // there can be up to two intersections with the pixel. any intersection + // with left or right edges can be handled by splitting into two (or three) + // regions. intersections with top & bottom do not necessitate case-wise logic. + // + // the old way of doing this found the intersections with the left & right edges, + // then used some simple logic to produce up to three segments in sorted order + // from top-to-bottom. however, this had a problem: if an x edge was epsilon + // across the x border, then the corresponding y position might not be distinct + // from the other y segment, and it might ignored as an empty segment. to avoid + // that, we need to explicitly produce segments based on x positions. + + // rename variables to clearly-defined pairs + y0 = y_top; + x1_clip = (float) (x); + x2_clip = (float) (x+1); + x3 = xb; + y3 = y_bottom; + + // x = e->x + e->dx * (y-y_top) + // (y-y_top) = (x - e->x) / e->dx + // y = (x - e->x) / e->dx + y_top + y1 = (x - x0) / dx + y_top; + y2 = (x+1 - x0) / dx + y_top; + + if (x0 < x1_clip && x3 > x2_clip) { // three segments descending down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1_clip,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1_clip,y1, x2_clip,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2_clip,y2, x3,y3); + } else if (x3 < x1_clip && x0 > x2_clip) { // three segments descending down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2_clip,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2_clip,y2, x1_clip,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1_clip,y1, x3,y3); + } else if (x0 < x1_clip && x3 > x1_clip) { // two segments across x, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1_clip,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1_clip,y1, x3,y3); + } else if (x3 < x1_clip && x0 > x1_clip) { // two segments across x, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x1_clip,y1); + stbtt__handle_clipped_edge(scanline,x,e, x1_clip,y1, x3,y3); + } else if (x0 < x2_clip && x3 > x2_clip) { // two segments across x+1, down-right + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2_clip,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2_clip,y2, x3,y3); + } else if (x3 < x2_clip && x0 > x2_clip) { // two segments across x+1, down-left + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x2_clip,y2); + stbtt__handle_clipped_edge(scanline,x,e, x2_clip,y2, x3,y3); + } else { // one segment + stbtt__handle_clipped_edge(scanline,x,e, x0,y0, x3,y3); + } + } + } + } + e = e->next; + } +} + +// directly AA rasterize edges w/o supersampling +static void stbtt__rasterize_sorted_edges(stbtt__bitmap *result, stbtt__edge *e, int n, int vsubsample, int off_x, int off_y, void *userdata) +{ + stbtt__hheap hh = { 0, 0, 0 }; + stbtt__active_edge *active = NULL; + int y,j=0, i; + float scanline_data[129], *scanline, *scanline2; + + // Variables moved outside loops for better performance + float scan_y_top, scan_y_bottom; + stbtt__active_edge **step; + stbtt__active_edge *z; + float sum; + float k; + int m; + + STBTT__NOTUSED(vsubsample); + + if (result->w > 64) + scanline = (float *) STBTT_malloc((result->w*2+1) * sizeof(float), userdata); + else + scanline = scanline_data; + + scanline2 = scanline + result->w; + + y = off_y; + e[n].y0 = (float) (off_y + result->h) + 1; + + while (j < result->h) { + // find center of pixel for this scanline + scan_y_top = y + 0.0f; + scan_y_bottom = y + 1.0f; + step = &active; + + STBTT_memset(scanline , 0, result->w*sizeof(scanline[0])); + STBTT_memset(scanline2, 0, (result->w+1)*sizeof(scanline[0])); + + // update all active edges; + // remove all active edges that terminate before the top of this scanline + while (*step) { + z = *step; + if (z->ey <= scan_y_top) { + *step = z->next; // delete from list + //STBTT_assert(z->direction); + z->direction = 0; + stbtt__hheap_free(&hh, z); + } else { + step = &((*step)->next); // advance through list + } + } + + // insert all edges that start before the bottom of this scanline + while (e->y0 <= scan_y_bottom) { + if (e->y0 != e->y1) { + z = stbtt__new_active(&hh, e, off_x, scan_y_top, userdata); + if (z != NULL) { + if (j == 0 && off_y != 0) { + if (z->ey < scan_y_top) { + // this can happen due to subpixel positioning and some kind of fp rounding error i think + z->ey = scan_y_top; + } + } + //STBTT_assert(z->ey >= scan_y_top); // if we get really unlucky a tiny bit of an edge can be out of bounds + // insert at front + z->next = active; + active = z; + } + } + ++e; + } + + // now process all active edges + if (active) + stbtt__fill_active_edges_new(scanline, scanline2+1, result->w, active, scan_y_top); + + { + sum = 0; + for (i=0; i < result->w; ++i) { + sum += scanline2[i]; + k = scanline[i] + sum; + k = (float) STBTT_fabs(k)*255 + 0.5f; + m = (int) k; + if (m > 255) m = 255; + result->pixels[j*result->stride + i] = (unsigned char) m; + } + } + // advance all the edges + step = &active; + while (*step) { + z = *step; + z->fx += z->fdx; // advance to position for current scanline + step = &((*step)->next); // advance through list + } + + ++y; + ++j; + } + + stbtt__hheap_cleanup(&hh, userdata); + + if (scanline != scanline_data) + STBTT_free(scanline, userdata); +} + +#else +#error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + +#define STBTT__COMPARE(a,b) ((a)->y0 < (b)->y0) + +static void stbtt__sort_edges_ins_sort(stbtt__edge *p, int n) +{ + int i,j; + int c; + stbtt__edge t; + for (i=1; i < n; ++i) { + t = p[i]; + stbtt__edge *a = &t; + j = i; + while (j > 0) { + stbtt__edge *b = &p[j-1]; + c = STBTT__COMPARE(a,b); + if (!c) break; + p[j] = p[j-1]; + --j; + } + if (i != j) + p[j] = t; + } +} + +static void stbtt__sort_edges_quicksort(stbtt__edge *p, int n) +{ + stbtt__edge t; + int c01,c12,c,m,i,j; + int z; + /* threshold for transitioning to insertion sort */ + while (n > 12) { + /* compute median of three */ + m = n >> 1; + c01 = STBTT__COMPARE(&p[0],&p[m]); + c12 = STBTT__COMPARE(&p[m],&p[n-1]); + /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ + if (c01 != c12) { + /* otherwise, we'll need to swap something else to middle */ + + c = STBTT__COMPARE(&p[0],&p[n-1]); + /* 0>mid && midn => n; 0 0 */ + /* 0n: 0>n => 0; 0 n */ + z = (c == c12) ? 0 : n-1; + t = p[z]; + p[z] = p[m]; + p[m] = t; + } + /* now p[m] is the median-of-three */ + /* swap it to the beginning so it won't move around */ + t = p[0]; + p[0] = p[m]; + p[m] = t; + + /* partition loop */ + i=1; + j=n-1; + for(;;) { + /* handling of equality is crucial here */ + /* for sentinels & efficiency with duplicates */ + for (;;++i) { + if (!STBTT__COMPARE(&p[i], &p[0])) break; + } + for (;;--j) { + if (!STBTT__COMPARE(&p[0], &p[j])) break; + } + /* make sure we haven't crossed */ + if (i >= j) break; + t = p[i]; + p[i] = p[j]; + p[j] = t; + + ++i; + --j; + } + /* recurse on smaller side, iterate on larger */ + if (j < (n-i)) { + stbtt__sort_edges_quicksort(p,j); + p = p+i; + n = n-i; + } else { + stbtt__sort_edges_quicksort(p+i, n-i); + n = j; + } + } +} + +static void stbtt__sort_edges(stbtt__edge *p, int n) +{ + stbtt__sort_edges_quicksort(p, n); + stbtt__sort_edges_ins_sort(p, n); +} + +typedef struct +{ + float x,y; +} stbtt__point; + +static void stbtt__rasterize(stbtt__bitmap *result, stbtt__point *pts, int *wcount, int windings, float scale_x, float scale_y, float shift_x, float shift_y, int off_x, int off_y, int invert, void *userdata) +{ + float y_scale_inv = invert ? -scale_y : scale_y; + stbtt__edge *e; + int n,i,j,k,m; +#if STBTT_RASTERIZER_VERSION == 1 + int vsubsample = result->h < 8 ? 15 : 5; +#elif STBTT_RASTERIZER_VERSION == 2 + int vsubsample = 1; +#else + #error "Unrecognized value of STBTT_RASTERIZER_VERSION" +#endif + // vsubsample should divide 255 evenly; otherwise we won't reach full opacity + + // now we have to blow out the windings into explicit edge lists + n = 0; + for (i=0; i < windings; ++i) + n += wcount[i]; + + e = (stbtt__edge *) STBTT_malloc(sizeof(*e) * (n+1), userdata); // add an extra one as a sentinel + if (e == 0) return; + n = 0; + + m=0; + int a, b; + for (i=0; i < windings; ++i) { + stbtt__point *p = pts + m; + m += wcount[i]; + j = wcount[i]-1; + for (k=0; k < wcount[i]; j=k++) { + a=k,b=j; + // skip the edge if horizontal + if (p[j].y == p[k].y) + continue; + // add edge from j to k to the list + e[n].invert = 0; + if (invert ? p[j].y > p[k].y : p[j].y < p[k].y) { + e[n].invert = 1; + a=j,b=k; + } + e[n].x0 = p[a].x * scale_x + shift_x; + e[n].y0 = (p[a].y * y_scale_inv + shift_y) * vsubsample; + e[n].x1 = p[b].x * scale_x + shift_x; + e[n].y1 = (p[b].y * y_scale_inv + shift_y) * vsubsample; + ++n; + } + } + + // now sort the edges by their highest point (should snap to integer, and then by x) + //STBTT_sort(e, n, sizeof(e[0]), stbtt__edge_compare); + stbtt__sort_edges(e, n); + + // now, traverse the scanlines and find the intersections on each scanline, use xor winding rule + stbtt__rasterize_sorted_edges(result, e, n, vsubsample, off_x, off_y, userdata); + + STBTT_free(e, userdata); +} + +static void stbtt__add_point(stbtt__point *points, int n, float x, float y) +{ + if (!points) return; // during first pass, it's unallocated + points[n].x = x; + points[n].y = y; +} + +// tessellate until threshold p is happy... @TODO warped to compensate for non-linear stretching +static int stbtt__tesselate_curve(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float objspace_flatness_squared, int n) +{ + // midpoint + float mx = (x0 + 2*x1 + x2)/4; + float my = (y0 + 2*y1 + y2)/4; + // versus directly drawn line + float dx = (x0+x2)/2 - mx; + float dy = (y0+y2)/2 - my; + if (n > 16) // 65536 segments on one curve better be enough! + return 1; + if (dx*dx+dy*dy > objspace_flatness_squared) { // half-pixel error allowed... need to be smaller if AA + stbtt__tesselate_curve(points, num_points, x0,y0, (x0+x1)/2.0f,(y0+y1)/2.0f, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_curve(points, num_points, mx,my, (x1+x2)/2.0f,(y1+y2)/2.0f, x2,y2, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x2,y2); + *num_points = *num_points+1; + } + return 1; +} + +static void stbtt__tesselate_cubic(stbtt__point *points, int *num_points, float x0, float y0, float x1, float y1, float x2, float y2, float x3, float y3, float objspace_flatness_squared, int n) +{ + // @TODO this "flatness" calculation is just made-up nonsense that seems to work well enough + float dx0 = x1-x0; + float dy0 = y1-y0; + float dx1 = x2-x1; + float dy1 = y2-y1; + float dx2 = x3-x2; + float dy2 = y3-y2; + float dx = x3-x0; + float dy = y3-y0; + float longlen = (float) (STBTT_sqrt(dx0*dx0+dy0*dy0)+STBTT_sqrt(dx1*dx1+dy1*dy1)+STBTT_sqrt(dx2*dx2+dy2*dy2)); + float shortlen = (float) STBTT_sqrt(dx*dx+dy*dy); + float flatness_squared = longlen*longlen-shortlen*shortlen; + + if (n > 16) // 65536 segments on one curve better be enough! + return; + + if (flatness_squared > objspace_flatness_squared) { + float x01 = (x0+x1)/2; + float y01 = (y0+y1)/2; + float x12 = (x1+x2)/2; + float y12 = (y1+y2)/2; + float x23 = (x2+x3)/2; + float y23 = (y2+y3)/2; + + float xa = (x01+x12)/2; + float ya = (y01+y12)/2; + float xb = (x12+x23)/2; + float yb = (y12+y23)/2; + + float mx = (xa+xb)/2; + float my = (ya+yb)/2; + + stbtt__tesselate_cubic(points, num_points, x0,y0, x01,y01, xa,ya, mx,my, objspace_flatness_squared,n+1); + stbtt__tesselate_cubic(points, num_points, mx,my, xb,yb, x23,y23, x3,y3, objspace_flatness_squared,n+1); + } else { + stbtt__add_point(points, *num_points,x3,y3); + *num_points = *num_points+1; + } +} + +// returns number of contours +static stbtt__point *stbtt_FlattenCurves(stbtt_vertex *vertices, int num_verts, float objspace_flatness, int **contour_lengths, int *num_contours, void *userdata) +{ + stbtt__point *points=0; + int num_points=0; + + float objspace_flatness_squared = objspace_flatness * objspace_flatness; + int i,n=0,start=0, pass; + + // count how many "moves" there are to get the contour count + for (i=0; i < num_verts; ++i) + if (vertices[i].type == STBTT_vmove) + ++n; + + *num_contours = n; + if (n == 0) return 0; + + *contour_lengths = (int *) STBTT_malloc(sizeof(**contour_lengths) * n, userdata); + + if (*contour_lengths == 0) { + *num_contours = 0; + return 0; + } + + float x,y; + // make two passes through the points so we don't need to realloc + for (pass=0; pass < 2; ++pass) { + x=0,y=0; + if (pass == 1) { + points = (stbtt__point *) STBTT_malloc(num_points * sizeof(points[0]), userdata); + if (points == NULL) goto error; + } + num_points = 0; + n= -1; + for (i=0; i < num_verts; ++i) { + switch (vertices[i].type) { + case STBTT_vmove: + // start the next contour + if (n >= 0) + (*contour_lengths)[n] = num_points - start; + ++n; + start = num_points; + + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x,y); + break; + case STBTT_vline: + x = vertices[i].x, y = vertices[i].y; + stbtt__add_point(points, num_points++, x, y); + break; + case STBTT_vcurve: + stbtt__tesselate_curve(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + case STBTT_vcubic: + stbtt__tesselate_cubic(points, &num_points, x,y, + vertices[i].cx, vertices[i].cy, + vertices[i].cx1, vertices[i].cy1, + vertices[i].x, vertices[i].y, + objspace_flatness_squared, 0); + x = vertices[i].x, y = vertices[i].y; + break; + } + } + (*contour_lengths)[n] = num_points - start; + } + + return points; +error: + STBTT_free(points, userdata); + STBTT_free(*contour_lengths, userdata); + *contour_lengths = 0; + *num_contours = 0; + return NULL; +} + +STBTT_DEF void stbtt_Rasterize(stbtt__bitmap *result, float flatness_in_pixels, stbtt_vertex *vertices, int num_verts, float scale_x, float scale_y, float shift_x, float shift_y, int x_off, int y_off, int invert, void *userdata) +{ + float scale = scale_x > scale_y ? scale_y : scale_x; + int winding_count = 0; + int *winding_lengths = NULL; + stbtt__point *windings = stbtt_FlattenCurves(vertices, num_verts, flatness_in_pixels / scale, &winding_lengths, &winding_count, userdata); + if (windings) { + stbtt__rasterize(result, windings, winding_lengths, winding_count, scale_x, scale_y, shift_x, shift_y, x_off, y_off, invert, userdata); + STBTT_free(winding_lengths, userdata); + STBTT_free(windings, userdata); + } +} + +STBTT_DEF void stbtt_FreeBitmap(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + int ix0,iy0,ix1,iy1; + stbtt__bitmap gbm; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + + if (scale_x == 0) scale_x = scale_y; + if (scale_y == 0) { + if (scale_x == 0) { + STBTT_free(vertices, info->userdata); + return NULL; + } + scale_y = scale_x; + } + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,&ix1,&iy1); + + // now we get the size + gbm.w = (ix1 - ix0); + gbm.h = (iy1 - iy0); + gbm.pixels = NULL; // in case we error + + if (width ) *width = gbm.w; + if (height) *height = gbm.h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + if (gbm.w && gbm.h) { + gbm.pixels = (unsigned char *) STBTT_malloc(gbm.w * gbm.h, info->userdata); + if (gbm.pixels) { + gbm.stride = gbm.w; + + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0, iy0, 1, info->userdata); + } + } + STBTT_free(vertices, info->userdata); + return gbm.pixels; +} + +STBTT_DEF unsigned char *stbtt_GetGlyphBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int glyph, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y, 0.0f, 0.0f, glyph, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int glyph) +{ + int ix0,iy0; + stbtt_vertex *vertices; + int num_verts = stbtt_GetGlyphShape(info, glyph, &vertices); + stbtt__bitmap gbm; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale_x, scale_y, shift_x, shift_y, &ix0,&iy0,0,0); + gbm.pixels = output; + gbm.w = out_w; + gbm.h = out_h; + gbm.stride = out_stride; + + if (gbm.w && gbm.h) + stbtt_Rasterize(&gbm, 0.35f, vertices, num_verts, scale_x, scale_y, shift_x, shift_y, ix0,iy0, 1, info->userdata); + + STBTT_free(vertices, info->userdata); +} + +STBTT_DEF void stbtt_MakeGlyphBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, glyph); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmapSubpixel(const stbtt_fontinfo *info, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphBitmapSubpixel(info, scale_x, scale_y,shift_x,shift_y, stbtt_FindGlyphIndex(info,codepoint), width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int oversample_x, int oversample_y, float *sub_x, float *sub_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixelPrefilter(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, oversample_x, oversample_y, sub_x, sub_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF void stbtt_MakeCodepointBitmapSubpixel(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int codepoint) +{ + stbtt_MakeGlyphBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, shift_x, shift_y, stbtt_FindGlyphIndex(info,codepoint)); +} + +STBTT_DEF unsigned char *stbtt_GetCodepointBitmap(const stbtt_fontinfo *info, float scale_x, float scale_y, int codepoint, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetCodepointBitmapSubpixel(info, scale_x, scale_y, 0.0f,0.0f, codepoint, width,height,xoff,yoff); +} + +STBTT_DEF void stbtt_MakeCodepointBitmap(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, int codepoint) +{ + stbtt_MakeCodepointBitmapSubpixel(info, output, out_w, out_h, out_stride, scale_x, scale_y, 0.0f,0.0f, codepoint); +} + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-CRAPPY packing to keep source code small + +static int stbtt_BakeFontBitmap_internal(unsigned char *data, int offset, // font location (use offset=0 for plain .ttf) + float pixel_height, // height of font in pixels + unsigned char *pixels, int pw, int ph, // bitmap to be filled in + int first_char, int num_chars, // characters to bake + stbtt_bakedchar *chardata) +{ + float scale; + int x,y,bottom_y, i; + stbtt_fontinfo f; + f.userdata = NULL; + if (!stbtt_InitFont(&f, data, offset)) + return -1; + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + x=y=1; + bottom_y = 1; + + scale = stbtt_ScaleForPixelHeight(&f, pixel_height); + + for (i=0; i < num_chars; ++i) { + int advance, lsb, x0,y0,x1,y1,gw,gh; + int g = stbtt_FindGlyphIndex(&f, first_char + i); + stbtt_GetGlyphHMetrics(&f, g, &advance, &lsb); + stbtt_GetGlyphBitmapBox(&f, g, scale,scale, &x0,&y0,&x1,&y1); + gw = x1-x0; + gh = y1-y0; + if (x + gw + 1 >= pw) + y = bottom_y, x = 1; // advance to next row + if (y + gh + 1 >= ph) // check if it fits vertically AFTER potentially moving to next row + return -i; + //STBTT_assert(x+gw < pw); + //STBTT_assert(y+gh < ph); + stbtt_MakeGlyphBitmap(&f, pixels+x+y*pw, gw,gh,pw, scale,scale, g); + chardata[i].x0 = (stbtt_int16) x; + chardata[i].y0 = (stbtt_int16) y; + chardata[i].x1 = (stbtt_int16) (x + gw); + chardata[i].y1 = (stbtt_int16) (y + gh); + chardata[i].xadvance = scale * advance; + chardata[i].xoff = (float) x0; + chardata[i].yoff = (float) y0; + x = x + gw + 1; + if (y+gh+1 > bottom_y) + bottom_y = y+gh+1; + } + return bottom_y; +} + +STBTT_DEF void stbtt_GetBakedQuad(const stbtt_bakedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int opengl_fillrule) +{ + float d3d_bias = opengl_fillrule ? 0 : -0.5f; + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_bakedchar *b = chardata + char_index; + int round_x = STBTT_ifloor((*xpos + b->xoff) + 0.5f); + int round_y = STBTT_ifloor((*ypos + b->yoff) + 0.5f); + + q->x0 = round_x + d3d_bias; + q->y0 = round_y + d3d_bias; + q->x1 = round_x + b->x1 - b->x0 + d3d_bias; + q->y1 = round_y + b->y1 - b->y0 + d3d_bias; + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// rectangle packing replacement routines if you don't have stb_rect_pack.h +// + +#ifndef STB_RECT_PACK_VERSION + +typedef int stbrp_coord; + +//////////////////////////////////////////////////////////////////////////////////// +// // +// // +// COMPILER WARNING ?!?!? // +// // +// // +// if you get a compile warning due to these symbols being defined more than // +// once, move #include "stb_rect_pack.h" before #include "stb_truetype.h" // +// // +//////////////////////////////////////////////////////////////////////////////////// + +typedef struct +{ + int width,height; + int x,y,bottom_y; +} stbrp_context; + +typedef struct +{ + unsigned char x; +} stbrp_node; + +struct stbrp_rect +{ + stbrp_coord x,y; + int id,w,h,was_packed; +}; + +static void stbrp_init_target(stbrp_context *con, int pw, int ph, stbrp_node *nodes, int num_nodes) +{ + con->width = pw; + con->height = ph; + con->x = 0; + con->y = 0; + con->bottom_y = 0; + STBTT__NOTUSED(nodes); + STBTT__NOTUSED(num_nodes); +} + +static void stbrp_pack_rects(stbrp_context *con, stbrp_rect *rects, int num_rects) +{ + int i; + for (i=0; i < num_rects; ++i) { + if (con->x + rects[i].w > con->width) { + con->x = 0; + con->y = con->bottom_y; + } + if (con->y + rects[i].h > con->height) + break; + rects[i].x = con->x; + rects[i].y = con->y; + rects[i].was_packed = 1; + con->x += rects[i].w; + if (con->y + rects[i].h > con->bottom_y) + con->bottom_y = con->y + rects[i].h; + } + for ( ; i < num_rects; ++i) + rects[i].was_packed = 0; +} +#endif + +////////////////////////////////////////////////////////////////////////////// +// +// bitmap baking +// +// This is SUPER-AWESOME (tm Ryan Gordon) packing using stb_rect_pack.h. If +// stb_rect_pack.h isn't available, it uses the BakeFontBitmap strategy. + +STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, unsigned char *pixels, int pw, int ph, int stride_in_bytes, int padding, void *alloc_context) +{ + stbrp_context *context = (stbrp_context *) STBTT_malloc(sizeof(*context) ,alloc_context); + int num_nodes = pw - padding; + stbrp_node *nodes = (stbrp_node *) STBTT_malloc(sizeof(*nodes ) * num_nodes,alloc_context); + + if (context == NULL || nodes == NULL) { + if (context != NULL) STBTT_free(context, alloc_context); + if (nodes != NULL) STBTT_free(nodes , alloc_context); + return 0; + } + + spc->user_allocator_context = alloc_context; + spc->width = pw; + spc->height = ph; + spc->pixels = pixels; + spc->pack_info = context; + spc->nodes = nodes; + spc->padding = padding; + spc->stride_in_bytes = stride_in_bytes != 0 ? stride_in_bytes : pw; + spc->h_oversample = 1; + spc->v_oversample = 1; + spc->skip_missing = 0; + + stbrp_init_target(context, pw-padding, ph-padding, nodes, num_nodes); + + if (pixels) + STBTT_memset(pixels, 0, pw*ph); // background of 0 around pixels + + return 1; +} + +STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc) +{ + STBTT_free(spc->nodes , spc->user_allocator_context); + STBTT_free(spc->pack_info, spc->user_allocator_context); +} + +STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample) +{ + //STBTT_assert(h_oversample <= STBTT_MAX_OVERSAMPLE); + //STBTT_assert(v_oversample <= STBTT_MAX_OVERSAMPLE); + if (h_oversample <= STBTT_MAX_OVERSAMPLE) + spc->h_oversample = h_oversample; + if (v_oversample <= STBTT_MAX_OVERSAMPLE) + spc->v_oversample = v_oversample; +} + +STBTT_DEF void stbtt_PackSetSkipMissingCodepoints(stbtt_pack_context *spc, int skip) +{ + spc->skip_missing = skip; +} + +#define STBTT__OVER_MASK (STBTT_MAX_OVERSAMPLE-1) + +static void stbtt__h_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_w = w - kernel_width; + int j; + int i; + unsigned int total; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < h; ++j) { + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_w; ++i) { + total += pixels[i] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i]; + pixels[i] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < w; ++i) { + //STBTT_assert(pixels[i] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i] = (unsigned char) (total / kernel_width); + } + + pixels += stride_in_bytes; + } +} + +static void stbtt__v_prefilter(unsigned char *pixels, int w, int h, int stride_in_bytes, unsigned int kernel_width) +{ + unsigned char buffer[STBTT_MAX_OVERSAMPLE]; + int safe_h = h - kernel_width; + int j; + int i; + unsigned int total; + STBTT_memset(buffer, 0, STBTT_MAX_OVERSAMPLE); // suppress bogus warning from VS2013 -analyze + for (j=0; j < w; ++j) { + STBTT_memset(buffer, 0, kernel_width); + + total = 0; + + // make kernel_width a constant in common cases so compiler can optimize out the divide + switch (kernel_width) { + case 2: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 2); + } + break; + case 3: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 3); + } + break; + case 4: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 4); + } + break; + case 5: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / 5); + } + break; + default: + for (i=0; i <= safe_h; ++i) { + total += pixels[i*stride_in_bytes] - buffer[i & STBTT__OVER_MASK]; + buffer[(i+kernel_width) & STBTT__OVER_MASK] = pixels[i*stride_in_bytes]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + break; + } + + for (; i < h; ++i) { + //STBTT_assert(pixels[i*stride_in_bytes] == 0); + total -= buffer[i & STBTT__OVER_MASK]; + pixels[i*stride_in_bytes] = (unsigned char) (total / kernel_width); + } + + pixels += 1; + } +} + +static float stbtt__oversample_shift(int oversample) +{ + if (!oversample) + return 0.0f; + + // The prefilter is a box filter of width "oversample", + // which shifts phase by (oversample - 1)/2 pixels in + // oversampled space. We want to shift in the opposite + // direction to counter this. + return (float)-(oversample - 1) / (2.0f * (float)oversample); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j; + int missing_glyph_added = 0; + float fh, scale; + int x0,y0,x1,y1; + int k=0; + int codepoint, glyph; + for (i=0; i < num_ranges; ++i) { + fh = ranges[i].font_size; + scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + ranges[i].h_oversample = (unsigned char) spc->h_oversample; + ranges[i].v_oversample = (unsigned char) spc->v_oversample; + for (j=0; j < ranges[i].num_chars; ++j) { + codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + glyph = stbtt_FindGlyphIndex(info, codepoint); + if (glyph == 0 && (spc->skip_missing || missing_glyph_added)) { + rects[k].w = rects[k].h = 0; + } else { + stbtt_GetGlyphBitmapBoxSubpixel(info,glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + &x0,&y0,&x1,&y1); + rects[k].w = (stbrp_coord) (x1-x0 + spc->padding + spc->h_oversample-1); + rects[k].h = (stbrp_coord) (y1-y0 + spc->padding + spc->v_oversample-1); + if (glyph == 0) + missing_glyph_added = 1; + } + ++k; + } + } + + return k; +} + +STBTT_DEF void stbtt_MakeGlyphBitmapSubpixelPrefilter(const stbtt_fontinfo *info, unsigned char *output, int out_w, int out_h, int out_stride, float scale_x, float scale_y, float shift_x, float shift_y, int prefilter_x, int prefilter_y, float *sub_x, float *sub_y, int glyph) +{ + stbtt_MakeGlyphBitmapSubpixel(info, + output, + out_w - (prefilter_x - 1), + out_h - (prefilter_y - 1), + out_stride, + scale_x, + scale_y, + shift_x, + shift_y, + glyph); + + if (prefilter_x > 1) + stbtt__h_prefilter(output, out_w, out_h, out_stride, prefilter_x); + + if (prefilter_y > 1) + stbtt__v_prefilter(output, out_w, out_h, out_stride, prefilter_y); + + *sub_x = stbtt__oversample_shift(prefilter_x); + *sub_y = stbtt__oversample_shift(prefilter_y); +} + +// rects array must be big enough to accommodate all characters in the given ranges +STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const stbtt_fontinfo *info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects) +{ + int i,j,k, missing_glyph = -1, return_value = 1; + + // save current values + int old_h_over = spc->h_oversample; + int old_v_over = spc->v_oversample; + float fh, scale; + float recip_h,recip_v,sub_x,sub_y; + + int advance, lsb, x0,y0,x1,y1; + int codepoint, glyph; + + k = 0; + for (i=0; i < num_ranges; ++i) { + fh = ranges[i].font_size; + scale = fh > 0 ? stbtt_ScaleForPixelHeight(info, fh) : stbtt_ScaleForMappingEmToPixels(info, -fh); + + spc->h_oversample = ranges[i].h_oversample; + spc->v_oversample = ranges[i].v_oversample; + recip_h = 1.0f / spc->h_oversample; + recip_v = 1.0f / spc->v_oversample; + sub_x = stbtt__oversample_shift(spc->h_oversample); + sub_y = stbtt__oversample_shift(spc->v_oversample); + for (j=0; j < ranges[i].num_chars; ++j) { + stbrp_rect *r = &rects[k]; + if (r->was_packed && r->w != 0 && r->h != 0) { + stbtt_packedchar *bc = &ranges[i].chardata_for_range[j]; + codepoint = ranges[i].array_of_unicode_codepoints == NULL ? ranges[i].first_unicode_codepoint_in_range + j : ranges[i].array_of_unicode_codepoints[j]; + glyph = stbtt_FindGlyphIndex(info, codepoint); + stbrp_coord pad = (stbrp_coord) spc->padding; + + // pad on left and top + r->x += pad; + r->y += pad; + r->w -= pad; + r->h -= pad; + stbtt_GetGlyphHMetrics(info, glyph, &advance, &lsb); + stbtt_GetGlyphBitmapBox(info, glyph, + scale * spc->h_oversample, + scale * spc->v_oversample, + &x0,&y0,&x1,&y1); + stbtt_MakeGlyphBitmapSubpixel(info, + spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w - spc->h_oversample+1, + r->h - spc->v_oversample+1, + spc->stride_in_bytes, + scale * spc->h_oversample, + scale * spc->v_oversample, + 0,0, + glyph); + + if (spc->h_oversample > 1) + stbtt__h_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->h_oversample); + + if (spc->v_oversample > 1) + stbtt__v_prefilter(spc->pixels + r->x + r->y*spc->stride_in_bytes, + r->w, r->h, spc->stride_in_bytes, + spc->v_oversample); + + bc->x0 = (stbtt_int16) r->x; + bc->y0 = (stbtt_int16) r->y; + bc->x1 = (stbtt_int16) (r->x + r->w); + bc->y1 = (stbtt_int16) (r->y + r->h); + bc->xadvance = scale * advance; + bc->xoff = (float) x0 * recip_h + sub_x; + bc->yoff = (float) y0 * recip_v + sub_y; + bc->xoff2 = (x0 + r->w) * recip_h + sub_x; + bc->yoff2 = (y0 + r->h) * recip_v + sub_y; + + if (glyph == 0) + missing_glyph = j; + } else if (spc->skip_missing) { + return_value = 0; + } else if (r->was_packed && r->w == 0 && r->h == 0 && missing_glyph >= 0) { + ranges[i].chardata_for_range[j] = ranges[i].chardata_for_range[missing_glyph]; + } else { + return_value = 0; // if any fail, report failure + } + + ++k; + } + } + + // restore original values + spc->h_oversample = old_h_over; + spc->v_oversample = old_v_over; + + return return_value; +} + +STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects) +{ + stbrp_pack_rects((stbrp_context *) spc->pack_info, rects, num_rects); +} + +STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges) +{ + stbtt_fontinfo info; + int i,j,n, return_value = 1; + //stbrp_context *context = (stbrp_context *) spc->pack_info; + stbrp_rect *rects; + + // flag all characters as NOT packed + for (i=0; i < num_ranges; ++i) + for (j=0; j < ranges[i].num_chars; ++j) + ranges[i].chardata_for_range[j].x0 = + ranges[i].chardata_for_range[j].y0 = + ranges[i].chardata_for_range[j].x1 = + ranges[i].chardata_for_range[j].y1 = 0; + + n = 0; + for (i=0; i < num_ranges; ++i) + n += ranges[i].num_chars; + + rects = (stbrp_rect *) STBTT_malloc(sizeof(*rects) * n, spc->user_allocator_context); + if (rects == NULL) + return 0; + + info.userdata = spc->user_allocator_context; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata,font_index)); + + n = stbtt_PackFontRangesGatherRects(spc, &info, ranges, num_ranges, rects); + + stbtt_PackFontRangesPackRects(spc, rects, n); + + return_value = stbtt_PackFontRangesRenderIntoRects(spc, &info, ranges, num_ranges, rects); + + STBTT_free(rects, spc->user_allocator_context); + return return_value; +} + +STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const unsigned char *fontdata, int font_index, float font_size, + int first_unicode_codepoint_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range) +{ + stbtt_pack_range range; + range.first_unicode_codepoint_in_range = first_unicode_codepoint_in_range; + range.array_of_unicode_codepoints = NULL; + range.num_chars = num_chars_in_range; + range.chardata_for_range = chardata_for_range; + range.font_size = font_size; + return stbtt_PackFontRanges(spc, fontdata, font_index, &range, 1); +} + +STBTT_DEF void stbtt_GetScaledFontVMetrics(const unsigned char *fontdata, int index, float size, float *ascent, float *descent, float *lineGap) +{ + int i_ascent, i_descent, i_lineGap; + float scale; + stbtt_fontinfo info; + stbtt_InitFont(&info, fontdata, stbtt_GetFontOffsetForIndex(fontdata, index)); + scale = size > 0 ? stbtt_ScaleForPixelHeight(&info, size) : stbtt_ScaleForMappingEmToPixels(&info, -size); + stbtt_GetFontVMetrics(&info, &i_ascent, &i_descent, &i_lineGap); + *ascent = (float) i_ascent * scale; + *descent = (float) i_descent * scale; + *lineGap = (float) i_lineGap * scale; +} + +STBTT_DEF void stbtt_GetPackedQuad(const stbtt_packedchar *chardata, int pw, int ph, int char_index, float *xpos, float *ypos, stbtt_aligned_quad *q, int align_to_integer) +{ + float ipw = 1.0f / pw, iph = 1.0f / ph; + const stbtt_packedchar *b = chardata + char_index; + + if (align_to_integer) { + float x = (float) STBTT_ifloor((*xpos + b->xoff) + 0.5f); + float y = (float) STBTT_ifloor((*ypos + b->yoff) + 0.5f); + q->x0 = x; + q->y0 = y; + q->x1 = x + b->xoff2 - b->xoff; + q->y1 = y + b->yoff2 - b->yoff; + } else { + q->x0 = *xpos + b->xoff; + q->y0 = *ypos + b->yoff; + q->x1 = *xpos + b->xoff2; + q->y1 = *ypos + b->yoff2; + } + + q->s0 = b->x0 * ipw; + q->t0 = b->y0 * iph; + q->s1 = b->x1 * ipw; + q->t1 = b->y1 * iph; + + *xpos += b->xadvance; +} + +////////////////////////////////////////////////////////////////////////////// +// +// sdf computation +// + +#define STBTT_min(a,b) ((a) < (b) ? (a) : (b)) +#define STBTT_max(a,b) ((a) < (b) ? (b) : (a)) + +static int stbtt__ray_intersect_bezier(float orig[2], float ray[2], float q0[2], float q1[2], float q2[2], float hits[2][2]) +{ + float q0perp = q0[1]*ray[0] - q0[0]*ray[1]; + float q1perp = q1[1]*ray[0] - q1[0]*ray[1]; + float q2perp = q2[1]*ray[0] - q2[0]*ray[1]; + float roperp = orig[1]*ray[0] - orig[0]*ray[1]; + + float a = q0perp - 2*q1perp + q2perp; + float b = q1perp - q0perp; + float c = q0perp - roperp; + + float s0 = 0., s1 = 0.; + int num_s = 0; + + if (a != 0.0) { + float discr = b*b - a*c; + if (discr > 0.0) { + float rcpna = -1 / a; + float d = (float) STBTT_sqrt(discr); + s0 = (b+d) * rcpna; + s1 = (b-d) * rcpna; + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + if (d > 0.0 && s1 >= 0.0 && s1 <= 1.0) { + if (num_s == 0) s0 = s1; + ++num_s; + } + } + } else { + // 2*b*s + c = 0 + // s = -c / (2*b) + s0 = c / (-2 * b); + if (s0 >= 0.0 && s0 <= 1.0) + num_s = 1; + } + + if (num_s == 0) + return 0; + else { + float rcp_len2 = 1 / (ray[0]*ray[0] + ray[1]*ray[1]); + float rayn_x = ray[0] * rcp_len2, rayn_y = ray[1] * rcp_len2; + + float q0d = q0[0]*rayn_x + q0[1]*rayn_y; + float q1d = q1[0]*rayn_x + q1[1]*rayn_y; + float q2d = q2[0]*rayn_x + q2[1]*rayn_y; + float rod = orig[0]*rayn_x + orig[1]*rayn_y; + + float q10d = q1d - q0d; + float q20d = q2d - q0d; + float q0rd = q0d - rod; + + hits[0][0] = q0rd + s0*(2.0f - 2.0f*s0)*q10d + s0*s0*q20d; + hits[0][1] = a*s0+b; + + if (num_s > 1) { + hits[1][0] = q0rd + s1*(2.0f - 2.0f*s1)*q10d + s1*s1*q20d; + hits[1][1] = a*s1+b; + return 2; + } else { + return 1; + } + } +} + +static int equal(float *a, float *b) +{ + return (a[0] == b[0] && a[1] == b[1]); +} + +static int stbtt__compute_crossings_x(float x, float y, int nverts, stbtt_vertex *verts) +{ + int i; + float orig[2], ray[2] = { 1, 0 }; + float y_frac; + int winding = 0; + + // Variables moved outside the loop for better performance + int x0, x1, y0, y1; // Used in both vline and vcurve cases + float x_inter; // Used for intersection calculation + int x2, y2; // Used in vcurve case + int ax, ay, by; // Used for bounding box calculations + float q0[2], q1[2], q2[2]; // Bezier curve points + float hits[2][2]; // Ray intersection results + int num_hits; // Number of intersections found + + // make sure y never passes through a vertex of the shape + y_frac = (float) STBTT_fmod(y, 1.0f); + if (y_frac < 0.01f) + y += 0.01f; + else if (y_frac > 0.99f) + y -= 0.01f; + orig[0] = x; + orig[1] = y; + + // test a ray from (-infinity,y) to (x,y) + for (i=0; i < nverts; ++i) { + if (verts[i].type == STBTT_vline) { + x0 = (int) verts[i-1].x; y0 = (int) verts[i-1].y; + x1 = (int) verts[i ].x; y1 = (int) verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } + if (verts[i].type == STBTT_vcurve) { + x0 = (int) verts[i-1].x ; y0 = (int) verts[i-1].y ; + x1 = (int) verts[i ].cx; y1 = (int) verts[i ].cy; + x2 = (int) verts[i ].x ; y2 = (int) verts[i ].y ; + ax = STBTT_min(x0,STBTT_min(x1,x2)); ay = STBTT_min(y0,STBTT_min(y1,y2)); + by = STBTT_max(y0,STBTT_max(y1,y2)); + if (y > ay && y < by && x > ax) { + q0[0] = (float)x0; + q0[1] = (float)y0; + q1[0] = (float)x1; + q1[1] = (float)y1; + q2[0] = (float)x2; + q2[1] = (float)y2; + if (equal(q0,q1) || equal(q1,q2)) { + x0 = (int)verts[i-1].x; + y0 = (int)verts[i-1].y; + x1 = (int)verts[i ].x; + y1 = (int)verts[i ].y; + if (y > STBTT_min(y0,y1) && y < STBTT_max(y0,y1) && x > STBTT_min(x0,x1)) { + x_inter = (y - y0) / (y1 - y0) * (x1-x0) + x0; + if (x_inter < x) + winding += (y0 < y1) ? 1 : -1; + } + } else { + num_hits = stbtt__ray_intersect_bezier(orig, ray, q0, q1, q2, hits); + if (num_hits >= 1) + if (hits[0][0] < 0) + winding += (hits[0][1] < 0 ? -1 : 1); + if (num_hits >= 2) + if (hits[1][0] < 0) + winding += (hits[1][1] < 0 ? -1 : 1); + } + } + } + } + return winding; // Fixed: was "wi" in original +} + +static float stbtt__cuberoot( float x ) +{ + if (x<0) + return -(float) STBTT_pow(-x,1.0f/3.0f); + else + return (float) STBTT_pow( x,1.0f/3.0f); +} + +// x^3 + a*x^2 + b*x + c = 0 +static int stbtt__solve_cubic(float a, float b, float c, float* r) +{ + float s = -a / 3; + float p = b - a*a / 3; + float q = a * (2*a*a - 9*b) / 27 + c; + float p3 = p*p*p; + float d = q*q + 4*p3 / 27; + if (d >= 0) { + float z = (float) STBTT_sqrt(d); + float u = (-q + z) / 2; + float v = (-q - z) / 2; + u = stbtt__cuberoot(u); + v = stbtt__cuberoot(v); + r[0] = s + u + v; + return 1; + } else { + float u = (float) STBTT_sqrt(-p/3); + float v = (float) STBTT_acos(-STBTT_sqrt(-27/p3) * q / 2) / 3; // p3 must be negative, since d is negative + float m = (float) STBTT_cos(v); + float n = (float) STBTT_cos(v-3.141592/2)*1.732050808f; + r[0] = s + u * 2 * m; + r[1] = s - u * (m + n); + r[2] = s - u * (m - n); + + //STBTT_assert( STBTT_fabs(((r[0]+a)*r[0]+b)*r[0]+c) < 0.05f); // these asserts may not be safe at all scales, though they're in bezier t parameter units so maybe? + //STBTT_assert( STBTT_fabs(((r[1]+a)*r[1]+b)*r[1]+c) < 0.05f); + //STBTT_assert( STBTT_fabs(((r[2]+a)*r[2]+b)*r[2]+c) < 0.05f); + return 3; + } +} + +STBTT_DEF unsigned char * stbtt_GetGlyphSDF(const stbtt_fontinfo *info, float scale, int glyph, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + float scale_x = scale, scale_y = scale; + int ix0,iy0,ix1,iy1; + int w,h; + unsigned char *data; + + if (scale == 0) return NULL; + + stbtt_GetGlyphBitmapBoxSubpixel(info, glyph, scale, scale, 0.0f,0.0f, &ix0,&iy0,&ix1,&iy1); + + // if empty, return NULL + if (ix0 == ix1 || iy0 == iy1) + return NULL; + + ix0 -= padding; + iy0 -= padding; + ix1 += padding; + iy1 += padding; + + w = (ix1 - ix0); + h = (iy1 - iy0); + + if (width ) *width = w; + if (height) *height = h; + if (xoff ) *xoff = ix0; + if (yoff ) *yoff = iy0; + + // invert for y-downwards bitmaps + scale_y = -scale_y; + + { + // distance from singular values (in the same units as the pixel grid) + const float eps = 1./1024, eps2 = eps*eps; + int x,y,i,j; + float *precompute; + stbtt_vertex *verts; + int num_verts = stbtt_GetGlyphShape(info, glyph, &verts); + + // Variables moved outside loops for better performance + float val; + float min_dist; + float sx, sy; + float x_gspace, y_gspace; + int winding; + float x0, y0, x1, y1, x2, y2; + float dist, dist2; + float dx, dy, px, py, t; + float box_x0, box_y0, box_x1, box_y1; + int num; + float ax, ay, bx, by, mx, my; + float res[3]; + float it; + float a_inv; + float a, b, c, d; + float discriminant, root; + + data = (unsigned char *) STBTT_malloc(w * h, info->userdata); + precompute = (float *) STBTT_malloc(num_verts * sizeof(float), info->userdata); + + float len2; + + for (i=0,j=num_verts-1; i < num_verts; j=i++) { + if (verts[i].type == STBTT_vline) { + x0 = verts[i].x*scale_x; y0 = verts[i].y*scale_y; + x1 = verts[j].x*scale_x; y1 = verts[j].y*scale_y; + dist = (float) STBTT_sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)); + precompute[i] = (dist < eps) ? 0.0f : 1.0f / dist; + } else if (verts[i].type == STBTT_vcurve) { + x2 = verts[j].x *scale_x; y2 = verts[j].y *scale_y; + x1 = verts[i].cx*scale_x; y1 = verts[i].cy*scale_y; + x0 = verts[i].x *scale_x; y0 = verts[i].y *scale_y; + bx = x0 - 2*x1 + x2; by = y0 - 2*y1 + y2; + len2 = bx*bx + by*by; + if (len2 >= eps2) + precompute[i] = 1.0f / len2; + else + precompute[i] = 0.0f; + } else + precompute[i] = 0.0f; + } + + for (y=iy0; y < iy1; ++y) { + for (x=ix0; x < ix1; ++x) { + min_dist = 999999.0f; + sx = (float) x + 0.5f; + sy = (float) y + 0.5f; + x_gspace = (sx / scale_x); + y_gspace = (sy / scale_y); + + winding = stbtt__compute_crossings_x(x_gspace, y_gspace, num_verts, verts); // @OPTIMIZE: this could just be a rasterization, but needs to be line vs. non-tesselated curves so a new path + + for (i=0; i < num_verts; ++i) { + x0 = verts[i].x*scale_x; y0 = verts[i].y*scale_y; + + if (verts[i].type == STBTT_vline && precompute[i] != 0.0f) { + x1 = verts[i-1].x*scale_x; y1 = verts[i-1].y*scale_y; + + dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + // coarse culling against bbox + //if (sx > STBTT_min(x0,x1)-min_dist && sx < STBTT_max(x0,x1)+min_dist && + // sy > STBTT_min(y0,y1)-min_dist && sy < STBTT_max(y0,y1)+min_dist) + dist = (float) STBTT_fabs((x1-x0)*(y0-sy) - (y1-y0)*(x0-sx)) * precompute[i]; + //STBTT_assert(i != 0); + if (dist < min_dist) { + // check position along line + // x' = x0 + t*(x1-x0), y' = y0 + t*(y1-y0) + // minimize (x'-sx)*(x'-sx)+(y'-sy)*(y'-sy) + dx = x1-x0; dy = y1-y0; + px = x0-sx; py = y0-sy; + // minimize (px+t*dx)^2 + (py+t*dy)^2 = px*px + 2*px*dx*t + t^2*dx*dx + py*py + 2*py*dy*t + t^2*dy*dy + // derivative: 2*px*dx + 2*py*dy + (2*dx*dx+2*dy*dy)*t, set to 0 and solve + t = -(px*dx + py*dy) / (dx*dx + dy*dy); + if (t >= 0.0f && t <= 1.0f) + min_dist = dist; + } + } else if (verts[i].type == STBTT_vcurve) { + x2 = verts[i-1].x *scale_x; y2 = verts[i-1].y *scale_y; + x1 = verts[i ].cx*scale_x; y1 = verts[i ].cy*scale_y; + box_x0 = STBTT_min(STBTT_min(x0,x1),x2); + box_y0 = STBTT_min(STBTT_min(y0,y1),y2); + box_x1 = STBTT_max(STBTT_max(x0,x1),x2); + box_y1 = STBTT_max(STBTT_max(y0,y1),y2); + // coarse culling against bbox to avoid computing cubic unnecessarily + if (sx > box_x0-min_dist && sx < box_x1+min_dist && sy > box_y0-min_dist && sy < box_y1+min_dist) { + num=0; + ax = x1-x0; ay = y1-y0; + bx = x0 - 2*x1 + x2; by = y0 - 2*y1 + y2; + mx = x0 - sx; my = y0 - sy; + res[0] = 0.f; res[1] = 0.f; res[2] = 0.f; + a_inv = precompute[i]; + if (a_inv == 0.0) { // if a_inv is 0, it's 2nd degree so use quadratic formula + a = 3*(ax*bx + ay*by); + b = 2*(ax*ax + ay*ay) + (mx*bx+my*by); + c = mx*ax+my*ay; + if (STBTT_fabs(a) < eps2) { // if a is 0, it's linear + if (STBTT_fabs(b) >= eps2) { + res[num++] = -c/b; + } + } else { + discriminant = b*b - 4*a*c; + if (discriminant < 0) + num = 0; + else { + root = (float) STBTT_sqrt(discriminant); + res[0] = (-b - root)/(2*a); + res[1] = (-b + root)/(2*a); + num = 2; // don't bother distinguishing 1-solution case, as code below will still work + } + } + } else { + b = 3*(ax*bx + ay*by) * a_inv; // could precompute this as it doesn't depend on sample point + c = (2*(ax*ax + ay*ay) + (mx*bx+my*by)) * a_inv; + d = (mx*ax+my*ay) * a_inv; + num = stbtt__solve_cubic(b, c, d, res); + } + dist2 = (x0-sx)*(x0-sx) + (y0-sy)*(y0-sy); + if (dist2 < min_dist*min_dist) + min_dist = (float) STBTT_sqrt(dist2); + + if (num >= 1 && res[0] >= 0.0f && res[0] <= 1.0f) { + t = res[0]; it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 2 && res[1] >= 0.0f && res[1] <= 1.0f) { + t = res[1]; it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + if (num >= 3 && res[2] >= 0.0f && res[2] <= 1.0f) { + t = res[2]; it = 1.0f - t; + px = it*it*x0 + 2*t*it*x1 + t*t*x2; + py = it*it*y0 + 2*t*it*y1 + t*t*y2; + dist2 = (px-sx)*(px-sx) + (py-sy)*(py-sy); + if (dist2 < min_dist * min_dist) + min_dist = (float) STBTT_sqrt(dist2); + } + } + } + } + if (winding == 0) + min_dist = -min_dist; // if outside the shape, value is negative + val = onedge_value + pixel_dist_scale * min_dist; + if (val < 0) + val = 0; + else if (val > 255) + val = 255; + data[(y-iy0)*w+(x-ix0)] = (unsigned char) val; + } + } + STBTT_free(precompute, info->userdata); + STBTT_free(verts, info->userdata); + } + return data; +} + +STBTT_DEF unsigned char * stbtt_GetCodepointSDF(const stbtt_fontinfo *info, float scale, int codepoint, int padding, unsigned char onedge_value, float pixel_dist_scale, int *width, int *height, int *xoff, int *yoff) +{ + return stbtt_GetGlyphSDF(info, scale, stbtt_FindGlyphIndex(info, codepoint), padding, onedge_value, pixel_dist_scale, width, height, xoff, yoff); +} + +STBTT_DEF void stbtt_FreeSDF(unsigned char *bitmap, void *userdata) +{ + STBTT_free(bitmap, userdata); +} + +////////////////////////////////////////////////////////////////////////////// +// +// font name matching -- recommended not to use this +// + +// check if a utf8 string contains a prefix which is the utf16 string; if so return length of matching utf8 string +static stbtt_int32 stbtt__CompareUTF8toUTF16_bigendian_prefix(stbtt_uint8 *s1, stbtt_int32 len1, stbtt_uint8 *s2, stbtt_int32 len2) +{ + stbtt_int32 i=0; + + // Variables moved outside the loop for better performance + stbtt_uint16 ch; + stbtt_uint32 c; + stbtt_uint16 ch2; + + // convert utf16 to utf8 and compare the results while converting + while (len2) { + ch = s2[0]*256 + s2[1]; + if (ch < 0x80) { + if (i >= len1) return -1; + if (s1[i++] != ch) return -1; + } else if (ch < 0x800) { + if (i+1 >= len1) return -1; + if (s1[i++] != 0xc0 + (ch >> 6)) return -1; + if (s1[i++] != 0x80 + (ch & 0x3f)) return -1; + } else if (ch >= 0xd800 && ch < 0xdc00) { + ch2 = s2[2]*256 + s2[3]; + if (i+3 >= len1) return -1; + c = ((ch - 0xd800) << 10) + (ch2 - 0xdc00) + 0x10000; + if (s1[i++] != 0xf0 + (c >> 18)) return -1; + if (s1[i++] != 0x80 + ((c >> 12) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((c ) & 0x3f)) return -1; + s2 += 2; // plus another 2 below + len2 -= 2; + } else if (ch >= 0xdc00 && ch < 0xe000) { + return -1; + } else { + if (i+2 >= len1) return -1; + if (s1[i++] != 0xe0 + (ch >> 12)) return -1; + if (s1[i++] != 0x80 + ((ch >> 6) & 0x3f)) return -1; + if (s1[i++] != 0x80 + ((ch ) & 0x3f)) return -1; + } + s2 += 2; + len2 -= 2; + } + return i; +} + +static int stbtt_CompareUTF8toUTF16_bigendian_internal(char *s1, int len1, char *s2, int len2) +{ + return len1 == stbtt__CompareUTF8toUTF16_bigendian_prefix((stbtt_uint8*) s1, len1, (stbtt_uint8*) s2, len2); +} + +// returns results in whatever encoding you request... but note that 2-byte encodings +// will be BIG-ENDIAN... use stbtt_CompareUTF8toUTF16_bigendian() to compare +STBTT_DEF const char *stbtt_GetFontNameString(const stbtt_fontinfo *font, int *length, int platformID, int encodingID, int languageID, int nameID) +{ + stbtt_int32 i,count,stringOffset; + stbtt_uint8 *fc = font->data; + stbtt_uint32 offset = font->fontstart; + stbtt_uint32 nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return NULL; + + count = ttUSHORT(fc+nm+2); + stringOffset = nm + ttUSHORT(fc+nm+4); + stbtt_uint32 loc; + for (i=0; i < count; ++i) { + loc = nm + 6 + 12 * i; + if (platformID == ttUSHORT(fc+loc+0) && encodingID == ttUSHORT(fc+loc+2) + && languageID == ttUSHORT(fc+loc+4) && nameID == ttUSHORT(fc+loc+6)) { + *length = ttUSHORT(fc+loc+8); + return (const char *) (fc+stringOffset+ttUSHORT(fc+loc+10)); + } + } + return NULL; +} + +static int stbtt__matchpair(stbtt_uint8 *fc, stbtt_uint32 nm, stbtt_uint8 *name, stbtt_int32 nlen, stbtt_int32 target_id, stbtt_int32 next_id) +{ + stbtt_int32 i; + stbtt_int32 count = ttUSHORT(fc+nm+2); + stbtt_int32 stringOffset = nm + ttUSHORT(fc+nm+4); + + // Variables moved outside the loop for better performance + stbtt_uint32 loc; + stbtt_int32 id; + stbtt_int32 platform, encoding, language; + stbtt_int32 slen, off; + stbtt_int32 matchlen; + + for (i=0; i < count; ++i) { + loc = nm + 6 + 12 * i; + id = ttUSHORT(fc+loc+6); + if (id == target_id) { + // find the encoding + platform = ttUSHORT(fc+loc+0); + encoding = ttUSHORT(fc+loc+2); + language = ttUSHORT(fc+loc+4); + // is this a Unicode encoding? + if (platform == 0 || (platform == 3 && encoding == 1) || (platform == 3 && encoding == 10)) { + slen = ttUSHORT(fc+loc+8); + off = ttUSHORT(fc+loc+10); + // check if there's a prefix match + matchlen = stbtt__CompareUTF8toUTF16_bigendian_prefix(name, nlen, fc+stringOffset+off,slen); + if (matchlen >= 0) { + // check for target_id+1 immediately following, with same encoding & language + if (i+1 < count && ttUSHORT(fc+loc+12+6) == next_id && ttUSHORT(fc+loc+12) == platform && ttUSHORT(fc+loc+12+2) == encoding && ttUSHORT(fc+loc+12+4) == language) { + slen = ttUSHORT(fc+loc+12+8); + off = ttUSHORT(fc+loc+12+10); + if (slen == 0) { + if (matchlen == nlen) + return 1; + } else if (matchlen < nlen && name[matchlen] == ' ') { + ++matchlen; + if (stbtt_CompareUTF8toUTF16_bigendian_internal((char*) (name+matchlen), nlen-matchlen, (char*)(fc+stringOffset+off),slen)) + return 1; + } + } else { + // if nothing immediately following + if (matchlen == nlen) + return 1; + } + } + } + // @TODO handle other encodings + } + } + return 0; +} + +static int stbtt__matches(stbtt_uint8 *fc, stbtt_uint32 offset, stbtt_uint8 *name, stbtt_int32 flags) +{ + stbtt_int32 nlen = (stbtt_int32) STBTT_strlen((char *) name); + stbtt_uint32 nm,hd; + if (!stbtt__isfont(fc+offset)) return 0; + + // check italics/bold/underline flags in macStyle... + if (flags) { + hd = stbtt__find_table(fc, offset, "head"); + if ((ttUSHORT(fc+hd+44) & 7) != (flags & 7)) return 0; + } + + nm = stbtt__find_table(fc, offset, "name"); + if (!nm) return 0; + + if (flags) { + // if we checked the macStyle flags, then just check the family and ignore the subfamily + if (stbtt__matchpair(fc, nm, name, nlen, 16, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, -1)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } else { + if (stbtt__matchpair(fc, nm, name, nlen, 16, 17)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 1, 2)) return 1; + if (stbtt__matchpair(fc, nm, name, nlen, 3, -1)) return 1; + } + + return 0; +} + +static int stbtt_FindMatchingFont_internal(unsigned char *font_collection, char *name_utf8, stbtt_int32 flags) +{ + stbtt_int32 i, off; + for (i=0;;++i) { + off = stbtt_GetFontOffsetForIndex(font_collection, i); + if (off < 0) return off; + if (stbtt__matches((stbtt_uint8 *) font_collection, off, (stbtt_uint8*) name_utf8, flags)) + return off; + } +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif + +STBTT_DEF int stbtt_BakeFontBitmap(const unsigned char *data, int offset, + float pixel_height, unsigned char *pixels, int pw, int ph, + int first_char, int num_chars, stbtt_bakedchar *chardata) +{ + return stbtt_BakeFontBitmap_internal((unsigned char *) data, offset, pixel_height, pixels, pw, ph, first_char, num_chars, chardata); +} + +STBTT_DEF int stbtt_GetFontOffsetForIndex(const unsigned char *data, int index) +{ + return stbtt_GetFontOffsetForIndex_internal((unsigned char *) data, index); +} + +STBTT_DEF int stbtt_GetNumberOfFonts(const unsigned char *data) +{ + return stbtt_GetNumberOfFonts_internal((unsigned char *) data); +} + +STBTT_DEF int stbtt_InitFont(stbtt_fontinfo *info, const unsigned char *data, int offset) +{ + return stbtt_InitFont_internal(info, (unsigned char *) data, offset); +} + +STBTT_DEF int stbtt_FindMatchingFont(const unsigned char *fontdata, const char *name, int flags) +{ + return stbtt_FindMatchingFont_internal((unsigned char *) fontdata, (char *) name, flags); +} + +STBTT_DEF int stbtt_CompareUTF8toUTF16_bigendian(const char *s1, int len1, const char *s2, int len2) +{ + return stbtt_CompareUTF8toUTF16_bigendian_internal((char *) s1, len1, (char *) s2, len2); +} + +#if defined(__GNUC__) || defined(__clang__) +#pragma GCC diagnostic pop +#endif + +#endif // STB_TRUETYPE_IMPLEMENTATION + + +// FULL VERSION HISTORY +// +// 1.25 (2021-07-11) many fixes +// 1.24 (2020-02-05) fix warning +// 1.23 (2020-02-02) query SVG data for glyphs; query whole kerning table (but only kern not GPOS) +// 1.22 (2019-08-11) minimize missing-glyph duplication; fix kerning if both 'GPOS' and 'kern' are defined +// 1.21 (2019-02-25) fix warning +// 1.20 (2019-02-07) PackFontRange skips missing codepoints; GetScaleFontVMetrics() +// 1.19 (2018-02-11) OpenType GPOS kerning (horizontal only), STBTT_fmod +// 1.18 (2018-01-29) add missing function +// 1.17 (2017-07-23) make more arguments const; doc fix +// 1.16 (2017-07-12) SDF support +// 1.15 (2017-03-03) make more arguments const +// 1.14 (2017-01-16) num-fonts-in-TTC function +// 1.13 (2017-01-02) support OpenType fonts, certain Apple fonts +// 1.12 (2016-10-25) suppress warnings about casting away const with -Wcast-qual +// 1.11 (2016-04-02) fix unused-variable warning +// 1.10 (2016-04-02) allow user-defined fabs() replacement +// fix memory leak if fontsize=0.0 +// fix warning from duplicate typedef +// 1.09 (2016-01-16) warning fix; avoid crash on outofmem; use alloc userdata for PackFontRanges +// 1.08 (2015-09-13) document stbtt_Rasterize(); fixes for vertical & horizontal edges +// 1.07 (2015-08-01) allow PackFontRanges to accept arrays of sparse codepoints; +// allow PackFontRanges to pack and render in separate phases; +// fix stbtt_GetFontOFfsetForIndex (never worked for non-0 input?); +// fixed an assert() bug in the new rasterizer +// replace assert() with STBTT_assert() in new rasterizer +// 1.06 (2015-07-14) performance improvements (~35% faster on x86 and x64 on test machine) +// also more precise AA rasterizer, except if shapes overlap +// remove need for STBTT_sort +// 1.05 (2015-04-15) fix misplaced definitions for STBTT_STATIC +// 1.04 (2015-04-15) typo in example +// 1.03 (2015-04-12) STBTT_STATIC, fix memory leak in new packing, various fixes +// 1.02 (2014-12-10) fix various warnings & compile issues w/ stb_rect_pack, C++ +// 1.01 (2014-12-08) fix subpixel position when oversampling to exactly match +// non-oversampled; STBTT_POINT_SIZE for packed case only +// 1.00 (2014-12-06) add new PackBegin etc. API, w/ support for oversampling +// 0.99 (2014-09-18) fix multiple bugs with subpixel rendering (ryg) +// 0.9 (2014-08-07) support certain mac/iOS fonts without an MS platformID +// 0.8b (2014-07-07) fix a warning +// 0.8 (2014-05-25) fix a few more warnings +// 0.7 (2013-09-25) bugfix: subpixel glyph bug fixed in 0.5 had come back +// 0.6c (2012-07-24) improve documentation +// 0.6b (2012-07-20) fix a few more warnings +// 0.6 (2012-07-17) fix warnings; added stbtt_ScaleForMappingEmToPixels, +// stbtt_GetFontBoundingBox, stbtt_IsGlyphEmpty +// 0.5 (2011-12-09) bugfixes: +// subpixel glyph renderer computed wrong bounding box +// first vertex of shape can be off-curve (FreeSans) +// 0.4b (2011-12-03) fixed an error in the font baking example +// 0.4 (2011-12-01) kerning, subpixel rendering (tor) +// bugfixes for: +// codepoint-to-glyph conversion using table fmt=12 +// codepoint-to-glyph conversion using table fmt=4 +// stbtt_GetBakedQuad with non-square texture (Zer) +// updated Hello World! sample to use kerning and subpixel +// fixed some warnings +// 0.3 (2009-06-24) cmap fmt=12, compound shapes (MM) +// userdata, malloc-from-userdata, non-zero fill (stb) +// 0.2 (2009-03-11) Fix unsigned/signed char warnings +// 0.1 (2009-03-09) First public release +// + +/* +------------------------------------------------------------------------------ +This software is available under 2 licenses -- choose whichever you prefer. +------------------------------------------------------------------------------ +ALTERNATIVE A - MIT License +Copyright (c) 2017 Sean Barrett +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies +of the Software, and to permit persons to whom the Software is furnished to do +so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +------------------------------------------------------------------------------ +ALTERNATIVE B - Public Domain (www.unlicense.org) +This is free and unencumbered software released into the public domain. +Anyone is free to copy, modify, publish, use, compile, sell, or distribute this +software, either in source code form or as a compiled binary, for any purpose, +commercial or non-commercial, and by any means. +In jurisdictions that recognize copyright laws, the author or authors of this +software dedicate any and all copyright interest in the software to the public +domain. We make this dedication for the benefit of the public at large and to +the detriment of our heirs and successors. We intend this dedication to be an +overt act of relinquishment in perpetuity of all present and future rights to +this software under copyright law. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN +ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +------------------------------------------------------------------------------ +*/ \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp new file mode 100644 index 00000000..155bde55 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp @@ -0,0 +1,12860 @@ +/******************************************************************************** + * Custom Fork Information + * + * File: tesla.hpp + * Author: ppkantorski + * Description: + * This file serves as the core logic for the Ultrahand Overlay project's custom fork + * of libtesla, an overlay executor. Within this file, you will find a collection of + * functions, menu structures, and interaction logic designed to facilitate the + * smooth execution and flexible customization of overlays within the project. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +/** + * Copyright (C) 2020 werwolv + * + * This file is part of libtesla. + * + * libtesla 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 2 of the License, or + * (at your option) any later version. + * + * libtesla 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 libtesla. If not, see . + */ + + +#pragma once + + +#include +#include +#include + +#include +#include + +#if !IS_LAUNCHER_DIRECTIVE +#include // unused, but preserved for projects that might need it +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +// Define this makro before including tesla.hpp in your main file. If you intend +// to use the tesla.hpp header in more than one source file, only define it once! + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-function" + +#ifdef TESLA_INIT_IMPL + #define STB_TRUETYPE_IMPLEMENTATION +#endif +#include "stb_truetype.h" + +#pragma GCC diagnostic pop + +#define ELEMENT_BOUNDS(elem) elem->getX(), elem->getY(), elem->getWidth(), elem->getHeight() + +#define ASSERT_EXIT(x) if (R_FAILED(x)) std::exit(1) +#define ASSERT_FATAL(x) if (Result res = x; R_FAILED(res)) fatalThrow(res) + +#define PACKED __attribute__((packed)) +#define ALWAYS_INLINE inline __attribute__((always_inline)) + +/// Evaluates an expression that returns a result, and returns the result if it would fail. +#define TSL_R_TRY(resultExpr) \ + ({ \ + const auto result = resultExpr; \ + if (R_FAILED(result)) { \ + return result; \ + } \ + }) + +using namespace std::literals::string_literals; +using namespace std::literals::chrono_literals; // potentially unused, restored for softare compatibility + +#if IS_STATUS_MONITOR_DIRECTIVE + +struct KeyPairHash { + std::size_t operator()(const std::pair& key) const { + // Combine hashes of both components + union returnValue { + char c[8]; + std::size_t s; + } value; + memcpy(&value.c[0], &key.first, 4); + memcpy(&value.c[4], &key.second, 4); + return value.s; + } +}; + +// Custom equality comparison for int-float pairs +struct KeyPairEqual { + bool operator()(const std::pair& lhs, const std::pair& rhs) const { + return lhs.first == rhs.first && + std::abs(lhs.second - rhs.second) < 0.00001f; + } +}; + +inline u8 TeslaFPS = 60; +inline std::atomic triggerExitNow{false}; +inline std::atomic isRendering{false}; +inline std::atomic delayUpdate{false}; +inline std::atomic pendingExit{false}; +inline std::atomic wasRendering{false}; + +inline LEvent renderingStopEvent; +inline bool FullMode = true; +inline bool deactivateOriginalFooter = false; +inline bool disableJumpTo = false; + +inline std::string lastMode; +inline std::set overlayModes = {"full", "mini", "micro", "fps_graph", "fps_counter", "game_resolutions"}; + +inline bool isValidOverlayMode() { + return overlayModes.count(lastMode) > 0; +} + +#endif + +#if USING_FPS_INDICATOR_DIRECTIVE +inline float fps = 0.0; +inline int frameCount = 0; +inline double elapsedTime = 0.0; +#endif + + +// Custom variables +inline std::atomic jumpToTop{false}; +inline std::atomic jumpToBottom{false}; +inline std::atomic skipUp{false}; +inline std::atomic skipDown{false}; +inline u32 offsetWidthVar = 112; +inline std::string lastOverlayFilename; +inline std::string lastOverlayMode; + +inline std::mutex jumpItemMutex; +inline std::string jumpItemName; +inline std::string jumpItemValue; +inline std::atomic jumpItemExactMatch{true}; + +inline std::atomic s_onLeftPage{false}; +inline std::atomic s_onRightPage{false}; +inline std::atomic screenshotsAreDisabled{false}; +inline std::atomic screenshotsAreForceDisabled{false}; + +inline bool hideHidden = false; +inline bool usingUnfocusedColor = true; +inline bool bypassUnfocused = false; + +inline std::atomic mainComboHasTriggered{false}; +inline std::atomic launchComboHasTriggered{false}; +inline std::atomic feedbackPollerStop{false}; +inline std::atomic hidReinitInProgress{false}; + + +// Sound triggering variables +inline std::atomic triggerNavigationSound{false}; +inline std::atomic triggerEnterSound{false}; +inline std::atomic triggerExitSound{false}; +inline std::atomic triggerWallSound{false}; +inline std::atomic triggerOnSound{false}; +inline std::atomic triggerOffSound{false}; +inline std::atomic triggerSettingsSound{false}; +inline std::atomic triggerMoveSound{false}; +inline std::atomic triggerNotificationSound{false}; +inline std::atomic disableSound{false}; +inline std::atomic disableHaptics{false}; +inline std::atomic reloadIfDockedChangedNow{false}; +inline std::atomic reloadSoundCacheNow{false}; + +// Haptic triggering variables +inline std::atomic triggerInitHaptics{false}; +inline std::atomic triggerRumbleClick{false}; +inline std::atomic triggerRumbleDoubleClick{false}; + + +__attribute__((noinline)) static void triggerFeedbackImpl( + std::atomic& rumble, std::atomic& sound) { + rumble.store(true, std::memory_order_release); + sound.store(true, std::memory_order_release); +} +inline void triggerNavigationFeedback() { triggerFeedbackImpl(triggerRumbleClick, triggerNavigationSound); } +inline void triggerWallFeedback() { triggerFeedbackImpl(triggerRumbleClick, triggerWallSound); } +inline void triggerEnterFeedback() { triggerFeedbackImpl(triggerRumbleClick, triggerEnterSound); } +inline void triggerExitFeedback() { triggerFeedbackImpl(triggerRumbleDoubleClick, triggerExitSound); } + + +/** + * @brief Checks if an NRO file uses new libnx (has LNY2 tag). + * + * @param filePath The path to the NRO file. + * @return true if the file uses new libnx (LNY2 present), false otherwise. + * Defined in tesla.cpp — file I/O + malloc body is too large to inline. + */ +bool usingLNY2(const std::string& filePath); + +/** + * @brief Checks if the current AMS version is at least the specified version. + * + * @param major Minimum major version required + * @param minor Minimum minor version required + * @param patch Minimum patch version required + * @return true if current AMS version >= specified version, false otherwise + */ +inline bool amsVersionAtLeast(uint8_t major, uint8_t minor, uint8_t patch) { + u64 packed_version; + if (R_FAILED(splGetConfig((SplConfigItem)65000, &packed_version))) { + return false; + } + + return ((packed_version >> 40) & 0xFFFFFF) >= static_cast((major << 16) | (minor << 8) | patch); +} + +inline bool requiresLNY2 = false; + + +namespace tsl { + + // Shared static specialChars vectors — avoids duplicate static init at each call site + inline const std::vector s_dividerSpecialChars = {ult::DIVIDER_SYMBOL}; + inline const std::vector s_footerSpecialChars = {"\uE0E1","\uE0E0","\uE0ED","\uE0EE","\uE0E5"}; + + // Booleans + inline std::atomic clearGlyphCacheNow(false); + + // Constants + namespace cfg { + + constexpr u32 ScreenWidth = 1920; ///< Width of the Screen + constexpr u32 ScreenHeight = 1080; ///< Height of the Screen + constexpr u32 LayerMaxWidth = 1280; + constexpr u32 LayerMaxHeight = 720; + + extern u16 LayerWidth; ///< Width of the Tesla layer + extern u16 LayerHeight; ///< Height of the Tesla layer + extern u16 LayerPosX; ///< X position of the Tesla layer + extern u16 LayerPosY; ///< Y position of the Tesla layer + extern u16 FramebufferWidth; ///< Width of the framebuffer + extern u16 FramebufferHeight; ///< Height of the framebuffer + extern u64 launchCombo; ///< Overlay activation key combo + extern u64 launchCombo2; ///< Overlay activation key combo + + } + + /** + * @brief RGBA4444 Color structure + */ + struct Color { + union { + struct { + u16 r: 4, g: 4, b: 4, a: 4; + } PACKED; + u16 rgba; + }; + + constexpr inline Color() : rgba(0) {} + constexpr inline Color(u16 raw) : rgba(raw) {} + constexpr inline Color(u8 r, u8 g, u8 b, u8 a) : r(r), g(g), b(b), a(a) {} + }; + + // Ultra-fast version - zero variables, optimized calculations + inline constexpr Color GradientColor(float temperature) { + if (temperature <= 35.0f) return Color(7, 7, 15, 0xF); + if (temperature >= 65.0f) return Color(15, 0, 0, 0xF); + + if (temperature < 45.0f) { + // Single calculation, avoid repetition + const float factor = (temperature - 35.0f) * 0.1f; + return Color(7 - 7 * factor, 7 + 8 * factor, 15 - 15 * factor, 0xF); + } + + if (temperature < 55.0f) { + return Color(15 * (temperature - 45.0f) * 0.1f, 15, 0, 0xF); + } + + return Color(15, 15 - 15 * (temperature - 55.0f) * 0.1f, 0, 0xF); + } + + + // Ultra-fast version - single variable, minimal branching + inline Color RGB888(const std::string& hexColor, size_t alpha = 15, const std::string& defaultHexColor = ult::whiteColor) { + const char* h = hexColor.size() == 6 ? hexColor.data() : + hexColor.size() == 7 && hexColor[0] == '#' ? hexColor.data() + 1 : + defaultHexColor.data(); + + return Color( + (ult::hexMap[h[0]] << 4 | ult::hexMap[h[1]]) >> 4, + (ult::hexMap[h[2]] << 4 | ult::hexMap[h[3]]) >> 4, + (ult::hexMap[h[4]] << 4 | ult::hexMap[h[5]]) >> 4, + alpha + ); + } + + inline Color lerpColor(const Color& c1, const Color& c2, float t) { + return { + static_cast((c1.r - c2.r) * t + c2.r + 0.5f), + static_cast((c1.g - c2.g) * t + c2.g + 0.5f), + static_cast((c1.b - c2.b) * t + c2.b + 0.5f), + 0xF + }; + } + + + namespace style { + constexpr u32 ListItemDefaultHeight = 70; ///< Standard list item height + constexpr u32 MiniListItemDefaultHeight = 40; ///< Mini list item height + constexpr u32 TrackBarDefaultHeight = 83; ///< Standard track bar height + constexpr u8 ListItemHighlightSaturation = 7; ///< Maximum saturation of Listitem highlights + constexpr u8 ListItemHighlightLength = 22; ///< Maximum length of Listitem highlights + + namespace color { + constexpr Color ColorFrameBackground = { 0x0, 0x0, 0x0, 0xD }; ///< Overlay frame background color + constexpr Color ColorTransparent = { 0x0, 0x0, 0x0, 0x0 }; ///< Transparent color + constexpr Color ColorHighlight = { 0x0, 0xF, 0xD, 0xF }; ///< Greenish highlight color + constexpr Color ColorFrame = { 0x7, 0x7, 0x7, 0x7 }; ///< Outer boarder color + constexpr Color ColorHandle = { 0x5, 0x5, 0x5, 0xF }; ///< Track bar handle color + constexpr Color ColorText = { 0xF, 0xF, 0xF, 0xF }; ///< Standard text color + constexpr Color ColorDescription = { 0xA, 0xA, 0xA, 0xF }; ///< Description text color + constexpr Color ColorHeaderBar = { 0xC, 0xC, 0xC, 0xF }; ///< Category header rectangle color + constexpr Color ColorClickAnimation = { 0x0, 0x2, 0x2, 0xF }; ///< Element click animation color + } + } + + inline bool overrideBackButton = false; // for properly overriding the automatic "go back" functionality of KEY_B button presses + inline bool disableHiding = false; // for manually disabling the hide overlay functionality + + // Theme color variable definitions — defined once in tesla.cpp + extern Color logoColor1; + extern Color logoColor2; + + extern size_t defaultBackgroundAlpha; + + extern Color defaultBackgroundColor; + extern Color defaultTextColor; + extern Color notificationTextColor; + extern Color notificationTitleColor; + extern Color notificationTimeColor; + extern Color headerTextColor; + extern Color headerSeparatorColor; + extern Color starColor; + extern Color selectionStarColor; + extern Color buttonColor; + extern Color bottomTextColor; + extern Color bottomSeparatorColor; + extern Color unfocusedColor; + extern Color topSeparatorColor; + + extern Color defaultOverlayColor; + extern Color defaultPackageColor; + extern Color defaultScriptColor; + extern Color clockColor; + extern Color temperatureColor; + extern Color batteryColor; + extern Color batteryChargingColor; + extern Color batteryLowColor; + extern size_t widgetBackdropAlpha; + extern Color widgetBackdropColor; + + extern Color overlayTextColor; + extern Color ultOverlayTextColor; + extern Color packageTextColor; + extern Color ultPackageTextColor; + + extern Color bannerVersionTextColor; + extern Color overlayVersionTextColor; + extern Color ultOverlayVersionTextColor; + extern Color packageVersionTextColor; + extern Color ultPackageVersionTextColor; + extern Color onTextColor; + extern Color offTextColor; + + #if IS_LAUNCHER_DIRECTIVE + extern Color dynamicLogoRGB1; + extern Color dynamicLogoRGB2; + #endif + + extern bool invertBGClickColor; + + extern size_t selectionBGAlpha; + extern Color selectionBGColor; + + extern Color highlightColor1; + extern Color highlightColor2; + extern Color highlightColor3; + extern Color highlightColor4; + + extern Color s_highlightColor; + + extern size_t clickAlpha; + extern Color clickColor; + + extern size_t progressAlpha; + extern Color progressColor; + + extern Color scrollBarColor; + extern Color scrollBarWallColor; + + extern size_t separatorAlpha; + extern Color separatorColor; + extern const Color edgeSeparatorColor; + + extern Color textSeparatorColor; + + extern Color selectedTextColor; + extern Color selectedValueTextColor; + extern Color inprogressTextColor; + extern Color invalidTextColor; + extern Color clickTextColor; + + extern size_t tableBGAlpha; + extern Color tableBGColor; + extern Color sectionTextColor; + extern Color infoTextColor; + extern Color warningTextColor; + + extern Color healthyRamTextColor; + extern Color neutralRamTextColor; + extern Color badRamTextColor; + + extern Color trackBarSliderColor; + extern Color trackBarSliderBorderColor; + extern Color trackBarSliderMalleableColor; + extern Color trackBarFullColor; + extern Color trackBarEmptyColor; + + // Prepare a map of default settings + struct ThemeDefault { const char* key; const char* value; }; + extern const ThemeDefault defaultThemeSettings[]; + extern const size_t defaultThemeSettingsCount; + const char* getThemeDefault(const char* key); + + bool isValidHexColor(std::string_view hexColor); + + // Defined in tesla.cpp — reads theme INI and populates all color vars above + void initializeThemeVars(); + + void initializeTheme(const std::string& themeIniPath = ult::THEME_CONFIG_INI_PATH); + + extern std::vector wrapText( + const std::string& text, + float maxWidth, + const std::string& wrappingMode, + bool useIndent, + const std::string& indent, + float indentWidth, + size_t fontSize + ); + + // Declarations + + /** + * @brief Direction in which focus moved before landing on + * the currently focused element + */ + enum class FocusDirection { + None, ///< Focus was placed on the element programatically without user input + Up, ///< Focus moved upwards + Down, ///< Focus moved downwards + Left, ///< Focus moved from left to rigth + Right ///< Focus moved from right to left + }; + + /** + * @brief Current input controll mode + * + */ + enum class InputMode { + Controller, ///< Input from controller + Touch, ///< Touch input + TouchScroll ///< Moving/scrolling touch input + }; + + class Overlay; + namespace elm { class Element; } + + void shiftItemFocus(elm::Element* element); // forward declare + + namespace impl { + + /** + * @brief Overlay launch parameters + */ + enum class LaunchFlags : u8 { + None = 0, ///< Do nothing special at launch + CloseOnExit = BIT(0) ///< Close the overlay the last Gui gets poped from the stack + }; + + static constexpr LaunchFlags operator|(LaunchFlags lhs, LaunchFlags rhs) { + return static_cast(u8(lhs) | u8(rhs)); + } + + + + } + + void goBack(u32 count = 1); + + void pop(u32 count = 1); + + void setNextOverlay(const std::string& ovlPath, std::string args = ""); + + template + int loop(int argc, char** argv); + + // Helpers + + namespace hlp { + + /** + * @brief Wrapper for service initialization + * + * @param f wrapped function + */ + template + static inline void doWithSmSession(F f) { + smInitialize(); + f(); + smExit(); + } + + /** + * @brief Wrapper for sd card access using stdio + * @note Consider using raw fs calls instead as they are faster and need less space + * + * @param f wrapped function + */ + template + static inline void doWithSDCardHandle(F f) { + fsdevMountSdmc(); + f(); + fsdevUnmountDevice("sdmc"); + } + + /** + * @brief Guard that will execute a passed function at the end of the current scope + * + * @param f wrapped function + */ + template + class ScopeGuard { + public: + ScopeGuard(const ScopeGuard&) = delete; + ScopeGuard& operator=(const ScopeGuard&) = delete; + + ALWAYS_INLINE explicit ScopeGuard(F func) : f(std::move(func)) { } + ALWAYS_INLINE ~ScopeGuard() { if (!canceled) { f(); } } + void dismiss() { canceled = true; } + + private: + F f; + bool canceled = false; + }; + + /** + * @brief libnx hid:sys shim that gives or takes away frocus to or from the process with the given aruid + * + * @param enable Give focus or take focus + * @param aruid Aruid of the process to focus/unfocus + * @return Result Result + */ + static Result hidsysEnableAppletToGetInput(bool enable, u64 aruid) { + const struct { + u8 permitInput; + u64 appletResourceUserId; + } in = { enable != 0, aruid }; + + return serviceDispatchIn(hidsysGetServiceSession(), 503, in); + } + + static Result viAddToLayerStack(ViLayer *layer, ViLayerStack stack) { + const struct { + u32 stack; + u64 layerId; + } in = { stack, layer->layer_id }; + + return serviceDispatchIn(viGetSession_IManagerDisplayService(), 6000, in); + } + + /** + * @brief Remove layer from layer stack + */ + static Result viRemoveFromLayerStack(ViLayer *layer, ViLayerStack stack) { + const struct { + u32 stack; + u64 layerId; + } in = { stack, layer->layer_id }; + + // Service command 6001 is commonly used for remove operations + // If this doesn't work, try 6002, 6010, or other nearby values + return serviceDispatchIn(viGetSession_IManagerDisplayService(), 6001, in); + } + + /** + * @brief Toggles focus between the Tesla overlay and the rest of the system + * + * @param enabled Focus Tesla? + */ + void requestForeground(bool enabled, bool updateGlobalFlag = true); + + + // Deprecated code, no longer used but preserved for consistency + namespace ini { + + /** + * @brief Ini file type + */ + using IniData = std::map>; + + /** + * @brief Parses a ini string + * + * @param str String to parse + * @return Parsed data + * // Modified to be "const std" instead of just "std" + */ + static IniData parseIni(const std::string &str) { + return ult::parseIni(str); + } + + /** + * @brief Unparses ini data into a string + * + * @param iniData Ini data + * @return Ini string + */ + std::string unparseIni(const IniData &iniData); + + + /** + * @brief Read Tesla settings file + * + * @return Settings data + */ + static IniData readOverlaySettings(auto& CONFIG_FILE) { + /* Open Sd card filesystem. */ + FsFileSystem fsSdmc; + if (R_FAILED(fsOpenSdCardFileSystem(&fsSdmc))) + return {}; + hlp::ScopeGuard fsGuard([&] { fsFsClose(&fsSdmc); }); + + /* Open config file. */ + FsFile fileConfig; + if (R_FAILED(fsFsOpenFile(&fsSdmc, CONFIG_FILE, FsOpenMode_Read, &fileConfig))) + return {}; + hlp::ScopeGuard fileGuard([&] { fsFileClose(&fileConfig); }); + + /* Get config file size. */ + s64 configFileSize; + if (R_FAILED(fsFileGetSize(&fileConfig, &configFileSize))) + return {}; + + /* Read and parse config file. */ + std::string configFileData(configFileSize, '\0'); + u64 readSize; + Result rc = fsFileRead(&fileConfig, 0, configFileData.data(), configFileSize, FsReadOption_None, &readSize); + if (R_FAILED(rc) || readSize != static_cast(configFileSize)) + return {}; + + return ult::parseIni(configFileData); + } + + /** + * @brief Replace Tesla settings file with new data + * + * @param iniData new data + */ + static void writeOverlaySettings(IniData const &iniData, auto& CONFIG_FILE) { + /* Open Sd card filesystem. */ + FsFileSystem fsSdmc; + if (R_FAILED(fsOpenSdCardFileSystem(&fsSdmc))) + return; + hlp::ScopeGuard fsGuard([&] { fsFsClose(&fsSdmc); }); + + /* Open config file. */ + FsFile fileConfig; + if (R_FAILED(fsFsOpenFile(&fsSdmc, CONFIG_FILE, FsOpenMode_Write, &fileConfig))) + return; + hlp::ScopeGuard fileGuard([&] { fsFileClose(&fileConfig); }); + + const std::string iniString = unparseIni(iniData); + + fsFileWrite(&fileConfig, 0, iniString.c_str(), iniString.length(), FsWriteOption_Flush); + } + + /** + * @brief Merge and save changes into Tesla settings file + * + * @param changes setting values to add or update + */ + static void updateOverlaySettings(IniData const &changes, auto& CONFIG_FILE) { + hlp::ini::IniData iniData = hlp::ini::readOverlaySettings(CONFIG_FILE); + for (auto §ion : changes) { + for (auto &keyValue : section.second) { + iniData[section.first][keyValue.first] = keyValue.second; + } + } + writeOverlaySettings(iniData, CONFIG_FILE); + } + + } + + /** + * @brief Decodes a key string into it's key code + * + * @param value Key string + * @return Key code + */ + static u64 stringToKeyCode(const std::string& value) { + for (const auto& keyInfo : ult::KEYS_INFO) { + if (strcasecmp(value.c_str(), keyInfo.name) == 0) + return keyInfo.key; + } + return 0; + } + + + /** + * @brief Decodes a combo string into key codes + * + * @param value Combo string + * @return Key codes + */ + static u64 comboStringToKeys(const std::string &value) { + u64 keyCombo = 0x00; + for (const auto& key : ult::split(ult::removeWhiteSpaces(value), '+')) { + keyCombo |= hlp::stringToKeyCode(key); + } + return keyCombo; + } + + /** + * @brief Encodes key codes into a combo string + * + * @param keys Key codes + * @return Combo string + */ + std::string keysToComboString(u64 keys); + + inline static std::mutex comboMutex; + + // Function to load key combo mappings from both overlays.ini and packages.ini + void loadEntryKeyCombos(); + + // Function to check if a key combination matches any overlay key combo + static OverlayCombo getEntryForKeyCombo(u64 keys) { + std::lock_guard lock(comboMutex); + if (auto it = ult::g_entryCombos.find(keys); it != ult::g_entryCombos.end()) + return it->second; + return { "", "" }; + } + + } + + + + // Renderer + + namespace gfx { + + extern "C" u64 __nx_vi_layer_id; + + + struct ScissoringConfig { + u32 x, y, w, h, x_max, y_max; + }; + + + // Forward declarations + class Renderer; + + inline static std::shared_mutex s_translationCacheMutex; + + class FontManager { + public: + struct Glyph { + stbtt_fontinfo *currFont; + float currFontSize; + int bounds[4]; + int xAdvance; + u8 *glyphBmp; + int width, height; + + ~Glyph() { + if (glyphBmp) { + stbtt_FreeBitmap(glyphBmp, nullptr); + glyphBmp = nullptr; + } + } + + Glyph(const Glyph&) = delete; + Glyph& operator=(const Glyph&) = delete; + + Glyph(Glyph&& other) noexcept + : currFont(other.currFont), currFontSize(other.currFontSize) + , xAdvance(other.xAdvance), glyphBmp(other.glyphBmp) + , width(other.width), height(other.height) { + memcpy(bounds, other.bounds, sizeof(bounds)); + other.glyphBmp = nullptr; + } + + Glyph& operator=(Glyph&& other) noexcept { + if (this != &other) { + if (glyphBmp) stbtt_FreeBitmap(glyphBmp, nullptr); + currFont = other.currFont; + currFontSize = other.currFontSize; + xAdvance = other.xAdvance; + glyphBmp = other.glyphBmp; + width = other.width; + height = other.height; + memcpy(bounds, other.bounds, sizeof(bounds)); + other.glyphBmp = nullptr; + } + return *this; + } + + Glyph() : currFont(nullptr), currFontSize(0.0f), xAdvance(0), + glyphBmp(nullptr), width(0), height(0) { + std::memset(bounds, 0, sizeof(bounds)); + } + }; + + struct FontMetrics { + int ascent, descent, lineGap; + int lineHeight; + stbtt_fontinfo* font; + float fontSize; + + FontMetrics() : ascent(0), descent(0), lineGap(0), lineHeight(0), font(nullptr), fontSize(0.0f) {} + + FontMetrics(stbtt_fontinfo* f, float size) : font(f), fontSize(size) { + if (font) { + stbtt_GetFontVMetrics(font, &ascent, &descent, &lineGap); + const float scale = stbtt_ScaleForPixelHeight(font, fontSize); + ascent = static_cast(ascent * scale); + descent = static_cast(descent * scale); + lineGap = static_cast(lineGap * scale); + lineHeight = ascent - descent + lineGap; + } else { + ascent = descent = lineGap = lineHeight = 0; + } + } + }; + + enum class CacheType { Regular, Notification }; + + private: + inline static std::shared_mutex s_cacheMutex; + inline static std::mutex s_initMutex; + + inline static std::unordered_map> s_sharedGlyphCache; + inline static std::unordered_map> s_notificationGlyphCache; + inline static std::unordered_map s_fontMetricsCache; + + static constexpr size_t MAX_CACHE_SIZE = 600; + static constexpr size_t CLEANUP_THRESHOLD = 500; + static constexpr size_t MAX_NOTIFICATION_CACHE_SIZE = 200; + + inline static stbtt_fontinfo* s_stdFont = nullptr; + inline static stbtt_fontinfo* s_localFont = nullptr; + inline static stbtt_fontinfo* s_localFontCN = nullptr; + inline static stbtt_fontinfo* s_localFontTW = nullptr; + inline static stbtt_fontinfo* s_localFontKO = nullptr; + inline static stbtt_fontinfo* s_extFont = nullptr; + inline static bool s_hasLocalFont = false; + inline static bool s_initialized = false; + + static u64 generateCacheKey(u32 character, bool monospace, u32 fontSize) { + u64 key = (static_cast(character) << 32) | static_cast(fontSize); + if (monospace) key |= (1ULL << 63); + return key; + } + + static u64 generateFontMetricsCacheKey(stbtt_fontinfo* font, u32 fontSize) { + return (reinterpret_cast(font) << 32) | static_cast(fontSize); + } + + // Consolidated trim — replaces cleanupOldEntries + cleanupNotificationCache + static void trimCache(std::unordered_map>& cache, size_t target) { + if (cache.size() <= target) return; + size_t toRemove = cache.size() - target; + for (auto it = cache.begin(); toRemove-- && it != cache.end();) + it = cache.erase(it); + } + + // Single helper to clear + release bucket memory — used everywhere + template + static void clearMap(std::unordered_map& m) { + m.clear(); + m.rehash(0); + } + + // Assumes lock already held by caller + static void clearAllUnsafe() { + clearMap(s_sharedGlyphCache); + clearMap(s_notificationGlyphCache); + clearMap(s_fontMetricsCache); + } + + static std::shared_ptr getOrCreateGlyphInternal(u32 character, bool monospace, u32 fontSize, CacheType cacheType) { + const u64 key = generateCacheKey(character, monospace, fontSize); + auto& targetCache = (cacheType == CacheType::Notification) + ? s_notificationGlyphCache : s_sharedGlyphCache; + + { + std::shared_lock readLock(s_cacheMutex); + if (!s_initialized) return nullptr; + auto it = targetCache.find(key); + if (it != targetCache.end()) return it->second; + } + + std::unique_lock writeLock(s_cacheMutex); + if (!s_initialized) return nullptr; + + // Double-checked + auto it = targetCache.find(key); + if (it != targetCache.end()) return it->second; + + if (cacheType == CacheType::Regular) + trimCache(s_sharedGlyphCache, CLEANUP_THRESHOLD); + else + trimCache(s_notificationGlyphCache, MAX_NOTIFICATION_CACHE_SIZE / 2); + + auto glyph = std::make_shared(); + glyph->currFont = selectFontForCharacterUnsafe(character); + if (!glyph->currFont) return nullptr; + + glyph->currFontSize = stbtt_ScaleForPixelHeight(glyph->currFont, fontSize); + + stbtt_GetCodepointBitmapBoxSubpixel(glyph->currFont, character, + glyph->currFontSize, glyph->currFontSize, 0, 0, + &glyph->bounds[0], &glyph->bounds[1], &glyph->bounds[2], &glyph->bounds[3]); + + s32 yAdvance = 0; + stbtt_GetCodepointHMetrics(glyph->currFont, monospace ? 'W' : character, + &glyph->xAdvance, &yAdvance); + + glyph->glyphBmp = stbtt_GetCodepointBitmap(glyph->currFont, + glyph->currFontSize, glyph->currFontSize, character, + &glyph->width, &glyph->height, nullptr, nullptr); + + targetCache[key] = glyph; + return glyph; + } + + static stbtt_fontinfo* selectFontForCharacterUnsafe(u32 character) { + if (!s_initialized) return nullptr; + if (stbtt_FindGlyphIndex(s_extFont, character)) return s_extFont; + if (character == 0x00B0) return s_stdFont; + if (s_hasLocalFont && stbtt_FindGlyphIndex(s_localFont, character)) return s_localFont; + if (stbtt_FindGlyphIndex(s_stdFont, character)) return s_stdFont; + if (stbtt_FindGlyphIndex(s_localFontCN, character)) return s_localFontCN; + if (stbtt_FindGlyphIndex(s_localFontTW, character)) return s_localFontTW; + if (stbtt_FindGlyphIndex(s_localFontKO, character)) return s_localFontKO; + return s_stdFont; + } + + public: + static void initializeFonts(stbtt_fontinfo* stdFont, + stbtt_fontinfo* localFont, + stbtt_fontinfo* localFontCN, + stbtt_fontinfo* localFontTW, + stbtt_fontinfo* localFontKO, + stbtt_fontinfo* extFont, + bool hasLocalFont) { + std::lock_guard initLock(s_initMutex); + std::unique_lock cacheLock(s_cacheMutex); + s_stdFont = stdFont; + s_localFont = localFont; + s_localFontCN = localFontCN; + s_localFontTW = localFontTW; + s_localFontKO = localFontKO; + s_extFont = extFont; + s_hasLocalFont = hasLocalFont; + s_initialized = true; + } + + static stbtt_fontinfo* selectFontForCharacter(u32 character) { + std::shared_lock lock(s_cacheMutex); + return selectFontForCharacterUnsafe(character); + } + + static FontMetrics getFontMetrics(stbtt_fontinfo* font, u32 fontSize) { + if (!font) return FontMetrics(); + const u64 key = generateFontMetricsCacheKey(font, fontSize); + { + std::shared_lock readLock(s_cacheMutex); + auto it = s_fontMetricsCache.find(key); + if (it != s_fontMetricsCache.end()) return it->second; + } + std::unique_lock writeLock(s_cacheMutex); + auto it = s_fontMetricsCache.find(key); + if (it != s_fontMetricsCache.end()) return it->second; + FontMetrics metrics(font, static_cast(fontSize)); + s_fontMetricsCache[key] = metrics; + return metrics; + } + + static FontMetrics getFontMetricsForCharacter(u32 character, u32 fontSize) { + return getFontMetrics(selectFontForCharacter(character), fontSize); + } + + [[nodiscard]] static std::shared_ptr getOrCreateGlyph(u32 character, bool monospace, u32 fontSize) { + return getOrCreateGlyphInternal(character, monospace, fontSize, CacheType::Regular); + } + + [[nodiscard]] static std::shared_ptr getOrCreateNotificationGlyph(u32 character, bool monospace, u32 fontSize) { + return getOrCreateGlyphInternal(character, monospace, fontSize, CacheType::Notification); + } + + static void clearNotificationCache() { + std::unique_lock lock(s_cacheMutex); + clearMap(s_notificationGlyphCache); + } + + static void clearCache() { + std::unique_lock lock(s_cacheMutex); + clearMap(s_sharedGlyphCache); + clearMap(s_fontMetricsCache); + } + + static void clearAllCaches() { + std::unique_lock lock(s_cacheMutex); + clearAllUnsafe(); + } + + static void cleanup() { + std::lock_guard initLock(s_initMutex); + std::unique_lock cacheLock(s_cacheMutex); + clearAllUnsafe(); + s_initialized = false; + s_stdFont = nullptr; + s_localFont = nullptr; + s_localFontCN = nullptr; + s_localFontTW = nullptr; + s_localFontKO = nullptr; + s_extFont = nullptr; + s_hasLocalFont = false; + } + + static bool isInitialized() { + std::shared_lock lock(s_cacheMutex); + return s_initialized; + } + + #ifndef NDEBUG + static size_t getCacheSize() { + std::shared_lock lock(s_cacheMutex); + return s_sharedGlyphCache.size(); + } + + static size_t getNotificationCacheSize() { + std::shared_lock lock(s_cacheMutex); + return s_notificationGlyphCache.size(); + } + + static size_t getFontMetricsCacheSize() { + std::shared_lock lock(s_cacheMutex); + return s_fontMetricsCache.size(); + } + + static size_t getMemoryUsage() { + std::shared_lock lock(s_cacheMutex); + size_t total = 0; + auto countCache = [&](const std::unordered_map>& cache) { + for (const auto& [k, g] : cache) + if (g && g->glyphBmp) total += g->width * g->height; + }; + countCache(s_sharedGlyphCache); + countCache(s_notificationGlyphCache); + return total; + } + #endif + }; + + // Updated thread-safe calculateStringWidth function + float calculateStringWidth(const std::string& originalString, const float fontSize, const bool monospace = false); + + static std::pair getUnderscanPixels(); + + /** + * @brief Manages the Tesla layer and draws raw data to the screen + */ + class Renderer final { + public: + + using Glyph = FontManager::Glyph; + + Renderer& operator=(Renderer&) = delete; + + friend class tsl::Overlay; + + /** + * @brief Gets the renderer instance + * + * @return Renderer + */ + inline static Renderer& get() { + static Renderer renderer; + + return renderer; + } + + stbtt_fontinfo m_stdFont, m_extFont; + stbtt_fontinfo m_localFont; // Primary font based on system language + stbtt_fontinfo m_localFontCN; // Chinese Simplified - always loaded + stbtt_fontinfo m_localFontTW; // Chinese Traditional - always loaded + stbtt_fontinfo m_localFontKO; // Korean - always loaded + bool m_hasLocalFont = false; // Whether primary local font is valid + + static inline float s_opacity = 1.0F; + + /** + * @brief Handles opacity of drawn colors for fadeout. Pass all colors through this function in order to apply opacity properly + * + * @param c Original color + * @return Color with applied opacity + */ + static inline Color a(const Color& c) { + const u8 opacity_limit = static_cast(0xF * Renderer::s_opacity); + return (c.rgba & 0x0FFF) | (static_cast( + ult::disableTransparency + ? (ult::useOpaqueScreenshots + ? 0xF // fully opaque when both flags on + : (c.a > 0xE ? c.a : 0xE)) // clamp to 14, keep lower values + : (c.a < opacity_limit ? c.a : opacity_limit) // normal fade logic + ) << 12); + } + + static inline Color aWithOpacity(const Color& c) { + const u8 opacity_limit = static_cast(0xF * Renderer::s_opacity); + return (c.rgba & 0x0FFF) | (static_cast( + ult::disableTransparency + ? 0xF // fully opaque when both flags on + : (c.a < opacity_limit ? c.a : opacity_limit) // normal fade logic + ) << 12); + } + + static inline Color a2(const Color& c) { + if (!ult::disableTransparency) + return c; + const u8 a = ult::useOpaqueScreenshots ? 0xF : (c.a > 0xE ? c.a : 0xE); + return (c.rgba & 0x0FFF) | (static_cast(a) << 12); + } + + /** + * @brief Enables scissoring, discarding of any draw outside the given boundaries + * + * @param x x pos + * @param y y pos + * @param w Width + * @param h Height + */ + inline void enableScissoring(const u32 x, const u32 y, const u32 w, const u32 h) { + this->m_scissoringStack.emplace(x, y, w, h, x+w, y+h); + } + + /** + * @brief Disables scissoring + */ + inline void disableScissoring() { + this->m_scissoringStack.pop(); + } + + + // Drawing functions + + /** + * @brief Draw a single pixel onto the screen + * + * @param x X pos + * @param y Y pos + * @param color Color + */ + inline void setPixel(const u32 x, const u32 y, const Color& color) { + const u32 offset = this->getPixelOffset(x, y); + if (offset != UINT32_MAX) [[likely]] { + Color* framebuffer = static_cast(this->getCurrentFramebuffer()); + framebuffer[offset] = color; + } + } + + inline void setPixelAtOffset(const u32 offset, const Color& color) { + Color* framebuffer = static_cast(this->getCurrentFramebuffer()); + framebuffer[offset] = color; + } + + + + /** + * @brief Blends two colors + * + * @param src Source color + * @param dst Destination color + * @param alpha Opacity + * @return Blended color + */ + static constexpr u8 inv_alpha_table[16] = {15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0}; + + inline u8 __attribute__((always_inline)) blendColor(const u8 src, const u8 dst, const u8 alpha) { + return ((src * inv_alpha_table[alpha]) + (dst * alpha)) >> 4; + } + + /** + * @brief Draws a single source blended pixel onto the screen + * + * @param x X pos + * @param y Y pos + * @param color Color + */ + inline void setPixelBlendSrc(const u32 x, const u32 y, const Color& color) { + const u32 offset = this->getPixelOffset(x, y); + if (offset == UINT32_MAX) [[unlikely]] + return; + + Color* framebuffer = static_cast(this->getCurrentFramebuffer()); + const Color src = framebuffer[offset]; + + // Direct write instead of calling setPixel + framebuffer[offset] = Color( + blendColor(src.r, color.r, color.a), + blendColor(src.g, color.g, color.a), + blendColor(src.b, color.b, color.a), + src.a + ); + } + + + // Compromise version - keep framebuffer lookup but inline the rest + inline void setPixelBlendDst(const u32 x, const u32 y, const Color& color) { + const u32 offset = this->getPixelOffset(x, y); + if (offset == UINT32_MAX) [[unlikely]] + return; + + Color* framebuffer = static_cast(this->getCurrentFramebuffer()); + const Color src = framebuffer[offset]; + + // Direct write instead of calling setPixel + framebuffer[offset] = Color( + blendColor(src.r, color.r, color.a), + blendColor(src.g, color.g, color.a), + blendColor(src.b, color.b, color.a), + (color.a + (src.a * (0xF - color.a) >> 4)) + ); + } + + // Batch version for setPixelBlendDst + inline void setPixelBlendDstBatch(const u32 baseX, const u32 baseY, + const u8 red[16], const u8 green[16], + const u8 blue[16], const u8 alpha[16], + const s32 count) { + Color* framebuffer = static_cast(this->getCurrentFramebuffer()); + + for (s32 i = 0; i < count; ++i) { + // Early exit for transparent pixels + const u8 currentAlpha = alpha[i]; + if (currentAlpha == 0) [[unlikely]] + continue; + + const u32 offset = this->getPixelOffset(baseX + i, baseY); + if (offset == UINT32_MAX) [[unlikely]] + continue; + + // Direct framebuffer read + const Color src = framebuffer[offset]; + const u8 invAlpha = 0xF - currentAlpha; + + // Direct framebuffer write - skip setPixelAtOffset call + framebuffer[offset] = Color( + blendColor(src.r, red[i], currentAlpha), + blendColor(src.g, green[i], currentAlpha), + blendColor(src.b, blue[i], currentAlpha), + currentAlpha + ((src.a * invAlpha) >> 4) + ); + } + } + + + /** + * @brief Draws a rectangle of given sizes + * + * @param x X pos + * @param y Y pos + * @param w Width + * @param h Height + * @param color Color + */ + inline void drawRect(const s32 x, const s32 y, const s32 w, const s32 h, const Color& color) { + // Early exit for invalid dimensions + //if (w <= 0 || h <= 0) return; + + // Calculate clipped bounds + const s32 x_start = x < 0 ? 0 : x; + const s32 y_start = y < 0 ? 0 : y; + const s32 x_end = (x + w > cfg::FramebufferWidth) ? cfg::FramebufferWidth : x + w; + const s32 y_end = (y + h > cfg::FramebufferHeight) ? cfg::FramebufferHeight : y + h; + + // Early exit if completely outside bounds + if (x_start >= x_end || y_start >= y_end) [[unlikely]] return; + + + this->processRectChunk(x_start, x_end, y_start, y_end, color); + } + + /** + * @brief Worker function for multithreaded rectangle drawing + * @param x_start Start X coordinate + * @param x_end End X coordinate + * @param y_start Start Y coordinate for this thread + * @param y_end End Y coordinate for this thread + * @param color Color to draw + */ + inline void processRectChunk(const s32 x_start, const s32 x_end, const s32 y_start, const s32 y_end, const Color& color) { + for (s32 yi = y_start; yi < y_end; ++yi) { + for (s32 xi = x_start; xi < x_end; ++xi) { + this->setPixelBlendDst(xi, yi, color); + } + } + } + + + /** + * @brief Draws a rectangle of given sizes (Multi-threaded) + * + * @param x X pos + * @param y Y pos + * @param w Width + * @param h Height + * @param color Color + */ + inline void drawRectMultiThreaded(const s32 x, const s32 y, const s32 w, const s32 h, const Color& color) { + // Early exit for invalid dimensions + if (w <= 0 || h <= 0) return; + + // Calculate clipped bounds + const s32 x_start = x < 0 ? 0 : x; + const s32 y_start = y < 0 ? 0 : y; + const s32 x_end = (x + w > cfg::FramebufferWidth) ? cfg::FramebufferWidth : x + w; + const s32 y_end = (y + h > cfg::FramebufferHeight) ? cfg::FramebufferHeight : y + h; + + // Early exit if completely outside bounds + if (x_start >= x_end || y_start >= y_end) return; + + // Calculate visible dimensions + const s32 visibleHeight = y_end - y_start; + + // Calculate chunk size - divide rows among threads + const s32 chunkSize = std::max(1, visibleHeight / static_cast(ult::numThreads)); + + // Launch threads using ult::renderThreads array + for (unsigned i = 0; i < static_cast(ult::numThreads); ++i) { + const s32 startRow = y_start + (i * chunkSize); + const s32 endRow = (i == static_cast(ult::numThreads) - 1) ? + y_end : + std::min(startRow + chunkSize, y_end); + + // Skip threads that have no work + if (startRow >= endRow) { + ult::renderThreads[i] = std::thread([](){}); // Empty thread (still needed for joining) + continue; + } + + // Use member function instead of lambda - much faster + ult::renderThreads[i] = std::thread(&Renderer::processRectChunk, this, + x_start, x_end, startRow, endRow, color); + } + + // Join all ult::renderThreads + for (auto& t : ult::renderThreads) { + t.join(); + } + } + + inline void drawRectAdaptive(s32 x, s32 y, s32 w, s32 h, const Color& color) { + if (ult::expandedMemory) + drawRectMultiThreaded(x, y, w, h, color); + else + drawRect(x, y, w, h, color); + } + + + /** + * @brief Draws a rectangle of given sizes with empty filling + * + * @param x X pos + * @param y Y pos + * @param w Width + * @param h Height + * @param color Color + */ + inline void drawEmptyRect(s32 x, s32 y, s32 w, s32 h, Color color) { + // Only precompute values that are actually reused + const s32 x_end = x + w - 1; + const s32 y_end = y + h - 1; + + // Early exit for completely out-of-bounds rectangles + if (x_end < 0 || y_end < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight) [[unlikely]] { + return; + } + + // These are reused for both horizontal lines + const s32 line_x_start = x < 0 ? 0 : x; + const s32 line_x_end = x_end >= cfg::FramebufferWidth ? cfg::FramebufferWidth - 1 : x_end; + + // Draw top horizontal line + if (y >= 0 && y < cfg::FramebufferHeight) { + for (s32 xi = line_x_start; xi <= line_x_end; ++xi) { + this->setPixelBlendDst(xi, y, color); + } + } + + // Draw bottom horizontal line (only if different from top) + if (h > 1 && y_end >= 0 && y_end < cfg::FramebufferHeight) { + for (s32 xi = line_x_start; xi <= line_x_end; ++xi) { + this->setPixelBlendDst(xi, y_end, color); + } + } + + // Draw vertical lines only if there's space between horizontal lines + if (h > 2) { + // These are reused for both vertical lines + const s32 line_y_start = (y + 1) < 0 ? 0 : (y + 1); + const s32 line_y_end = (y_end - 1) >= cfg::FramebufferHeight ? cfg::FramebufferHeight - 1 : (y_end - 1); + + // Only proceed if there are actually vertical pixels to draw + if (line_y_start <= line_y_end) { + // Left vertical line + if (x >= 0 && x < cfg::FramebufferWidth) { + for (s32 yi = line_y_start; yi <= line_y_end; ++yi) { + this->setPixelBlendDst(x, yi, color); + } + } + + // Right vertical line (only if different from left) + if (w > 1 && x_end >= 0 && x_end < cfg::FramebufferWidth) { + for (s32 yi = line_y_start; yi <= line_y_end; ++yi) { + this->setPixelBlendDst(x_end, yi, color); + } + } + } + } + } + + /** + * @brief Draws a line + * + * @param x0 Start X pos + * @param y0 Start Y pos + * @param x1 End X pos + * @param y1 End Y pos + * @param color Color + */ + inline void drawLine(s32 x0, s32 y0, s32 x1, s32 y1, Color color) { + // Early exit for single point + if (x0 == x1 && y0 == y1) { + if (x0 >= 0 && y0 >= 0 && x0 < cfg::FramebufferWidth && y0 < cfg::FramebufferHeight) { + this->setPixelBlendDst(x0, y0, color); + } + return; + } + + // Calculate deltas + const s32 dx = x1 - x0; + const s32 dy = y1 - y0; + + // Calculate absolute deltas and steps + const s32 abs_dx = dx < 0 ? -dx : dx; + const s32 abs_dy = dy < 0 ? -dy : dy; + const s32 step_x = dx < 0 ? -1 : 1; + const s32 step_y = dy < 0 ? -1 : 1; + + // Bresenham's algorithm + s32 x = x0, y = y0; + s32 error = abs_dx - abs_dy; + s32 error2; + + while (true) { + // Bounds check and draw pixel + if (x >= 0 && y >= 0 && x < cfg::FramebufferWidth && y < cfg::FramebufferHeight) { + this->setPixelBlendDst(x, y, color); + } + + // Check if we've reached the end point + if (x == x1 && y == y1) break; + + // Calculate error and step + error2 = error << 1; // error * 2 + + if (error2 > -abs_dy) { + error -= abs_dy; + x += step_x; + } + if (error2 < abs_dx) { + error += abs_dx; + y += step_y; + } + } + } + + /** + * @brief Draws a dashed line + * + * @param x0 Start X pos + * @param y0 Start Y pos + * @param x1 End X pos + * @param y1 End Y pos + * @param line_width How long one line can be + * @param color Color + */ + inline void drawDashedLine(s32 x0, s32 y0, s32 x1, s32 y1, s32 line_width, Color color) { + // Source of formula: https://www.cc.gatech.edu/grads/m/Aaron.E.McClennen/Bresenham/code.html + + const s32 x_min = std::min(x0, x1); + const s32 x_max = std::max(x0, x1); + const s32 y_min = std::min(y0, y1); + const s32 y_max = std::max(y0, y1); + + if (x_min < 0 || y_min < 0 || x_min >= cfg::FramebufferWidth || y_min >= cfg::FramebufferHeight) + return; + + const s32 dx = x_max - x_min; + const s32 dy = y_max - y_min; + s32 d = 2 * dy - dx; + + const s32 incrE = 2*dy; + const s32 incrNE = 2*(dy - dx); + + this->setPixelBlendDst(x_min, y_min, color); + + s32 x = x_min; + s32 y = y_min; + s32 rendered = 0; + + while(x < x1) { + if (d <= 0) { + d += incrE; + x++; + } + else { + d += incrNE; + x++; + y++; + } + rendered++; + if (x < 0 || y < 0 || x >= cfg::FramebufferWidth || y >= cfg::FramebufferHeight) + continue; + if (x <= x_max && y <= y_max) { + if (rendered > 0 && rendered < line_width) { + this->setPixelBlendDst(x, y, color); + } + else if (rendered > 0 && rendered >= line_width) { + rendered *= -1; + } + } + } + + } + + inline void drawCircle(const s32 centerX, const s32 centerY, const u16 radius, const bool filled, const Color& color) { + // Use Bresenham-style algorithm for small radii + if (radius <= 3) { + s32 x = radius; + s32 y = 0; + s32 radiusError = 0; + s32 xChange = 1 - (radius << 1); + s32 yChange = 0; + + while (x >= y) { + if (filled) { + for (s32 i = centerX - x; i <= centerX + x; i++) { + this->setPixelBlendDst(i, centerY + y, color); + this->setPixelBlendDst(i, centerY - y, color); + } + for (s32 i = centerX - y; i <= centerX + y; i++) { + this->setPixelBlendDst(i, centerY + x, color); + this->setPixelBlendDst(i, centerY - x, color); + } + y++; + radiusError += yChange; + yChange += 2; + if (((radiusError << 1) + xChange) > 0) { + x--; + radiusError += xChange; + xChange += 2; + } + } else { + this->setPixelBlendDst(centerX + x, centerY + y, color); + this->setPixelBlendDst(centerX + y, centerY + x, color); + this->setPixelBlendDst(centerX - y, centerY + x, color); + this->setPixelBlendDst(centerX - x, centerY + y, color); + this->setPixelBlendDst(centerX - x, centerY - y, color); + this->setPixelBlendDst(centerX - y, centerY - x, color); + this->setPixelBlendDst(centerX + y, centerY - x, color); + this->setPixelBlendDst(centerX + x, centerY - y, color); + if (radiusError <= 0) { + y++; + radiusError += 2 * y + 1; + } else { + x--; + radiusError -= 2 * x + 1; + } + } + } + return; + } + + // Original supersampling algorithm for larger radii + const float r_f = static_cast(radius); + const float r2 = r_f * r_f; + const u8 base_a = color.a; + const bool full_opacity = (base_a == 0xFF); + + const s32 bound = radius + 2; + const s32 clip_left = std::max(0, centerX - bound); + const s32 clip_right = std::min(static_cast(cfg::FramebufferWidth), centerX + bound); + const s32 clip_top = std::max(0, centerY - bound); + const s32 clip_bottom = std::min(static_cast(cfg::FramebufferHeight), centerY + bound); + + const float offset = 0.353553f; // sqrt(2)/4 + const float samples[8][2] = { + {-offset, -offset}, {offset, -offset}, + {-offset, offset}, {offset, offset}, + {-0.5f, 0.0f}, {0.5f, 0.0f}, + {0.0f, -0.5f}, {0.0f, 0.5f} + }; + + for (s32 yc = clip_top; yc < clip_bottom; ++yc) { + const float py = static_cast(yc - centerY) + 0.5f; + const float py_sq = py * py; + + for (s32 xc = clip_left; xc < clip_right; ++xc) { + const float px = static_cast(xc - centerX) + 0.5f; + const float px_sq = px * px; + const float center_d2 = px_sq + py_sq; + + if (filled) { + if (center_d2 <= r2 - r_f) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + if (full_opacity) this->setPixelAtOffset(off, color); + else this->setPixelBlendDst(xc, yc, color); + } + continue; + } else if (center_d2 > r2 + r_f) { + continue; + } + + u32 inside_count = 0; + for (u32 s = 0; s < 8; ++s) { + const float sx = px + samples[s][0]; + const float sy = py + samples[s][1]; + if (sx*sx + sy*sy <= r2) { + inside_count++; + } + } + + if (inside_count > 0) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + Color c = color; + c.a = static_cast((base_a * inside_count + 4) / 8); + this->setPixelBlendDst(xc, yc, c); + } + } + } else { + const float inner_r2 = (r_f - 1.0f) * (r_f - 1.0f); + + if (center_d2 >= inner_r2 + r_f && center_d2 <= r2 - r_f) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + if (full_opacity) this->setPixelAtOffset(off, color); + else this->setPixelBlendDst(xc, yc, color); + } + continue; + } else if (center_d2 < inner_r2 - r_f || center_d2 > r2 + r_f) { + continue; + } + + u32 inside_count = 0; + for (u32 s = 0; s < 8; ++s) { + const float sx = px + samples[s][0]; + const float sy = py + samples[s][1]; + const float sd2 = sx*sx + sy*sy; + if (sd2 >= inner_r2 && sd2 <= r2) { + inside_count++; + } + } + + if (inside_count > 0) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + Color c = color; + c.a = static_cast((base_a * inside_count + 4) / 8); + this->setPixelBlendDst(xc, yc, c); + } + } + } + } + } + } + + inline void drawBorderedRoundedRect(const s32 x, const s32 y, const s32 width, const s32 height, const s32 thickness, const s32 radius, const Color& highlightColor) { + const s32 startX = x + 4; + const s32 startY = y; + const s32 adjustedWidth = width - 12; + const s32 adjustedHeight = height + 1; + + // Pre-calculate corner positions + const s32 leftCornerX = startX; + const s32 rightCornerX = x + width - 9; + const s32 topCornerY = startY; + const s32 bottomCornerY = startY + height; + + // Draw borders + this->drawRect(startX, startY - thickness, adjustedWidth, thickness, highlightColor); + this->drawRect(startX, startY + adjustedHeight, adjustedWidth, thickness, highlightColor); + this->drawRect(startX - thickness, startY, thickness, adjustedHeight, highlightColor); + this->drawRect(startX + adjustedWidth, startY, thickness, adjustedHeight, highlightColor); + + // Pre-calculate AA colors once + const Color aaColor1 = {highlightColor.r, highlightColor.g, highlightColor.b, static_cast(highlightColor.a >> 1)}; // 50% + const Color aaColor2 = {highlightColor.r, highlightColor.g, highlightColor.b, static_cast(highlightColor.a >> 2)}; // 25% + + // Circle drawing with AA - optimized Bresenham + s32 cx = radius; + s32 cy = 0; + s32 radiusError = 0; + const s32 diameter = radius << 1; + s32 xChange = 1 - diameter; + s32 yChange = 0; + s32 lastCx = cx; + + while (cx >= cy) { + // Pre-calculate Y coordinates (hoist invariants) + const s32 topY1 = topCornerY - cy; + const s32 topY2 = topCornerY - cx; + const s32 bottomY1 = bottomCornerY + cy; + const s32 bottomY2 = bottomCornerY + cx; + + // Pre-calculate X bounds + const s32 leftX1Start = leftCornerX - cx; + const s32 leftX2Start = leftCornerX - cy; + const s32 rightX1Start = rightCornerX + 1; + const s32 rightX1End = rightCornerX + cx; + const s32 rightX2End = rightCornerX + cy; + + // Draw filled spans - NOW PERFECTLY MIRRORED + // Upper-left corner (exclusive) + for (s32 i = leftX1Start; i < leftCornerX; i++) { + this->setPixelBlendDst(i, topY1, highlightColor); + } + for (s32 i = leftX2Start; i < leftCornerX; i++) { + this->setPixelBlendDst(i, topY2, highlightColor); + } + + // Lower-left corner (NOW exclusive like top) + for (s32 i = leftX1Start; i < leftCornerX; i++) { + this->setPixelBlendDst(i, bottomY1, highlightColor); + } + for (s32 i = leftX2Start; i < leftCornerX; i++) { + this->setPixelBlendDst(i, bottomY2, highlightColor); + } + + // Upper-right corner (starts at +1) + for (s32 i = rightX1Start; i <= rightX1End; i++) { + this->setPixelBlendDst(i, topY1, highlightColor); + } + for (s32 i = rightX1Start; i <= rightX2End; i++) { + this->setPixelBlendDst(i, topY2, highlightColor); + } + + // Lower-right corner (NOW starts at +1 like top) + for (s32 i = rightX1Start; i <= rightX1End; i++) { + this->setPixelBlendDst(i, bottomY1, highlightColor); + } + for (s32 i = rightX1Start; i <= rightX2End; i++) { + this->setPixelBlendDst(i, bottomY2, highlightColor); + } + + // Add AA at step transitions + if (__builtin_expect(cx != lastCx && cy > 0, 0)) { + // Pre-calculate AA pixel positions + const s32 cxAA = cx + 1; + + // Upper-left AA + this->setPixelBlendDst(leftCornerX - cxAA, topY1, aaColor1); + this->setPixelBlendDst(leftCornerX - cxAA, topY1 + 1, aaColor2); + this->setPixelBlendDst(leftX2Start, topY2 - 1, aaColor1); + this->setPixelBlendDst(leftX2Start + 1, topY2 - 1, aaColor2); + + // Upper-right AA + this->setPixelBlendDst(rightCornerX + cxAA, topY1, aaColor1); + this->setPixelBlendDst(rightCornerX + cxAA, topY1 + 1, aaColor2); + this->setPixelBlendDst(rightX2End, topY2 - 1, aaColor1); + this->setPixelBlendDst(rightX2End - 1, topY2 - 1, aaColor2); + + // Lower-left AA + this->setPixelBlendDst(leftCornerX - cxAA, bottomY1, aaColor1); + this->setPixelBlendDst(leftCornerX - cxAA, bottomY1 - 1, aaColor2); + this->setPixelBlendDst(leftX2Start, bottomY2 + 1, aaColor1); + this->setPixelBlendDst(leftX2Start + 1, bottomY2 + 1, aaColor2); + + // Lower-right AA + this->setPixelBlendDst(rightCornerX + cxAA, bottomY1, aaColor1); + this->setPixelBlendDst(rightCornerX + cxAA, bottomY1 - 1, aaColor2); + this->setPixelBlendDst(rightX2End, bottomY2 + 1, aaColor1); + this->setPixelBlendDst(rightX2End - 1, bottomY2 + 1, aaColor2); + } + + lastCx = cx; + + // Bresenham iteration - optimized + cy++; + radiusError += yChange; + yChange += 2; + + if (__builtin_expect(((radiusError << 1) + xChange) > 0, 0)) { + cx--; + radiusError += xChange; + xChange += 2; + } + } + } + + // Pre-compute all horizontal spans for the entire shape + struct HorizontalSpan { + s32 start_x, end_x; + }; + + // Helper function - defined outside, compiler will inline + static inline void sampleAndBlendArcPixel(Renderer* self, s32 xp, s32 yc, + int px2, int cx2, int sx, int py2, int cy2, int sy, + long long r2_scaled, const Color& color, u8 base_a) { + int hits = 0; + const long long dx1 = px2 + sx - cx2; + const long long dx2 = px2 - sx - cx2; + const long long dy1 = py2 + sy - cy2; + const long long dy2 = py2 - sy - cy2; + + if (dx1*dx1 + dy1*dy1 <= r2_scaled) ++hits; + if (dx1*dx1 + dy2*dy2 <= r2_scaled) ++hits; + if (dx2*dx2 + dy1*dy1 <= r2_scaled) ++hits; + if (dx2*dx2 + dy2*dy2 <= r2_scaled) ++hits; + + if (hits == 4) { + self->setPixelBlendDst(xp, yc, color); + } else if (hits > 0) { + u8 a = (base_a * hits + 2) >> 2; + if (a) { + Color c = color; + c.a = a; + self->setPixelBlendDst(xp, yc, c); + } + } + } + + static void processRoundedRectChunk(Renderer* self, const s32 x, const s32 y, const s32 w, const s32 h, + const s32 radius, const Color& color, + const s32 startRow, const s32 endRow) { + if (radius <= 0) return; + + const s32 x_end = x + w; + const s32 y_end = y + h; + + const s32 clip_x = std::max(0, x); + const s32 clip_x_end = std::min(cfg::FramebufferWidth, x_end); + + const s32 left_arc_end = x + radius - 1; + const s32 right_arc_start = x_end - radius; + const s32 top_arc_end = y + radius - 1; + const s32 bottom_arc_start = y_end - radius; + + const int cx2_left = 2 * (x + radius); + const int cx2_right = 2 * (x_end - radius); + const int cy2_top = 2 * (y + radius); + const int cy2_bottom = 2 * (y_end - radius); + + const long long r2_scaled = 4LL * radius * radius; + const long long reject_threshold = (2LL*radius + 2)*(2LL*radius + 2); + + const u8 base_a = color.a; + + // Pre-compute sample offsets (constant per corner) + const int sx_left = ((x + radius) & 1) ? -1 : 1; + const int sx_right = ((x_end - radius) & 1) ? -1 : 1; + const int sy_top = ((y + radius) & 1) ? -1 : 1; + const int sy_bottom = ((y_end - radius) & 1) ? -1 : 1; + + alignas(64) u8 redArray[512], greenArray[512], blueArray[512], alphaArray[512]; + const uint8x16_t rv = vdupq_n_u8(color.r); + const uint8x16_t gv = vdupq_n_u8(color.g); + const uint8x16_t bv = vdupq_n_u8(color.b); + const uint8x16_t av = vdupq_n_u8(color.a); + for (int i = 0; i < 512; i += 16) { + vst1q_u8(redArray + i, rv); + vst1q_u8(greenArray + i, gv); + vst1q_u8(blueArray + i, bv); + vst1q_u8(alphaArray + i, av); + } + + for (s32 yc = startRow; yc < endRow; ++yc) { + if (yc < y || yc >= y_end) continue; + + const bool is_top = (yc <= top_arc_end); + const bool in_arc_rows = is_top || (yc >= bottom_arc_start); + + if (!in_arc_rows) { + s32 xs = std::max(clip_x, x); + s32 xe = std::min(clip_x_end, x_end); + for (s32 xp = xs; xp < xe; xp += 512) + self->setPixelBlendDstBatch(xp, yc, redArray, greenArray, blueArray, alphaArray, + std::min(512, xe - xp)); + continue; + } + + const int cy2 = is_top ? cy2_top : cy2_bottom; + const int py2 = 2 * yc + 1; + const int sy = is_top ? sy_top : sy_bottom; + + // Quick row reject + const long long dy = py2 - cy2; + if (dy * dy > reject_threshold) continue; + + const s32 xe = std::min(clip_x_end, x_end); + s32 xp = std::max(clip_x, x); + + // Left arc + for (; xp <= left_arc_end && xp < xe; ++xp) { + sampleAndBlendArcPixel(self, xp, yc, 2*xp + 1, cx2_left, sx_left, + py2, cy2, sy, r2_scaled, color, base_a); + } + + // Middle flat + s32 mid_start = std::max(xp, left_arc_end + 1); + s32 mid_end = std::min(xe, right_arc_start); + if (mid_start < mid_end) { + for (s32 bx = mid_start; bx < mid_end; bx += 512) + self->setPixelBlendDstBatch(bx, yc, redArray, greenArray, blueArray, alphaArray, + std::min(512, mid_end - bx)); + } + + // Right arc + xp = std::max(xp, right_arc_start); + for (; xp < xe; ++xp) { + sampleAndBlendArcPixel(self, xp, yc, 2*xp + 1, cx2_right, sx_right, + py2, cy2, sy, r2_scaled, color, base_a); + } + } + } + + + /** + * @brief Draws a rounded rectangle of given sizes and corner radius (Multi-threaded) + * + * @param x X pos + * @param y Y pos + * @param w Width + * @param h Height + * @param radius Corner radius + * @param color Color + */ + inline void drawRoundedRectMultiThreaded(const s32 x, const s32 y, const s32 w, const s32 h, const s32 radius, const Color& color) { + if (w <= 0 || h <= 0) return; + + // Calculate clipped bounds for early exit check + const s32 clampedX = std::max(0, x); + const s32 clampedY = std::max(0, y); + const s32 clampedXEnd = std::min(static_cast(cfg::FramebufferWidth), x + w); + const s32 clampedYEnd = std::min(static_cast(cfg::FramebufferHeight), y + h); + + // Early exit if nothing to draw after clamping + if (clampedX >= clampedXEnd || clampedY >= clampedYEnd) return; + + // Calculate visible dimensions + const s32 visibleHeight = clampedYEnd - clampedY; + + // Dynamic chunk size based on visible rectangle height + const s32 chunkSize = std::max(1, visibleHeight / (static_cast(ult::numThreads) * 2)); + std::atomic currentRow(clampedY); + + auto threadTask = [&]() { + s32 startRow, endRow; + while ((startRow = currentRow.fetch_add(chunkSize)) < clampedYEnd) { + endRow = std::min(startRow + chunkSize, clampedYEnd); + processRoundedRectChunk(this, x, y, w, h, radius, color, startRow, endRow); + } + }; + + // Launch threads using ult::renderThreads array + for (unsigned i = 0; i < static_cast(ult::numThreads); ++i) { + ult::renderThreads[i] = std::thread(threadTask); + } + + // Join all ult::renderThreads + for (auto& t : ult::renderThreads) { + t.join(); + } + } + + /** + * @brief Draws a rounded rectangle of given sizes and corner radius (Single-threaded) + * + * @param x X pos + * @param y Y pos + * @param w Width + * @param h Height + * @param radius Corner radius + * @param color Color + */ + inline void drawRoundedRectSingleThreaded(s32 x, s32 y, s32 w, s32 h, s32 radius, const Color& color) { + if (w <= 0 || h <= 0) return; + + const s32 clampedY = std::max(0, y); + const s32 clampedYEnd = std::min(static_cast(cfg::FramebufferHeight), y + h); + + // Early exit if nothing to draw after clamping + if (x + w <= 0 || x >= static_cast(cfg::FramebufferWidth) || clampedY >= clampedYEnd) + return; + + processRoundedRectChunk(this, x, y, w, h, radius, color, clampedY, clampedYEnd); + } + + inline void drawRoundedRect(s32 x, s32 y, s32 w, s32 h, s32 radius, Color color) { + if (ult::expandedMemory) + drawRoundedRectMultiThreaded(x, y, w, h, radius, color); + else + drawRoundedRectSingleThreaded(x, y, w, h, radius, color); + } + + + inline void drawUniformRoundedRect(const s32 x, const s32 y, const s32 w, const s32 h, const Color& color) { + const s32 radius = h >> 1; + const s32 clip_left = std::max(0, x); + const s32 clip_top = std::max(0, y); + const s32 clip_right = std::min(static_cast(cfg::FramebufferWidth), x + w); + const s32 clip_bottom = std::min(static_cast(cfg::FramebufferHeight), y + h); + + if (clip_left >= clip_right || clip_top >= clip_bottom) return; + + const s32 x_end = x + w; + const s32 y_end = y + h; + const s32 corner_x_left = x + radius; + const s32 corner_x_right = x_end - radius - 1; + const s32 corner_y_top = y + radius; + const s32 corner_y_bottom = y_end - radius - 1; + const float r_f = static_cast(radius); + const float r2 = r_f * r_f; + const float aa_thresh = r2 + 2.0f * r_f + 1.0f; + const u8 base_a = color.a; + const bool full_opacity = (base_a == 0xF); + + for (s32 yc = clip_top; yc < clip_bottom; ++yc) { + if (yc < y || yc >= y_end) continue; + + const bool in_corners = yc < corner_y_top || yc > corner_y_bottom; + + if (!in_corners) { + const s32 span_start = std::max(x, clip_left); + const s32 span_end = std::min(x_end, clip_right); + + for (s32 xc = span_start; xc < span_end; ++xc) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + if (full_opacity) { + this->setPixelAtOffset(off, color); + } else { + this->setPixelBlendDst(xc, yc, color); + } + } + } + } else { + const float dy = (yc < corner_y_top) ? static_cast(corner_y_top - yc) : + static_cast(yc - corner_y_bottom); + const float dy_sq = dy * dy; + + if (dy_sq > aa_thresh) continue; + + const float dy_half = dy - 0.5f; + const float dy_half_sq = dy_half * dy_half; + + const s32 span_start = std::max(x, clip_left); + const s32 span_end = std::min(x_end, clip_right); + s32 xc = span_start; + + // Left corner/edge + const s32 left_end = std::min(corner_x_left + 1, span_end); + for (; xc < left_end; ++xc) { + const float dx = static_cast(corner_x_left - xc); + const float dx_sq = dx * dx; + const float d2 = dx_sq + dy_sq; + + if (d2 <= r2) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + if (full_opacity) this->setPixelAtOffset(off, color); + else this->setPixelBlendDst(xc, yc, color); + } + } else if (d2 <= aa_thresh) { + const float dx_half = dx - 0.5f; + float cov = 0.0f; + if (dx_sq + dy_sq <= r2) cov += 0.25f; + if (dx_half*dx_half + dy_sq <= r2) cov += 0.25f; + if (dx_sq + dy_half_sq <= r2) cov += 0.25f; + if (dx_half*dx_half + dy_half_sq <= r2) cov += 0.25f; + + if (cov > 0.0f) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + Color c = color; + c.a = static_cast((base_a * static_cast(cov * 15.0f + 0.5f)) / 15); + this->setPixelBlendDst(xc, yc, c); + } + } + } + } + + // Middle section + const s32 mid_end = std::min(corner_x_right, span_end); + for (; xc < mid_end; ++xc) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + if (full_opacity) this->setPixelAtOffset(off, color); + else this->setPixelBlendDst(xc, yc, color); + } + } + + // Right corner/edge + for (; xc < span_end; ++xc) { + const float dx = static_cast(xc - corner_x_right); + const float dx_sq = dx * dx; + const float d2 = dx_sq + dy_sq; + + if (d2 <= r2) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + if (full_opacity) this->setPixelAtOffset(off, color); + else this->setPixelBlendDst(xc, yc, color); + } + } else if (d2 <= aa_thresh) { + const float dx_half = dx - 0.5f; + float cov = 0.0f; + if (dx_sq + dy_sq <= r2) cov += 0.25f; + if (dx_half*dx_half + dy_sq <= r2) cov += 0.25f; + if (dx_sq + dy_half_sq <= r2) cov += 0.25f; + if (dx_half*dx_half + dy_half_sq <= r2) cov += 0.25f; + + if (cov > 0.0f) { + const u32 off = this->getPixelOffset(xc, yc); + if (off != UINT32_MAX) { + Color c = color; + c.a = static_cast((base_a * static_cast(cov * 15.0f + 0.5f)) / 15); + this->setPixelBlendDst(xc, yc, c); + } + } + } + } + } + } + } + + // RGBA4444 processing - no expansion needed + const uint8x16_t mask_low = vdupq_n_u8(0x0F); + + inline void processBMPChunk(const u32 x, const u32 y, const s32 imageW, const u8 *preprocessedData, + const s32 startRow, const s32 endRow, const u8 globalAlphaLimit, + const bool useBarrier = true, const bool preserveAlpha = false) { + const s32 bytesPerRow = imageW * 2; + const s32 endX16 = imageW & ~15; + const uint8x16_t alpha_limit_vec = vdupq_n_u8(globalAlphaLimit); + + Color* const framebuffer = static_cast(this->getCurrentFramebuffer()); + + const bool hasScissor = !this->m_scissoringStack.empty(); + const auto scissor = hasScissor ? this->m_scissoringStack.top() : ScissoringConfig{}; + + for (s32 y1 = startRow; y1 < endRow; ++y1) { + const u32 baseY = y + y1; + + if (hasScissor && (baseY < scissor.y || baseY >= scissor.y_max)) [[unlikely]] + continue; + + const u32 yPart = ((((baseY & 127) >> 4) + ((baseY >> 7) * offsetWidthVar)) << 9) + + ((baseY & 8) << 5) + ((baseY & 6) << 4) + ((baseY & 1) << 3); + + const u8 *rowPtr = preprocessedData + (y1 * bytesPerRow); + s32 x1 = 0; + + for (; x1 < endX16; x1 += 16) { + const u8* ptr = rowPtr + (x1 << 1); + + uint8x16x2_t packed = vld2q_u8(ptr); + uint8x16_t high1 = vshrq_n_u8(packed.val[0], 4); + uint8x16_t low1 = vandq_u8(packed.val[0], mask_low); + uint8x16_t high2 = vshrq_n_u8(packed.val[1], 4); + uint8x16_t low2 = vminq_u8(vandq_u8(packed.val[1], mask_low), alpha_limit_vec); + + alignas(16) u8 red_vals[16], green_vals[16], blue_vals[16], alpha_vals[16]; + vst1q_u8(red_vals, high1); + vst1q_u8(green_vals, low1); + vst1q_u8(blue_vals, high2); + vst1q_u8(alpha_vals, low2); + + const u32 baseX = x + x1; + + for (int i = 0; i < 16; ++i) { + const u8 a = alpha_vals[i]; + if (a == 0) [[unlikely]] continue; + const u32 px = baseX + i; + if (hasScissor && (px < scissor.x || px >= scissor.x_max)) [[unlikely]] continue; + const u32 offset = yPart + ((px >> 5) << 12) + + ((px & 16) << 3) + ((px & 8) << 1) + (px & 7); + const Color src = framebuffer[offset]; + framebuffer[offset] = { + blendColor(src.r, red_vals[i], a), + blendColor(src.g, green_vals[i], a), + blendColor(src.b, blue_vals[i], a), + static_cast(preserveAlpha ? src.a : (a + ((src.a * (0xF - a)) >> 4))) + }; + } + } + + for (; x1 < imageW; ++x1) { + const u8 p1 = rowPtr[x1 << 1]; + const u8 p2 = rowPtr[(x1 << 1) + 1]; + const u8 alpha = std::min(static_cast(p2 & 0x0F), globalAlphaLimit); + if (alpha == 0) [[unlikely]] continue; + const u32 px = x + x1; + if (hasScissor && (px < scissor.x || px >= scissor.x_max)) [[unlikely]] continue; + const u32 offset = yPart + ((px >> 5) << 12) + + ((px & 16) << 3) + ((px & 8) << 1) + (px & 7); + const Color bg = framebuffer[offset]; + framebuffer[offset] = { + blendColor(bg.r, static_cast(p1 >> 4), alpha), + blendColor(bg.g, static_cast(p1 & 0x0F), alpha), + blendColor(bg.b, static_cast(p2 >> 4), alpha), + static_cast(preserveAlpha ? bg.a : (alpha + ((bg.a * (0xF - alpha)) >> 4))) + }; + } + } + + if (useBarrier) + ult::inPlotBarrier.arrive_and_wait(); + } + + inline void drawBitmapRGBA4444(const u32 x, const u32 y, const u32 imageW, const u32 imageH, + const u8 *preprocessedData, float opacity = 1.0f, bool preserveAlpha = false) { + const u8 globalAlphaLimit = static_cast(0xF * opacity); + + if (imageW < 448) { + processBMPChunk(x, y, imageW, preprocessedData, 0, imageH, globalAlphaLimit, false, preserveAlpha); + return; + } + + for (unsigned i = 0; i < ult::numThreads; ++i) { + const u32 startRow = i * ult::bmpChunkSize; + const u32 endRow = std::min(startRow + ult::bmpChunkSize, imageH); + ult::renderThreads[i] = std::thread([this, x, y, imageW, preprocessedData, startRow, endRow, globalAlphaLimit, preserveAlpha](){ + processBMPChunk(x, y, imageW, preprocessedData, startRow, endRow, globalAlphaLimit, true, preserveAlpha); + }); + } + for (auto& t : ult::renderThreads) t.join(); + } + + inline void drawWallpaper() { + if (!ult::expandedMemory || ult::refreshWallpaper.load(std::memory_order_acquire)) { + return; + } + + ult::inPlot.store(true, std::memory_order_release); + + if (!ult::wallpaperData.empty() && + !ult::refreshWallpaper.load(std::memory_order_acquire) && + ult::correctFrameSize) { + drawBitmapRGBA4444(0, 0, cfg::FramebufferWidth, cfg::FramebufferHeight, + ult::wallpaperData.data(), Renderer::s_opacity, true); + } + + ult::inPlot.store(false, std::memory_order_release); + } + + + /** + * @brief Draws a RGBA8888 bitmap from memory + * + * @param x X start position + * @param y Y start position + * @param w Bitmap width + * @param h Bitmap height + * @param bmp Pointer to bitmap data + */ + inline void drawBitmap(s32 x, s32 y, s32 w, s32 h, const u8 *bmp) { + if (w <= 0 || h <= 0) [[unlikely]] return; + + const u8* __restrict__ src = bmp; + + // Pre-compute alpha limit once using global opacity + const u8 alphaLimit = static_cast(0xF * Renderer::s_opacity); + + // Completely unroll small bitmaps for maximum speed + if (w <= 8 && h <= 8) [[likely]] { + s32 px; + // Specialized path for small bitmaps (icons, etc.) + for (s32 py = 0; py < h; ++py) { + const s32 rowY = y + py; + px = x; + + // Unroll inner loop completely for small widths + switch(w) { + case 8: goto pixel8; + case 7: goto pixel7; + case 6: goto pixel6; + case 5: goto pixel5; + case 4: goto pixel4; + case 3: goto pixel3; + case 2: goto pixel2; + case 1: goto pixel1; + default: break; + } + + pixel8: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + px++; src += 4; + } + pixel7: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + px++; src += 4; + } + pixel6: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + px++; src += 4; + } + pixel5: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + px++; src += 4; + } + pixel4: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + px++; src += 4; + } + pixel3: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + px++; src += 4; + } + pixel2: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + px++; src += 4; + } + pixel1: { + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, a(c)); + } + src += 4; + } + } + return; + } + + // Optimized scalar path for larger bitmaps + for (s32 py = 0; py < h; ++py) { + const s32 rowY = y + py; + s32 px = x; + const u8* rowEnd = src + (w * 4); + + // Prefetch first cache line + __builtin_prefetch(src, 0, 3); + + // Process all pixels in the row + while (src < rowEnd) { + // Prefetch ahead every 16 pixels (64 bytes) + if (((uintptr_t)src & 63) == 0) [[unlikely]] { + __builtin_prefetch(src + 64, 0, 3); + } + + u8 alpha = src[3] >> 4; + if (alpha > 0) { + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), alpha}; + setPixelBlendSrc(px, rowY, c); + } + px++; + src += 4; + } + } + } + + /** + * @brief Fills the entire layer with a given color + * + * @param color Color + */ + inline void fillScreen(const Color& color) { + std::fill_n(static_cast(this->getCurrentFramebuffer()), this->getFramebufferSize() / sizeof(Color), color); + } + + /** + * @brief Clears the layer (With transparency) + * + */ + inline void clearScreen() { + this->fillScreen(Color(0x0, 0x0, 0x0, 0x0)); // Fully transparent + } + + const stbtt_fontinfo& getStandardFont() const { + return m_stdFont; + } + + + // Optimized unified drawString method with thread safety + inline std::pair drawString(const std::string& originalString, bool monospace, + const s32 x, const s32 y, const u32 fontSize, + const Color& defaultColor, const ssize_t maxWidth = 0, + bool draw = true, + const Color* highlightColor = nullptr, + const std::vector* specialSymbols = nullptr, + const u32 highlightStartChar = 0, + const u32 highlightEndChar = 0, + const bool useNotificationCache = false) { + + // Thread-safe translation cache access + const std::string* text = &originalString; + std::string translatedText; + + { + std::shared_lock readLock(s_translationCacheMutex); + auto translatedIt = ult::translationCache.find(originalString); + if (translatedIt != ult::translationCache.end()) { + translatedText = translatedIt->second; + text = &translatedText; + } + } + + if (text->empty() || fontSize == 0) return {0, 0}; + + const float maxWidthLimit = maxWidth > 0 ? x + maxWidth : std::numeric_limits::max(); + + // Check if highlighting is enabled + const bool highlightingEnabled = highlightColor && highlightStartChar != 0 && highlightEndChar != 0; + + // Get font metrics once + const auto fontMetrics = FontManager::getFontMetricsForCharacter('A', fontSize); + const s32 lineHeight = static_cast(fontMetrics.lineHeight); + + // Fast ASCII check with early exit + bool isAsciiOnly = true; + const char* textPtr = text->data(); + const char* textEnd = textPtr + text->size(); + + for (const char* p = textPtr; p < textEnd; ++p) { + if (static_cast(*p) > 127) { + isAsciiOnly = false; + break; + } + } + + s32 maxX = x, currX = x, currY = y; + s32 maxY = y + lineHeight; + bool inHighlight = false; + const Color* currentColor = &defaultColor; + + // Main processing loop + if (isAsciiOnly && !specialSymbols) { + // Fast ASCII-only path + for (const char* p = textPtr; p < textEnd && currX < maxWidthLimit; ++p) { + u32 currCharacter = static_cast(*p); + + // Handle highlighting + if (highlightingEnabled) { + if (currCharacter == highlightStartChar) { + inHighlight = true; + currentColor = &defaultColor; + } else if (currCharacter == highlightEndChar) { + inHighlight = false; + currentColor = &defaultColor; + } else { + currentColor = inHighlight ? highlightColor : &defaultColor; + } + } + + // Handle newline + if (currCharacter == '\n') { + maxX = std::max(currX, maxX); + currX = x; + currY += lineHeight; + maxY = std::max(maxY, currY + lineHeight); + continue; + } + + // Get glyph + std::shared_ptr glyph = useNotificationCache ? + FontManager::getOrCreateNotificationGlyph(currCharacter, monospace, fontSize) : + FontManager::getOrCreateGlyph(currCharacter, monospace, fontSize); + + if (!glyph) continue; + + maxY = std::max(maxY, currY + lineHeight); + + // Render if needed + if (draw && glyph->glyphBmp && currCharacter > 32) { + renderGlyph(glyph, currX, currY, *currentColor, useNotificationCache); + } + + currX += static_cast(glyph->xAdvance * glyph->currFontSize); + } + } else { + // UTF-8 path with special symbols support + auto itStr = text->cbegin(); + const auto itStrEnd = text->cend(); + + while (itStr != itStrEnd && currX < maxWidthLimit) { + // Check for special symbols first + bool symbolProcessed = false; + + if (specialSymbols) { + const size_t remainingLength = itStrEnd - itStr; + + for (const auto& symbol : *specialSymbols) { + if (remainingLength >= symbol.length() && + std::equal(symbol.begin(), symbol.end(), itStr)) { + + // Process special symbol + for (size_t i = 0; i < symbol.length(); ) { + u32 symChar; + const ssize_t symWidth = decode_utf8(&symChar, + reinterpret_cast(&symbol[i])); + if (symWidth <= 0) break; + + if (symChar == '\n') { + maxX = std::max(currX, maxX); + currX = x; + currY += lineHeight; + maxY = std::max(maxY, currY + lineHeight); + } else { + auto glyph = FontManager::getOrCreateGlyph(symChar, monospace, fontSize); + if (glyph) { + maxY = std::max(maxY, currY + lineHeight); + + if (draw && glyph->glyphBmp && symChar > 32) { + renderGlyph(glyph, currX, currY, *highlightColor, useNotificationCache); + } + currX += static_cast(glyph->xAdvance * glyph->currFontSize); + } + } + i += symWidth; + } + itStr += symbol.length(); + symbolProcessed = true; + break; + } + } + } + + if (symbolProcessed) continue; + + // Decode character + u32 currCharacter; + ssize_t codepointWidth; + + if (isAsciiOnly) { + currCharacter = static_cast(*itStr); + codepointWidth = 1; + } else { + codepointWidth = decode_utf8(&currCharacter, reinterpret_cast(&(*itStr))); + if (codepointWidth <= 0) break; + } + + itStr += codepointWidth; + + // Handle highlighting + if (highlightingEnabled) { + if (currCharacter == highlightStartChar) { + inHighlight = true; + currentColor = &defaultColor; + } else if (currCharacter == highlightEndChar) { + inHighlight = false; + currentColor = &defaultColor; + } else { + currentColor = inHighlight ? highlightColor : &defaultColor; + } + } + + // Handle newline + if (currCharacter == '\n') { + maxX = std::max(currX, maxX); + currX = x; + currY += lineHeight; + maxY = std::max(maxY, currY + lineHeight); + continue; + } + + // Get glyph + auto glyph = FontManager::getOrCreateGlyph(currCharacter, monospace, fontSize); + if (!glyph) continue; + + maxY = std::max(maxY, currY + lineHeight); + + // Render if needed + if (draw && glyph->glyphBmp && currCharacter > 32) { + renderGlyph(glyph, currX, currY, *currentColor, useNotificationCache); + } + + currX += static_cast(glyph->xAdvance * glyph->currFontSize); + } + } + + maxX = std::max(currX, maxX); + return {maxX - x, maxY - y}; + } + + inline std::pair drawNotificationString(const std::string& text, bool monospace, + const s32 x, const s32 y, const u32 fontSize, + const Color& defaultColor, const ssize_t maxWidth = 0, + bool draw = true, + const Color* highlightColor = nullptr, + const std::vector* specialSymbols = nullptr, + const u32 highlightStartChar = 0, + const u32 highlightEndChar = 0) { + return drawString(text, monospace, x, y, fontSize, defaultColor, maxWidth, draw, + highlightColor, specialSymbols, highlightStartChar, highlightEndChar, true); + } + + // Convenience wrappers for backward compatibility + inline std::pair drawStringWithHighlight(const std::string& text, bool monospace, + s32 x, s32 y, const u32 fontSize, + const Color& defaultColor, + const Color& specialColor, + const ssize_t maxWidth = 0, + const u32 startChar = '(', + const u32 endChar = ')') { + return drawString(text, monospace, x, y, fontSize, defaultColor, maxWidth, true, &specialColor, nullptr, startChar, endChar); + } + + inline std::pair drawStringWithColoredSections(const std::string& text, bool monospace, + const std::vector& specialSymbols, + s32 x, const s32 y, const u32 fontSize, + const Color& defaultColor, + const Color& specialColor) { + return drawString(text, monospace, x, y, fontSize, defaultColor, 0, true, &specialColor, &specialSymbols); + } + + // Calculate string dimensions without drawing + inline std::pair getTextDimensions(const std::string& text, bool monospace, + const u32 fontSize, const ssize_t maxWidth = 0) { + return drawString(text, monospace, 0, 0, fontSize, Color{0,0,0,0}, maxWidth, false); + } + + inline std::pair getNotificationTextDimensions(const std::string& text, bool monospace, + const u32 fontSize, const ssize_t maxWidth = 0) { + return drawString(text, monospace, 0, 0, fontSize, Color{0,0,0,0}, maxWidth, false, + nullptr, nullptr, 0, 0, true); + } + + // Thread-safe limitStringLength using the unified cache + inline std::string limitStringLength(const std::string& originalString, const bool monospace, + const u32 fontSize, const s32 maxLength) { // Changed fontSize to u32 + + // Thread-safe translation cache access + std::string text; + { + std::shared_lock readLock(s_translationCacheMutex); + auto translatedIt = ult::translationCache.find(originalString); + if (translatedIt != ult::translationCache.end()) { + text = translatedIt->second; + } else { + // Don't insert anything, just fallback to original string + text = originalString; + } + } + + if (text.size() < 2) return text; + + // Get ellipsis width using shared cache (now thread-safe) + static constexpr u32 ellipsisChar = 0x2026; + std::shared_ptr ellipsisGlyph = FontManager::getOrCreateGlyph(ellipsisChar, monospace, fontSize); + if (!ellipsisGlyph) return text; + + // Fixed: Use consistent s32 calculation like other functions + const s32 ellipsisWidth = static_cast(ellipsisGlyph->xAdvance * ellipsisGlyph->currFontSize); + const s32 maxWidthWithoutEllipsis = maxLength - ellipsisWidth; + + if (maxWidthWithoutEllipsis <= 0) { + return "…"; // If there's no room for text, just return ellipsis + } + + // Calculate width incrementally + s32 currX = 0; + auto itStr = text.cbegin(); + const auto itStrEnd = text.cend(); + auto lastValidPos = itStr; + + // Fast ASCII check + bool isAsciiOnly = true; + for (unsigned char c : text) { + if (c > 127) { + isAsciiOnly = false; + break; + } + } + + // Move variable declarations outside the loop + u32 currCharacter; + ssize_t codepointWidth; + s32 charWidth; + size_t bytePos; + + while (itStr != itStrEnd) { + // Decode UTF-8 codepoint + if (isAsciiOnly) { + currCharacter = static_cast(*itStr); + codepointWidth = 1; + } else { + codepointWidth = decode_utf8(&currCharacter, reinterpret_cast(&(*itStr))); + if (codepointWidth <= 0) break; + } + + // FontManager::getOrCreateGlyph is now thread-safe + std::shared_ptr glyph = FontManager::getOrCreateGlyph(currCharacter, monospace, fontSize); + if (!glyph) { + itStr += codepointWidth; + continue; + } + + // Fixed: Use consistent s32 calculation + charWidth = static_cast(glyph->xAdvance * glyph->currFontSize); + + if (currX + charWidth > maxWidthWithoutEllipsis) { + // Calculate the byte position for substring + bytePos = std::distance(text.cbegin(), lastValidPos); + return text.substr(0, bytePos) + "…"; + } + + currX += charWidth; + itStr += codepointWidth; + lastValidPos = itStr; + } + + return text; + } + + inline void setLayerPos(u32 x, u32 y) { + if (x > cfg::ScreenWidth - (int)(1.5 * cfg::FramebufferWidth) || y > cfg::ScreenHeight - (int)(1.5 * cfg::FramebufferHeight)) { + return; + } + setLayerPosImpl(x, y); + } + + void updateLayerSize() { + const auto [horizontalUnderscanPixels, verticalUnderscanPixels] = getUnderscanPixels(); + + // Recalculate layer dimensions with new underscan values + cfg::LayerWidth = cfg::ScreenWidth * (float(cfg::FramebufferWidth) / float(cfg::LayerMaxWidth)); + cfg::LayerHeight = cfg::ScreenHeight * (float(cfg::FramebufferHeight) / float(cfg::LayerMaxHeight)); + + // Apply underscan adjustments + if (ult::DefaultFramebufferWidth == 1280 && ult::DefaultFramebufferHeight == 28) { + cfg::LayerHeight += cfg::ScreenHeight/720. * verticalUnderscanPixels; + } else if (ult::correctFrameSize) { + cfg::LayerWidth += horizontalUnderscanPixels; + } + + // Update position if using right alignment + if (ult::useRightAlignment && ult::correctFrameSize) { + ult::layerEdge = (1280 - 448); + } + + // Update the existing layer with new dimensions + viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight); + + // Update position if using right alignment + if (ult::useRightAlignment && ult::correctFrameSize) { + viSetLayerPosition(&this->m_layer, 1280-32 - horizontalUnderscanPixels, 0); + viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight); + viSetLayerPosition(&this->m_layer, 1280-32 - horizontalUnderscanPixels, 0); + } + // ADD THIS: Update position for micro mode bottom positioning + else if (ult::DefaultFramebufferWidth == 1280 && ult::DefaultFramebufferHeight == 28 && cfg::LayerPosY > 500) { + // Only adjust if already positioned at bottom (LayerPosY > 500 indicates bottom positioning) + const u32 targetY = !verticalUnderscanPixels ? 1038 : 1038- (cfg::ScreenHeight/720. * verticalUnderscanPixels) +0.5; + viSetLayerPosition(&this->m_layer, 0, targetY); + viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight); + viSetLayerPosition(&this->m_layer, 0, targetY); + } + } + + inline void setLayerPosImpl(u32 x, u32 y) { + + // Simply set the position to what was requested - no automatic right alignment + cfg::LayerPosX = x; + cfg::LayerPosY = y; + + ASSERT_FATAL(viSetLayerPosition(&this->m_layer, cfg::LayerPosX, cfg::LayerPosY)); + } + + + #if USING_WIDGET_DIRECTIVE + // Method to draw clock, temperatures, and battery percentage + inline bool drawWidget() { + static time_t lastTimeUpdate = 0; + static char timeStr[20]; + static char PCB_temperatureStr[10]; + static char SOC_temperatureStr[10]; + static char chargeString[6]; + static time_t lastSensorUpdate = 0; + + const bool showAnyWidget = !(ult::hideBattery && ult::hidePCBTemp && ult::hideSOCTemp && ult::hideClock); + + // Draw separator and backdrop if showing any widget + if (showAnyWidget) { + drawRect(239, 15 + 2 - 2, 1, 64 + 2, aWithOpacity(topSeparatorColor)); + if (!ult::hideWidgetBackdrop) { + drawUniformRoundedRect( + 247, 15 + 2 - 2, + (ult::extendedWidgetBackdrop + ? tsl::cfg::FramebufferWidth - 255 + : tsl::cfg::FramebufferWidth - 215), + 64 + 2, a(widgetBackdropColor) + ); + } + } + + // Calculate base Y offset + size_t y_offset = ((ult::hideBattery && ult::hidePCBTemp && ult::hideSOCTemp) || ult::hideClock) + ? (55 + 2 - 1) + : (44 + 2 - 1); + + // Constants for centering calculations + const int backdropCenterX = 247 + ((tsl::cfg::FramebufferWidth - 255) >> 1); + + time_t currentTime = time(nullptr); + + // Draw clock + if (!ult::hideClock) { + if (currentTime != lastTimeUpdate || ult::languageWasChanged.load(std::memory_order_acquire)) { + strftime(timeStr, sizeof(timeStr), ult::datetimeFormat.c_str(), localtime(¤tTime)); + ult::localizeTimeStr(timeStr); + lastTimeUpdate = currentTime; + } + + const int timeWidth = getTextDimensions(timeStr, false, 20).first; + + if (ult::centerWidgetAlignment) { + // Centered alignment + drawString(timeStr, false, backdropCenterX - (timeWidth >> 1), y_offset, 20, clockColor); + } else { + // Right alignment + drawString(timeStr, false, tsl::cfg::FramebufferWidth - timeWidth - 25, y_offset, 20, clockColor); + } + + y_offset += 22; + } + + // Update sensor data every second + if ((currentTime - lastSensorUpdate) >= 1) { + if (!ult::hideSOCTemp) { + float socTemp = 0.0f; + ult::ReadSocTemperature(&socTemp); + ult::SOC_temperature.store(socTemp, std::memory_order_release); + snprintf( + SOC_temperatureStr, sizeof(SOC_temperatureStr), + "%d°C", + static_cast(round(ult::SOC_temperature.load(std::memory_order_acquire))) + ); + } + + if (!ult::hidePCBTemp) { + float pcbTemp = 0.0f; + ult::ReadPcbTemperature(&pcbTemp); + ult::PCB_temperature.store(pcbTemp, std::memory_order_release); + snprintf( + PCB_temperatureStr, sizeof(PCB_temperatureStr), + "%d°C", + static_cast(round(ult::PCB_temperature.load(std::memory_order_acquire))) + ); + } + + if (!ult::hideBattery) { + uint32_t bc = 0; + bool charging = false; + ult::powerGetDetails(&bc, &charging); + bc = std::min(bc, 100U); + ult::batteryCharge.store(bc, std::memory_order_release); + ult::isCharging.store(charging, std::memory_order_release); + snprintf(chargeString, sizeof(chargeString), "%u%%", bc); + } + + lastSensorUpdate = currentTime; + } + + if (ult::centerWidgetAlignment) { + // CENTERED ALIGNMENT + int totalWidth = 0; + int socWidth = 0, pcbWidth = 0, chargeWidth = 0; + bool hasMultiple = false; + + const float socTemp = ult::SOC_temperature.load(std::memory_order_acquire); + const float pcbTemp = ult::PCB_temperature.load(std::memory_order_acquire); + const uint32_t batteryCharge = ult::batteryCharge.load(std::memory_order_acquire); + const bool charging = ult::isCharging.load(std::memory_order_acquire); + + if (!ult::hideSOCTemp && socTemp > 0.0f) { + socWidth = getTextDimensions(SOC_temperatureStr, false, 20).first; + totalWidth += socWidth; + hasMultiple = true; + } + if (!ult::hidePCBTemp && pcbTemp > 0.0f) { + pcbWidth = getTextDimensions(PCB_temperatureStr, false, 20).first; + if (hasMultiple) totalWidth += 5; + totalWidth += pcbWidth; + hasMultiple = true; + } + if (!ult::hideBattery && batteryCharge > 0) { + chargeWidth = getTextDimensions(chargeString, false, 20).first; + if (hasMultiple) totalWidth += 5; + totalWidth += chargeWidth; + } + + int currentX = backdropCenterX - (totalWidth >> 1); + if (socWidth > 0) { + drawString( + SOC_temperatureStr, false, currentX, y_offset, 20, + ult::dynamicWidgetColors + ? tsl::GradientColor(socTemp) + : temperatureColor + ); + currentX += socWidth + 5; + } + if (pcbWidth > 0) { + drawString( + PCB_temperatureStr, false, currentX, y_offset, 20, + ult::dynamicWidgetColors + ? tsl::GradientColor(pcbTemp) + : temperatureColor + ); + currentX += pcbWidth + 5; + } + if (chargeWidth > 0) { + const Color batteryColorToUse = charging + ? batteryChargingColor + : (batteryCharge < 20 ? batteryLowColor : batteryColor); + drawString(chargeString, false, currentX, y_offset, 20, batteryColorToUse); + } + + } else { + // RIGHT ALIGNMENT + int chargeWidth = 0, pcbWidth = 0, socWidth = 0; + const float pcbTemp = ult::PCB_temperature.load(std::memory_order_acquire); + const float socTemp = ult::SOC_temperature.load(std::memory_order_acquire); + const uint32_t batteryCharge = ult::batteryCharge.load(std::memory_order_acquire); + const bool charging = ult::isCharging.load(std::memory_order_acquire); + + if (!ult::hideBattery && batteryCharge > 0) { + const Color batteryColorToUse = charging + ? batteryChargingColor + : (batteryCharge < 20 ? batteryLowColor : batteryColor); + chargeWidth = getTextDimensions(chargeString, false, 20).first; + drawString( + chargeString, false, + tsl::cfg::FramebufferWidth - chargeWidth - 25, + y_offset, 20, batteryColorToUse + ); + } + + int offset = 0; + if (!ult::hidePCBTemp && pcbTemp > 0.0f) { + if (!ult::hideBattery) offset -= 5; + pcbWidth = getTextDimensions(PCB_temperatureStr, false, 20).first; + drawString( + PCB_temperatureStr, false, + tsl::cfg::FramebufferWidth + offset - pcbWidth - chargeWidth - 25, + y_offset, 20, + ult::dynamicWidgetColors + ? tsl::GradientColor(pcbTemp) + : defaultTextColor + ); + } + if (!ult::hideSOCTemp && socTemp > 0.0f) { + if (!ult::hidePCBTemp || !ult::hideBattery) offset -= 5; + socWidth = getTextDimensions(SOC_temperatureStr, false, 20).first; + drawString( + SOC_temperatureStr, false, + tsl::cfg::FramebufferWidth + offset - socWidth - pcbWidth - chargeWidth - 25, + y_offset, 20, + ult::dynamicWidgetColors + ? tsl::GradientColor(socTemp) + : defaultTextColor + ); + } + } + return showAnyWidget; + } + #endif + + // Optimized glyph rendering + inline void renderGlyph(std::shared_ptr glyph, float x, float y, const Color& color, bool skipAlphaLimit = false) { + if (!glyph->glyphBmp || color.a == 0) [[unlikely]] return; + + const s32 xPos = static_cast(x + glyph->bounds[0]); + const s32 yPos = static_cast(y + glyph->bounds[1]); + + if (xPos >= cfg::FramebufferWidth || yPos >= cfg::FramebufferHeight || + xPos + glyph->width <= 0 || yPos + glyph->height <= 0) [[unlikely]] return; + + const s32 startX = std::max(0, -xPos); + const s32 startY = std::max(0, -yPos); + const s32 endX = std::min(glyph->width, static_cast(cfg::FramebufferWidth) - xPos); + const s32 endY = std::min(glyph->height, static_cast(cfg::FramebufferHeight) - yPos); + const u8 alphaLimit = skipAlphaLimit ? color.a : static_cast(0xF * Renderer::s_opacity); + const uint8_t* bmpPtr = glyph->glyphBmp + startY * glyph->width; + + for (s32 bmpY = startY; bmpY < endY; ++bmpY, bmpPtr += glyph->width) { + const s32 pixelY = yPos + bmpY; + + for (s32 bmpX = startX; bmpX < endX; ++bmpX) { + u8 alpha = bmpPtr[bmpX] >> 4; + if (alpha == 0) [[unlikely]] continue; + + alpha = (alpha < alphaLimit) ? alpha : alphaLimit; + const s32 pixelX = xPos + bmpX; + + if (alpha == 0xF) [[likely]] { + this->setPixel(pixelX, pixelY, color); + } else { + this->setPixelBlendDst(pixelX, pixelY, Color(color.r, color.g, color.b, alpha)); + } + } + } + } + + + /** + * @brief Adds the layer from screenshot and recording stacks + */ + inline void addScreenshotStacks(bool forceDisable = true) { + tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Screenshot); + tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Recording); + screenshotsAreDisabled.store(false, std::memory_order_release); + if (forceDisable) + screenshotsAreForceDisabled.store(false, std::memory_order_release); + } + + /** + * @brief Removes the layer from screenshot and recording stacks + */ + inline void removeScreenshotStacks(bool forceDisable = true) { + tsl::hlp::viRemoveFromLayerStack(&this->m_layer, ViLayerStack_Screenshot); + tsl::hlp::viRemoveFromLayerStack(&this->m_layer, ViLayerStack_Recording); + screenshotsAreDisabled.store(true, std::memory_order_release); + if (forceDisable) + screenshotsAreForceDisabled.store(true, std::memory_order_release); + } + + private: + Renderer() {} + + /** + * @brief Sets the opacity of the layer + * + * @param opacity Opacity + */ + inline static void setOpacity(float opacity) { + opacity = std::clamp(opacity, 0.0F, 1.0F); + + Renderer::s_opacity = opacity; + } + + bool m_initialized = false; + ViDisplay m_display; + ViLayer m_layer; + Event m_vsyncEvent; + + NWindow m_window; + Framebuffer m_framebuffer; + void *m_currentFramebuffer = nullptr; + + std::stack m_scissoringStack; + + + + /** + * @brief Get the current framebuffer address + * + * @return Framebuffer address + */ + inline void* getCurrentFramebuffer() { + return this->m_currentFramebuffer; + } + + /** + * @brief Get the next framebuffer address + * + * @return Next framebuffer address + */ + inline void* getNextFramebuffer() { + return static_cast(this->m_framebuffer.buf) + this->getNextFramebufferSlot() * this->getFramebufferSize(); + } + + /** + * @brief Get the framebuffer size + * + * @return Framebuffer size + */ + inline size_t getFramebufferSize() { + return this->m_framebuffer.fb_size; + } + + /** + * @brief Get the number of framebuffers in use + * + * @return Number of framebuffers + */ + inline size_t getFramebufferCount() { + return this->m_framebuffer.num_fbs; + } + + /** + * @brief Get the currently used framebuffer's slot + * + * @return Slot + */ + inline u8 getCurrentFramebufferSlot() { + return this->m_window.cur_slot; + } + + /** + * @brief Get the next framebuffer's slot + * + * @return Next slot + */ + inline u8 getNextFramebufferSlot() { + return (this->getCurrentFramebufferSlot() + 1) % this->getFramebufferCount(); + } + + /** + * @brief Waits for the vsync event + * + */ + inline void waitForVSync() { + eventWait(&this->m_vsyncEvent, UINT64_MAX); + } + + /** + * @brief Decodes a x and y coordinate into a offset into the swizzled framebuffer + * + * @param x X pos + * @param y Y Pos + * @return Offset + */ + + inline u32 __attribute__((always_inline)) getPixelOffset(const u32 x, const u32 y) { + // Check for scissoring boundaries + if (!this->m_scissoringStack.empty()) [[unlikely]] { + const auto& currScissorConfig = this->m_scissoringStack.top(); + if (x < currScissorConfig.x || y < currScissorConfig.y || + x >= currScissorConfig.x_max || + y >= currScissorConfig.y_max) { + return UINT32_MAX; + } + } + + return ((((y & 127) >> 4) + ((x >> 5) << 3) + ((y >> 7) * offsetWidthVar)) << 9) + + ((y & 8) << 5) + ((x & 16) << 3) + ((y & 6) << 4) + + ((x & 8) << 1) + ((y & 1) << 3) + (x & 7); + } + + + /** + * @brief Initializes the renderer and layers + * + */ + void init() { + // Get the underscan pixel values for both horizontal and vertical borders + const auto [horizontalUnderscanPixels, verticalUnderscanPixels] = getUnderscanPixels(); + + ult::useRightAlignment = (ult::parseValueFromIniSection(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, "right_alignment") == ult::TRUE_STR); + + cfg::LayerPosX = 0; + cfg::LayerPosY = 0; + cfg::FramebufferWidth = ult::DefaultFramebufferWidth; + cfg::FramebufferHeight = ult::DefaultFramebufferHeight; + + offsetWidthVar = (((cfg::FramebufferWidth / 2) >> 4) << 3); + + ult::correctFrameSize = (cfg::FramebufferWidth == 448 && cfg::FramebufferHeight == 720); // for detecting the correct Overlay display size + if (ult::useRightAlignment && ult::correctFrameSize) { + cfg::LayerPosX = 1280-32 - horizontalUnderscanPixels; + ult::layerEdge = (1280-448); + } + + cfg::LayerWidth = cfg::ScreenWidth * (float(cfg::FramebufferWidth) / float(cfg::LayerMaxWidth)); + cfg::LayerHeight = cfg::ScreenHeight * (float(cfg::FramebufferHeight) / float(cfg::LayerMaxHeight)); + + // Apply underscanning offset + if (ult::DefaultFramebufferWidth == 1280 && ult::DefaultFramebufferHeight == 28) // for status monitor micro mode + cfg::LayerHeight += cfg::ScreenHeight/720. *verticalUnderscanPixels; + else if (ult::correctFrameSize) + cfg::LayerWidth += horizontalUnderscanPixels; + + if (this->m_initialized) + return; + + tsl::hlp::doWithSmSession([this, horizontalUnderscanPixels]{ + + ASSERT_FATAL(viInitialize(ViServiceType_Manager)); + ASSERT_FATAL(viOpenDefaultDisplay(&this->m_display)); + ASSERT_FATAL(viGetDisplayVsyncEvent(&this->m_display, &this->m_vsyncEvent)); + ASSERT_FATAL(viCreateManagedLayer(&this->m_display, static_cast(0), 0, &__nx_vi_layer_id)); + ASSERT_FATAL(viCreateLayer(&this->m_display, &this->m_layer)); + ASSERT_FATAL(viSetLayerScalingMode(&this->m_layer, ViScalingMode_FitToLayer)); + + if (horizontalUnderscanPixels == 0) { + s32 layerZ = 0; + if (R_SUCCEEDED(viGetZOrderCountMax(&this->m_display, &layerZ)) && layerZ > 0) { + ASSERT_FATAL(viSetLayerZ(&this->m_layer, layerZ)); + } + else { + ASSERT_FATAL(viSetLayerZ(&this->m_layer, 255)); // max value 255 as fallback + } + } else { + ASSERT_FATAL(viSetLayerZ(&this->m_layer, 34)); // 34 is the edge for underscanning + } + + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Default)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Screenshot)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Recording)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Arbitrary)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_LastFrame)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Null)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_ApplicationForDebug)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Lcd)); + + ASSERT_FATAL(viSetLayerSize(&this->m_layer, cfg::LayerWidth, cfg::LayerHeight)); + ASSERT_FATAL(viSetLayerPosition(&this->m_layer, cfg::LayerPosX, cfg::LayerPosY)); + ASSERT_FATAL(nwindowCreateFromLayer(&this->m_window, &this->m_layer)); + ASSERT_FATAL(framebufferCreate(&this->m_framebuffer, &this->m_window, cfg::FramebufferWidth, cfg::FramebufferHeight, PIXEL_FORMAT_RGBA_4444, 2)); + ASSERT_FATAL(setInitialize()); + ASSERT_FATAL(this->initFonts()); + setExit(); + }); + + this->m_initialized = true; + } + + /** + * @brief Exits the renderer and layer + * + */ + void exit() { + if (!this->m_initialized) + return; + + // Cleanup shared font manager + FontManager::cleanup(); + + framebufferClose(&this->m_framebuffer); + nwindowClose(&this->m_window); + viDestroyManagedLayer(&this->m_layer); + viCloseDisplay(&this->m_display); + eventClose(&this->m_vsyncEvent); + viExit(); + } + + /** + * @brief Initializes Nintendo's shared fonts. Default and Extended + * + * @return Result + */ + Result initFonts() { + PlFontData stdFontData, localFontData, extFontData; + + // Nintendo's default font + TSL_R_TRY(plGetSharedFontByType(&stdFontData, PlSharedFontType_Standard)); + + u8 *fontBuffer = reinterpret_cast(stdFontData.address); + stbtt_InitFont(&this->m_stdFont, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); + + u64 languageCode; + if (R_SUCCEEDED(setGetSystemLanguage(&languageCode))) { + // Check if need localization font + SetLanguage setLanguage; + TSL_R_TRY(setMakeLanguage(languageCode, &setLanguage)); + this->m_hasLocalFont = true; + switch (setLanguage) { + case SetLanguage_ZHCN: + case SetLanguage_ZHHANS: + TSL_R_TRY(plGetSharedFontByType(&localFontData, PlSharedFontType_ChineseSimplified)); + break; + case SetLanguage_ZHTW: + case SetLanguage_ZHHANT: + TSL_R_TRY(plGetSharedFontByType(&localFontData, PlSharedFontType_ChineseTraditional)); + break; + case SetLanguage_KO: + TSL_R_TRY(plGetSharedFontByType(&localFontData, PlSharedFontType_KO)); + break; + default: + this->m_hasLocalFont = false; + break; + } + + if (this->m_hasLocalFont) { + fontBuffer = reinterpret_cast(localFontData.address); + stbtt_InitFont(&this->m_localFont, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); + } + } + + // Nintendo's extended font containing a bunch of icons + TSL_R_TRY(plGetSharedFontByType(&extFontData, PlSharedFontType_NintendoExt)); + + fontBuffer = reinterpret_cast(extFontData.address); + stbtt_InitFont(&this->m_extFont, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); + + // Load all three local fonts unconditionally for fallback support + PlFontData cnFontData, twFontData, koFontData; + + TSL_R_TRY(plGetSharedFontByType(&cnFontData, PlSharedFontType_ChineseSimplified)); + fontBuffer = reinterpret_cast(cnFontData.address); + stbtt_InitFont(&this->m_localFontCN, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); + + TSL_R_TRY(plGetSharedFontByType(&twFontData, PlSharedFontType_ChineseTraditional)); + fontBuffer = reinterpret_cast(twFontData.address); + stbtt_InitFont(&this->m_localFontTW, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); + + TSL_R_TRY(plGetSharedFontByType(&koFontData, PlSharedFontType_KO)); + fontBuffer = reinterpret_cast(koFontData.address); + stbtt_InitFont(&this->m_localFontKO, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); + + // Initialize the shared font manager + FontManager::initializeFonts(&this->m_stdFont, + &this->m_localFont, + &this->m_localFontCN, + &this->m_localFontTW, + &this->m_localFontKO, + &this->m_extFont, + this->m_hasLocalFont); + + return 0; + } + + + /** + * @brief Start a new frame + * @warning Don't call this more than once before calling \ref endFrame + */ + inline void startFrame() { + this->m_currentFramebuffer = framebufferBegin(&this->m_framebuffer, nullptr); + } + + inline void endFrame() { + #if IS_STATUS_MONITOR_DIRECTIVE + if (isRendering) { + static u32 lastFPS = 0; + static u64 cachedIntervalNs = 1000000000ULL / 60; + + u32 fps = TeslaFPS; + if (__builtin_expect(fps != lastFPS, 0)) { + cachedIntervalNs = (fps > 0) ? (1000000000ULL / fps) : cachedIntervalNs; + lastFPS = fps; + } + + // Just wait - touch thread will signal if needed + leventWait(&renderingStopEvent, cachedIntervalNs); + } + #endif + + this->waitForVSync(); + framebufferEnd(&this->m_framebuffer); + this->m_currentFramebuffer = nullptr; + + if (tsl::clearGlyphCacheNow.exchange(false, std::memory_order_acq_rel)) { + tsl::gfx::FontManager::clearCache(); + } + } + + + }; + + static std::pair getUnderscanPixels() { + if (!ult::consoleIsDocked()) { + return {0, 0}; + } + + // Retrieve the TV settings + SetSysTvSettings tvSettings; + Result res = setsysGetTvSettings(&tvSettings); + if (R_FAILED(res)) { + // Handle error: return default underscan or log error + return {0, 0}; + } + + // The underscan value might not be a percentage, we need to interpret it correctly + const u32 underscanValue = tvSettings.underscan; + + // Convert the underscan value to a fraction. Assuming 0 means no underscan and larger values represent + // greater underscan. Adjust this formula based on actual observed behavior or documentation. + const float underscanPercentage = 1.0f - (underscanValue / 100.0f); + + // Original dimensions of the full 720p image (1280x720) + const float originalWidth = 1280; + const float originalHeight = 720; + + // Adjust the width and height based on the underscan percentage + const float adjustedWidth = (originalWidth * underscanPercentage); + const float adjustedHeight = (originalHeight * underscanPercentage); + + // Calculate the underscan in pixels (left/right and top/bottom) + const int horizontalUnderscanPixels = (originalWidth - adjustedWidth); + const int verticalUnderscanPixels = (originalHeight - adjustedHeight); + + return {horizontalUnderscanPixels, verticalUnderscanPixels}; + } + + } + + + // Elements + + namespace elm { + + enum class TouchEvent { + Touch, + Hold, + Scroll, + Release, + None + }; + + /** + * @brief The top level Element of the libtesla UI library + * @note When creating your own elements, extend from this or one of it's sub classes + */ + class Element { + public: + + Element() {} + virtual ~Element() { + m_clickListener = {}; // frees captures immediately + } + + bool m_isTable = false; // Default to false for non-table elements + bool m_isItem = true; + + + u64 t_ns; // Changed from chrono::duration to nanoseconds + u8 saturation; + float progress; + + s32 x, y; + s32 amplitude; + u64 m_animationStartTime; // Changed from chrono::time_point to nanoseconds + + virtual bool isTable() const { + return m_isTable; + } + + virtual bool isItem() const { + return m_isItem; + } + + /** + * @brief Handles focus requesting + * @note This function should return the element to focus. + * When this element should be focused, return `this`. + * When one of it's child should be focused, return `this->child->requestFocus(oldFocus, direction)` + * When this element is not focusable, return `nullptr` + * + * @param oldFocus Previously focused element + * @param direction Direction in which focus moved. \ref FocusDirection::None is passed for the initial load + * @return Element to focus + */ + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) { + return nullptr; + } + + /** + * @brief Function called when a joycon button got pressed + * + * @param keys Keys pressed in the last frame + * @return true when button press has been consumed + * @return false when button press should be passed on to the parent + */ + virtual bool onClick(u64 keys) { + return m_clickListener(keys); + } + + /** + * @brief Called once per frame with the latest HID inputs + * + * @param keysDown Buttons pressed in the last frame + * @param keysHeld Buttons held down longer than one frame + * @param touchInput Last touch position + * @param leftJoyStick Left joystick position + * @param rightJoyStick Right joystick position + * @return Weather or not the input has been consumed + */ + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) { + return false; + } + + /** + * @brief Function called when the element got touched + * @todo Not yet implemented + * + * @param x X pos + * @param y Y pos + * @return true when touch input has been consumed + * @return false when touch input should be passed on to the parent + */ + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) { + return false; + } + + /** + * @brief Called once per frame to draw the element + * @warning Do not call this yourself. Use \ref Element::frame(gfx::Renderer *renderer) + * + * @param renderer Renderer + */ + virtual void draw(gfx::Renderer *renderer) = 0; + + /** + * @brief Called when the underlying Gui gets created and after calling \ref Gui::invalidate() to calculate positions and boundaries of the element + * @warning Do not call this yourself. Use \ref Element::invalidate() + * + * @param parentX Parent X pos + * @param parentY Parent Y pos + * @param parentWidth Parent Width + * @param parentHeight Parent Height + */ + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) = 0; + + /** + * @brief Draws highlighting and the element itself + * @note When drawing children of a element in \ref Element::draw(gfx::Renderer *renderer), use `this->child->frame(renderer)` instead of calling draw directly + * + * @param renderer + */ + void inline frame(gfx::Renderer *renderer) { + + if (this->m_focused) { + renderer->enableScissoring(0, ult::activeHeaderHeight, tsl::cfg::FramebufferWidth, tsl::cfg::FramebufferHeight-73-ult::activeHeaderHeight); + this->drawFocusBackground(renderer); + this->drawHighlight(renderer); + renderer->disableScissoring(); + } + + this->draw(renderer); + } + + /** + * @brief Forces a layout recreation of a element + * + */ + void inline invalidate() { + const auto& parent = this->getParent(); + + if (parent == nullptr) + this->layout(0, 0, cfg::FramebufferWidth, cfg::FramebufferHeight); + else + this->layout(ELEMENT_BOUNDS(parent)); + } + + /** + * @brief Shake the highlight in the given direction to signal that the focus cannot move there + * + * @param direction Direction to shake highlight in + */ + void inline shakeHighlight(FocusDirection direction) { + this->m_highlightShaking = true; + this->m_highlightShakingDirection = direction; + this->m_highlightShakingStartTime = ult::nowNs(); // Changed + if (direction != FocusDirection::None && m_isItem) { + triggerWallFeedback(); + } + } + + /** + * @brief Triggers the blue click animation to signal a element has been clicked on + * + */ + void inline triggerClickAnimation() { + this->m_clickAnimationProgress = tsl::style::ListItemHighlightLength; + this->m_animationStartTime = ult::nowNs(); // Changed + } + + + + /** + * @brief Resets the click animation progress, canceling the animation + */ + void inline resetClickAnimation() { + this->m_clickAnimationProgress = 0; + } + + /** + * @brief Draws the blue highlight animation when clicking on a button + * @note Override this if you have a element that e.g requires a non-rectangular animation or a different color + * + * @param renderer Renderer + */ + virtual void drawClickAnimation(gfx::Renderer *renderer) { + if (!m_isItem) + return; + if (ult::useSelectionBG) { + renderer->drawRectAdaptive(this->getX() + x + 4, this->getY() + y, this->getWidth() - 8, this->getHeight(), aWithOpacity(selectionBGColor)); + } + + saturation = tsl::style::ListItemHighlightSaturation * (float(this->m_clickAnimationProgress) / float(tsl::style::ListItemHighlightLength)); + + Color animColor = {0xF,0xF,0xF,0xF}; + if (invertBGClickColor) { + const u8 inverted = 15-saturation; + animColor = {inverted, inverted, inverted, selectionBGColor.a}; + } else { + animColor = {saturation, saturation, saturation, selectionBGColor.a}; + } + renderer->drawRectAdaptive(ELEMENT_BOUNDS(this), aWithOpacity(animColor)); + + // Cache time calculation - only compute once + static u64 lastTimeUpdate = 0; + static double cachedProgress = 0.0; + const u64 currentTime_ns = ult::nowNs(); + + // Only recalculate progress if enough time has passed (reduce computation frequency) + if (currentTime_ns - lastTimeUpdate > 16666666) { // ~60 FPS update rate + cachedProgress = (ult::cos(2.0 * ult::_M_PI * std::fmod(currentTime_ns / 1000000000.0 - 0.25, 1.0)) + 1.0) / 2.0; + lastTimeUpdate = currentTime_ns; + } + progress = cachedProgress; + + Color clickColor1 = highlightColor1; + Color clickColor2 = clickColor; + + if (progress >= 0.5) { + clickColor1 = clickColor; + clickColor2 = highlightColor2; + } + + // Combine color interpolation into single calculation + s_highlightColor = lerpColor(clickColor1, clickColor2, progress); + + x = 0; + y = 0; + if (this->m_highlightShaking) { + t_ns = currentTime_ns - this->m_highlightShakingStartTime; + const double t_ms = t_ns / 1000000.0; + + static constexpr double SHAKE_DURATION_MS = 200.0; + + if (t_ms >= SHAKE_DURATION_MS) + this->m_highlightShaking = false; + else { + // Generate random amplitude only once per shake using the start time as seed + const double amplitude = 6.0 + ((this->m_highlightShakingStartTime / 1000000) % 5); + const double progress = t_ms / SHAKE_DURATION_MS; // 0 to 1 + + // Lighter damping so both bounces are visible + const double damping = 1.0 / (1.0 + 2.5 * progress * (1.0 + 1.3 * progress)); + + // 2 full oscillations = 2 clear bounces + const double oscillation = ult::cos(ult::_M_PI * 4.0 * progress); + const double displacement = amplitude * oscillation * damping; + const int offset = static_cast(displacement); + + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: y = -offset; break; + case FocusDirection::Down: y = offset; break; + case FocusDirection::Left: x = -offset; break; + case FocusDirection::Right: x = offset; break; + default: break; + } + } + } + + renderer->drawBorderedRoundedRect(this->getX() + x, this->getY() + y, this->getWidth() +4, this->getHeight(), 5, 5, a(s_highlightColor)); + } + + /** + * @brief Draws the back background when a element is highlighted + * @note Override this if you have a element that e.g requires a non-rectangular focus + * + * @param renderer Renderer + */ + virtual void drawFocusBackground(gfx::Renderer *renderer) { + if (this->m_clickAnimationProgress > 0) { + this->drawClickAnimation(renderer); + + // Direct calculation without intermediate multiplication + this->m_clickAnimationProgress = tsl::style::ListItemHighlightLength * (1.0f - ((ult::nowNs() - this->m_animationStartTime) * 0.000001) * 0.002f); // 0.002f = 1/500 + + // Clamp to 0 in one operation + if (this->m_clickAnimationProgress < 0) { + this->m_clickAnimationProgress = 0; + } + } + } + + /** + * @brief Draws the blue boarder when a element is highlighted + * @note Override this if you have a element that e.g requires a non-rectangular focus + * + * @param renderer Renderer + */ + virtual void drawHighlight(gfx::Renderer *renderer) { + if (!m_isItem) + return; + + // Use cached time calculation from drawClickAnimation if possible + static u64 lastHighlightUpdate = 0; + static double cachedHighlightProgress = 0.0; + const u64 currentTime_ns = ult::nowNs(); + + // Update progress at 60 FPS rate with high-precision calculation + if (currentTime_ns - lastHighlightUpdate > 16666666) { + + // Match original calculation exactly but with higher precision + cachedHighlightProgress = (ult::cos(2.0 * ult::_M_PI * std::fmod(currentTime_ns * 0.000000001 - 0.25, 1.0)) + 1.0) * 0.5; + + lastHighlightUpdate = currentTime_ns; + } + progress = cachedHighlightProgress; + + // Cache the interpreter state check result to avoid atomic load overhead + static bool lastInterpreterState = false; + static u64 lastInterpreterCheck = 0; + if (currentTime_ns - lastInterpreterCheck > 50000000) { // Check every 50ms + lastInterpreterState = ult::runningInterpreter.load(std::memory_order_acquire); + lastInterpreterCheck = currentTime_ns; + } + + if (lastInterpreterState) { + // High precision floating point color interpolation for interpreter colors + s_highlightColor = { + static_cast(highlightColor4.r + (highlightColor3.r - highlightColor4.r) * progress + 0.5), + static_cast(highlightColor4.g + (highlightColor3.g - highlightColor4.g) * progress + 0.5), + static_cast(highlightColor4.b + (highlightColor3.b - highlightColor4.b) * progress + 0.5), + 0xF + }; + } else { + // High precision floating point color interpolation for normal colors + s_highlightColor = { + static_cast(highlightColor2.r + (highlightColor1.r - highlightColor2.r) * progress + 0.5), + static_cast(highlightColor2.g + (highlightColor1.g - highlightColor2.g) * progress + 0.5), + static_cast(highlightColor2.b + (highlightColor1.b - highlightColor2.b) * progress + 0.5), + 0xF + }; + } + + x = 0; + y = 0; + + if (this->m_highlightShaking) { + t_ns = currentTime_ns - this->m_highlightShakingStartTime; + const double t_ms = t_ns / 1000000.0; + + static constexpr double SHAKE_DURATION_MS = 200.0; + + if (t_ms >= SHAKE_DURATION_MS) + this->m_highlightShaking = false; + else { + // Generate random amplitude only once per shake using the start time as seed + const double amplitude = 6.0 + ((this->m_highlightShakingStartTime / 1000000) % 5); + const double progress = t_ms / SHAKE_DURATION_MS; // 0 to 1 + + // Lighter damping so both bounces are visible + const double damping = 1.0 / (1.0 + 2.5 * progress * (1.0 + 1.3 * progress)); + + // 2 full oscillations = 2 clear bounces + const double oscillation = ult::cos(ult::_M_PI * 4.0 * progress); + const double displacement = amplitude * oscillation * damping; + const int offset = static_cast(displacement); + + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: y = -offset; break; + case FocusDirection::Down: y = offset; break; + case FocusDirection::Left: x = -offset; break; + case FocusDirection::Right: x = offset; break; + default: break; + } + } + } + + if (this->m_clickAnimationProgress == 0) { + if (ult::useSelectionBG) { + renderer->drawRectAdaptive(this->getX() + x + 4, this->getY() + y, this->getWidth() - 12 +4, this->getHeight(), aWithOpacity(selectionBGColor)); + } + + #if IS_LAUNCHER_DIRECTIVE + // Determine the active percentage to use + const float activePercentage = ult::displayPercentage.load(std::memory_order_acquire); + if (activePercentage > 0){ + renderer->drawRectAdaptive(this->getX() + x + 4, this->getY() + y, (this->getWidth()- 12 +4)*(activePercentage * 0.01f), this->getHeight(), aWithOpacity(progressColor)); + } + #endif + + renderer->drawBorderedRoundedRect(this->getX() + x, this->getY() + y, this->getWidth() +4, this->getHeight(), 5, 5, a(s_highlightColor)); + } + + ult::onTrackBar.store(false, std::memory_order_release); + } + + + + /** + * @brief Sets the boundaries of this view + * + * @param x Start X pos + * @param y Start Y pos + * @param width Width + * @param height Height + */ + inline void setBoundaries(s32 x, s32 y, s32 width, s32 height) { + this->m_x = x; + this->m_y = y; + this->m_width = width; + this->m_height = height; + } + + /** + * @brief Adds a click listener to the element + * + * @param clickListener Click listener called with keys that were pressed last frame. Callback should return true if keys got consumed + */ + virtual void setClickListener(std::function clickListener) { + this->m_clickListener = clickListener; + } + + /** + * @brief Gets the element's X position + * + * @return X position + */ + inline s32 getX() { return this->m_x; } + /** + * @brief Gets the element's Y position + * + * @return Y position + */ + inline s32 getY() { return this->m_y; } + /** + * @brief Gets the element's Width + * + * @return Width + */ + inline s32 getWidth() { return this->m_width; } + /** + * @brief Gets the element's Height + * + * @return Height + */ + inline s32 getHeight() { return this->m_height; } + + inline s32 getTopBound() { return this->getY(); } + inline s32 getLeftBound() { return this->getX(); } + inline s32 getRightBound() { return this->getX() + this->getWidth(); } + inline s32 getBottomBound() { return this->getY() + this->getHeight(); } + + /** + * @brief Check if the coordinates are in the elements bounds + * + * @return true if coordinates are in bounds, false otherwise + */ + bool inBounds(s32 touchX, s32 touchY) { + return touchX >= this->getLeftBound() + int(ult::layerEdge) && touchX <= this->getRightBound() + int(ult::layerEdge) && touchY >= this->getTopBound() && touchY <= this->getBottomBound(); + } + + /** + * @brief Sets the element's parent + * @note This is required to handle focus and button downpassing properly + * + * @param parent Parent + */ + inline void setParent(Element *parent) { this->m_parent = parent; } + + /** + * @brief Get the element's parent + * + * @return Parent + */ + inline Element* getParent() { return this->m_parent; } + + + virtual std::vector getChildren() const { + return {}; // Return empty vector for simplicity + } + + /** + * @brief Marks this element as focused or unfocused to draw the highlight + * + * @param focused Focused + */ + virtual void setFocused(bool focused) { + this->m_focused = focused; + this->m_clickAnimationProgress = 0; + } + + inline bool hasFocus() { + return this->m_focused; + } + + virtual bool matchesJumpCriteria(const std::string& jumpText, const std::string& jumpValue, bool contains) const { + return false; // Default implementation for non-ListItem elements + } + + + static InputMode getInputMode() { return Element::s_inputMode; } + + static void setInputMode(InputMode mode) { Element::s_inputMode = mode; } + + protected: + constexpr static inline auto a = &gfx::Renderer::a; + constexpr static inline auto aWithOpacity = &gfx::Renderer::aWithOpacity; + bool m_focused = false; + u8 m_clickAnimationProgress = 0; + + // Highlight shake animation + bool m_highlightShaking = false; + u64 m_highlightShakingStartTime; // Changed from chrono::time_point to nanoseconds + FocusDirection m_highlightShakingDirection; + + static inline InputMode s_inputMode; + + private: + friend class Gui; + + s32 m_x = 0, m_y = 0, m_width = 0, m_height = 0; + Element *m_parent = nullptr; + std::vector m_children; + std::function m_clickListener = [](u64) { return false; }; + }; + + /** + * @brief A Element that exposes the renderer directly to draw custom views easily + */ + class CustomDrawer : public Element { + public: + /** + * @brief Constructor + * @note This element should only be used to draw static things the user cannot interact with e.g info text, images, etc. + * + * @param renderFunc Callback that will be called once every frame to draw this view + */ + CustomDrawer(std::function renderFunc) : Element(), m_renderFunc(renderFunc) { + m_isItem = false; + m_isTable = true; + } + + virtual ~CustomDrawer() {} + + virtual void draw(gfx::Renderer* renderer) override { + this->m_renderFunc(renderer, ELEMENT_BOUNDS(this)); + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + + } + + private: + std::function m_renderFunc; + }; + + /** + * @brief A Element that exposes the renderer directly to draw custom views easily + */ + class TableDrawer : public Element { + public: + TableDrawer(std::function renderFunc, bool _hideTableBackground, size_t _endGap, bool _isScrollable = false) + : Element(), m_renderFunc(renderFunc), hideTableBackground(_hideTableBackground), endGap(_endGap), isScrollable(_isScrollable) { + m_isTable = isScrollable; // Mark this element as a table + m_isItem = false; + } + + virtual ~TableDrawer() {} + + virtual void draw(gfx::Renderer* renderer) override { + + renderer->enableScissoring(0, 88, tsl::cfg::FramebufferWidth, tsl::cfg::FramebufferHeight - 73 - 97 +2+5); + + if (!hideTableBackground) + renderer->drawRoundedRect(this->getX() + 4+2, this->getY()-4-1, this->getWidth() +2 + 1, this->getHeight() + 20 - endGap+2, 12.0, aWithOpacity(tableBGColor)); + + m_renderFunc(renderer, this->getX() + 4, this->getY(), this->getWidth() + 4, this->getHeight()); + + renderer->disableScissoring(); + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override {} + + + virtual bool onClick(u64 keys) { + return false; + } + + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) override { + return nullptr; + } + + private: + std::function m_renderFunc; + bool hideTableBackground = false; + size_t endGap = 3; + bool isScrollable = false; + }; + + + #if IS_LAUNCHER_DIRECTIVE + // Simple utility function to draw the dynamic "Ultra" part of the logo + static s32 drawDynamicUltraText(gfx::Renderer* renderer, s32 startX, s32 y, u32 fontSize, + const tsl::Color& staticColor, bool useNotificationMethod = false) { + static constexpr double cycleDuration = 1.6; + s32 currentX = startX; + + if (ult::useDynamicLogo) { + const u64 currentTime_ns = ult::nowNs(); + const double currentTimeCount = static_cast(currentTime_ns) / 1000000000.0; + const double timeBase = std::fmod(currentTimeCount, cycleDuration); + const double waveScale = 2.0 * ult::_M_PI / cycleDuration; + static constexpr double phaseShift = ult::_M_PI / 2.0; + + float countOffset = 0; + for (const char letter : ult::SPLIT_PROJECT_NAME_1) { + const double wavePhase = waveScale * (timeBase + static_cast(countOffset)); + const double rawProgress = ult::cos(wavePhase - phaseShift); + + const double normalizedProgress = (rawProgress + 1.0) * 0.5; + const double smoothedProgress = normalizedProgress * normalizedProgress * (3.0 - 2.0 * normalizedProgress); + const double ultraSmoothProgress = smoothedProgress * smoothedProgress * (3.0 - 2.0 * smoothedProgress); + + const double blend = std::max(0.0, std::min(1.0, ultraSmoothProgress)); + + const tsl::Color _highlightColor = lerpColor(dynamicLogoRGB2, dynamicLogoRGB1, blend); + + const std::string letterStr(1, letter); + if (useNotificationMethod) { + currentX += renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, _highlightColor).first; + } else { + currentX += renderer->drawString(letterStr, false, currentX, y, fontSize, _highlightColor).first; + } + countOffset -= static_cast(cycleDuration / 8.0); + } + } else { + // Static rendering + for (const char letter : ult::SPLIT_PROJECT_NAME_1) { + const std::string letterStr(1, letter); + if (useNotificationMethod) { + currentX += renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, staticColor).first; + } else { + currentX += renderer->drawString(letterStr, false, currentX, y, fontSize, staticColor).first; + } + } + } + + return currentX; + } + + // Utility function to calculate width of the Ultra text (for notification centering) + static s32 calculateUltraTextWidth(gfx::Renderer* renderer, u32 fontSize, bool useNotificationMethod = false) { + s32 totalWidth = 0; + + if (ult::useDynamicLogo) { + // Calculate width by measuring each character for dynamic rendering + for (const char letter : ult::SPLIT_PROJECT_NAME_1) { + const std::string letterStr(1, letter); + if (useNotificationMethod) { + totalWidth += renderer->getNotificationTextDimensions(letterStr, false, fontSize).first; + } else { + totalWidth += renderer->getTextDimensions(letterStr, false, fontSize).first; + } + } + } else { + // Static rendering - measure the whole string at once + if (useNotificationMethod) { + totalWidth = renderer->getNotificationTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize).first; + } else { + totalWidth = renderer->getTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize).first; + } + } + + return totalWidth; + } + + #endif + + /** + * @brief The base frame which can contain another view + * + */ + class OverlayFrame : public Element { + public: + /** + * @brief Constructor + * + * @param title Name of the Overlay drawn bolt at the top + * @param subtitle Subtitle drawn bellow the title e.g version number + */ + std::string m_title; + std::string m_subtitle; + + bool m_noClickableItems; + + #if IS_LAUNCHER_DIRECTIVE + std::string m_menuMode; + std::string m_colorSelection; + + tsl::Color titleColor = {0xF,0xF,0xF,0xF}; + float letterWidth; + #endif + + std::string m_pageLeftName; + std::string m_pageRightName; + + #if USING_WIDGET_DIRECTIVE + bool m_showWidget = false; + #endif + + float x, y; + int offset, y_offset; + int fontSize; + + #if IS_LAUNCHER_DIRECTIVE + OverlayFrame(const std::string& title, const std::string& subtitle, const bool& _noClickableItems=false, const std::string& menuMode = "", const std::string& colorSelection = "", const std::string& pageLeftName = "", const std::string& pageRightName = "") + : Element(), m_title(title), m_subtitle(subtitle), m_noClickableItems(_noClickableItems), m_menuMode(menuMode), m_colorSelection(colorSelection), m_pageLeftName(pageLeftName), m_pageRightName(pageRightName) { + #else + OverlayFrame(const std::string& title, const std::string& subtitle, const bool& _noClickableItems=false, const std::string& pageLeftName = "", const std::string& pageRightName = "") + : Element(), m_title(title), m_subtitle(subtitle), m_noClickableItems(_noClickableItems), m_pageLeftName(pageLeftName), m_pageRightName(pageRightName) { + #endif + ult::activeHeaderHeight = 97; + ult::loadWallpaperFileWhenSafe(); + m_isItem = false; + disableSound.store(false, std::memory_order_release); + } + + ~OverlayFrame() { + delete m_contentElement; + } + + #if USING_FPS_INDICATOR_DIRECTIVE + // Function to calculate FPS + inline float updateFPS(double currentTimeCount) { + static double lastUpdateTime = currentTimeCount; + static int frameCount = 0; + static float fps = 0.0f; + + ++frameCount; + const double elapsedTime = currentTimeCount - lastUpdateTime; + + if (elapsedTime >= 1.0) { // Update FPS every second + fps = frameCount / static_cast(elapsedTime); + lastUpdateTime = currentTimeCount; + frameCount = 0; + } + return fps; + } + #endif + + void draw(gfx::Renderer *renderer) override { + + renderer->fillScreen(a(defaultBackgroundColor)); + renderer->drawWallpaper(); + + y = 50; + offset = 0; + + #if IS_LAUNCHER_DIRECTIVE + const bool interpreterIsRunningNow = ult::runningInterpreter.load(std::memory_order_acquire) && + (ult::downloadPercentage.load(std::memory_order_acquire) != -1 || + ult::unzipPercentage.load(std::memory_order_acquire) != -1 || + ult::copyPercentage.load(std::memory_order_acquire) != -1); + + if (m_noClickableItems != ult::noClickableItems.load(std::memory_order_acquire)) + ult::noClickableItems.store(m_noClickableItems, std::memory_order_release); + + const bool renderIsUltrahandMenu = (m_title == ult::CAPITAL_ULTRAHAND_PROJECT_NAME && + m_subtitle.find("Ultrahand Package") == std::string::npos && + m_subtitle.find("Ultrahand Script") == std::string::npos); + + bool widgetDrawn = false; + if (renderIsUltrahandMenu) { + #if USING_WIDGET_DIRECTIVE + widgetDrawn = renderer->drawWidget(); + #endif + if (ult::touchingMenu.load(std::memory_order_acquire) && + (ult::inMainMenu.load(std::memory_order_acquire) || + (ult::inHiddenMode.load(std::memory_order_acquire) && + !ult::inSettingsMenu.load(std::memory_order_acquire) && + !ult::inSubSettingsMenu.load(std::memory_order_acquire)))) { + renderer->drawRoundedRect(7.0f, 12.0f, 232.0f, 73.0f, 12.0f, a(clickColor)); + } + x = 20; fontSize = 42; offset = 6; + if (ult::useDynamicLogo) { + x = drawDynamicUltraText(renderer, x, y + offset, fontSize, logoColor1, false); + } else { + for (const char letter : ult::SPLIT_PROJECT_NAME_1) { + const std::string letterStr(1, letter); + x += renderer->drawString(letterStr, false, x, y + offset, fontSize, logoColor1).first; + } + } + renderer->drawString(ult::SPLIT_PROJECT_NAME_2, false, x, y + offset, fontSize, logoColor2); + } else { + #if USING_WIDGET_DIRECTIVE + widgetDrawn = m_showWidget && renderer->drawWidget(); + #endif + x = 20; y = 50; fontSize = 32; + calcScrollWidth(renderer, titleScroll, m_title, 32, widgetDrawn); + const bool isScript = m_subtitle.find("Ultrahand Script") != std::string::npos; + drawScrollableText(renderer, titleScroll, isScript ? defaultScriptColor : getPackageColor(), x, y, 32, 27, 35); + } + + { + std::string subtitle = m_subtitle; + const size_t pos = subtitle.find("?Ultrahand Script"); + if (pos != std::string::npos) subtitle.erase(pos, 17); + calcScrollWidth(renderer, subScroll, subtitle, 15, widgetDrawn); + const int subtitleX = 20, subtitleY = y + 25; + if (m_title == ult::CAPITAL_ULTRAHAND_PROJECT_NAME) { + renderer->drawStringWithColoredSections(ult::versionLabel, false, tsl::s_dividerSpecialChars, + subtitleX, subtitleY, 15, bannerVersionTextColor, textSeparatorColor); + } else if (subScroll.trunc) { + if (!subScroll.active) { subScroll.active = true; subScroll.timeIn = ult::nowNs(); } + renderer->enableScissoring(subtitleX, subtitleY - 16, subScroll.maxW, 24); + renderer->drawStringWithColoredSections(subScroll.scrollText, false, tsl::s_dividerSpecialChars, + subtitleX - static_cast(subScroll.offset), subtitleY, 15, bannerVersionTextColor, textSeparatorColor); + renderer->disableScissoring(); + updateScroll(subScroll); + } else { + renderer->drawStringWithColoredSections(subtitle, false, tsl::s_dividerSpecialChars, + subtitleX, subtitleY, 15, bannerVersionTextColor, textSeparatorColor); + } + } + + #else + if (m_noClickableItems != ult::noClickableItems.load(std::memory_order_acquire)) + ult::noClickableItems.store(m_noClickableItems, std::memory_order_release); + + bool widgetDrawn = false; + #if USING_WIDGET_DIRECTIVE + widgetDrawn = m_showWidget && renderer->drawWidget(); + #endif + calcScrollWidth(renderer, titleScroll, m_title, 32, widgetDrawn); + drawScrollableText(renderer, titleScroll, defaultOverlayColor, 20, 50, 32, 27, 35); + calcScrollWidth(renderer, subScroll, m_subtitle, 15, widgetDrawn); + { + const int subtitleX = 20, subtitleY = y + 25; + if (subScroll.trunc) { + if (!subScroll.active) { subScroll.active = true; subScroll.timeIn = ult::nowNs(); } + renderer->enableScissoring(subtitleX, subtitleY - 16, subScroll.maxW, 24); + renderer->drawString(subScroll.scrollText, false, + subtitleX - static_cast(subScroll.offset), subtitleY, 15, bannerVersionTextColor); + renderer->disableScissoring(); + updateScroll(subScroll); + } else { + renderer->drawString(m_subtitle, false, subtitleX, subtitleY, 15, bannerVersionTextColor); + } + } + #endif + + renderer->drawRect(15, tsl::cfg::FramebufferHeight - 73, tsl::cfg::FramebufferWidth - 30, 1, a(bottomSeparatorColor)); + + // Atomic update helper + const auto updateAtomic = [](std::atomic& atom, float val) { + if (val != atom.load(std::memory_order_acquire)) + atom.store(val, std::memory_order_release); + }; + + const float gapWidth = renderer->getTextDimensions(ult::GAP_1, false, 23).first; + #if IS_LAUNCHER_DIRECTIVE + const float backTextWidth = renderer->getTextDimensions("\uE0E1" + ult::GAP_2 + (!interpreterIsRunningNow ? ult::BACK : ult::HIDE), false, 23).first; + const float selectTextWidth = renderer->getTextDimensions("\uE0E0" + ult::GAP_2 + (!interpreterIsRunningNow ? ult::OK : ult::CANCEL), false, 23).first; + #else + const float backTextWidth = renderer->getTextDimensions("\uE0E1" + ult::GAP_2 + ult::BACK, false, 23).first; + const float selectTextWidth = renderer->getTextDimensions("\uE0E0" + ult::GAP_2 + ult::OK, false, 23).first; + #endif + const float _halfGap = gapWidth * 0.5f; + const float _backWidth = backTextWidth + gapWidth; + const float _selectWidth = selectTextWidth + gapWidth; + updateAtomic(ult::halfGap, _halfGap); + updateAtomic(ult::backWidth, _backWidth); + updateAtomic(ult::selectWidth, _selectWidth); + + static constexpr float buttonStartX = 30; + const float buttonY = static_cast(cfg::FramebufferHeight - 73 + 1); + + if (ult::touchingBack) + renderer->drawRoundedRect(buttonStartX+2 - _halfGap, buttonY, _backWidth-1, 73.0f, 12.0f, a(clickColor)); + if (ult::touchingSelect.load(std::memory_order_acquire) && !m_noClickableItems) + renderer->drawRoundedRect(buttonStartX+2 - _halfGap + _backWidth+1, buttonY, _selectWidth-2, 73.0f, 12.0f, a(clickColor)); + + #if IS_LAUNCHER_DIRECTIVE + const bool hasNextPage = !interpreterIsRunningNow && + ((ult::inMainMenu.load(std::memory_order_acquire) && + ((m_menuMode == ult::OVERLAYS_STR) || (m_menuMode == ult::PACKAGES_STR))) || + !m_pageLeftName.empty() || !m_pageRightName.empty()); + if (hasNextPage != ult::hasNextPageButton.load(std::memory_order_acquire)) + ult::hasNextPageButton.store(hasNextPage, std::memory_order_release); + if (hasNextPage) { + const float _nextPageWidth = renderer->getTextDimensions( + !m_pageLeftName.empty() ? ("\uE0ED" + ult::GAP_2 + m_pageLeftName) : + !m_pageRightName.empty() ? ("\uE0EE" + ult::GAP_2 + m_pageRightName) : + (ult::inMainMenu.load(std::memory_order_acquire) ? + (((m_menuMode == "packages") ? (ult::usePageSwap ? "\uE0EE" : "\uE0ED") : + (ult::usePageSwap ? "\uE0ED" : "\uE0EE")) + + ult::GAP_2 + (ult::inOverlaysPage.load(std::memory_order_acquire) ? ult::PACKAGES : ult::OVERLAYS_ABBR)) : ""), + false, 23).first + gapWidth; + updateAtomic(ult::nextPageWidth, _nextPageWidth); + if (ult::touchingNextPage.load(std::memory_order_acquire)) { + float nextX = buttonStartX+2 - _halfGap + _backWidth + 1; + if (!m_noClickableItems) nextX += _selectWidth; + renderer->drawRoundedRect(nextX, buttonY, _nextPageWidth-2, 73.0f, 12.0f, a(clickColor)); + } + } + #else + const bool hasNextPage = !m_pageLeftName.empty() || !m_pageRightName.empty(); + if (hasNextPage != ult::hasNextPageButton.load(std::memory_order_acquire)) + ult::hasNextPageButton.store(hasNextPage, std::memory_order_release); + if (hasNextPage) { + const float _nextPageWidth = renderer->getTextDimensions( + !m_pageLeftName.empty() ? ("\uE0ED" + ult::GAP_2 + m_pageLeftName) + : ("\uE0EE" + ult::GAP_2 + m_pageRightName), + false, 23).first + gapWidth; + updateAtomic(ult::nextPageWidth, _nextPageWidth); + if (ult::touchingNextPage.load(std::memory_order_acquire)) { + float nextX = buttonStartX+2 - _halfGap + _backWidth + 1; + if (!m_noClickableItems) nextX += _selectWidth; + renderer->drawRoundedRect(nextX, buttonY, _nextPageWidth-2, 73.0f, 12.0f, a(clickColor)); + } + } else { + ult::nextPageWidth.store(0.0f, std::memory_order_release); + } + #endif + + #if IS_LAUNCHER_DIRECTIVE + const std::string currentBottomLine = + "\uE0E1" + ult::GAP_2 + + (interpreterIsRunningNow ? ult::HIDE : ult::BACK) + ult::GAP_1 + + (!m_noClickableItems && !interpreterIsRunningNow ? "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1 : "") + + (interpreterIsRunningNow ? "\uE0E5" + ult::GAP_2 + ult::CANCEL + ult::GAP_1 : "") + + (!interpreterIsRunningNow + ? (!ult::usePageSwap + ? ((m_menuMode == "packages") ? "\uE0ED" + ult::GAP_2 + ult::OVERLAYS_ABBR + : (m_menuMode == "overlays") ? "\uE0EE" + ult::GAP_2 + ult::PACKAGES : "") + : ((m_menuMode == "packages") ? "\uE0EE" + ult::GAP_2 + ult::OVERLAYS_ABBR + : (m_menuMode == "overlays") ? "\uE0ED" + ult::GAP_2 + ult::PACKAGES : "")) + : "") + + (!interpreterIsRunningNow && !m_pageLeftName.empty() ? "\uE0ED" + ult::GAP_2 + m_pageLeftName : + !interpreterIsRunningNow && !m_pageRightName.empty() ? "\uE0EE" + ult::GAP_2 + m_pageRightName : ""); + const bool _hasOkBtn = !m_noClickableItems && !interpreterIsRunningNow; + #else + const std::string currentBottomLine = + "\uE0E1" + ult::GAP_2 + ult::BACK + ult::GAP_1 + + (!m_noClickableItems ? "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1 : "") + + (!m_pageLeftName.empty() ? "\uE0ED" + ult::GAP_2 + m_pageLeftName : + !m_pageRightName.empty() ? "\uE0EE" + ult::GAP_2 + m_pageRightName : ""); + const bool _hasOkBtn = !m_noClickableItems; + #endif + + renderer->drawStringWithColoredSections(currentBottomLine, false, tsl::s_footerSpecialChars, + buttonStartX, 693, 23, bottomTextColor, buttonColor); + if (_hasOkBtn && !usingUnfocusedColor) { + static const std::string okOverdraw = "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1; + renderer->drawStringWithColoredSections(okOverdraw, false, tsl::s_footerSpecialChars, + buttonStartX + _backWidth, 693, 23, unfocusedColor, unfocusedColor); + } + + #if USING_FPS_INDICATOR_DIRECTIVE + { + const u64 currentTime_ns = ult::nowNs(); + const float currentFps = updateFPS(currentTime_ns / 1e9); + static char fpsBuffer[32]; + static float lastFps = -1.0f; + if (std::abs(currentFps - lastFps) > 0.1f) { + snprintf(fpsBuffer, sizeof(fpsBuffer), "FPS: %.2f", currentFps); + lastFps = currentFps; + } + static constexpr tsl::Color whiteColor = {0xF,0xF,0xF,0xF}; + renderer->drawString(fpsBuffer, false, 20, tsl::cfg::FramebufferHeight - 60, 20, whiteColor); + } + #endif + + if (m_contentElement != nullptr) + m_contentElement->frame(renderer); + + if (!ult::useRightAlignment) + renderer->drawRect(447, 0, 448, 720, a(edgeSeparatorColor)); + else + renderer->drawRect(0, 0, 1, 720, a(edgeSeparatorColor)); + } + + inline void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + setBoundaries(parentX, parentY, parentWidth, parentHeight); + + if (m_contentElement != nullptr) { + m_contentElement->setBoundaries(parentX + 35, parentY + 97, parentWidth - 85, parentHeight - 73 - 105); + m_contentElement->invalidate(); + } + } + + inline Element* requestFocus(Element *oldFocus, FocusDirection direction) override { + return m_contentElement ? m_contentElement->requestFocus(oldFocus, direction) : nullptr; + } + + inline bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) { + // Discard touches outside bounds + if (!m_contentElement || !m_contentElement->inBounds(currX, currY)) + return false; + + return m_contentElement->onTouch(event, currX, currY, prevX, prevY, initialX, initialY); + } + + /** + * @brief Sets the content of the frame + * + * @param content Element + */ + inline void setContent(Element *content) { + delete m_contentElement; + m_contentElement = content; + + if (content != nullptr) { + m_contentElement->setParent(this); + invalidate(); + } + } + + /** + * @brief Changes the title of the menu + * + * @param title Title to change to + */ + inline void setTitle(const std::string& t) { resetScroll(titleScroll, m_title, t); } + + /** + * @brief Changes the subtitle of the menu + * + * @param title Subtitle to change to + */ + inline void setSubtitle(const std::string& s) { resetScroll(subScroll, m_subtitle, s); } + + protected: + Element *m_contentElement = nullptr; + + private: + // Unified scroll state structure + struct ScrollState { + u64 timeIn, lastUpd; + float offset; + u32 maxW, textW; + bool active, trunc; + std::string scrollText; + }; + + ScrollState subScroll = {0, 0, 0.0f, 0, 0, false, false, ""}; + ScrollState titleScroll = {0, 0, 0.0f, 0, 0, false, false, ""}; + + // Unified width calculation + void calcScrollWidth(gfx::Renderer* renderer, ScrollState& s, const std::string& text, u32 fontSize, bool widgetDrawn) { + if (s.maxW) return; + + s.maxW = widgetDrawn ? 217 : (tsl::cfg::FramebufferWidth - 40); + + const u32 w = renderer->getTextDimensions(text, false, fontSize).first; + s.trunc = w > s.maxW; + + if (s.trunc) { + s.scrollText = text + " "; + s.textW = renderer->getTextDimensions(s.scrollText, false, fontSize).first; + s.scrollText += text; + } else { + s.textW = w; + } + } + + static void resetScroll(ScrollState& s, std::string& dest, const std::string& src) { + if (dest == src) return; + dest = src; + s.maxW = 0; + s.active = s.trunc = false; + } + + #if IS_LAUNCHER_DIRECTIVE + // Get package color based on m_colorSelection + tsl::Color getPackageColor() const { + if (m_colorSelection.empty()) return defaultPackageColor; + + const char c = m_colorSelection[0]; + const size_t len = m_colorSelection.length(); + + switch (c) { + case 'g': return (len == 5) ? tsl::Color{0x0,0xF,0x0,0xF} : defaultPackageColor; + case 'r': return (len == 3) ? tsl::Color{0xF,0x2,0x4,0xF} : defaultPackageColor; + case 'b': return (len == 4) ? tsl::Color{0x7,0x7,0xF,0xF} : defaultPackageColor; + case 'y': return (len == 6) ? tsl::Color{0xF,0xF,0x0,0xF} : defaultPackageColor; + case 'o': return (len == 6) ? tsl::Color{0xF,0xA,0x0,0xF} : defaultPackageColor; + case 'p': + if (len == 4) return tsl::Color{0xF,0x6,0xB,0xF}; + if (len == 6) return tsl::Color{0x8,0x0,0x8,0xF}; + return defaultPackageColor; + case 'w': return (len == 5) ? tsl::Color{0xF,0xF,0xF,0xF} : defaultPackageColor; + case '#': + return (len == 7 && isValidHexColor(m_colorSelection.substr(1))) + ? RGB888(m_colorSelection.substr(1)) : defaultPackageColor; + default: return defaultPackageColor; + } + } + #endif + + // Draw scrollable text with common parameters + void drawScrollableText(gfx::Renderer* renderer, ScrollState& s, const tsl::Color& clr, + int xPos, int yPos, u32 fontSize, int scissorYOffset, int scissorHeight) { + if (s.trunc) { + if (!s.active) { + s.active = true; + s.timeIn = ult::nowNs(); + } + + renderer->enableScissoring(xPos, yPos - scissorYOffset, s.maxW, scissorHeight); + renderer->drawString(s.scrollText, false, xPos - static_cast(s.offset), yPos, fontSize, clr); + renderer->disableScissoring(); + + updateScroll(s); + } else { + renderer->drawString(m_title, false, xPos, yPos, fontSize, clr); + } + } + + // Unified scroll update + void updateScroll(ScrollState& s) { + const u64 now = ult::nowNs(); + + // Only update at ~120Hz + if (now - s.lastUpd < 8333333ULL) return; + + static constexpr double delay = 3.0, pause = 2.0, vel = 100.0, accel = 0.5, decel = 0.5; + static constexpr double invBil = 1e-9, invAccel = 2.0, invDecel = 2.0; + + const double minDist = s.textW; + const double accelDist = 0.5 * vel * accel; + const double decelDist = 0.5 * vel * decel; + const double constDist = std::max(0.0, minDist - accelDist - decelDist); + const double constTime = constDist / vel; + const double totalDur = delay + accel + constTime + decel + pause; + + const double t = (now - s.timeIn) * invBil; + const double cycle = std::fmod(t, totalDur); + + if (cycle < delay) { + s.offset = 0.0f; + } else if (cycle < delay + accel + constTime + decel) { + const double st = cycle - delay; + double d; + + if (st <= accel) { + const double r = st * invAccel; + d = r * r * accelDist; + } else if (st <= accel + constTime) { + d = accelDist + (st - accel) * vel; + } else { + const double r = (st - accel - constTime) * invDecel; + const double omr = 1.0 - r; + d = accelDist + constDist + (1.0 - omr * omr) * (minDist - accelDist - constDist); + } + + s.offset = static_cast(std::min(d, minDist)); + } else { + s.offset = static_cast(s.textW); + } + + s.lastUpd = now; + + if (t >= totalDur) s.timeIn = now; + } + }; + + #if IS_STATUS_MONITOR_DIRECTIVE + + /** + * @brief The base frame which can contain another view + * + */ + class HeaderOverlayFrame : public Element { + public: + /** + * @brief Constructor + * + * @param title Name of the Overlay drawn bolt at the top + * @param subtitle Subtitle drawn bellow the title e.g version number + */ + std::string m_title; + std::string m_subtitle; + bool m_noClickableItems; + + float x, y; + int offset, y_offset; + int fontSize; + + HeaderOverlayFrame(const std::string& title, const std::string& subtitle, const bool& _noClickableItems=false) + : Element(), m_title(title), m_subtitle(subtitle), m_noClickableItems(_noClickableItems) { + ult::activeHeaderHeight = 97; + + if (FullMode) + ult::loadWallpaperFileWhenSafe(); + else + svcSleepThread(250'000); // sleep thread for initial values to auto-load + + m_isItem = false; + } + + virtual ~HeaderOverlayFrame() { + if (this->m_contentElement != nullptr) + delete this->m_contentElement; + } + + + virtual void draw(gfx::Renderer *renderer) override { + + if (m_noClickableItems != ult::noClickableItems.load(std::memory_order_acquire)) { + ult::noClickableItems.store(m_noClickableItems, std::memory_order_release); + } + + + if (FullMode == true) { + renderer->fillScreen(a(defaultBackgroundColor)); + if (lastMode.empty() || (lastMode.compare("returning") == 0)) + renderer->drawWallpaper(); + } else { + renderer->fillScreen({ 0x0, 0x0, 0x0, 0x0}); + } + + y = 50; + offset = 0; + + // Use cached or current data for rendering + const std::string& renderTitle = m_title; + const std::string& renderSubtitle = m_subtitle; + + renderer->drawString(renderTitle, false, 20, 50, 32, defaultOverlayColor); + renderer->drawString(renderSubtitle, false, 20, y+2+23, 15, bannerVersionTextColor); + + if (FullMode == true) + renderer->drawRect(15, tsl::cfg::FramebufferHeight - 73, tsl::cfg::FramebufferWidth - 30, 1, a(bottomSeparatorColor)); + + // Set initial button position + static constexpr float buttonStartX = 30; + + if (FullMode && !deactivateOriginalFooter) { + // Get the exact gap width from ult::GAP_1 + const auto gapWidth = renderer->getTextDimensions(ult::GAP_1, false, 23).first; + const float _halfGap = gapWidth / 2.0f; + if (_halfGap != ult::halfGap.load(std::memory_order_acquire)) + ult::halfGap.store(_halfGap, std::memory_order_release); + + // Calculate text dimensions for buttons without gaps + const auto backTextWidth = renderer->getTextDimensions("\uE0E1" + ult::GAP_2 + ult::BACK, false, 23).first; + const auto selectTextWidth = renderer->getTextDimensions("\uE0E0" + ult::GAP_2 + ult::OK, false, 23).first; + + // Update widths to include the half-gap padding on each side + const float _backWidth = backTextWidth + gapWidth; + if (_backWidth != ult::backWidth.load(std::memory_order_acquire)) + ult::backWidth.store(_backWidth, std::memory_order_release); + const float _selectWidth = selectTextWidth + gapWidth; + if (_selectWidth != ult::selectWidth.load(std::memory_order_acquire)) + ult::selectWidth.store(_selectWidth, std::memory_order_release); + + const float buttonY = static_cast(cfg::FramebufferHeight - 73 + 1); + + // Draw back button rectangle + if (ult::touchingBack.load(std::memory_order_acquire)) { + renderer->drawRoundedRect(buttonStartX+2 - _halfGap, buttonY, _backWidth-1, 73.0f, 12.0f, a(clickColor)); + } + + // Draw select button rectangle (starts right after back button) + if (ult::touchingSelect.load(std::memory_order_acquire) && !m_noClickableItems) { + renderer->drawRoundedRect(buttonStartX+2 - _halfGap + _backWidth+1, buttonY, + _selectWidth-2, 73.0f, 12.0f, a(clickColor)); + } + } + + // Build current bottom line + const std::string currentBottomLine = + "\uE0E1" + ult::GAP_2 + ult::BACK + ult::GAP_1 + + (!m_noClickableItems + ? "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1 + : ""); + + const std::string& menuBottomLine = currentBottomLine; + + // Render the text with special character handling + if (!deactivateOriginalFooter) { + renderer->drawStringWithColoredSections(menuBottomLine, false, tsl::s_footerSpecialChars, + buttonStartX, 693, 23, bottomTextColor, buttonColor); + if (!m_noClickableItems && !usingUnfocusedColor) { + renderer->drawStringWithColoredSections("\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1, false, + tsl::s_footerSpecialChars, + buttonStartX + ult::backWidth.load(std::memory_order_acquire), + 693, 23, unfocusedColor, unfocusedColor); + } + } + + if (this->m_contentElement != nullptr) + this->m_contentElement->frame(renderer); + + if (FullMode) { + if (!ult::useRightAlignment) + renderer->drawRect(447, 0, 448, 720, a(edgeSeparatorColor)); + else + renderer->drawRect(0, 0, 1, 720, a(edgeSeparatorColor)); + } + } + + + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + this->setBoundaries(parentX, parentY, parentWidth, parentHeight); + + if (this->m_contentElement != nullptr) { + this->m_contentElement->setBoundaries(parentX + 35, parentY + ult::activeHeaderHeight, parentWidth - 85, parentHeight - 73 - 105); + this->m_contentElement->invalidate(); + } + } + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) override { + if (this->m_contentElement != nullptr) + return this->m_contentElement->requestFocus(oldFocus, direction); + else + return nullptr; + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) { + // Discard touches outside bounds + if (!this->m_contentElement->inBounds(currX, currY)) + return false; + + if (this->m_contentElement != nullptr) + return this->m_contentElement->onTouch(event, currX, currY, prevX, prevY, initialX, initialY); + else return false; + } + + /** + * @brief Sets the content of the frame + * + * @param content Element + */ + inline void setContent(Element *content) { + if (this->m_contentElement != nullptr) + delete this->m_contentElement; + + this->m_contentElement = content; + + if (content != nullptr) { + this->m_contentElement->setParent(this); + this->invalidate(); + } + } + + /** + * @brief Changes the title of the menu + * + * @param title Title to change to + */ + inline void setTitle(const std::string &title) { + this->m_title = title; + } + + /** + * @brief Changes the subtitle of the menu + * + * @param title Subtitle to change to + */ + inline void setSubtitle(const std::string &subtitle) { + this->m_subtitle = subtitle; + } + + protected: + Element *m_contentElement = nullptr; + + //std::string m_title, m_subtitle; + }; + #else + /** + * @brief The base frame which can contain another view with a customizable header + * + */ + class HeaderOverlayFrame : public Element { + public: + #if USING_WIDGET_DIRECTIVE + bool m_showWidget = false; + #endif + + HeaderOverlayFrame(u16 headerHeight = 175) : Element(), m_headerHeight(headerHeight) { + ult::activeHeaderHeight = headerHeight; + // Load the bitmap file into memory + ult::loadWallpaperFileWhenSafe(); + m_isItem = false; + + } + virtual ~HeaderOverlayFrame() { + if (this->m_contentElement != nullptr) + delete this->m_contentElement; + + if (this->m_header != nullptr) + delete this->m_header; + } + + virtual void draw(gfx::Renderer *renderer) override { + + renderer->fillScreen(a(defaultBackgroundColor)); + renderer->drawWallpaper(); + renderer->drawRect(15, tsl::cfg::FramebufferHeight - 73, tsl::cfg::FramebufferWidth - 30, 1, a(bottomSeparatorColor)); + + #if USING_WIDGET_DIRECTIVE + if (m_showWidget) + renderer->drawWidget(); + #endif + + // Get the exact gap width from ult::GAP_1 + const float gapWidth = renderer->getTextDimensions(ult::GAP_1, false, 23).first; + const float _halfGap = gapWidth / 2.0f; + if (_halfGap != ult::halfGap.load(std::memory_order_acquire)) + ult::halfGap.store(_halfGap, std::memory_order_release); + + // Calculate text dimensions for buttons without gaps + const float backTextWidth = renderer->getTextDimensions("\uE0E1" + ult::GAP_2 + ult::BACK, false, 23).first; + const float selectTextWidth = renderer->getTextDimensions("\uE0E0" + ult::GAP_2 + ult::OK, false, 23).first; + + // Store final widths with gap padding included + const float _backWidth = backTextWidth + gapWidth; + if (_backWidth != ult::backWidth.load(std::memory_order_acquire)) + ult::backWidth.store(_backWidth, std::memory_order_release); + const float _selectWidth = selectTextWidth + gapWidth; + if (_selectWidth != ult::selectWidth.load(std::memory_order_acquire)) + ult::selectWidth.store(_selectWidth, std::memory_order_release); + + // Set initial button position + static constexpr float buttonStartX = 30; + const float buttonY = static_cast(cfg::FramebufferHeight - 73 + 1); + + // Draw back button rectangle + if (ult::touchingBack.load(std::memory_order_acquire)) { + renderer->drawRoundedRect(buttonStartX+2 - _halfGap, buttonY, _backWidth-1, 73.0f, 12.0f, a(clickColor)); + } + + // Draw select button rectangle + if (ult::touchingSelect.load(std::memory_order_acquire)) { + renderer->drawRoundedRect(buttonStartX+2 - _halfGap + _backWidth+1, buttonY, + _selectWidth-2, 73.0f, 12.0f, a(clickColor)); + } + + // Draw bottom text + const std::string menuBottomLine = "\uE0E1" + ult::GAP_2 + ult::BACK + ult::GAP_1 + + "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1; + renderer->drawStringWithColoredSections(menuBottomLine, false, + {"\uE0E1", "\uE0E0", "\uE0ED", "\uE0EE"}, + buttonStartX, 693, 23, + bottomTextColor, buttonColor); + if (!usingUnfocusedColor) { + renderer->drawStringWithColoredSections("\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1, false, + {"\uE0E1", "\uE0E0", "\uE0ED", "\uE0EE"}, + buttonStartX + _backWidth, 693, 23, + unfocusedColor, unfocusedColor); + } + + if (this->m_header != nullptr) + this->m_header->frame(renderer); + + if (this->m_contentElement != nullptr) + this->m_contentElement->frame(renderer); + + if (!ult::useRightAlignment) + renderer->drawRect(447, 0, 448, 720, a(edgeSeparatorColor)); + else + renderer->drawRect(0, 0, 1, 720, a(edgeSeparatorColor)); + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + this->setBoundaries(parentX, parentY, parentWidth, parentHeight); + + if (this->m_contentElement != nullptr) { + this->m_contentElement->setBoundaries(parentX + 35, parentY + this->m_headerHeight, parentWidth - 85, parentHeight - 73 - this->m_headerHeight -8); + this->m_contentElement->invalidate(); + } + + if (this->m_header != nullptr) { + this->m_header->setBoundaries(parentX, parentY, parentWidth, this->m_headerHeight); + this->m_header->invalidate(); + } + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) { + // Discard touches outside bounds + if (!this->m_contentElement->inBounds(currX, currY)) + return false; + + if (this->m_contentElement != nullptr) + return this->m_contentElement->onTouch(event, currX, currY, prevX, prevY, initialX, initialY); + else return false; + } + + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) override { + if (this->m_contentElement != nullptr) + return this->m_contentElement->requestFocus(oldFocus, direction); + else + return nullptr; + } + + /** + * @brief Sets the content of the frame + * + * @param content Element + */ + inline void setContent(Element *content) { + if (this->m_contentElement != nullptr) + delete this->m_contentElement; + + this->m_contentElement = content; + + if (content != nullptr) { + this->m_contentElement->setParent(this); + this->invalidate(); + } + } + + /** + * @brief Sets the header of the frame + * + * @param header Header custom drawer + */ + inline void setHeader(CustomDrawer *header) { + if (this->m_header != nullptr) + delete this->m_header; + + this->m_header = header; + + if (header != nullptr) { + this->m_header->setParent(this); + this->invalidate(); + } + } + + protected: + Element *m_contentElement = nullptr; + CustomDrawer *m_header = nullptr; + + u16 m_headerHeight; + }; + #endif + + + + /** + * @brief Single color rectangle element mainly used for debugging to visualize boundaries + * + */ + class DebugRectangle : public Element { + public: + /** + * @brief Constructor + * + * @param color Color of the rectangle + */ + DebugRectangle(Color color) : Element(), m_color(color) { + m_isItem = false; + } + virtual ~DebugRectangle() {} + + virtual void draw(gfx::Renderer *renderer) override { + renderer->drawRect(ELEMENT_BOUNDS(this), a(this->m_color)); + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override {} + + private: + Color m_color; + }; + + class ListItem; // forward declaration + + static std::atomic s_currentScrollVelocity{0}; + static std::atomic s_directionalKeyReleased{false}; + static std::atomic lastInternalTouchRelease{true}; + + static std::mutex s_safeToSwapMutex; + static std::atomic s_safeToSwap{false}; + static std::atomic skipOnce{false}; + + static std::atomic isTableScrolling{false}; + + class List : public Element { + + public: + List() : Element() { + + s_safeToSwap.store(false, std::memory_order_release); + + // Clear table scrolling flag when list is cleared + isTableScrolling.store(false, std::memory_order_release); + + // Initialize instance state + m_pendingJump = false; + m_clearList = false; + m_focusedIndex = 0; + m_offset = 0; + m_nextOffset = 0; + m_listHeight = 0; + actualItemCount = 0; + m_isItem = false; + m_hasSetInitialFocusHack = false; + m_hasRenderedInitialFocus = false; + + // Initialize new scrollbar color transition members + m_scrollbarAtWall = false; + m_scrollbarColorTransition = 0.0f; + m_lastWallReleaseTime = 0; + } + + virtual ~List() { + s_safeToSwap.store(false, std::memory_order_release); + purgePendingItems(); + clearItems(); + } + + + virtual void draw(gfx::Renderer* renderer) override { + + s_safeToSwap.store(false, std::memory_order_release); + std::lock_guard lock(s_safeToSwapMutex); + + if (m_clearList) { + clearItems(); + return; + } + + bool justResolved = false; + + // Process pending operations + if (!m_itemsToAdd.empty()) { + // Add items to m_items but DON'T invalidate yet + addPendingItems(true); // Skip invalidate + + // Calculate m_listHeight FIRST + m_listHeight = BOTTOM_PADDING; + for (Element* entry : m_items) { + m_listHeight += entry->getHeight(); + } + + // NOW invalidate with m_offset still at 0 to get initial positions + invalidate(); + + // THEN resolve jump AFTER layout has positioned items + if (m_pendingJump && !m_items.empty()) { + resolveJumpImmediately(); + justResolved = true; + } else if (!m_hasSetInitialFocusHack && !m_items.empty()) { + // NO JUMP: Set up focus on first item + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i]->m_isItem) { + m_focusedIndex = i; + m_hasSetInitialFocusHack = true; + + // Calculate position using the same logic as updateScrollOffset + float itemPos = 0.0f; + for (size_t j = 0; j < i && j < m_items.size(); ++j) { + itemPos += m_items[j]->getHeight(); + } + + const float itemHeight = m_items[i]->getHeight(); + const float viewHeight = static_cast(getHeight()); + const float maxOffset = (m_listHeight > viewHeight) ? + static_cast(m_listHeight - viewHeight) : 0.0f; + + const float itemCenterPos = itemPos + (itemHeight / 2.0f); + const float viewportCenter = viewHeight / 2.0f + VIEW_CENTER_OFFSET + 0.5f; + const float idealOffset = std::max(0.0f, std::min(itemCenterPos - viewportCenter, maxOffset)); + + m_offset = m_nextOffset = idealOffset; + + // Now invalidate AGAIN with correct offset + invalidate(); + justResolved = true; + break; + } + } + } + } + if (!m_itemsToRemove.empty()) { + removePendingItems(); + } + + const s32 topBound = getTopBound(); + const s32 bottomBound = getBottomBound(); + const s32 height = getHeight(); + + renderer->enableScissoring(getLeftBound(), topBound-8, getWidth() + 8, height + 14); + + // Manually set focus flag on the target item for the first frame + if (m_hasSetInitialFocusHack && !m_hasRenderedInitialFocus && !m_items.empty() && m_focusedIndex < m_items.size()) { + bool anyItemFocused = false; + for (Element* item : m_items) { + if (item && item->hasFocus()) { + anyItemFocused = true; + break; + } + } + + if (!anyItemFocused) { + m_items[m_focusedIndex]->setFocused(true); + } + m_hasRenderedInitialFocus = true; + } + + for (Element* entry : m_items) { + if (entry->getBottomBound() > topBound && entry->getTopBound() < bottomBound) { + entry->frame(renderer); + } + } + + renderer->disableScissoring(); + + if (m_listHeight > height) { + drawScrollbar(renderer, height); + if (!justResolved) { + updateScrollAnimation(); + } + } + + s_safeToSwap.store(true, std::memory_order_release); + } + + void resolveJumpImmediately() { + float h = 0.0f; + bool foundMatch = false; + + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i]->matchesJumpCriteria(m_jumpToText, m_jumpToValue, m_jumpToExactMatch)) { + m_focusedIndex = i; + foundMatch = true; + + // Calculate position using the same logic as updateScrollOffset + const float itemHeight = m_items[i]->getHeight(); + const float viewHeight = static_cast(getHeight()); + const float maxOffset = (m_listHeight > viewHeight) ? + static_cast(m_listHeight - viewHeight) : 0.0f; + + const float itemCenterPos = h + (itemHeight / 2.0f); + const float viewportCenter = viewHeight / 2.0f + VIEW_CENTER_OFFSET + 0.5f; + const float idealOffset = std::max(0.0f, std::min(itemCenterPos - viewportCenter, maxOffset)); + + m_offset = m_nextOffset = idealOffset; + + // Now invalidate AGAIN with correct offset so layout repositions items + invalidate(); + + // Manually set the focus flag for first frame drawing + m_items[m_focusedIndex]->setFocused(true); + + m_hasSetInitialFocusHack = true; + m_hasRenderedInitialFocus = true; + m_pendingJump = false; + + break; + } + + h += m_items[i]->getHeight(); + } + + // FALLBACK: If no match found, focus first item instead + if (!foundMatch) { + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i]->m_isItem) { + m_focusedIndex = i; + m_hasSetInitialFocusHack = true; + + // Calculate position using the same logic as updateScrollOffset + float itemPos = 0.0f; + for (size_t j = 0; j < i && j < m_items.size(); ++j) { + itemPos += m_items[j]->getHeight(); + } + + const float itemHeight = m_items[i]->getHeight(); + const float viewHeight = static_cast(getHeight()); + const float maxOffset = (m_listHeight > viewHeight) ? + static_cast(m_listHeight - viewHeight) : 0.0f; + + const float itemCenterPos = itemPos + (itemHeight / 2.0f); + const float viewportCenter = viewHeight / 2.0f + VIEW_CENTER_OFFSET + 0.5f; + const float idealOffset = std::max(0.0f, std::min(itemCenterPos - viewportCenter, maxOffset)); + + m_offset = m_nextOffset = idealOffset; + + // Now invalidate AGAIN with correct offset + invalidate(); + + // Manually set the focus flag for first frame drawing + m_items[i]->setFocused(true); + + m_hasRenderedInitialFocus = true; + + break; + } + } + } + + m_pendingJump = false; + } + + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + s32 y = getY() - m_offset; + + // Position all items first (don't calculate m_listHeight here) + for (Element* entry : m_items) { + entry->setBoundaries(getX(), y, getWidth(), entry->getHeight()); + entry->invalidate(); + y += entry->getHeight(); + } + + + // Calculate total height AFTER all invalidations are done + m_listHeight = BOTTOM_PADDING; + for (Element* entry : m_items) { + m_listHeight += entry->getHeight(); + } + } + + // Fixed onTouch method - prevents controller state corruption + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + // Quick bounds check + if (!inBounds(currX, currY)) return false; + + // Forward to children first + for (Element* item : m_items) { + if (item->onTouch(event, currX, currY, prevX, prevY, initialX, initialY)) { + return true; + } + } + + // Handle scrolling + if (event != TouchEvent::Release && Element::getInputMode() == InputMode::TouchScroll) { + if (prevX && prevY) { + m_nextOffset += (prevY - currY); + m_nextOffset = std::clamp(m_nextOffset, 0.0f, static_cast(m_listHeight - getHeight())); + + // Track that we're touch scrolling + m_touchScrollActive = true; + } + return true; + } + + return false; + } + + + inline void addItem(Element* element, u16 height = 0, ssize_t index = -1) { + if (!element) return; + + // First item optimization + if (actualItemCount == 0 && element->m_isItem) { + auto* customDrawer = new tsl::elm::CustomDrawer([](gfx::Renderer*, s32, s32, s32, s32) {}); + customDrawer->setBoundaries(getX(), getY(), getWidth(), 29+4); + customDrawer->setParent(this); + customDrawer->invalidate(); + m_itemsToAdd.emplace_back(-1, customDrawer); + } + + if (height) { + element->setBoundaries(getX(), getY(), getWidth(), height); + } + + element->setParent(this); + element->invalidate(); + m_itemsToAdd.emplace_back(index, element); + ++actualItemCount; + } + + virtual void removeItem(Element *element) { + if (element) m_itemsToRemove.push_back(element); + } + + virtual void removeIndex(size_t index) { + if (index < m_items.size()) removeItem(m_items[index]); + } + + inline void clear() { + m_clearList = true; + } + + virtual Element* requestFocus(Element* oldFocus, FocusDirection direction) override { + if (m_clearList || !m_itemsToAdd.empty()) return nullptr; + + // If jump was just resolved, return the target item with proper focus + if (m_hasSetInitialFocusHack && direction == FocusDirection::None && m_focusedIndex < m_items.size()) { + // Request focus properly through the focus system + Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus) { + return newFocus; + } + } + + if (jumpToBottom.exchange(false, std::memory_order_acq_rel)) + return handleJumpToBottom(oldFocus); + + if (jumpToTop.exchange(false, std::memory_order_acq_rel)) + return handleJumpToTop(oldFocus); + + if (skipDown.exchange(false, std::memory_order_acq_rel)) + return handleSkipDown(oldFocus); + + if (skipUp.exchange(false, std::memory_order_acq_rel)) + return handleSkipUp(oldFocus); + + if (direction == FocusDirection::None) { + return handleInitialFocus(oldFocus); + } + else if (direction == FocusDirection::Down) { + return handleDownFocus(oldFocus); + } + else if (direction == FocusDirection::Up) { + return handleUpFocus(oldFocus); + } + + return oldFocus; + } + + inline void jumpToItem(const std::string& text = "", const std::string& value = "", bool exactMatch=true) { + + if (!text.empty() || !value.empty()) { + m_pendingJump = true; + m_jumpToText = text; + m_jumpToValue = value; + m_jumpToExactMatch = exactMatch; + } + + } + + virtual Element* getItemAtIndex(u32 index) { + return (m_items.size() <= index) ? nullptr : m_items[index]; + } + + virtual s32 getIndexInList(Element *element) { + auto it = std::find(m_items.begin(), m_items.end(), element); + return (it == m_items.end()) ? -1 : static_cast(it - m_items.begin()); + } + + virtual s32 getLastIndex() { + return static_cast(m_items.size()) - 1; + } + + virtual void setFocusedIndex(u32 index) { + if (m_items.size() > index) { + m_focusedIndex = index; + updateScrollOffset(); + } + } + + inline void onDirectionalKeyReleased() { + m_hasWrappedInCurrentSequence = false; + m_lastNavigationResult = NavigationResult::None; + m_isHolding = false; + m_stoppedAtBoundary = false; + m_justArrivedAtBoundary = false; + m_lastNavigationTime = 0; + m_lastScrollTime = 0; + } + + protected: + + std::vector m_items; + u16 m_focusedIndex = 0; + + float m_offset = 0, m_nextOffset = 0; + s32 m_listHeight = 0; + + bool m_clearList = false; + std::vector m_itemsToRemove; + std::vector> m_itemsToAdd; + std::vector prefixSums; + + + // Enhanced navigation state tracking + bool m_justWrapped = false; + bool m_isHolding = false; + bool m_stoppedAtBoundary = false; + u64 m_lastNavigationTime = 0; + static constexpr u64 HOLD_THRESHOLD_NS = 100000000ULL; // 100ms + + size_t actualItemCount = 0; + + // Jump to navigation variables + std::string m_jumpToText; + std::string m_jumpToValue; + bool m_jumpToExactMatch = false; + bool m_pendingJump = false; + + bool m_justArrivedAtBoundary = false; + bool m_hasSetInitialFocusHack = false; + bool m_hasRenderedInitialFocus = false; + + // Stack variables for hot path - reused to avoid allocations + u32 scrollbarHeight; + u32 scrollbarOffset; + u32 prevOffset; + static constexpr float SCROLLBAR_X_OFFSET = 21.0f; + static constexpr float SCROLLBAR_Y_OFFSET = 3.0f; + static constexpr float SCROLLBAR_HEIGHT_TRIM = 6.0f; + + bool m_scrollbarAtWall = false; + float m_scrollbarColorTransition = 0.0f; // 0.0 = scrollBarColor, 1.0 = scrollBarWallColor + u64 m_lastWallReleaseTime = 0; + static constexpr u64 COLOR_TRANSITION_DURATION_NS = 300000000ULL; // 0.3 seconds + + static constexpr float TABLE_SCROLL_SPEED_PPS = 120.0f*4; // Pixels per second when holding + static constexpr float TABLE_SCROLL_SPEED_CLICK_PPS = 120.0f*4; // Pixels per second for single click + + static constexpr float BOTTOM_PADDING = 7.0f; + static constexpr float VIEW_CENTER_OFFSET = 7.0f; + + u64 m_lastScrollTime = 0; + float m_scrollVelocity = 0.0f; + bool m_touchScrollActive = false; + + enum class NavigationResult { + None, + Success, + HitBoundary, + Wrapped + }; + + bool m_hasWrappedInCurrentSequence = false; + NavigationResult m_lastNavigationResult = NavigationResult::None; + + private: + + void clearItems() { + + for (Element* item : m_items) delete item; + m_items = {}; + m_offset = 0; + m_focusedIndex = 0; + invalidate(); + m_clearList = false; + actualItemCount = 0; + m_hasSetInitialFocusHack = false; + + // Clear table scrolling flag when list is cleared + isTableScrolling.store(false, std::memory_order_release); + } + + void addPendingItems(bool skipInvalidate = false) { + for (auto [index, element] : m_itemsToAdd) { + element->invalidate(); + if (index >= 0 && static_cast(index) < m_items.size()) { + m_items.insert(m_items.begin() + index, element); + } else { + m_items.push_back(element); + } + } + m_itemsToAdd.clear(); + + if (!skipInvalidate) { + invalidate(); + updateScrollOffset(); + } + } + + void removePendingItems() { + //size_t index; + for (Element* element : m_itemsToRemove) { + auto it = std::find(m_items.begin(), m_items.end(), element); + if (it != m_items.end()) { + const size_t index = static_cast(it - m_items.begin()); + m_items.erase(it); + if (m_focusedIndex >= index && m_focusedIndex > 0) { + --m_focusedIndex; + } + delete element; + } + } + m_itemsToRemove = {}; + invalidate(); + updateScrollOffset(); + } + + void purgePendingItems() { + for (auto& [_, element] : m_itemsToAdd) { + if (element) { element->invalidate(); delete element; } + } + m_itemsToAdd = {}; + + //size_t index; + for (Element* element : m_itemsToRemove) { + auto it = std::find(m_items.begin(), m_items.end(), element); + if (it != m_items.end()) { + const u16 index16 = static_cast(static_cast(it - m_items.begin())); + element->invalidate(); + delete element; + m_items.erase(it); + + constexpr u16 noFocus = static_cast(0xFFFF); + if (m_focusedIndex == index16) + m_focusedIndex = noFocus; + else if (m_focusedIndex != noFocus && m_focusedIndex > index16) + --m_focusedIndex; + } + } + m_itemsToRemove = {}; + + invalidate(); + updateScrollOffset(); + } + + + void drawScrollbar(gfx::Renderer* renderer, s32 height) { + const float viewHeight = static_cast(height); + const float totalHeight = static_cast(m_listHeight); + const u32 maxScrollableHeight = std::max(static_cast(totalHeight - viewHeight), 1u); + + scrollbarHeight = std::min(static_cast((viewHeight * viewHeight) / totalHeight), + static_cast(viewHeight)); + + scrollbarOffset = std::min(static_cast((m_offset / maxScrollableHeight) * (viewHeight - scrollbarHeight)), + static_cast(viewHeight - scrollbarHeight)); + + const u32 scrollbarX = getRightBound() + SCROLLBAR_X_OFFSET; + const u32 scrollbarY = getY() + scrollbarOffset + SCROLLBAR_Y_OFFSET; + + scrollbarHeight -= SCROLLBAR_HEIGHT_TRIM; + + // Check if we're at a wall (boundary) + const bool currentlyAtWall = (m_lastNavigationResult == NavigationResult::HitBoundary) && + (m_stoppedAtBoundary || m_justArrivedAtBoundary); + + static bool triggerOnce = true; + + // Detect transition from "not at wall" to "at wall" - trigger flash ONCE + if (currentlyAtWall && !m_scrollbarAtWall && !s_directionalKeyReleased.load(std::memory_order_acquire)) { + m_scrollbarColorTransition = 1.0f; // Instant jump to wall color + + if (triggerOnce) { + // NEW: Trigger wall effect here based on scroll position + const float maxOffset = static_cast(m_listHeight - getHeight()); + if (m_offset <= 0.0f) { + triggerWallEffect(FocusDirection::Up); + } else if (m_offset >= maxOffset - 1.0f) { + triggerWallEffect(FocusDirection::Down); + } + } + triggerOnce = false; + } else { + triggerOnce = true; + } + + // Detect transition from "not at wall" to "at wall" - trigger flash ONCE + if (currentlyAtWall && !m_scrollbarAtWall && s_directionalKeyReleased.load(std::memory_order_acquire)) { + m_scrollbarAtWall = true; + m_scrollbarColorTransition = 1.0f; // Instant jump to wall color + m_lastWallReleaseTime = ult::nowNs(); // Start transition immediately + } + + // Reset flag when we leave the wall (so we can trigger again next time) + if (!currentlyAtWall && m_scrollbarAtWall) { + m_scrollbarAtWall = false; + m_scrollbarColorTransition = 0.0f; // Reset to normal immediately + } + + // Smooth transition back to scrollBarColor over 0.5s + if (m_scrollbarAtWall && m_scrollbarColorTransition > 0.0f) { + const u64 currentTime = ult::nowNs(); + const u64 elapsed = currentTime - m_lastWallReleaseTime; + + if (elapsed >= COLOR_TRANSITION_DURATION_NS) { + m_scrollbarColorTransition = 0.0f; // Transition complete + } else { + // Linear interpolation from 1.0 to 0.0 + const float progress = static_cast(elapsed) / static_cast(COLOR_TRANSITION_DURATION_NS); + m_scrollbarColorTransition = 1.0f - progress; + } + } + + // Interpolate between scrollBarColor and scrollBarWallColor + tsl::Color currentColor = scrollBarColor; + if (m_scrollbarColorTransition >= 1.0f) { + currentColor = scrollBarWallColor; + } else if (m_scrollbarColorTransition > 0.0f) { + const float t = m_scrollbarColorTransition; + const float oneMinusT = 1.0f - t; + + const u8 r = static_cast(scrollBarColor.r * oneMinusT + scrollBarWallColor.r * t); + const u8 g = static_cast(scrollBarColor.g * oneMinusT + scrollBarWallColor.g * t); + const u8 b = static_cast(scrollBarColor.b * oneMinusT + scrollBarWallColor.b * t); + const u8 a = static_cast(scrollBarColor.a * oneMinusT + scrollBarWallColor.a * t); + + currentColor = tsl::Color(r, g, b, a); + } + + // Draw scrollbar with interpolated color + renderer->drawRect(scrollbarX, scrollbarY, 5, scrollbarHeight, a(currentColor)); + renderer->drawCircle(scrollbarX + 2, scrollbarY, 2, true, a(currentColor)); + renderer->drawCircle(scrollbarX + 2, scrollbarY + scrollbarHeight, 2, true, a(currentColor)); + } + + + inline void updateScrollAnimation() { + if (Element::getInputMode() == InputMode::Controller) { + m_touchScrollActive = false; + + const float diff = m_nextOffset - m_offset; + const float distance = std::abs(diff); + + // Boundary snapping + if (distance < 1.0f) { + m_offset = m_nextOffset; + m_scrollVelocity = 0.0f; + s_currentScrollVelocity.store(m_scrollVelocity, std::memory_order_release); + + if (prevOffset != m_offset) { + invalidate(); + prevOffset = m_offset; + } + return; + } + + const float maxOffset = static_cast(m_listHeight - getHeight()); + if (m_nextOffset == 0.0f || m_nextOffset == maxOffset) { + if (distance < 3.0f) { + m_offset = m_nextOffset; + m_scrollVelocity = 0.0f; + s_currentScrollVelocity.store(m_scrollVelocity, std::memory_order_release); + + if (prevOffset != m_offset) { + invalidate(); + prevOffset = m_offset; + } + return; + } + } + + // Emergency correction + if (m_focusedIndex < m_items.size()) { + float itemTop = 0.0f; + for (size_t i = 0; i < m_focusedIndex; ++i) { + itemTop += m_items[i]->getHeight(); + } + const float itemBottom = itemTop + m_items[m_focusedIndex]->getHeight(); + const float viewBottom = m_offset + getHeight(); + + if (itemTop < m_offset || itemBottom > viewBottom) { + const float emergencySpeed = (itemBottom < m_offset || itemTop > viewBottom) ? 0.9f : 0.6f; + m_offset += diff * emergencySpeed; + m_scrollVelocity = diff * 0.3f; + s_currentScrollVelocity.store(m_scrollVelocity, std::memory_order_release); + + if (prevOffset != m_offset) { + invalidate(); + prevOffset = m_offset; + } + return; + } + } + + const bool isTableScrolling = tsl::elm::isTableScrolling.load(std::memory_order_acquire); + + if (isTableScrolling) { + // Direct assignment - instant updates, smoothness comes from small frequent steps + m_offset = m_nextOffset; + m_scrollVelocity = 0.0f; + } else { + // Original smooth scrolling for regular navigation + const bool isLargeJump = distance > getHeight() * 1.5f; + const bool isFromRest = std::abs(m_scrollVelocity) < 2.0f; + + if (isLargeJump && isFromRest) { + static constexpr float gentleAcceleration = 0.08f; + static constexpr float gentleDamping = 0.85f; + + const float targetVelocity = diff * gentleAcceleration; + m_scrollVelocity += (targetVelocity - m_scrollVelocity) * gentleDamping; + } else { + const float urgency = std::min(distance / getHeight(), 1.0f); + const float accelerationFactor = 0.18f + (0.24f * urgency); + const float dampingFactor = 0.48f - (0.18f * urgency); + + const float targetVelocity = diff * accelerationFactor; + m_scrollVelocity += (targetVelocity - m_scrollVelocity) * dampingFactor; + } + + m_offset += m_scrollVelocity; + } + + // Overshoot prevention + if ((m_scrollVelocity > 0 && m_offset > m_nextOffset) || + (m_scrollVelocity < 0 && m_offset < m_nextOffset)) { + m_offset = m_nextOffset; + m_scrollVelocity = 0.0f; + } + + // Force exact boundary values + if (m_nextOffset == 0.0f && m_offset < 1.0f) { + m_offset = 0.0f; + m_scrollVelocity = 0.0f; + } else if (m_nextOffset == maxOffset && m_offset > maxOffset - 1.0f) { + m_offset = maxOffset; + m_scrollVelocity = 0.0f; + } + + s_currentScrollVelocity.store(m_scrollVelocity, std::memory_order_release); + + } else if (Element::getInputMode() == InputMode::TouchScroll) { + m_offset = m_nextOffset; + m_scrollVelocity = 0.0f; + + if (m_touchScrollActive) { + const float viewCenter = m_offset + (getHeight() / 2.0f); + float accumHeight = 0.0f; + + for (size_t i = 0; i < m_items.size(); ++i) { + const float itemHeight = m_items[i]->getHeight(); + const float itemCenter = accumHeight + (itemHeight / 2.0f); + + if (itemCenter >= viewCenter) { + m_focusedIndex = i; + break; + } + + accumHeight += itemHeight; + } + } + } + + if (prevOffset != m_offset) { + invalidate(); + prevOffset = m_offset; + } + } + + + Element* handleInitialFocus(Element* oldFocus) { + const size_t itemCount = m_items.size(); + if (itemCount == 0) return nullptr; + + size_t startIndex = 0; + + // Calculate starting index based on current scroll position + if (!oldFocus && m_offset > 0) { + float elementHeight = 0.0f; + const size_t maxIndex = itemCount - 1; + while (elementHeight < m_offset && startIndex < maxIndex) { + elementHeight += m_items[startIndex]->getHeight(); + ++startIndex; + } + } + + // Save current offset to prevent scroll jumping + const float savedOffset = m_offset; + const float savedNextOffset = m_nextOffset; + + // Single loop with wraparound logic - visits each item exactly once + for (size_t count = 0; count < itemCount; ++count) { + const size_t i = (startIndex + count) % itemCount; + + if (!m_items[i]->isTable()) { + Element* const newFocus = m_items[i]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus) { + m_focusedIndex = i; + m_offset = savedOffset; + m_nextOffset = savedNextOffset; + return newFocus; + } + } + } + + return nullptr; + } + + inline void triggerWallEffect(FocusDirection direction) { + + if (m_items.empty()) { + triggerWallFeedback(); + return; + } + + // Directional search bounds + ssize_t i = static_cast(m_focusedIndex); + ssize_t end = (direction == FocusDirection::Down) ? -1 : static_cast(m_items.size()); + ssize_t step = (direction == FocusDirection::Down) ? -1 : 1; + + // Walk until we hit a real item + for (; i != end; i += step) { + auto *it = m_items[i]; + if (it->m_isItem) { + it->shakeHighlight(direction); + return; + } + } + + triggerWallFeedback(); + } + + inline Element* handleDownFocus(Element* oldFocus) { + const bool atBottom = isAtBottom(); + updateHoldState(); + + // Check if the next item is non-focusable + if (m_focusedIndex + 1 < static_cast(m_items.size()) && + !m_items[m_focusedIndex + 1]->m_isItem && m_listHeight > getHeight()) { + isTableScrolling.store(true, std::memory_order_release); + } + + // If holding and at boundary, try to scroll first + if (m_isHolding && m_stoppedAtBoundary && !atBottom) { + scrollDown(); + m_stoppedAtBoundary = false; + return oldFocus; + } + + Element* result = navigateDown(oldFocus); + + if (result != oldFocus) { + m_lastNavigationResult = NavigationResult::Success; + m_stoppedAtBoundary = false; + + // NEW: Check if we just navigated to the last focusable item + // If so, set boundary flag regardless of scroll position + bool isLastFocusableItem = true; + for (size_t i = m_focusedIndex + 1; i < m_items.size(); ++i) { + if (m_items[i]->m_isItem) { + isLastFocusableItem = false; + break; + } + } + + // Set boundary flag if we're at last focusable item OR at scroll bottom + m_justArrivedAtBoundary = isLastFocusableItem || isAtBottom(); + + triggerNavigationFeedback(); + return result; + } + + // Check if we can still scroll down + if (!atBottom) { + scrollDown(); + return oldFocus; + } + + // Force boundary hit before allowing wrap + if (m_justArrivedAtBoundary) { + m_justArrivedAtBoundary = false; + m_stoppedAtBoundary = true; + m_lastNavigationResult = NavigationResult::HitBoundary; + if (m_listHeight <= getHeight()) + triggerWallEffect(FocusDirection::Down); + return oldFocus; + } + + // Check for wrapping (single tap only) + if (!m_isHolding && !m_hasWrappedInCurrentSequence) { + s_directionalKeyReleased.store(false, std::memory_order_release); + m_hasWrappedInCurrentSequence = true; + m_lastNavigationResult = NavigationResult::Wrapped; + return handleJumpToTop(oldFocus); + } + + // Set boundary flag (for holding) + m_lastNavigationResult = NavigationResult::HitBoundary; + if (m_isHolding) { + m_stoppedAtBoundary = true; + } + + return oldFocus; + } + + inline Element* handleUpFocus(Element* oldFocus) { + const bool atTop = isAtTop(); + updateHoldState(); + + // Check if the previous item is non-focusable + if (m_focusedIndex > 0 && m_items[m_focusedIndex - 1]->isTable() && m_listHeight > getHeight()) { + isTableScrolling.store(true, std::memory_order_release); + } + + // If holding and at boundary, try to scroll first + if (m_isHolding && m_stoppedAtBoundary && !atTop) { + scrollUp(); + m_stoppedAtBoundary = false; + return oldFocus; + } + + Element* result = navigateUp(oldFocus); + + if (result != oldFocus) { + m_lastNavigationResult = NavigationResult::Success; + m_stoppedAtBoundary = false; + + // NEW: Check if we just navigated to the first focusable item + // If so, set boundary flag regardless of scroll position + bool isFirstFocusableItem = true; + for (size_t i = 0; i < m_focusedIndex; ++i) { + if (m_items[i]->m_isItem) { + isFirstFocusableItem = false; + break; + } + } + + // Set boundary flag if we're at first focusable item OR at scroll top + m_justArrivedAtBoundary = isFirstFocusableItem || isAtTop(); + + triggerNavigationFeedback(); + return result; + } + + // Check if we can still scroll up + if (!atTop) { + scrollUp(); + return oldFocus; + } + + // Force boundary hit before allowing wrap + if (m_justArrivedAtBoundary) { + m_justArrivedAtBoundary = false; + m_stoppedAtBoundary = true; + m_lastNavigationResult = NavigationResult::HitBoundary; + if (m_listHeight <= getHeight()) + triggerWallEffect(FocusDirection::Up); + return oldFocus; + } + + // Check for wrapping (single tap only) + if (!m_isHolding && !m_hasWrappedInCurrentSequence) { + s_directionalKeyReleased.store(false, std::memory_order_release); + m_hasWrappedInCurrentSequence = true; + m_lastNavigationResult = NavigationResult::Wrapped; + return handleJumpToBottom(oldFocus); + } + + // Set boundary flag (for holding) + m_lastNavigationResult = NavigationResult::HitBoundary; + if (m_isHolding) { + m_stoppedAtBoundary = true; + } + + return oldFocus; + } + + + inline bool isAtTop() { + if (m_items.empty()) return true; + + // Check if we're at scroll position 0 + if (m_offset != 0.0f) return false; + + // Even at offset 0, check if the first item is actually visible + // This handles cases where the first item might be partially above viewport + if (!m_items.empty()) { + Element* firstItem = m_items[0]; + return firstItem->getTopBound() >= getTopBound(); + } + + return true; + } + + inline bool isAtBottom() { + if (m_items.empty()) return true; + + // First check: are we at the maximum scroll offset? + const bool atMaxOffset = (m_offset >= static_cast(m_listHeight - getHeight())); + + // If list is shorter than viewport, we're always at bottom + if (m_listHeight <= getHeight()) return true; + + // If we're not at max offset, we're definitely not at bottom + if (!atMaxOffset) return false; + + // At max offset - now check if the last item is actually fully visible + // This prevents wrap-around when there's still content below viewport + if (!m_items.empty()) { + Element* lastItem = m_items.back(); + + // We're truly at bottom only if: + // 1. We're at max scroll offset AND + // 2. The last item's bottom is at or above the viewport bottom + return lastItem->getBottomBound() <= getBottomBound(); + } + + return atMaxOffset; + } + + // Helper to check if there are any focusable items + inline bool hasAnyFocusableItems() { + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i]->m_isItem) return true; + } + return false; + } + + + inline void updateHoldState() { + const u64 currentTime = ult::nowNs(); + if ((m_lastNavigationTime != 0 && (currentTime - m_lastNavigationTime) < HOLD_THRESHOLD_NS)) { + m_isHolding = true; + } else { + m_isHolding = false; + m_stoppedAtBoundary = false; + m_hasWrappedInCurrentSequence = false; + } + m_lastNavigationTime = currentTime; + + // bug fix, boundary reset upon key release + if (s_directionalKeyReleased.load(std::memory_order_acquire)) + m_justArrivedAtBoundary = false; + } + + inline void resetNavigationState() { + m_hasWrappedInCurrentSequence = false; + m_lastNavigationResult = NavigationResult::None; + m_isHolding = false; + m_stoppedAtBoundary = false; + m_justArrivedAtBoundary = false; + m_lastNavigationTime = 0; + } + + inline Element* handleJumpToItem(Element* oldFocus) { + resetNavigationState(); + invalidate(); + + const bool needsScroll = m_listHeight > getHeight(); + const float viewHeight = static_cast(getHeight()); + const float maxOffset = needsScroll ? m_listHeight - viewHeight : 0.0f; + + float h = 0.0f; + + + for (size_t i = 0; i < m_items.size(); ++i) { + m_focusedIndex = i; + + Element* newFocus = m_items[i]->requestFocus(oldFocus, FocusDirection::Down); + if (newFocus && newFocus != oldFocus && m_items[i]->matchesJumpCriteria(m_jumpToText, m_jumpToValue, m_jumpToExactMatch)) { + // CHANGED: Calculate center of the item and center it in viewport + const float itemHeight = m_items[i]->getHeight(); + // For middle items, use centering logic + const float itemCenterPos = h + (itemHeight / 2.0f); // FIXED: Use center, not bottom + const float viewportCenter = viewHeight / 2.0f + VIEW_CENTER_OFFSET + 0.5f; // Same offset as updateScrollOffset + + // Clamp to valid bounds (same as updateScrollOffset) + const float idealOffset = std::max(0.0f, std::min(itemCenterPos - viewportCenter, maxOffset)); + + // Set both current and target offset + m_offset = m_nextOffset = idealOffset; + + return newFocus; + } + + h += m_items[i]->getHeight(); + } + + // No match found + return handleInitialFocus(oldFocus); + } + + inline void syncFocusIndex(Element* oldFocus, ssize_t& searchIndex) { + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i] == oldFocus) { + m_focusedIndex = i; + searchIndex = static_cast(i); + break; + } + } + } + + // Core navigation logic + // Optimized version with variable definitions pulled outside the loop + inline Element* navigateDown(Element* oldFocus) { + size_t searchIndex = m_focusedIndex + 1; + + // If currently on a table that needs more scrolling + if (m_focusedIndex < m_items.size() && m_items[m_focusedIndex]->isTable()) { + Element* currentTable = m_items[m_focusedIndex]; + if (currentTable->getBottomBound() > getBottomBound()) { + isTableScrolling.store(true, std::memory_order_release); + scrollDown(); + return oldFocus; + } + } + + // Sync AFTER table check - if we're not mid-table-scroll + if (oldFocus && !isTableScrolling.load(std::memory_order_acquire)) { + syncFocusIndex(oldFocus, reinterpret_cast(searchIndex)); + searchIndex++; // Down increments after sync + } + + + const s32 viewBottom = getBottomBound(); + const float containerHeight = getHeight(); + const float offsetPlusHeight = m_offset + containerHeight; + + while (searchIndex < m_items.size()) { + Element* item = m_items[searchIndex]; + m_focusedIndex = searchIndex; + + if (item->isTable()) { + const s32 tableBottom = item->getBottomBound(); + if (tableBottom > viewBottom) { + isTableScrolling.store(true, std::memory_order_release); + scrollDown(); + return oldFocus; + } + searchIndex++; + continue; + } + + Element* newFocus = item->requestFocus(oldFocus, FocusDirection::Down); + if (newFocus && newFocus != oldFocus) { + isTableScrolling.store(false, std::memory_order_release); + updateScrollOffset(); + return newFocus; + } else { + const float itemBottom = calculateItemPosition(searchIndex) + item->getHeight(); + if (itemBottom > offsetPlusHeight) { + isTableScrolling.store(true, std::memory_order_release); + scrollDown(); + return oldFocus; + } + searchIndex++; + } + } + + // ADDED: Clear flag when navigation completes without finding anything + if (m_focusedIndex >= m_items.size() || !m_items[m_focusedIndex]->isTable()) + isTableScrolling.store(false, std::memory_order_release); + return oldFocus; + } + + inline Element* navigateUp(Element* oldFocus) { + + ssize_t searchIndex = static_cast(m_focusedIndex) - 1; + + // If currently on a table that needs more scrolling + if (m_focusedIndex < m_items.size() && m_items[m_focusedIndex]->isTable()) { + Element* currentTable = m_items[m_focusedIndex]; + if (currentTable->getTopBound() < getTopBound()) { + isTableScrolling.store(true, std::memory_order_release); + scrollUp(); + return oldFocus; + } + } + + // Sync AFTER table check - if we're not mid-table-scroll + if (oldFocus && !isTableScrolling.load(std::memory_order_acquire)) { + syncFocusIndex(oldFocus, searchIndex); + searchIndex--; // Up decrements after sync + } + + const s32 viewTop = getTopBound(); + const float offset = m_offset; + + while (searchIndex >= 0) { + Element* item = m_items[searchIndex]; + m_focusedIndex = static_cast(searchIndex); + + if (item->isTable()) { + const s32 tableTop = item->getTopBound(); + if (tableTop < viewTop) { + isTableScrolling.store(true, std::memory_order_release); + scrollUp(); + return oldFocus; + } + searchIndex--; + continue; + } + + Element* newFocus = item->requestFocus(oldFocus, FocusDirection::Up); + if (newFocus && newFocus != oldFocus) { + isTableScrolling.store(false, std::memory_order_release); + updateScrollOffset(); + return newFocus; + } else { + const float itemTop = calculateItemPosition(static_cast(searchIndex)); + if (itemTop < offset) { + isTableScrolling.store(true, std::memory_order_release); + scrollUp(); + return oldFocus; + } + searchIndex--; + } + } + + // Only clear table scrolling if we're not still focused on a table + if (m_focusedIndex >= m_items.size() || !m_items[m_focusedIndex]->isTable()) + isTableScrolling.store(false, std::memory_order_release); + return oldFocus; + } + + // Helper method to calculate an item's position in the list + inline float calculateItemPosition(size_t index) { + float position = 0.0f; + for (size_t i = 0; i < index && i < m_items.size(); ++i) { + position += m_items[i]->getHeight(); + } + return position; + } + + + inline float getScrollDelta() { + const u64 currentTime = ult::nowNs(); + float deltaTime = (m_lastScrollTime != 0) + ? static_cast(currentTime - m_lastScrollTime) / 1000000000.0f + : 1.0f / 60.0f; + m_lastScrollTime = currentTime; + deltaTime = std::min(deltaTime, 0.1f); + const float speedPPS = m_isHolding ? TABLE_SCROLL_SPEED_PPS : TABLE_SCROLL_SPEED_CLICK_PPS; + return speedPPS * deltaTime; + } + + // Enhanced scroll methods that snap to exact boundaries + inline void scrollDown() { + m_nextOffset = std::min(m_nextOffset + getScrollDelta(), + static_cast(m_listHeight - getHeight())); + } + + inline void scrollUp() { + m_nextOffset = std::max(m_nextOffset - getScrollDelta(), 0.0f); + } + + // Unified jump-to-edge: toBottom=true → jump to bottom, false → jump to top + Element* handleJumpToEdge(Element* oldFocus, bool toBottom) { + if (m_items.empty()) return oldFocus; + + invalidate(); + resetNavigationState(); + if (toBottom) jumpToBottom.store(false, std::memory_order_release); + else jumpToTop.store(false, std::memory_order_release); + + static constexpr float tolerance = 5.0f; + const float targetOffset = toBottom + ? ((m_listHeight > getHeight()) ? static_cast(m_listHeight - getHeight()) : 0.0f) + : 0.0f; + + // Find the edge focusable item + size_t edgeFocusableIndex = m_items.size(); + if (toBottom) { + for (ssize_t i = static_cast(m_items.size()) - 1; i >= 0; --i) { + if (m_items[i]->requestFocus(nullptr, FocusDirection::None)) { + edgeFocusableIndex = static_cast(i); + break; + } + } + } else { + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i]->requestFocus(nullptr, FocusDirection::None)) { + edgeFocusableIndex = i; + break; + } + } + } + + if (edgeFocusableIndex == m_items.size()) return oldFocus; + + const bool alreadyAtEdge = (m_focusedIndex == edgeFocusableIndex) && + (std::abs(m_nextOffset - targetOffset) <= tolerance); + if (alreadyAtEdge) return oldFocus; + + const float oldOffset = m_nextOffset; + m_focusedIndex = edgeFocusableIndex; + m_nextOffset = targetOffset; + + // Check for adjacent tables and update table scrolling state + bool hasTables = false; + if (toBottom) { + for (size_t i = edgeFocusableIndex + 1; i < m_items.size(); ++i) { + if (m_items[i]->isTable()) { m_focusedIndex = i; hasTables = true; } + } + } else if (edgeFocusableIndex > 0) { + for (ssize_t i = static_cast(edgeFocusableIndex) - 1; i >= 0; --i) { + if (m_items[i]->isTable()) { m_focusedIndex = static_cast(i); hasTables = true; } + } + } + + if (hasTables && m_listHeight > getHeight()) { + float itemPos = 0.0f; + for (size_t i = 0; i < edgeFocusableIndex; ++i) itemPos += m_items[i]->getHeight(); + const float itemCenter = itemPos + m_items[edgeFocusableIndex]->getHeight() * 0.5f; + const float viewHeight = static_cast(getHeight()); + const float viewportCenter = m_nextOffset + (viewHeight * 0.5f + VIEW_CENTER_OFFSET + 0.5f); + isTableScrolling.store( + toBottom ? (itemCenter < viewportCenter - 1.0f) + : (itemCenter > viewportCenter + 1.0f), + std::memory_order_release); + } else { + isTableScrolling.store(false, std::memory_order_release); + } + + Element* newFocus = m_items[edgeFocusableIndex]->requestFocus(oldFocus, FocusDirection::None); + if ((newFocus && newFocus != oldFocus) || (std::abs(m_nextOffset - oldOffset) > tolerance)) + triggerNavigationFeedback(); + + return newFocus ? newFocus : oldFocus; + } + + Element* handleJumpToBottom(Element* oldFocus) { return handleJumpToEdge(oldFocus, true); } + Element* handleJumpToTop (Element* oldFocus) { return handleJumpToEdge(oldFocus, false); } + + + // Unified page-skip: skipDown=true → skip down, false → skip up + Element* handleSkip(Element* oldFocus, bool skipDown) { + if (m_items.empty()) return oldFocus; + + invalidate(); + resetNavigationState(); + + const float viewHeight = static_cast(getHeight()); + const float maxOffset = (m_listHeight > viewHeight) ? static_cast(m_listHeight - viewHeight) : 0.0f; + static constexpr float tolerance = 0.0f; + + // Find the edge focusable item for the "already there" check + size_t edgeFocusableIndex = m_items.size(); + if (skipDown) { + for (ssize_t i = static_cast(m_items.size()) - 1; i >= 0; --i) { + if (m_items[i]->requestFocus(nullptr, FocusDirection::None)) { + edgeFocusableIndex = static_cast(i); break; + } + } + const bool alreadyAtEdge = (edgeFocusableIndex < m_items.size()) && + (m_focusedIndex == edgeFocusableIndex) && + (std::abs(m_nextOffset - maxOffset) <= tolerance); + if (alreadyAtEdge) return oldFocus; + } else { + for (size_t i = 0; i < m_items.size(); ++i) { + if (m_items[i]->requestFocus(nullptr, FocusDirection::None)) { + edgeFocusableIndex = i; break; + } + } + const bool alreadyAtEdge = (edgeFocusableIndex < m_items.size()) && + (m_focusedIndex == edgeFocusableIndex) && + (std::abs(m_nextOffset - 0.0f) <= tolerance); + if (alreadyAtEdge) return oldFocus; + } + + // Calculate target viewport + const float targetViewportTop = skipDown + ? std::min(m_offset + viewHeight, maxOffset) + : std::max(0.0f, m_offset - viewHeight); + + const float actualTravelDistance = skipDown + ? (targetViewportTop - m_offset) + : (m_offset - targetViewportTop); + const bool traveledFullViewport = (actualTravelDistance >= viewHeight - tolerance); + const float targetViewportCenter = targetViewportTop + (viewHeight * 0.5f + VIEW_CENTER_OFFSET); + + // Find the focusable item closest to the target viewport center + float itemTop = 0.0f; + size_t targetIndex = 0; + bool foundFocusable = false; + float bestDistance = std::numeric_limits::max(); + + for (size_t i = 0; i < m_items.size(); ++i) { + const float itemHeight = m_items[i]->getHeight(); + const float itemCenter = itemTop + itemHeight * 0.5f; + const float dist = std::abs(itemCenter - targetViewportCenter); + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test && test->m_isItem && dist < bestDistance) { + targetIndex = i; bestDistance = dist; foundFocusable = true; + } + itemTop += itemHeight; + } + + const float oldOffset = m_nextOffset; + + if (foundFocusable) { + bool nearEdge = true; + const bool movedPastFocus = skipDown ? (targetIndex > m_focusedIndex) + : (targetIndex < m_focusedIndex); + if (movedPastFocus && traveledFullViewport) { + m_focusedIndex = targetIndex; + nearEdge = false; + } + isTableScrolling.store(false, std::memory_order_release); + updateScrollOffset(); + + Element* newFocus = m_items[targetIndex]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus && !nearEdge && traveledFullViewport) { + triggerNavigationFeedback(); + return newFocus; + } else { + return handleJumpToEdge(oldFocus, skipDown); + } + } else { + // No focusable items — scroll viewport and update focus to nearest visible item + isTableScrolling.store(true, std::memory_order_release); + m_nextOffset = targetViewportTop; + + if (std::abs(m_nextOffset - oldOffset) > 0.0f) + triggerNavigationFeedback(); + + float searchItemTop = 0.0f; + size_t bestVisible = m_focusedIndex; + + for (size_t i = 0; i < m_items.size(); ++i) { + const float itemHeight = m_items[i]->getHeight(); + const float itemBottom = searchItemTop + itemHeight; + const bool inViewport = itemBottom > targetViewportTop && + searchItemTop < targetViewportTop + viewHeight; + + if (skipDown) { + // Wants the LAST visible focusable + if (searchItemTop >= targetViewportTop + viewHeight) break; + if (inViewport) { + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test && test->m_isItem) bestVisible = i; + } + } else { + // Wants the FIRST visible focusable + if (inViewport) { + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test && test->m_isItem) { bestVisible = i; break; } + } + } + searchItemTop += itemHeight; + } + + if (bestVisible != m_focusedIndex) { + m_focusedIndex = bestVisible; + Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus) { + triggerNavigationFeedback(); + return newFocus; + } + } + } + + return oldFocus; + } + + Element* handleSkipDown(Element* oldFocus) { return handleSkip(oldFocus, true); } + Element* handleSkipUp (Element* oldFocus) { return handleSkip(oldFocus, false); } + + + inline void initializePrefixSums() { + prefixSums.clear(); + prefixSums.resize(m_items.size() + 1, 0.0f); + + for (size_t i = 1; i < prefixSums.size(); ++i) { + prefixSums[i] = prefixSums[i - 1] + m_items[i - 1]->getHeight(); + } + } + + + virtual void updateScrollOffset() { + if (Element::getInputMode() != InputMode::Controller) return; + + if (m_listHeight <= getHeight()) { + m_nextOffset = m_offset = 0; + return; + } + + // Calculate position of focused item + float itemPos = 0.0f; + for (size_t i = 0; i < m_focusedIndex && i < m_items.size(); ++i) { + itemPos += m_items[i]->getHeight(); + } + + // Get the focused item's height + const float itemHeight = (m_focusedIndex < m_items.size()) ? m_items[m_focusedIndex]->getHeight() : 0.0f; + + // Calculate viewport height + const float viewHeight = static_cast(getHeight()); + + // FIXED: Special handling for items near the bottom + const float maxOffset = static_cast(m_listHeight - getHeight()); + + // For middle items, use centering logic + const float itemCenterPos = itemPos + (itemHeight / 2.0f); + const float viewportCenter = viewHeight / 2.0f + VIEW_CENTER_OFFSET + 0.5f; // add slight offset + + // Clamp to valid scroll bounds + const float idealOffset = std::max(0.0f, std::min(itemCenterPos - viewportCenter, maxOffset)); + + // Set target for smooth animation + m_nextOffset = idealOffset; + } + + }; + + + + + /** + * @brief A item that goes into a list + * + */ + class ListItem : public Element { + public: + u32 width, height; + u64 m_touchStartTime_ns; + bool isLocked = false; + bool m_touched = false; + + u64 m_shortHoldKey = KEY_Y; + u64 m_longHoldKey = KEY_X; + + ListItem(const std::string& text, const std::string& value = "", bool isMini = false) + : Element(), m_text(text), m_value(value), m_listItemHeight(isMini ? tsl::style::MiniListItemDefaultHeight : tsl::style::ListItemDefaultHeight) { + m_isItem = true; + m_flags.m_useClickAnimation = true; + m_text_clean = m_text; + ult::removeTag(m_text_clean); + applyInitialTranslations(); + if (!value.empty()) applyInitialTranslations(true); + } + + + virtual ~ListItem() = default; + + virtual void draw(gfx::Renderer *renderer) override { + const bool useClickTextColor = m_touched && Element::getInputMode() == InputMode::Touch && ult::touchInBounds; + + if (useClickTextColor && !m_flags.m_isTouchHolding) [[unlikely]] + renderer->drawRectAdaptive(this->getX() + 4, this->getY(), this->getWidth() - 8, this->getHeight(), aWithOpacity(clickColor)); + + #if IS_LAUNCHER_DIRECTIVE + + if (m_flags.m_isTouchHolding) [[unlikely]] { + // Determine the active percentage to use + const float activePercentage = ult::displayPercentage.load(std::memory_order_acquire); + if (activePercentage > 0){ + renderer->drawRectAdaptive(this->getX() + 4, this->getY(), (this->getWidth()- 12 +4)*(activePercentage * 0.01f), this->getHeight(), aWithOpacity(progressColor)); // Direct percentage conversion + } + } + #endif + + const s16 yOffset = ((tsl::style::ListItemDefaultHeight - m_listItemHeight) >> 1) + 1; + + if (!m_maxWidth) [[unlikely]] { + calculateWidths(renderer); + } + + // Optimized separator drawing + const float topBound = this->getTopBound(); + const float bottomBound = this->getBottomBound(); + static float lastBottomBound = 0.0f; + + if (lastBottomBound != topBound) [[unlikely]] { + renderer->drawRect(this->getX() + 4, topBound, this->getWidth() + 10, 1, a(separatorColor)); + } + renderer->drawRect(this->getX() + 4, bottomBound, this->getWidth() + 10, 1, a(separatorColor)); + lastBottomBound = bottomBound; + + #if IS_LAUNCHER_DIRECTIVE + static const std::vector specialChars = {ult::STAR_SYMBOL}; + #else + static const std::vector specialChars = s_dividerSpecialChars; + #endif + // Fast path for non-truncated text + if (!m_flags.m_truncated) [[likely]] { + const Color textColor = m_focused + ? (!ult::useSelectionText + ? (m_flags.m_hasCustomTextColor ? m_customTextColor : defaultTextColor) + : (useClickTextColor + ? clickTextColor + : selectedTextColor)) + : (m_flags.m_hasCustomTextColor + ? m_customTextColor + : (useClickTextColor + ? clickTextColor + : defaultTextColor)); + #if IS_LAUNCHER_DIRECTIVE + renderer->drawStringWithColoredSections(m_text_clean, false, specialChars, this->getX() + 19, this->getY() + 45 - yOffset, 23, + textColor, m_focused ? starColor : selectionStarColor); + #else + renderer->drawStringWithColoredSections(m_text_clean, false, specialChars, this->getX() + 19, this->getY() + 45 - yOffset, 23, + textColor, textSeparatorColor); + #endif + } else { + drawTruncatedText(renderer, yOffset, useClickTextColor, specialChars); + } + + if (!m_value.empty()) [[likely]] { + drawValue(renderer, yOffset, useClickTextColor); + } + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + this->setBoundaries(this->getX() + 3, this->getY(), this->getWidth() + 9, m_listItemHeight); + } + + virtual bool onClick(u64 keys) override { + if (keys & KEY_A) [[likely]] { + + if (!isLocked) { + triggerRumbleClick.store(true, std::memory_order_release); + if (m_value.find(ult::CAPITAL_ON_STR) != std::string::npos) + triggerOffSound.store(true, std::memory_order_release); + else if (m_value.find(ult::CAPITAL_OFF_STR) != std::string::npos) + triggerOnSound.store(true, std::memory_order_release); + else + triggerEnterSound.store(true, std::memory_order_release); + } else { + triggerRumbleDoubleClick.store(true,std::memory_order_release); + triggerWallSound.store(true, std::memory_order_release); + } + + if (m_flags.m_useClickAnimation) + triggerClickAnimation(); + } else if (keys & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) [[unlikely]] { + m_clickAnimationProgress = 0; + } + + return Element::onClick(keys); + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + if (event == TouchEvent::Touch) [[likely]] { + if ((m_touched = inBounds(currX, currY))) [[likely]] { + m_touchStartTime_ns = ult::nowNs(); + m_flags.m_isTouchHolding = false; // Will be set to true when hold activates + m_flags.m_shortThresholdCrossed = false; + m_flags.m_longThresholdCrossed = false; + triggerNavigationFeedback(); + } + } + + if (event == TouchEvent::Hold && m_touched) [[likely]] { + const u64 touchDuration_ns = ult::nowNs() - m_touchStartTime_ns; + const float touchDurationInSeconds = static_cast(touchDuration_ns) * 1e-9f; + + // Activate touch hold immediately when Hold event fires + if (m_flags.m_usingTouchHolding && !m_flags.m_isTouchHolding && touchDurationInSeconds >= 0.1f) { + m_flags.m_isTouchHolding = true; + // Trigger the click with KEY_A to start hold behavior + + return onClick(KEY_A); + } + + if (m_flags.m_useLongThreshold && !m_flags.m_longThresholdCrossed && touchDurationInSeconds >= 1.0f) [[unlikely]] { + m_flags.m_longThresholdCrossed = true; + triggerRumbleClick.store(true, std::memory_order_release); + } else if (m_flags.m_useShortThreshold && !m_flags.m_shortThresholdCrossed && touchDurationInSeconds >= 0.5f) [[unlikely]] { + m_flags.m_shortThresholdCrossed = true; + triggerRumbleClick.store(true, std::memory_order_release); + } + + return true; // Keep handling hold + } + + if (event == TouchEvent::Release && m_touched) [[likely]] { + m_touched = false; + const bool wasHolding = m_flags.m_isTouchHolding; + m_flags.m_isTouchHolding = false; // Stop tracking hold on release + + if (Element::getInputMode() == InputMode::Touch) [[likely]] { + m_clickAnimationProgress = 0; + // Only trigger normal click if we weren't in a hold + if (!wasHolding) { + return onClick(determineKeyOnTouchRelease()); + } + } + } + return false; + } + + virtual void setFocused(bool state) override { + if (state != m_focused) [[likely]] { + m_flags.m_scroll = false; + m_scrollOffset = 0; + timeIn_ns = ult::nowNs(); + Element::setFocused(state); + } + } + + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) override { + return this; + } + + inline void setText(const std::string& text) { + if (m_text_clean != text) [[likely]] { + m_text = text; + m_text_clean = m_text; + if (!m_flags.m_keepTag) ult::removeTag(m_text_clean); + resetTextProperties(); + applyInitialTranslations(); + } + } + + inline void setValue(const std::string& value, bool faint = false) { + if (m_value != value || m_flags.m_faint != faint) [[likely]] { + m_value = value; + m_flags.m_faint = faint; + m_maxWidth = 0; + if (!value.empty()) applyInitialTranslations(true); + } + } + + inline void setTextColor(Color color) { + m_customTextColor = color; + m_flags.m_hasCustomTextColor = true; + } + + inline void setValueColor(Color color) { + m_customValueColor = color; + m_flags.m_hasCustomValueColor = true; + } + + inline void clearTextColor() { + m_flags.m_hasCustomTextColor = false; + } + + inline void clearValueColor() { + m_flags.m_hasCustomValueColor = false; + } + + inline void disableClickAnimation() { + m_flags.m_useClickAnimation = false; + } + + inline void enableClickAnimation() { + m_flags.m_useClickAnimation = true; + } + + inline void enableShortHoldKey() { + m_flags.m_useShortThreshold = true; + } + + inline void disableShortHoldKey() { + m_flags.m_useShortThreshold = false; + } + + inline void enableLongHoldKey() { + m_flags.m_useLongThreshold = true; + } + + inline void disableLongHoldKey() { + m_flags.m_useLongThreshold = false; + } + + inline void enableTouchHolding() { + m_flags.m_usingTouchHolding = true; + } + + inline void disableTouchHolding() { + m_flags.m_usingTouchHolding = false; + } + + inline bool isTouchHolding() const noexcept { + return m_flags.m_isTouchHolding; + } + + inline void resetTouchHold() { + m_flags.m_isTouchHolding = false; + } + + inline void setKeepTag(bool keep) { + m_flags.m_keepTag = keep; + setText(m_text); + } + + inline const std::string& getText() const noexcept { + return m_text; + } + + inline const std::string& getValue() const noexcept { + return m_value; + } + + virtual bool matchesJumpCriteria(const std::string& jumpText, const std::string& jumpValue, bool exactMatch=true) const { + if (jumpText.empty() && jumpValue.empty()) return false; + + bool textMatches, valueMatches; + if (exactMatch) { + textMatches = (m_text == jumpText); + valueMatches = (m_value == jumpValue); + } else { // contains check + textMatches = (m_text.find(jumpText) != std::string::npos); + valueMatches = (m_value.find(jumpValue) != std::string::npos); + } + + if (jumpText.empty() && !jumpValue.empty()) + return valueMatches; + else if (!jumpText.empty() && jumpValue.empty()) + return textMatches; + + return (textMatches && valueMatches); + } + + protected: + u64 timeIn_ns; + std::string m_text; + std::string m_text_clean; + std::string m_value; + std::string m_scrollText; + std::string m_ellipsisText; + u16 m_listItemHeight; // Changed from u32 to u16 + + // Bitfield for boolean flags - saves ~7 bytes per instance + struct { + bool m_keepTag : 1; + bool m_scroll : 1; + bool m_truncated : 1; + bool m_faint : 1; + bool m_hasCustomTextColor : 1; + bool m_hasCustomValueColor : 1; + bool m_useClickAnimation : 1; + bool m_useShortThreshold : 1; + bool m_useLongThreshold : 1; + bool m_usingTouchHolding : 1; + bool m_isTouchHolding: 1; + bool m_shortThresholdCrossed : 1; + bool m_longThresholdCrossed : 1; + } m_flags = {}; + + Color m_customTextColor; + Color m_customValueColor; + + float m_scrollOffset = 0.0f; + u16 m_maxWidth = 0; // Changed from u32 to u16 + u16 m_textWidth = 0; // Changed from u32 to u16 + + private: + // Consolidated scroll constants struct + struct ScrollConstants { + double totalCycleDuration; + double delayDuration; + double scrollDuration; + double accelTime; + double constantVelocityTime; + double maxVelocity; + double accelDistance; + double constantVelocityDistance; + double minScrollDistance; + double invAccelTime; + double invDecelTime; + double invBillion; + bool initialized = false; + }; + + void applyInitialTranslations(bool isValue = false) { + std::string& target = isValue ? m_value : m_text_clean; + ult::applyLangReplacements(target, isValue); + ult::convertComboToUnicode(target); + + { + const std::string originalKey = target; + + std::shared_lock readLock(tsl::gfx::s_translationCacheMutex); + auto translatedIt = ult::translationCache.find(originalKey); + if (translatedIt != ult::translationCache.end()) { + target = translatedIt->second; + } else { + readLock.unlock(); + std::unique_lock writeLock(tsl::gfx::s_translationCacheMutex); + + translatedIt = ult::translationCache.find(originalKey); + if (translatedIt != ult::translationCache.end()) { + target = translatedIt->second; + } else { + ult::translationCache[originalKey] = originalKey; + } + } + } + } + + void calculateWidths(gfx::Renderer* renderer) { + if (m_value.empty()) { + m_maxWidth = getWidth() - 62; + } else { + m_maxWidth = getWidth() - renderer->getTextDimensions(m_value, false, 20).first - 66; + } + + const u16 width = renderer->getTextDimensions(m_text_clean, false, 23).first; + m_flags.m_truncated = width > m_maxWidth + 20; + + if (m_flags.m_truncated) [[unlikely]] { + m_scrollText.clear(); + m_scrollText.reserve(m_text_clean.size() * 2 + 8); + + m_scrollText.append(m_text_clean).append(" "); + m_textWidth = renderer->getTextDimensions(m_scrollText, false, 23).first; + m_scrollText.append(m_text_clean); + + m_ellipsisText = renderer->limitStringLength(m_text_clean, false, 23, m_maxWidth); + } else { + m_textWidth = width; + } + } + + void drawTruncatedText(gfx::Renderer* renderer, s32 yOffset, bool useClickTextColor, const std::vector& specialSymbols = {}) { + if (m_focused) { + renderer->enableScissoring(getX() + 6, 97, m_maxWidth + (m_value.empty() ? 49 : 27), tsl::cfg::FramebufferHeight - 170); + #if IS_LAUNCHER_DIRECTIVE + renderer->drawStringWithColoredSections(m_scrollText, false, specialSymbols, getX() + 19 - static_cast(m_scrollOffset), getY() + 45 - yOffset, 23, + !ult::useSelectionText ? defaultTextColor: (useClickTextColor ? clickTextColor : selectedTextColor), starColor); + #else + renderer->drawStringWithColoredSections(m_scrollText, false, specialSymbols, getX() + 19 - static_cast(m_scrollOffset), getY() + 45 - yOffset, 23, + !ult::useSelectionText ? defaultTextColor: (useClickTextColor ? clickTextColor : selectedTextColor), textSeparatorColor); + #endif + renderer->disableScissoring(); + handleScrolling(); + } else { + #if IS_LAUNCHER_DIRECTIVE + renderer->drawStringWithColoredSections(m_ellipsisText, false, specialSymbols, getX() + 19, getY() + 45 - yOffset, 23, + m_flags.m_hasCustomTextColor ? m_customTextColor : (useClickTextColor ? clickTextColor : defaultTextColor), starColor); + #else + renderer->drawStringWithColoredSections(m_ellipsisText, false, specialSymbols, getX() + 19, getY() + 45 - yOffset, 23, + m_flags.m_hasCustomTextColor ? m_customTextColor : (useClickTextColor ? clickTextColor : defaultTextColor), textSeparatorColor); + #endif + } + } + + void handleScrolling() { + static ScrollConstants sc; + static u64 lastUpdateTime = 0; + static float cachedScrollOffset = 0.0f; + + const u64 currentTime_ns = ult::nowNs(); + const u64 elapsed_ns = currentTime_ns - timeIn_ns; + + if (!sc.initialized || sc.minScrollDistance != static_cast(m_textWidth)) { + sc.delayDuration = 2.0; + static constexpr double pauseDuration = 1.0; + sc.maxVelocity = 166.0; + sc.accelTime = 0.5; + static constexpr double decelTime = 0.5; + + sc.minScrollDistance = static_cast(m_textWidth); + sc.accelDistance = 0.5 * sc.maxVelocity * sc.accelTime; + const double decelDistance = 0.5 * sc.maxVelocity * decelTime; + sc.constantVelocityDistance = std::max(0.0, sc.minScrollDistance - sc.accelDistance - decelDistance); + sc.constantVelocityTime = sc.constantVelocityDistance / sc.maxVelocity; + sc.scrollDuration = sc.accelTime + sc.constantVelocityTime + decelTime; + sc.totalCycleDuration = sc.delayDuration + sc.scrollDuration + pauseDuration; + + sc.invAccelTime = 1.0 / sc.accelTime; + sc.invDecelTime = 1.0 / decelTime; + sc.invBillion = 1.0 / 1000000000.0; + + sc.initialized = true; + } + + const double elapsed_seconds = static_cast(elapsed_ns) * sc.invBillion; + + if (currentTime_ns - lastUpdateTime >= 8333333ULL) { + const double cyclePosition = std::fmod(elapsed_seconds, sc.totalCycleDuration); + + if (cyclePosition < sc.delayDuration) [[likely]] { + cachedScrollOffset = 0.0f; + } else if (cyclePosition < sc.delayDuration + sc.scrollDuration) [[likely]] { + const double scrollTime = cyclePosition - sc.delayDuration; + double distance; + + if (scrollTime <= sc.accelTime) { + const double t = scrollTime * sc.invAccelTime; + const double smoothT = t * t; + distance = smoothT * sc.accelDistance; + } else if (scrollTime <= sc.accelTime + sc.constantVelocityTime) { + const double constantTime = scrollTime - sc.accelTime; + distance = sc.accelDistance + (constantTime * sc.maxVelocity); + } else { + const double decelStartTime = sc.accelTime + sc.constantVelocityTime; + const double t = (scrollTime - decelStartTime) * sc.invDecelTime; + const double oneMinusT = 1.0 - t; + const double smoothT = 1.0 - oneMinusT * oneMinusT; + distance = sc.accelDistance + sc.constantVelocityDistance + (smoothT * (sc.minScrollDistance - sc.accelDistance - sc.constantVelocityDistance)); + } + + cachedScrollOffset = static_cast(distance < sc.minScrollDistance ? distance : sc.minScrollDistance); + } else [[unlikely]] { + cachedScrollOffset = static_cast(m_textWidth); + } + + lastUpdateTime = currentTime_ns; + } + + m_scrollOffset = cachedScrollOffset; + + if (elapsed_seconds >= sc.totalCycleDuration) [[unlikely]] { + timeIn_ns = currentTime_ns; + } + } + + void drawValue(gfx::Renderer* renderer, s32 yOffset, bool useClickTextColor) { + const s32 xPosition = getX() + m_maxWidth + 47; + const s32 yPosition = getY() + 45 - yOffset-1; + static constexpr s32 fontSize = 20; + + #if IS_LAUNCHER_DIRECTIVE + static bool lastRunningInterpreter = false; + const auto textColor = determineValueTextColor(useClickTextColor, lastRunningInterpreter); + + if (m_value != ult::INPROGRESS_SYMBOL) [[likely]] { + renderer->drawStringWithColoredSections(m_value, false, s_dividerSpecialChars, xPosition, yPosition, fontSize, textColor, textSeparatorColor); + } else { + drawThrobber(renderer, xPosition, yPosition, fontSize, textColor); + } + lastRunningInterpreter = ult::runningInterpreter.load(std::memory_order_acquire); + #else + const auto textColor = determineValueTextColor(useClickTextColor); + if (m_value != ult::INPROGRESS_SYMBOL) [[likely]] { + renderer->drawStringWithColoredSections(m_value, false, s_dividerSpecialChars, xPosition, yPosition, fontSize, textColor, textSeparatorColor); + } else { + drawThrobber(renderer, xPosition, yPosition, fontSize, textColor); + } + #endif + } + + #if IS_LAUNCHER_DIRECTIVE + Color determineValueTextColor(bool useClickTextColor, bool lastRunningInterpreter = false) const { + #else + Color determineValueTextColor(bool useClickTextColor) const { + #endif + if (m_focused && ult::useSelectionValue) { + if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { + return useClickTextColor ? clickTextColor : + (m_flags.m_faint ? offTextColor : (ult::useSelectionText ? selectedTextColor : defaultTextColor)); + } + // unique to focused: falls through to shared block below, but returns selectedValueTextColor at end + } else { + if (m_flags.m_hasCustomValueColor) return m_customValueColor; + if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { + return useClickTextColor ? clickTextColor : + (m_flags.m_faint ? offTextColor : (m_focused ? (ult::useSelectionText ? selectedTextColor : defaultTextColor) : defaultTextColor)); + } + } + + // shared logic — only reached once per path + #if IS_LAUNCHER_DIRECTIVE + const bool isRunning = ult::runningInterpreter.load(std::memory_order_acquire) || lastRunningInterpreter; + if (isRunning && (m_value.find(ult::DOWNLOAD_SYMBOL) != std::string::npos || + m_value.find(ult::UNZIP_SYMBOL) != std::string::npos || + m_value.find(ult::COPY_SYMBOL) != std::string::npos)) + return m_flags.m_faint ? offTextColor : inprogressTextColor; + #endif + if (m_value == ult::INPROGRESS_SYMBOL) return m_flags.m_faint ? offTextColor : inprogressTextColor; + if (m_value == ult::CROSSMARK_SYMBOL) return m_flags.m_faint ? offTextColor : invalidTextColor; + + return (m_focused && ult::useSelectionValue) + ? (useClickTextColor ? clickTextColor : selectedValueTextColor) + : (m_flags.m_faint ? offTextColor : onTextColor); + } + + void drawThrobber(gfx::Renderer* renderer, s32 xPosition, s32 yPosition, s32 fontSize, Color textColor) { + static size_t throbberCounter = 0; + const auto& throbberSymbol = ult::THROBBER_SYMBOLS[(throbberCounter / 10) % ult::THROBBER_SYMBOLS.size()]; + throbberCounter = (throbberCounter + 1) % (10 * ult::THROBBER_SYMBOLS.size()); + renderer->drawString(throbberSymbol, false, xPosition, yPosition, fontSize, textColor); + } + + s64 determineKeyOnTouchRelease() const { + const u64 touchDuration_ns = ult::nowNs() - m_touchStartTime_ns; + const float touchDurationInSeconds = static_cast(touchDuration_ns) * 1e-9f; + + if (m_flags.m_useLongThreshold) { + if (touchDurationInSeconds >= 1.0f) { + ult::longTouchAndRelease.store(true, std::memory_order_release); + return m_longHoldKey; + } + } + if (m_flags.m_useShortThreshold) { + if (touchDurationInSeconds >= 0.5f) { + ult::shortTouchAndRelease.store(true, std::memory_order_release); + return m_shortHoldKey; + } + } + return KEY_A; + } + + void resetTextProperties() { + m_scrollText.clear(); + m_ellipsisText.clear(); + m_maxWidth = 0; + } + }; + + class SilentListItem : public tsl::elm::ListItem { + public: + using tsl::elm::ListItem::ListItem; + virtual bool onClick(u64 keys) override { + // Skip all sound/rumble triggers, go straight to click listener + if (keys & KEY_A) { + if (m_flags.m_useClickAnimation) + triggerClickAnimation(); + } else if (keys & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) { + m_clickAnimationProgress = 0; + } + return Element::onClick(keys); + } + }; + + class MiniListItem : public ListItem { + public: + MiniListItem(const std::string& text, const std::string& value = "") + : ListItem(text, value, true) { // Call the parent constructor with `isMini = true` + } + + // Destructor if needed (inherits default behavior from ListItem) + virtual ~MiniListItem() {} + }; + + /** + * @brief A wrapper item that extends ListItem with custom color support for inputs + * (this version uses value and faint color sourcing) + */ + class ListItemV2 : public ListItem { + public: + /** + * @brief Constructor + * + * @param text Initial description text + * @param value Initial value text + * @param valueColor Color to use for the value when not faint + * @param faintColor Color to use for the value when faint + * @param isMini Whether to use mini list item height + * @param useScriptKey Whether to use script key (launcher only) + */ + ListItemV2(const std::string& text, + const std::string& value = "", + Color valueColor = onTextColor, + Color faintColor = offTextColor, + bool isMini = false) + : ListItem(text, value, isMini), + m_valueColorOverride(valueColor), + m_faintColorOverride(faintColor), + m_hasColorOverrides(true) { + + // Set the custom value color on the base ListItem + setValueColor(valueColor); + } + + virtual ~ListItemV2() = default; + + /** + * @brief Override setValue to maintain custom color behavior + */ + inline void setValue(const std::string& value, bool faint = false) { + // Call parent implementation + ListItem::setValue(value, faint); + + // Re-apply color override based on faint state + if (m_hasColorOverrides) { + setValueColor(faint ? m_faintColorOverride : m_valueColorOverride); + } + } + + /** + * @brief Set custom value color + */ + inline void setValueColorOverride(Color color) { + m_valueColorOverride = color; + m_hasColorOverrides = true; + // Update the base class if not currently faint + if (!m_flags.m_faint) { + setValueColor(color); + } + } + + /** + * @brief Set custom faint color + */ + inline void setFaintColorOverride(Color color) { + m_faintColorOverride = color; + m_hasColorOverrides = true; + // Update the base class if currently faint + if (m_flags.m_faint) { + setValueColor(color); + } + } + + /** + * @brief Get the current value color override + */ + inline Color getValueColorOverride() const { + return m_valueColorOverride; + } + + /** + * @brief Get the current faint color override + */ + inline Color getFaintColorOverride() const { + return m_faintColorOverride; + } + + /** + * @brief Clear color overrides and revert to default behavior + */ + inline void clearColorOverrides() { + m_hasColorOverrides = false; + clearValueColor(); + } + + protected: + Color m_valueColorOverride; + Color m_faintColorOverride; + bool m_hasColorOverrides; + }; + + + /** + * @brief Mini version of ListItemV2 + */ + class MiniListItemV2 : public ListItemV2 { + public: + MiniListItemV2(const std::string& text, + const std::string& value = "", + Color valueColor = onTextColor, + Color faintColor = offTextColor) + : ListItemV2(text, value, valueColor, faintColor, true) { + } + + virtual ~MiniListItemV2() {} + }; + + /** + * @brief A toggleable list item that changes the state from On to Off when the A button gets pressed + * + */ + class ToggleListItem : public ListItem { + public: + /** + * @brief Constructor + * + * @param text Initial description text + * @param initialState Is the toggle set to On or Off initially + * @param onValue Value drawn if the toggle is on + * @param offValue Value drawn if the toggle is off + */ + ToggleListItem(const std::string& text, bool initialState, const std::string& onValue = ult::ON, const std::string& offValue = ult::OFF, bool isMini = false, bool delayedHandle=false) + : ListItem(text, "", isMini), m_state(initialState), m_onValue(onValue), m_offValue(offValue), m_delayedHandle(delayedHandle) { + this->setState(this->m_state); + } + + virtual ~ToggleListItem() {} + + virtual bool onClick(u64 keys) override { + + #if IS_LAUNCHER_DIRECTIVE + if (ult::runningInterpreter.load(std::memory_order_acquire)) + return false; + #endif + + // Handle KEY_A for toggling + if (keys & KEY_A) { + triggerRumbleClick.store(true, std::memory_order_release); + if (!this->m_state) + triggerOnSound.store(true, std::memory_order_release); + else + triggerOffSound.store(true, std::memory_order_release); + + + this->m_state = !this->m_state; + + if (!m_delayedHandle) + this->setState(this->m_state); + + this->m_stateChangedListener(this->m_state); + this->triggerClickAnimation(); + + return Element::onClick(keys); + } + + #if IS_LAUNCHER_DIRECTIVE + // Handle SCRIPT_KEY for executing script logic + else if (keys & SCRIPT_KEY) { + // Trigger the script key listener + if (this->m_scriptKeyListener) { + this->m_scriptKeyListener(this->m_state); // Pass the current state to the script key listener + } + return ListItem::onClick(keys); + } + #endif + return false; + } + + /** + * @brief Gets the current state of the toggle + * + * @return State + */ + virtual bool getState() { + return this->m_state; + } + + /** + * @brief Sets the current state of the toggle. Updates the Value + * + * @param state State + */ + virtual void setState(bool state) { + #if IS_LAUNCHER_DIRECTIVE + if (ult::runningInterpreter.load(std::memory_order_acquire)) + return; + #endif + + this->m_state = state; + this->setValue(state ? this->m_onValue : this->m_offValue, !state); + } + + /** + * @brief Adds a listener that gets called whenever the state of the toggle changes + * + * @param stateChangedListener Listener with the current state passed in as parameter + */ + void setStateChangedListener(std::function stateChangedListener) { + this->m_stateChangedListener = stateChangedListener; + } + + #if IS_LAUNCHER_DIRECTIVE + // Attach the script key listener for SCRIPT_KEY handling + void setScriptKeyListener(std::function scriptKeyListener) { + this->m_scriptKeyListener = scriptKeyListener; + } + #endif + + + protected: + bool m_state = true; + + std::string m_onValue, m_offValue; + bool m_delayedHandle = false; + + std::function m_stateChangedListener = [](bool){}; + + #if IS_LAUNCHER_DIRECTIVE + std::function m_scriptKeyListener = nullptr; // Script key listener (with state) + #endif + }; + + class MiniToggleListItem : public ToggleListItem { + public: + // Constructor for MiniToggleListItem, with no `isMini` boolean. + MiniToggleListItem(const std::string& text, bool initialState, const std::string& onValue = ult::ON, const std::string& offValue = ult::OFF) + : ToggleListItem(text, initialState, onValue, offValue, true) { + } + + // Destructor if needed (inherits default behavior from ListItem) + virtual ~MiniToggleListItem() {} + }; + + + class DummyListItem : public ListItem { + public: + DummyListItem() + : ListItem("") { // Use an empty string for the base class constructor + // Set the properties to indicate it's a dummy item + this->m_text = ""; + this->m_value = ""; + this->m_maxWidth = 0; + this->width = 0; + this->height = 0; + m_isItem = false; + isLocked = true; + } + + virtual ~DummyListItem() {} + + // Override the draw method to do nothing + virtual void draw(gfx::Renderer* renderer) override { + // Intentionally left blank + } + + // Override the layout method to set the dimensions to zero + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + this->setBoundaries(this->getX(), this->getY(), 0, 0); + } + + // Override the requestFocus method to allow this item to be focusable + virtual Element* requestFocus(Element* oldFocus, FocusDirection direction) override { + return this; // Allow this item to be focusable + } + }; + + + class CategoryHeader : public Element { + public: + CategoryHeader(const std::string &title, bool hasSeparator = true) + : m_text(title), + m_value(""), + m_valueColor(tsl::headerTextColor), + m_hasSeparator(hasSeparator), + m_scroll(false), + m_truncated(false), + m_scrollOffset(0.0f), + m_maxWidth(0), + m_textWidth(0) { + ult::applyLangReplacements(m_text); + ult::convertComboToUnicode(m_text); + m_isItem = false; + } + + virtual ~CategoryHeader() {} + + // --- new setters --- + void setValue(const std::string &value, const tsl::Color &color = tsl::headerTextColor) { + m_value = value; + m_valueColor = color; + } + + void clearValue() { + m_value.clear(); + } + + virtual void draw(gfx::Renderer* renderer) override { + if (!m_maxWidth) calculateWidths(renderer); + + const int fontHeight = 16; + + // Keep a fixed header area for separator and text (matches old 33px height) + const int headerTop = this->getBottomBound() - 33; + const int textY = this->getBottomBound() - 16; + const int textX = m_hasSeparator ? (this->getX() + 16) : this->getX(); + + // Draw the separator rectangle on the left (fixed 22px height, 4px wide) + if (m_hasSeparator) { + renderer->drawRect( + this->getX() + 2, + headerTop, + 4, + 22, + aWithOpacity(headerSeparatorColor)); + } + + // Draw header text + if (m_truncated) { + if (!m_scroll) m_scroll = true; + handleScrolling(); + + renderer->enableScissoring(textX, ult::activeHeaderHeight-8, m_maxWidth, cfg::FramebufferHeight - 73 - (ult::activeHeaderHeight-8)); + renderer->drawStringWithColoredSections( + m_scrollText, false, s_dividerSpecialChars, + textX - static_cast(m_scrollOffset), + textY, + fontHeight, + headerTextColor, + textSeparatorColor + ); + renderer->disableScissoring(); + } else { + renderer->drawStringWithColoredSections( + m_text, false, s_dividerSpecialChars, + textX, textY, + fontHeight, + headerTextColor, + textSeparatorColor + ); + } + + // Draw optional value, right-aligned + if (!m_value.empty()) { + const int valueWidth = renderer->getTextDimensions(m_value, false, fontHeight).first; + const int valueX = this->getX() + 2 + this->getWidth() - valueWidth; + + renderer->drawString( + m_value, + false, + valueX, + textY, + fontHeight, + m_valueColor, + 0, true, nullptr, nullptr, 0, 0, false + ); + } + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + if (List *list = static_cast(this->getParent()); list != nullptr) { + if (list->getIndexInList(this) == 0) { + this->setBoundaries(this->getX(), this->getY(), this->getWidth(), 33); + return; + } + } + + this->setBoundaries( + this->getX(), + this->getY(), + this->getWidth(), + tsl::style::ListItemDefaultHeight * 0.90); + } + + inline void setText(const std::string &text) { + if (m_text != text) { + m_text = text; + ult::applyLangReplacements(m_text); + ult::convertComboToUnicode(m_text); + + resetTextProperties(); + } + } + + inline const std::string &getText() const { + return m_text; + } + + private: + std::string m_text; + std::string m_value; + tsl::Color m_valueColor; + bool m_hasSeparator; + + bool m_scroll; + bool m_truncated; + float m_scrollOffset; + u32 m_maxWidth; + u32 m_textWidth; + + std::string m_scrollText; + + /* Delta-time animation state */ + u64 lastFrameTime_ns = 0; + double accumulatedTime_s = 0.0; + + /* Cached calculations */ + bool constantsInitialized = false; + double totalCycleDuration; + double delayDuration; + double scrollDuration; + double accelTime; + double constantVelocityTime; + double maxVelocity; + double accelDistance; + double constantVelocityDistance; + double minScrollDistance; + + double invAccelTime; + double invDecelTime; + double invBillion; + + float cachedScrollOffset = 0.0f; + + void calculateWidths(gfx::Renderer *renderer) { + m_maxWidth = getWidth() - (m_hasSeparator ? 17 : 4); + + const u32 width = renderer->getTextDimensions(m_text, false, 16).first; + m_truncated = width > m_maxWidth; + + if (m_truncated) { + m_scrollText.clear(); + m_scrollText.reserve(m_text.size() * 2 + 8); + m_scrollText.append(m_text).append(" "); + m_textWidth = renderer->getTextDimensions(m_scrollText, false, 16).first; + m_scrollText.append(m_text); + } else { + m_textWidth = width; + } + + constantsInitialized = false; + } + + void handleScrolling() { + const u64 currentTime_ns = ult::nowNs(); + + if (!constantsInitialized || minScrollDistance != static_cast(m_textWidth)) { + delayDuration = 3.0; + static constexpr double pauseDuration = 2.0; + + maxVelocity = 100.0; + accelTime = 0.5; + static constexpr double decelTime = 0.5; + + minScrollDistance = static_cast(m_textWidth); + accelDistance = 0.5 * maxVelocity * accelTime; + const double decelDistance = 0.5 * maxVelocity * decelTime; + + constantVelocityDistance = + std::max(0.0, minScrollDistance - accelDistance - decelDistance); + + constantVelocityTime = constantVelocityDistance / maxVelocity; + + scrollDuration = accelTime + constantVelocityTime + decelTime; + totalCycleDuration = delayDuration + scrollDuration + pauseDuration; + + invAccelTime = 1.0 / accelTime; + invDecelTime = 1.0 / decelTime; + invBillion = 1.0 / 1000000000.0; + + constantsInitialized = true; + } + + if (lastFrameTime_ns != 0) { + double delta_s = + static_cast(currentTime_ns - lastFrameTime_ns) * invBillion; + + /* Clamp large jumps (list switches / lag spikes) */ + delta_s = std::min(delta_s, 0.05); + + accumulatedTime_s += delta_s; + } + + lastFrameTime_ns = currentTime_ns; + + const double cyclePosition = + std::fmod(accumulatedTime_s, totalCycleDuration); + + if (cyclePosition < delayDuration) { + cachedScrollOffset = 0.0f; + } else if (cyclePosition < delayDuration + scrollDuration) { + const double scrollTime = cyclePosition - delayDuration; + double distance; + + if (scrollTime <= accelTime) { + const double t = scrollTime * invAccelTime; + distance = (t * t) * accelDistance; + } else if (scrollTime <= accelTime + constantVelocityTime) { + const double t = scrollTime - accelTime; + distance = accelDistance + (t * maxVelocity); + } else { + const double decelStart = accelTime + constantVelocityTime; + const double t = (scrollTime - decelStart) * invDecelTime; + const double smooth = 1.0 - (1.0 - t) * (1.0 - t); + + distance = accelDistance + constantVelocityDistance + + smooth * (minScrollDistance - accelDistance - constantVelocityDistance); + } + + cachedScrollOffset = static_cast( + distance < minScrollDistance ? distance : minScrollDistance); + } else { + cachedScrollOffset = static_cast(m_textWidth); + } + + m_scrollOffset = cachedScrollOffset; + } + + void resetTextProperties() { + m_scrollOffset = 0.0f; + cachedScrollOffset = 0.0f; + + lastFrameTime_ns = 0; + accumulatedTime_s = 0.0; + + m_maxWidth = 0; + m_textWidth = 0; + + m_scroll = false; + constantsInitialized = false; + } + }; + + + /** + * @brief A customizable analog trackbar going from 0% to 100% (like the brightness slider) + * + */ + class TrackBar : public Element { + public: + /** + * @brief Constructor + * + * @param icon Icon shown next to the track bar + * @param usingStepTrackbar Whether this is a step trackbar + * @param usingNamedStepTrackbar Whether this is a named step trackbar + * @param useV2Style Whether to use V2 visual style (label + value instead of icon) + * @param label Label text for V2 style + * @param units Units text for V2 style + */ + TrackBar(const char icon[3], bool usingStepTrackbar=false, bool usingNamedStepTrackbar = false, + bool useV2Style = false, const std::string& label = "", const std::string& units = "", + bool unlockedTrackbar = true) + : m_icon(icon), m_usingStepTrackbar(usingStepTrackbar), m_usingNamedStepTrackbar(usingNamedStepTrackbar), + m_unlockedTrackbar(unlockedTrackbar), m_useV2Style(useV2Style), m_label(label), m_units(units) { + m_isItem = true; + } + + virtual ~TrackBar() {} + + virtual void triggerClickAnimation() { + Element::triggerClickAnimation(); + + // Activate the click animation + this->m_clickAnimationStartTime = ult::nowNs(); + this->m_clickAnimationActive = true; + } + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) { + return this; + } + + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { + const u64 keysReleased = m_prevKeysHeld & ~keysHeld; + m_prevKeysHeld = keysHeld; + + const u64 currentTime_ns = ult::nowNs(); + static u64 lastUpdate_ns = currentTime_ns; + const u64 elapsed_ns = currentTime_ns - lastUpdate_ns; + + // KEY_R + directional: shake highlight (same as V2) + if (keysHeld & KEY_R) { + if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Up); + else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Down); + else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Left); + else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Right); + return true; + } + + // KEY_A: lock/unlock toggle (when locked), or click animation (when unlocked) + if ((keysDown & KEY_A) && !(keysHeld & ~KEY_A & ALL_KEYS_MASK)) { + if (!m_unlockedTrackbar) { + ult::atomicToggle(ult::allowSlide); + m_holding = false; + if (ult::allowSlide.load(std::memory_order_acquire)) { + // Unlocking: rumble + on sound only, no click animation, no enter feedback + triggerRumbleClick.store(true, std::memory_order_release); + triggerOnSound.store(true, std::memory_order_release); + } else { + // Locking: rumble + off sound only, no click animation + triggerRumbleClick.store(true, std::memory_order_release); + triggerOffSound.store(true, std::memory_order_release); + } + } else { + // Always-unlocked trackbar: full click animation + enter feedback + this->triggerClickAnimation(); + triggerEnterFeedback(); + } + return true; + } + + // Guard all movement behind lock state + if (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire)) { + return false; + } + + static s16 lastHapticSegment = -1; + + // Handle key release + if ((keysReleased & KEY_LEFT) || (keysReleased & KEY_RIGHT)) { + lastHapticSegment = -1; + + if (m_wasLastHeld) { + m_wasLastHeld = false; + m_holding = false; + lastUpdate_ns = currentTime_ns; + return true; + } else if (m_holding) { + m_holding = false; + lastUpdate_ns = currentTime_ns; + return true; + } + } + + // Ignore simultaneous left+right + if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) + return true; + + // Handle initial key press + if (keysDown & KEY_LEFT || keysDown & KEY_RIGHT) { + m_holding = true; + m_wasLastHeld = false; + m_holdStartTime_ns = currentTime_ns; + lastUpdate_ns = currentTime_ns; + + if (keysDown & KEY_LEFT && this->m_value > 0) { + this->m_value--; + this->m_valueChangedListener(this->m_value); + + const s16 currentSegment = (this->m_value * 10) / 100; + if (this->m_value == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + } else if (keysDown & KEY_RIGHT && this->m_value < 100) { + this->m_value++; + this->m_valueChangedListener(this->m_value); + + const s16 currentSegment = (this->m_value * 10) / 100; + if (this->m_value == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + } + return true; + } + + // Handle continued holding with acceleration + if (m_holding && ((keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT))) { + const u64 holdDuration_ns = currentTime_ns - m_holdStartTime_ns; + + static constexpr u64 initialDelay_ns = 300000000ULL; + static constexpr u64 initialInterval_ns = 67000000ULL; + static constexpr u64 shortInterval_ns = 10000000ULL; + static constexpr u64 transitionPoint_ns = 1000000000ULL; + + if (holdDuration_ns < initialDelay_ns) { + return true; + } + + const u64 holdDurationAfterDelay_ns = holdDuration_ns - initialDelay_ns; + const float t = std::min(1.0f, static_cast(holdDurationAfterDelay_ns) / static_cast(transitionPoint_ns)); + const u64 currentInterval_ns = static_cast((initialInterval_ns - shortInterval_ns) * (1.0f - t) + shortInterval_ns); + + if (elapsed_ns >= currentInterval_ns) { + if (keysHeld & KEY_LEFT && this->m_value > 0) { + this->m_value--; + this->m_valueChangedListener(this->m_value); + + const s16 currentSegment = (this->m_value * 10) / 100; + if (this->m_value == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + + lastUpdate_ns = currentTime_ns; + m_wasLastHeld = true; + return true; + } + + if (keysHeld & KEY_RIGHT && this->m_value < 100) { + this->m_value++; + this->m_valueChangedListener(this->m_value); + + const s16 currentSegment = (this->m_value * 10) / 100; + if (this->m_value == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + + lastUpdate_ns = currentTime_ns; + m_wasLastHeld = true; + return true; + } + } + } else { + m_holding = false; + } + + return false; + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + s32 trackBarLeft = this->getX() + 59; + s32 width = this->getWidth() - 95; + + if (m_icon[0] != '\0') { + const s32 iconOffset = 14 + 23; + trackBarLeft += iconOffset; + width -= iconOffset; + } + + const s32 trackBarRight = trackBarLeft + width; + const u16 handlePos = (width * this->m_value) / 100; + const s32 circleCenterX = trackBarLeft + handlePos; + const s32 circleCenterY = this->getY() + 40 + 16 - 3 - ((!m_usingNamedStepTrackbar && !m_useV2Style) ? 11 : 0); + static constexpr s32 circleRadius = 16; + static bool triggerOnce = true; + static s16 lastHapticSegment = -1; + + const bool touchInCircle = (std::abs(currX - circleCenterX) <= circleRadius) && (std::abs(currY - circleCenterY) <= circleRadius); + const bool currentlyInHorizontalBounds = (currX >= trackBarLeft && currX <= trackBarRight); + + if (event == TouchEvent::Release) { + triggerOnce = true; + lastHapticSegment = -1; + + if (touchInSliderBounds) { + triggerRumbleDoubleClick.store(true, std::memory_order_release); + triggerOffSound.store(true, std::memory_order_release); + tsl::shiftItemFocus(this); + } + + touchInSliderBounds = false; + return false; + } + + if (touchInCircle || touchInSliderBounds) { + if (touchInSliderBounds && !currentlyInHorizontalBounds) { + if (currX > trackBarRight) { + this->m_value = 100; + } else if (currX < trackBarLeft) { + this->m_value = 0; + } + this->m_valueChangedListener(this->getProgress()); + + touchInSliderBounds = false; + return false; + } + + if (currentlyInHorizontalBounds) { + if (triggerOnce) { + triggerOnce = false; + triggerRumbleClick.store(true, std::memory_order_release); + triggerOnSound.store(true, std::memory_order_release); + } + touchInSliderBounds = true; + + s16 newValue = (static_cast(currX - trackBarLeft) / static_cast(width)) * 100; + + if (newValue < 0) { + newValue = 0; + } else if (newValue > 100) { + newValue = 100; + } + + if (newValue != this->m_value) { + this->m_value = newValue; + this->m_valueChangedListener(this->getProgress()); + + const s16 currentSegment = (this->m_value * 10) / 100; + if (this->m_value == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + } + + return true; + } + } + + return false; + } + + + + // Define drawBar function outside the draw method + void drawBar(gfx::Renderer *renderer, s32 x, s32 y, u16 width, Color& color, bool isRounded = true) { + if (isRounded) { + renderer->drawUniformRoundedRect(x, y, width, 7, a(color)); + } else { + renderer->drawRect(x, y, width, 7, a(color)); + } + } + + virtual void draw(gfx::Renderer *renderer) override { + + if (touchInSliderBounds) { + m_drawFrameless = true; + drawHighlight(renderer); + } else { + m_drawFrameless = false; + } + + s32 xPos = this->getX() + 59; + s32 yPos = this->getY() + 40 + 16 - 3; + s32 width = this->getWidth() - 95; + const int maxValue = (m_usingStepTrackbar || m_usingNamedStepTrackbar) + ? ((100 / (this->m_numSteps - 1)) * (this->m_numSteps - 1)) + : 100; + u16 handlePos = width * (this->m_value) / maxValue; + + if (!m_usingNamedStepTrackbar && !m_useV2Style) { + yPos -= 11; + } + + s32 iconOffset = 0; + + if (m_icon[0] != '\0') { + s32 iconWidth = 23; + iconOffset = 14 + iconWidth; + xPos += iconOffset; + width -= iconOffset; + handlePos = (width) * (this->m_value) / (100); + } + + // Draw step tick marks if this is a step trackbar + if (m_usingStepTrackbar || m_usingNamedStepTrackbar) { + const u8 numSteps = m_numSteps; + const u16 baseX = xPos; + const u16 baseY = this->getY() + 44; + const u8 halfNumSteps = (numSteps - 1) / 2; + const u16 lastStepX = baseX + width - 1; + const float stepSpacing = static_cast(width) / (numSteps - 1); + const auto stepColor = a(trackBarEmptyColor); + + u16 stepX; + for (u8 i = 0; i < numSteps; i++) { + if (i == numSteps - 1) { + stepX = lastStepX; + } else { + stepX = baseX + static_cast(std::round(i * stepSpacing)); + if (i > halfNumSteps) { + stepX -= 1; + } + } + renderer->drawRect(stepX, baseY, 1, 8, stepColor); + } + } + + // Draw track bar background + drawBar(renderer, xPos, yPos-3, width, trackBarEmptyColor, !m_usingNamedStepTrackbar); + + const bool isEffectivelyUnlocked = m_unlockedTrackbar || ult::allowSlide.load(std::memory_order_acquire); + + if (!this->m_focused) { + drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); + renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(m_drawFrameless ? s_highlightColor : trackBarSliderBorderColor)); + renderer->drawCircle(xPos + handlePos, yPos, 13, true, a((isEffectivelyUnlocked || touchInSliderBounds) ? trackBarSliderMalleableColor : trackBarSliderColor)); + } else { + touchInSliderBounds = false; + if (m_unlockedTrackbar != ult::unlockedSlide.load(std::memory_order_acquire)) + ult::unlockedSlide.store(m_unlockedTrackbar, std::memory_order_release); + drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); + renderer->drawCircle(xPos + x + handlePos, yPos +y, 16, true, a(s_highlightColor)); + renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a(isEffectivelyUnlocked ? trackBarSliderMalleableColor : trackBarSliderColor)); + } + + // Draw icon (always if provided), then label + value (V2 style) + if (m_useV2Style) { + std::string labelPart = this->m_label; + ult::removeTag(labelPart); + + std::string valuePart; + if (!m_usingNamedStepTrackbar) { + valuePart = (m_units.compare("%") == 0 || m_units.compare("°C") == 0 || m_units.compare("°F") == 0) + ? ult::to_string(m_value) + m_units + : ult::to_string(m_value) + (m_units.empty() ? "" : " ") + m_units; + } else { + valuePart = this->m_selection; + } + + const auto valueWidth = renderer->getTextDimensions(valuePart, false, 16).first; + const s32 labelX = xPos; + const s32 valueX = xPos + width - valueWidth; + + renderer->drawString(labelPart, false, labelX, this->getY() + 14 + 16, 16, + ((!this->m_focused || !ult::useSelectionText) ? defaultTextColor : selectedTextColor)); + renderer->drawString(valuePart, false, valueX, this->getY() + 14 + 16, 16, + (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); + + if (m_icon[0] != '\0') + renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2+2, 30, tsl::style::color::ColorText); + } else { + if (m_icon[0] != '\0') + renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2+2, 30, tsl::style::color::ColorText); + } + + if (m_lastBottomBound != this->getTopBound()) + renderer->drawRect(this->getX() + 4+20-1, this->getTopBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); + renderer->drawRect(this->getX() + 4+20-1, this->getBottomBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); + m_lastBottomBound = this->getBottomBound(); + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + this->setBoundaries(this->getX() - 16 , this->getY(), this->getWidth()+20+4, tsl::style::TrackBarDefaultHeight ); + } + + virtual void drawFocusBackground(gfx::Renderer *renderer) { + // No background drawn here in HOS + } + + virtual void drawHighlight(gfx::Renderer *renderer) override { + + const u64 currentTime_ns = ult::nowNs(); + const double time_seconds = static_cast(currentTime_ns) / 1000000000.0; + progress = (ult::cos(2.0 * ult::_M_PI * std::fmod(time_seconds, 1.0) - ult::_M_PI / 2) + 1.0) / 2.0; + + if (m_clickAnimationActive) { + Color clickColor1 = highlightColor1; + Color clickColor2 = clickColor; + + if (progress >= 0.5) { + clickColor1 = clickColor; + clickColor2 = highlightColor2; + } + const u64 elapsedTime_ns = currentTime_ns - this->m_clickAnimationStartTime; + if (elapsedTime_ns < 500000000ULL) { + s_highlightColor = lerpColor(clickColor1, clickColor2, progress); + } else { + m_clickAnimationActive = false; + } + } else { + // Use dim colors when locked, bright colors when unlocked + if (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire)) { + s_highlightColor = lerpColor(highlightColor3, highlightColor4, progress); + } else { + s_highlightColor = lerpColor(highlightColor1, highlightColor2, progress); + } + } + + x = 0; + y = 0; + + if (this->m_highlightShaking) { + t_ns = currentTime_ns - this->m_highlightShakingStartTime; + const double t_ms = t_ns / 1000000.0; + + static constexpr double SHAKE_DURATION_MS = 200.0; + + if (t_ms >= SHAKE_DURATION_MS) + this->m_highlightShaking = false; + else { + const double amplitude = 6.0 + ((this->m_highlightShakingStartTime / 1000000) % 5); + const double progress = t_ms / SHAKE_DURATION_MS; + const double damping = 1.0 / (1.0 + 2.5 * progress * (1.0 + 1.3 * progress)); + const double oscillation = ult::cos(ult::_M_PI * 4.0 * progress); + const double displacement = amplitude * oscillation * damping; + const int offset = static_cast(displacement); + + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: y = -offset; break; + case FocusDirection::Down: y = offset; break; + case FocusDirection::Left: x = -offset; break; + case FocusDirection::Right: x = offset; break; + default: break; + } + } + } + + if (!m_drawFrameless) { + if (ult::useSelectionBG) { + renderer->drawRectAdaptive(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); + } + renderer->drawBorderedRoundedRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11, this->getHeight(), 5, 5, a(s_highlightColor)); + } else { + if (ult::useSelectionBG) { + renderer->drawRectAdaptive(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); + } + } + + ult::onTrackBar.exchange(true, std::memory_order_acq_rel); + + if (this->m_clickAnimationActive) { + const u64 elapsedTime_ns = currentTime_ns - this->m_clickAnimationStartTime; + + auto clickAnimationProgress = tsl::style::ListItemHighlightLength * (1.0f - (static_cast(elapsedTime_ns) / 500000000.0f)); + + if (clickAnimationProgress < 0.0f) { + clickAnimationProgress = 0.0f; + this->m_clickAnimationActive = false; + } + + if (clickAnimationProgress > 0.0f) { + const u8 saturation = tsl::style::ListItemHighlightSaturation * (float(clickAnimationProgress) / float(tsl::style::ListItemHighlightLength)); + + Color animColor = {0xF, 0xF, 0xF, 0xF}; + if (invertBGClickColor) { + animColor.r = 15 - saturation; + animColor.g = 15 - saturation; + animColor.b = 15 - saturation; + } else { + animColor.r = saturation; + animColor.g = saturation; + animColor.b = saturation; + } + animColor.a = selectionBGColor.a; + renderer->drawRect(this->getX() +22, this->getY(), this->getWidth() -22, this->getHeight(), aWithOpacity(animColor)); + } + } + } + + /** + * @brief Gets the current value of the trackbar + * + * @return State + */ + virtual u8 getProgress() { + return this->m_value; + } + + /** + * @brief Sets the current state of the toggle. Updates the Value + * + * @param state State + */ + virtual void setProgress(u8 value) { + this->m_value = value; + } + + /** + * @brief Adds a listener that gets called whenever the state of the toggle changes + * + * @param stateChangedListener Listener with the current state passed in as parameter + */ + void setValueChangedListener(std::function valueChangedListener) { + this->m_valueChangedListener = valueChangedListener; + } + + protected: + const char *m_icon = nullptr; + s16 m_value = 0; + bool m_interactionLocked = false; + + std::function m_valueChangedListener = [](u8){}; + + bool m_usingStepTrackbar = false; + bool m_usingNamedStepTrackbar = false; + bool m_unlockedTrackbar = true; + bool touchInSliderBounds = false; + + u64 m_clickAnimationStartTime = 0; + bool m_clickAnimationActive = false; + + u8 m_numSteps = 101; + // V2 Style properties + bool m_useV2Style = false; + std::string m_label; + std::string m_units; + std::string m_selection; // Used for named step trackbars + bool m_drawFrameless = false; + + float m_lastBottomBound; + + s16 m_index = 0; // Add index tracking like V2 + u64 m_holdStartTime_ns = 0; + bool m_holding = false; + bool m_wasLastHeld = false; + u64 m_prevKeysHeld = 0; + }; + + + /** + * @brief A customizable analog trackbar going from 0% to 100% but using discrete steps (Like the volume slider) + * + */ + class StepTrackBar : public TrackBar { + public: + /** + * @brief Constructor + * + * @param icon Icon shown next to the track bar + * @param numSteps Number of steps the track bar has + * @param usingNamedStepTrackbar Whether this is a named step trackbar + * @param useV2Style Whether to use V2 visual style (label + value instead of icon) + * @param label Label text for V2 style + * @param units Units text for V2 style + */ + StepTrackBar(const char icon[3], size_t numSteps, bool usingNamedStepTrackbar = false, + bool useV2Style = false, const std::string& label = "", const std::string& units = "", + bool unlockedTrackbar = true) + : TrackBar(icon, true, usingNamedStepTrackbar, useV2Style, label, units, unlockedTrackbar), m_numSteps(numSteps) {} + + virtual ~StepTrackBar() {} + + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { + const u64 keysReleased = m_prevKeysHeld & ~keysHeld; + m_prevKeysHeld = keysHeld; + + const u64 currentTime_ns = ult::nowNs(); + static u64 lastUpdate_ns = currentTime_ns; + const u64 elapsed_ns = currentTime_ns - lastUpdate_ns; + + // KEY_R + directional: shake highlight + if (keysHeld & KEY_R) { + if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Up); + else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Down); + else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Left); + else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Right); + return true; + } + + // KEY_A: lock/unlock toggle (when locked), or click animation (when unlocked) + if ((keysDown & KEY_A) && !(keysHeld & ~KEY_A & ALL_KEYS_MASK)) { + if (!m_unlockedTrackbar) { + ult::atomicToggle(ult::allowSlide); + m_holding = false; + if (ult::allowSlide.load(std::memory_order_acquire)) { + // Unlocking: rumble + on sound only, no click animation, no enter feedback + triggerRumbleClick.store(true, std::memory_order_release); + triggerOnSound.store(true, std::memory_order_release); + } else { + // Locking: rumble + off sound only, no click animation + triggerRumbleClick.store(true, std::memory_order_release); + triggerOffSound.store(true, std::memory_order_release); + } + } else { + // Always-unlocked trackbar: full click animation + enter feedback + this->triggerClickAnimation(); + triggerEnterFeedback(); + } + return true; + } + + // Guard all movement behind lock state + if (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire)) { + return false; + } + + // Calculate actual max value based on steps + const int stepSize = 100 / (this->m_numSteps - 1); + const int maxValue = stepSize * (this->m_numSteps - 1); + + // Handle key release + if ((keysReleased & KEY_LEFT) || (keysReleased & KEY_RIGHT)) { + if (m_wasLastHeld) { + m_wasLastHeld = false; + m_holding = false; + lastUpdate_ns = currentTime_ns; + return true; + } else if (m_holding) { + m_holding = false; + lastUpdate_ns = currentTime_ns; + return true; + } + } + + // Ignore simultaneous left+right + if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) + return true; + + // Handle initial key press + if (keysDown & KEY_LEFT || keysDown & KEY_RIGHT) { + m_holding = true; + m_wasLastHeld = false; + m_holdStartTime_ns = currentTime_ns; + lastUpdate_ns = currentTime_ns; + + if (keysDown & KEY_LEFT && this->m_value > 0) { + triggerNavigationFeedback(); + this->m_value = std::max(this->m_value - stepSize, 0); + this->m_valueChangedListener(this->getProgress()); + } else if (keysDown & KEY_RIGHT && this->m_value < maxValue) { + triggerNavigationFeedback(); + this->m_value = std::min(this->m_value + stepSize, maxValue); + this->m_valueChangedListener(this->getProgress()); + } + return true; + } + + // Handle continued holding with acceleration + if (m_holding && ((keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT))) { + const u64 holdDuration_ns = currentTime_ns - m_holdStartTime_ns; + + static constexpr u64 initialDelay_ns = 300000000ULL; + static constexpr u64 initialInterval_ns = 67000000ULL; + static constexpr u64 shortInterval_ns = 10000000ULL; + static constexpr u64 transitionPoint_ns = 1000000000ULL; + + if (holdDuration_ns < initialDelay_ns) { + return true; + } + + const u64 holdDurationAfterDelay_ns = holdDuration_ns - initialDelay_ns; + const float t = std::min(1.0f, static_cast(holdDurationAfterDelay_ns) / static_cast(transitionPoint_ns)); + const u64 currentInterval_ns = static_cast((initialInterval_ns - shortInterval_ns) * (1.0f - t) + shortInterval_ns); + + if (elapsed_ns >= currentInterval_ns) { + if (keysHeld & KEY_LEFT && this->m_value > 0) { + triggerNavigationFeedback(); + this->m_value = std::max(this->m_value - stepSize, 0); + this->m_valueChangedListener(this->getProgress()); + lastUpdate_ns = currentTime_ns; + m_wasLastHeld = true; + return true; + } + + if (keysHeld & KEY_RIGHT && this->m_value < maxValue) { + triggerNavigationFeedback(); + this->m_value = std::min(this->m_value + stepSize, maxValue); + this->m_valueChangedListener(this->getProgress()); + lastUpdate_ns = currentTime_ns; + m_wasLastHeld = true; + return true; + } + } + } else { + m_holding = false; + } + + return false; + } + + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + const int stepSize = 100 / (this->m_numSteps - 1); + const int maxValue = stepSize * (this->m_numSteps - 1); + + s32 trackBarLeft = this->getX() + 59; + s32 width = this->getWidth() - 95; + + if (m_icon[0] != '\0') { + const s32 iconOffset = 14 + 23; + trackBarLeft += iconOffset; + width -= iconOffset; + } + + const s32 trackBarRight = trackBarLeft + width; + const u16 handlePos = (width * this->m_value) / maxValue; + const s32 circleCenterX = trackBarLeft + handlePos; + const s32 circleCenterY = this->getY() + 40 + 16 - 3 - ((!m_usingNamedStepTrackbar && !m_useV2Style) ? 11 : 0); + static constexpr s32 circleRadius = 16; + static bool triggerOnce = true; + + const bool touchInCircle = (std::abs(currX - circleCenterX) <= circleRadius) && (std::abs(currY - circleCenterY) <= circleRadius); + const bool currentlyInHorizontalBounds = (currX >= trackBarLeft && currX <= trackBarRight); + + if (event == TouchEvent::Release) { + triggerOnce = true; + + if (touchInSliderBounds) { + triggerRumbleDoubleClick.store(true, std::memory_order_release); + triggerOffSound.store(true, std::memory_order_release); + tsl::shiftItemFocus(this); + } + + touchInSliderBounds = false; + return false; + } + + if (touchInCircle || touchInSliderBounds) { + if (touchInSliderBounds && !currentlyInHorizontalBounds) { + if (currX > trackBarRight) { + this->m_value = maxValue; + } else if (currX < trackBarLeft) { + this->m_value = 0; + } + this->m_valueChangedListener(this->getProgress()); + + touchInSliderBounds = false; + return false; + } + + if (currentlyInHorizontalBounds) { + if (triggerOnce) { + triggerOnce = false; + triggerRumbleClick.store(true, std::memory_order_release); + triggerOnSound.store(true, std::memory_order_release); + } + touchInSliderBounds = true; + + float rawValue = (static_cast(currX - trackBarLeft) / static_cast(width)) * maxValue; + s16 newValue; + + if (rawValue < 0) { + newValue = 0; + } else if (rawValue > maxValue) { + newValue = maxValue; + } else { + newValue = std::round(rawValue / stepSize) * stepSize; + newValue = std::min(std::max(newValue, s16(0)), s16(maxValue)); + } + + if (newValue != this->m_value) { + triggerNavigationFeedback(); + this->m_value = newValue; + this->m_valueChangedListener(this->getProgress()); + } + + return true; + } + } + + return false; + } + + /** + * @brief Gets the current value of the trackbar + * + * @return State + */ + virtual u8 getProgress() override { + return this->m_value / (100 / (this->m_numSteps - 1)); + } + + /** + * @brief Sets the current state of the toggle. Updates the Value + * + * @param state State + */ + virtual void setProgress(u8 value) override { + value = std::min(value, u8(this->m_numSteps - 1)); + this->m_value = value * (100 / (this->m_numSteps - 1)); + } + + protected: + u8 m_numSteps = 1; + }; + + + /** + * @brief A customizable trackbar with multiple discrete steps with specific names. Name gets displayed above the bar + * + */ + class NamedStepTrackBar : public StepTrackBar { + public: + NamedStepTrackBar(const char icon[3], std::initializer_list stepDescriptions, + bool useV2Style = false, const std::string& label = "", bool unlockedTrackbar = true) + : StepTrackBar(icon, stepDescriptions.size(), true, useV2Style, label, "", unlockedTrackbar), + m_stepDescriptions(stepDescriptions.begin(), stepDescriptions.end()) { + this->m_usingNamedStepTrackbar = true; + m_numSteps = m_stepDescriptions.size(); + if (!m_stepDescriptions.empty()) { + this->m_selection = m_stepDescriptions[0]; + } + } + + virtual ~NamedStepTrackBar() {} + + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, + HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { + const u8 prevProgress = this->getProgress(); + const bool result = StepTrackBar::handleInput(keysDown, keysHeld, touchPos, leftJoyStick, rightJoyStick); + + if (this->getProgress() != prevProgress) { + const u8 currentIndex = this->getProgress(); + if (currentIndex < m_stepDescriptions.size()) { + this->m_selection = m_stepDescriptions[currentIndex]; + } + } + + return result; + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, + s32 initialX, s32 initialY) override { + const u8 prevProgress = this->getProgress(); + const bool result = StepTrackBar::onTouch(event, currX, currY, prevX, prevY, initialX, initialY); + + if (result && this->getProgress() != prevProgress) { + const u8 currentIndex = this->getProgress(); + if (currentIndex < m_stepDescriptions.size()) { + this->m_selection = m_stepDescriptions[currentIndex]; + } + } + + return result; + } + + virtual void setProgress(u8 value) override { + StepTrackBar::setProgress(value); + + const u8 currentIndex = this->getProgress(); + if (currentIndex < m_stepDescriptions.size()) { + this->m_selection = m_stepDescriptions[currentIndex]; + } + } + + const std::string& getSelection() const { + return this->m_selection; + } + + virtual void draw(gfx::Renderer *renderer) override { + if (touchInSliderBounds) { + m_drawFrameless = true; + drawHighlight(renderer); + } else { + m_drawFrameless = false; + } + + s32 xPos = this->getX() + 59; + s32 yPos = this->getY() + 40 + 16 - 3; + s32 width = this->getWidth() - 95; + const int maxValue = (100 / (this->m_numSteps - 1)) * (this->m_numSteps - 1); + u16 handlePos = width * (this->m_value) / maxValue; + + s32 iconOffset = 0; + + if (m_icon[0] != '\0') { + s32 iconWidth = 23; + iconOffset = 14 + iconWidth; + xPos += iconOffset; + width -= iconOffset; + handlePos = (width) * (this->m_value) / (100); + } + + // Draw step tick marks + const u8 numSteps = m_numSteps; + const u16 baseX = xPos; + const u16 baseY = this->getY() + 44; + const u8 halfNumSteps = (numSteps - 1) / 2; + const u16 lastStepX = baseX + width - 1; + const float stepSpacing = static_cast(width) / (numSteps - 1); + const auto stepColor = a(trackBarEmptyColor); + + u16 stepX; + for (u8 i = 0; i < numSteps; i++) { + if (i == numSteps - 1) { + stepX = lastStepX; + } else { + stepX = baseX + static_cast(std::round(i * stepSpacing)); + if (i > halfNumSteps) { + stepX -= 1; + } + } + renderer->drawRect(stepX, baseY, 1, 8, stepColor); + } + + // Draw track bar background + drawBar(renderer, xPos, yPos-3, width, trackBarEmptyColor, false); + + const bool isEffectivelyUnlocked = m_unlockedTrackbar || ult::allowSlide.load(std::memory_order_acquire); + + if (!this->m_focused) { + drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, false); + renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(m_drawFrameless ? s_highlightColor : trackBarSliderBorderColor)); + renderer->drawCircle(xPos + handlePos, yPos, 13, true, a((isEffectivelyUnlocked || touchInSliderBounds) ? trackBarSliderMalleableColor : trackBarSliderColor)); + } else { + touchInSliderBounds = false; + if (m_unlockedTrackbar != ult::unlockedSlide.load(std::memory_order_acquire)) + ult::unlockedSlide.store(m_unlockedTrackbar, std::memory_order_release); + drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, false); + renderer->drawCircle(xPos + x + handlePos, yPos +y, 16, true, a(s_highlightColor)); + renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a(isEffectivelyUnlocked ? trackBarSliderMalleableColor : trackBarSliderColor)); + } + + if (m_useV2Style) { + std::string labelPart = this->m_label; + ult::removeTag(labelPart); + + std::string valuePart = this->m_selection; + const auto valueWidth = renderer->getTextDimensions(valuePart, false, 16).first; + const s32 labelX = xPos; + const s32 valueX = xPos + width - valueWidth; + + renderer->drawString(labelPart, false, labelX, this->getY() + 14 + 16, 16, + ((!this->m_focused || !ult::useSelectionText) ? defaultTextColor : selectedTextColor)); + renderer->drawString(valuePart, false, valueX, this->getY() + 14 + 16, 16, + (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); + + if (m_icon[0] != '\0') + renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2+2, 30, tsl::style::color::ColorText); + } else { + const auto textDimensions = renderer->getTextDimensions(this->m_selection, false, 16); + const s32 textWidth = textDimensions.first; + const s32 textX = xPos + (width / 2) - (textWidth / 2); + const s32 textY = this->getY() + 14 + 16; + + renderer->drawString(this->m_selection.c_str(), false, textX, textY, 16, + a(this->m_focused ? tsl::style::color::ColorHighlight : tsl::style::color::ColorText)); + + if (m_icon[0] != '\0') + renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2+2, 30, tsl::style::color::ColorText); + } + + // Draw separators + if (m_lastBottomBound != this->getTopBound()) + renderer->drawRect(this->getX() + 4+20-1, this->getTopBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); + renderer->drawRect(this->getX() + 4+20-1, this->getBottomBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); + m_lastBottomBound = this->getBottomBound(); + } + + protected: + std::vector m_stepDescriptions; + }; + + + /** + * @brief A customizable analog trackbar going from minValue to maxValue + * + */ + class TrackBarV2 : public Element { + public: + using SimpleValueChangeCallback = std::function; + + u64 lastUpdate_ns; + + Color highlightColor = {0xf, 0xf, 0xf, 0xf}; + float progress; + float counter = 0.0; + s32 x, y; + s32 amplitude; + u32 descWidth, descHeight; + + void setScriptKeyListener(std::function listener) { + m_scriptKeyListener = std::move(listener); + } + + TrackBarV2(std::string label, std::string packagePath = "", s16 minValue = 0, s16 maxValue = 100, std::string units = "", + std::function>&&, const std::string&, const std::string&)> executeCommands = nullptr, + std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> sourceReplacementFunc = nullptr, + std::vector> cmd = {}, const std::string& selCmd = "", bool usingStepTrackbar = false, bool usingNamedStepTrackbar = false, s16 numSteps = -1, bool unlockedTrackbar = false, bool executeOnEveryTick = false) + : m_label(label), m_packagePath(packagePath), m_minValue(minValue), m_maxValue(maxValue), m_units(units), + interpretAndExecuteCommands(executeCommands), getSourceReplacement(sourceReplacementFunc), commands(std::move(cmd)), selectedCommand(selCmd), + m_usingStepTrackbar(usingStepTrackbar), m_usingNamedStepTrackbar(usingNamedStepTrackbar), m_numSteps(numSteps), m_unlockedTrackbar(unlockedTrackbar), m_executeOnEveryTick(executeOnEveryTick) { + + m_isItem = true; + + if (maxValue < minValue) { + std::swap(minValue, maxValue); + m_minValue = minValue; + m_maxValue = maxValue; + } + + if ((!usingStepTrackbar && !usingNamedStepTrackbar) || numSteps == -1) { + m_numSteps = (maxValue - minValue) + 1; + } + + if (m_numSteps < 2) { + m_numSteps = 2; + } + + bool loadedValue = false; + + if (!m_packagePath.empty()) { + auto configIniData = ult::getParsedDataFromIniFile(m_packagePath + "config.ini"); + auto sectionIt = configIniData.find(m_label); + + if (sectionIt != configIniData.end()) { + auto indexIt = sectionIt->second.find("index"); + if (indexIt != sectionIt->second.end() && !indexIt->second.empty()) { + m_index = static_cast(ult::stoi(indexIt->second)); + } + + if (!m_usingNamedStepTrackbar) { + auto valueIt = sectionIt->second.find("value"); + if (valueIt != sectionIt->second.end() && !valueIt->second.empty()) { + m_value = static_cast(ult::stoi(valueIt->second)); + loadedValue = true; + } + } + } + } + + if (m_index >= m_numSteps) m_index = m_numSteps - 1; + if (m_index < 0) m_index = 0; + + if (!loadedValue) { + if (m_numSteps > 1) { + m_value = minValue + m_index * (static_cast(maxValue - minValue) / (m_numSteps - 1)); + } else { + m_value = minValue; + } + } + + if (m_value > maxValue) m_value = maxValue; + if (m_value < minValue) m_value = minValue; + + lastUpdate_ns = ult::nowNs(); + } + + virtual ~TrackBarV2() {} + + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) { + return this; + } + + inline void updateAndExecute(bool updateIni = true) { + if (m_simpleCallback) { + m_simpleCallback(m_value, m_index); + return; + } + + + if (m_packagePath.empty()) { + return; + } + + const std::string indexStr = ult::to_string(m_index); + const std::string valueStr = m_usingNamedStepTrackbar ? m_selection : ult::to_string(m_value); + + if (updateIni) { + const std::string configPath = m_packagePath + "config.ini"; + ult::setIniFileValue(configPath, m_label, "index", indexStr); + ult::setIniFileValue(configPath, m_label, "value", valueStr); + } + bool success = false; + + static const std::string valuePlaceholder = "{value}"; + static const std::string indexPlaceholder = "{index}"; + static const size_t valuePlaceholderLen = valuePlaceholder.length(); + static const size_t indexPlaceholderLen = indexPlaceholder.length(); + const size_t valueStrLen = valueStr.length(); + const size_t indexStrLen = indexStr.length(); + + size_t tryCount = 0; + while (!success) { + if (interpretAndExecuteCommands) { + if (tryCount > 3) + break; + auto modifiedCmds = getSourceReplacement(commands, valueStr, m_index, m_packagePath); + + for (auto& cmd : modifiedCmds) { + for (auto& arg : cmd) { + for (size_t pos = 0; (pos = arg.find(valuePlaceholder, pos)) != std::string::npos; pos += valueStrLen) { + arg.replace(pos, valuePlaceholderLen, valueStr); + } + + if (m_usingNamedStepTrackbar) { + for (size_t pos = 0; (pos = arg.find(indexPlaceholder, pos)) != std::string::npos; pos += indexStrLen) { + arg.replace(pos, indexPlaceholderLen, indexStr); + } + } + } + } + + success = interpretAndExecuteCommands(std::move(modifiedCmds), m_packagePath, selectedCommand); + ult::resetPercentages(); + + if (success) + break; + tryCount++; + } + } + } + + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { + const u64 keysReleased = m_prevKeysHeld & ~keysHeld; + m_prevKeysHeld = keysHeld; + + const u64 currentTime_ns = ult::nowNs(); + const u64 elapsed_ns = currentTime_ns - lastUpdate_ns; + + m_keyRHeld = (keysHeld & KEY_R) != 0; + + if ((keysHeld & KEY_R)) { + if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Up); + else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Down); + else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ~KEY_R & ALL_KEYS_MASK)){ + this->shakeHighlight(FocusDirection::Left); + } + else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ~KEY_R & ALL_KEYS_MASK)) { + this->shakeHighlight(FocusDirection::Right); + } + return true; + } + + if ((keysDown & KEY_A) && !(keysHeld & ~KEY_A & ALL_KEYS_MASK)) { + + + if (!m_unlockedTrackbar) { + ult::atomicToggle(ult::allowSlide); + m_holding = false; + + if (ult::allowSlide.load(std::memory_order_acquire)) { + triggerRumbleClick.store(true, std::memory_order_release); + triggerOnSound.store(true, std::memory_order_release); + } + } + if (m_unlockedTrackbar || (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire))) { + // Only trigger click animation when unlocked + if (m_unlockedTrackbar || ult::allowSlide.load(std::memory_order_acquire)) { + triggerClick = true; + triggerEnterFeedback(); + } else if (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire)) { + triggerRumbleClick.store(true, std::memory_order_release); + triggerOffSound.store(true, std::memory_order_release); + } + updateAndExecute(); + } + return true; + } + + if ((keysDown & SCRIPT_KEY) && !(keysHeld & ~SCRIPT_KEY & ALL_KEYS_MASK)) { + if (m_scriptKeyListener) { + m_scriptKeyListener(); + } + return true; + } + + if (ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) { + static s16 lastHapticSegment = -1; + + // Handle key release + if (((keysReleased & KEY_LEFT) || (keysReleased & KEY_RIGHT))) { + lastHapticSegment = -1; // Reset for next interaction + + // If we were holding and repeating, just stop + if (m_wasLastHeld) { + m_wasLastHeld = false; + m_holding = false; + updateAndExecute(); + lastUpdate_ns = ult::nowNs(); + return true; + } + // If it was a quick tap (no repeat happened), handle the single tick + else if (m_holding) { + m_holding = false; + updateAndExecute(); + lastUpdate_ns = ult::nowNs(); + return true; + } + } + + // Ignore simultaneous left+right + if (keysDown & KEY_LEFT && keysDown & KEY_RIGHT) + return true; + if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) + return true; + + // Handle initial key press + if (keysDown & KEY_LEFT || keysDown & KEY_RIGHT) { + triggerRumbleClick.store(true, std::memory_order_release); + + // Start tracking the hold + m_holding = true; + m_wasLastHeld = false; + m_holdStartTime_ns = ult::nowNs(); + lastUpdate_ns = currentTime_ns; + + // Perform the initial single tick + if (keysDown & KEY_LEFT && this->m_value > m_minValue) { + this->m_index--; + this->m_value--; + this->m_valueChangedListener(this->m_value); + updateAndExecute(false); + + // Calculate and store initial segment (0-10 for 11 segments) + const s16 currentSegment = (this->m_index * 10) / (m_numSteps - 1); + if (this->m_index == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + } else if (keysDown & KEY_RIGHT && this->m_value < m_maxValue) { + this->m_index++; + this->m_value++; + this->m_valueChangedListener(this->m_value); + updateAndExecute(false); + + // Calculate and store initial segment (0-10 for 11 segments) + const s16 currentSegment = (this->m_index * 10) / (m_numSteps - 1); + if (this->m_index == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + } + return true; + } + + // Handle continued holding (after initial press) + if (m_holding && ((keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT))) { + const u64 holdDuration_ns = currentTime_ns - m_holdStartTime_ns; + + // Initial delay before repeating starts (e.g., 300ms) + static constexpr u64 initialDelay_ns = 300000000ULL; + // Calculate interval with acceleration + static constexpr u64 initialInterval_ns = 67000000ULL; // ~67ms + static constexpr u64 shortInterval_ns = 10000000ULL; // ~10ms + static constexpr u64 transitionPoint_ns = 1000000000ULL; // 1 second + + // If we haven't passed the initial delay, don't repeat yet + if (holdDuration_ns < initialDelay_ns) { + return true; + } + + const u64 holdDurationAfterDelay_ns = holdDuration_ns - initialDelay_ns; + const float t = std::min(1.0f, static_cast(holdDurationAfterDelay_ns) / static_cast(transitionPoint_ns)); + const u64 currentInterval_ns = static_cast((initialInterval_ns - shortInterval_ns) * (1.0f - t) + shortInterval_ns); + + if (elapsed_ns >= currentInterval_ns) { + if (keysHeld & KEY_LEFT && this->m_value > m_minValue) { + this->m_index--; + this->m_value--; + this->m_valueChangedListener(this->m_value); + if (m_executeOnEveryTick) { + updateAndExecute(false); + } + + // Calculate current segment (0-10 for 11 segments) and trigger haptics on segment change + const s16 currentSegment = (this->m_index * 10) / (m_numSteps - 1); + if (this->m_index == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + + lastUpdate_ns = currentTime_ns; + m_wasLastHeld = true; + return true; + } + + if (keysHeld & KEY_RIGHT && this->m_value < m_maxValue) { + this->m_index++; + this->m_value++; + this->m_valueChangedListener(this->m_value); + if (m_executeOnEveryTick) { + updateAndExecute(false); + } + + // Calculate current segment (0-10 for 11 segments) and trigger haptics on segment change + const s16 currentSegment = (this->m_index * 10) / (m_numSteps - 1); + if (this->m_index == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + + lastUpdate_ns = currentTime_ns; + m_wasLastHeld = true; + return true; + } + } + } else { + m_holding = false; + } + } + + return false; + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + const u16 trackBarWidth = this->getWidth() - 95; + const u16 handlePos = (trackBarWidth * (this->m_value - m_minValue)) / (m_maxValue - m_minValue); + const s32 circleCenterX = this->getX() + 59 + handlePos; + const s32 circleCenterY = this->getY() + 40 + 16 - 1; + static constexpr s32 circleRadius = 16; + static bool triggerOnce = true; + static s16 lastHapticSegment = -1; + static bool wasOriginallyLocked = false; + + const bool touchInCircle = (std::abs(initialX - circleCenterX) <= circleRadius) && (std::abs(initialY - circleCenterY) <= circleRadius); + + // CRITICAL FIX: Check if current touch is within valid horizontal bounds + // Allow vertical drift (top/bottom), only care about left/right bounds + const s32 trackBarLeft = this->getX() + 59; + const s32 trackBarRight = trackBarLeft + trackBarWidth; + const bool currentlyInHorizontalBounds = (currX >= trackBarLeft && currX <= trackBarRight); + + // Handle touch start + if (event == TouchEvent::Touch && touchInCircle) { + // Remember if it was locked before we touched it + wasOriginallyLocked = !m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire); + + // Temporarily unlock if it was locked + if (wasOriginallyLocked) { + ult::allowSlide.store(true, std::memory_order_release); + } + } + + // Handle release + if (event == TouchEvent::Release) { + triggerOnce = true; + lastHapticSegment = -1; + + // Re-lock if it was originally locked + if (wasOriginallyLocked) { + ult::allowSlide.store(false, std::memory_order_release); + wasOriginallyLocked = false; + } + + if (touchInSliderBounds) { + updateAndExecute(); + touchInSliderBounds = false; + triggerRumbleDoubleClick.store(true, std::memory_order_release); + triggerOffSound.store(true, std::memory_order_release); + tsl::shiftItemFocus(this); + } + return false; + } + + const bool isUnlocked = m_unlockedTrackbar || ult::allowSlide.load(std::memory_order_acquire); + + // CRITICAL FIX: Only process touch if we're in bounds OR if we were already interacting + // When going out of horizontal bounds, clamp to min/max value before stopping + if ((touchInCircle || touchInSliderBounds) && isUnlocked) { + // If we were touching but now went out of horizontal bounds, clamp to edge value then stop + if (touchInSliderBounds && !currentlyInHorizontalBounds) { + // Clamp to max if past right edge, min if past left edge + if (currX > trackBarRight) { + this->m_value = m_maxValue; + this->m_index = m_numSteps - 1; + } else if (currX < trackBarLeft) { + this->m_value = m_minValue; + this->m_index = 0; + } + this->m_valueChangedListener(this->getProgress()); + if (m_executeOnEveryTick) { + updateAndExecute(false); + } + + touchInSliderBounds = false; + return false; + } + + // We're in valid horizontal bounds, continue interaction + if (currentlyInHorizontalBounds) { + touchInSliderBounds = true; + if (triggerOnce) { + triggerOnce = false; + triggerRumbleClick.store(true, std::memory_order_release); + triggerOnSound.store(true, std::memory_order_release); + } + + // Add 0.5 to round to nearest step instead of truncating + const s16 newIndex = std::max(static_cast(0), std::min(static_cast((currX - trackBarLeft) / static_cast(trackBarWidth) * (m_numSteps - 1) + 0.5f), static_cast(m_numSteps - 1))); + const s16 newValue = m_minValue + newIndex * (static_cast(m_maxValue - m_minValue) / (m_numSteps - 1)); + + if (newValue != this->m_value || newIndex != this->m_index) { + this->m_value = newValue; + this->m_index = newIndex; + this->m_valueChangedListener(this->getProgress()); + if (m_executeOnEveryTick) { + updateAndExecute(false); + } + + // Calculate which 10% segment we're in (0-10 for 11 segments) + const s16 currentSegment = (newIndex * 10) / (m_numSteps - 1); + + // Trigger haptics when crossing into a new 10% segment OR at index 0 + if (newIndex == 0 || currentSegment != lastHapticSegment) { + lastHapticSegment = currentSegment; + triggerNavigationFeedback(); + } + } + + return true; + } + } + + return false; + } + + void drawBar(gfx::Renderer *renderer, s32 x, s32 y, u16 width, Color& color, bool isRounded = true) { + if (isRounded) { + renderer->drawUniformRoundedRect(x, y, width, 7, a(color)); + } else { + renderer->drawRect(x, y, width, 7, a(color)); + } + } + + virtual void draw(gfx::Renderer *renderer) override { + const u16 handlePos = (this->getWidth() - 95) * (this->m_value - m_minValue) / (m_maxValue - m_minValue); + const s32 xPos = this->getX() + 59; + const s32 yPos = this->getY() + 40 + 16 - 3; + const s32 width = this->getWidth() - 95; + + const bool shouldAppearLocked = m_unlockedTrackbar && m_keyRHeld; + const bool visuallyUnlocked = (m_unlockedTrackbar && !m_keyRHeld) || touchInSliderBounds; + + if (visuallyUnlocked && touchInSliderBounds) { + m_drawFrameless = true; + drawHighlight(renderer); + } else { + m_drawFrameless = false; + } + + drawBar(renderer, xPos, yPos-3, width, trackBarEmptyColor, !m_usingNamedStepTrackbar); + + + if (!this->m_focused) { + drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); + renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(!m_drawFrameless ? trackBarSliderBorderColor : highlightColor)); + renderer->drawCircle(xPos + handlePos, yPos, 13, true, a(visuallyUnlocked ? trackBarSliderMalleableColor : trackBarSliderColor)); + } else { + touchInSliderBounds = false; + if (m_unlockedTrackbar != ult::unlockedSlide.load(std::memory_order_acquire)) + ult::unlockedSlide.store(m_unlockedTrackbar, std::memory_order_release); + drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); + renderer->drawCircle(xPos + x + handlePos, yPos +y, 16, true, a(highlightColor)); + const bool focusedVisuallyUnlocked = (ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) && !shouldAppearLocked; + renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a(focusedVisuallyUnlocked ? trackBarSliderMalleableColor : trackBarSliderColor)); + } + + std::string labelPart = this->m_label; + ult::removeTag(labelPart); + + if (!m_usingNamedStepTrackbar) { + m_valuePart = (this->m_units.compare("%") == 0 || this->m_units.compare("°C") == 0 || this->m_units.compare("°F") == 0) + ? ult::to_string(this->m_value) + this->m_units + : ult::to_string(this->m_value) + (this->m_units.empty() ? "" : " ") + this->m_units; + } else + m_valuePart = this->m_selection; + + const auto valueWidth = renderer->getTextDimensions(m_valuePart, false, 16).first; + + renderer->drawString(labelPart, false, xPos, this->getY() + 14 + 16, 16, (!this->m_focused || !ult::useSelectionText) ? defaultTextColor : selectedTextColor); + renderer->drawString(m_valuePart, false, this->getWidth() -17 - valueWidth, this->getY() + 14 + 16, 16, + (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); + + if (m_lastBottomBound != this->getTopBound()) + renderer->drawRect(this->getX() + 4+20-1, this->getTopBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); + renderer->drawRect(this->getX() + 4+20-1, this->getBottomBound(), this->getWidth() + 6 + 10+20 +4, 1, a(separatorColor)); + m_lastBottomBound = this->getBottomBound(); + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + this->setBoundaries(this->getX() - 16 , this->getY(), this->getWidth()+20+4, tsl::style::TrackBarDefaultHeight ); + } + + virtual void drawFocusBackground(gfx::Renderer *renderer) { + } + + virtual void drawHighlight(gfx::Renderer *renderer) override { + const u64 currentTime_ns = ult::nowNs(); + const double timeInSeconds = static_cast(currentTime_ns) / 1000000000.0; + progress = ((ult::cos(2.0 * ult::_M_PI * std::fmod(timeInSeconds, 1.0) - ult::_M_PI / 2) + 1.0) / 2.0); + + Color clickColor1 = highlightColor1; + Color clickColor2 = clickColor; + + if (triggerClick && !m_clickActive) { + m_clickStartTime_ns = currentTime_ns; + m_clickActive = true; + if (progress >= 0.5) { + clickColor1 = clickColor; + clickColor2 = highlightColor2; + } + } + + if (m_lastLabel != m_label) { + m_clickActive = false; + triggerClick = false; + } + m_lastLabel = m_label; + + if (m_clickActive) { + const u64 elapsedTime_ns = currentTime_ns - m_clickStartTime_ns; + if (elapsedTime_ns < 500000000ULL) { + highlightColor = lerpColor(clickColor1, clickColor2, progress); + } else { + m_clickActive = false; + triggerClick = false; + } + } else { + const bool shouldAppearLocked = m_unlockedTrackbar && m_keyRHeld; + + if ((ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) && !shouldAppearLocked) { + highlightColor = lerpColor(highlightColor1, highlightColor2, progress); + } else { + highlightColor = lerpColor(highlightColor3, highlightColor4, progress); + } + } + + x = 0; + y = 0; + + if (this->m_highlightShaking) { + t_ns = currentTime_ns - this->m_highlightShakingStartTime; + const double t_ms = t_ns / 1000000.0; + + static constexpr double SHAKE_DURATION_MS = 200.0; + + if (t_ms >= SHAKE_DURATION_MS) + this->m_highlightShaking = false; + else { + // Generate random amplitude only once per shake using the start time as seed + const double amplitude = 6.0 + ((this->m_highlightShakingStartTime / 1000000) % 5); + const double progress = t_ms / SHAKE_DURATION_MS; // 0 to 1 + + // Lighter damping so both bounces are visible + const double damping = 1.0 / (1.0 + 2.5 * progress * (1.0 + 1.3 * progress)); + + // 2 full oscillations = 2 clear bounces + const double oscillation = ult::cos(ult::_M_PI * 4.0 * progress); + const double displacement = amplitude * oscillation * damping; + const int offset = static_cast(displacement); + + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: y = -offset; break; + case FocusDirection::Down: y = offset; break; + case FocusDirection::Left: x = -offset; break; + case FocusDirection::Right: x = offset; break; + default: break; + } + } + } + + + if (ult::useSelectionBG) + renderer->drawRectAdaptive(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(m_drawFrameless ? clickColor : selectionBGColor)); + if (!m_drawFrameless) + renderer->drawBorderedRoundedRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11, this->getHeight(), 5, 5, a(highlightColor)); + + ult::onTrackBar.store(true, std::memory_order_release); + + if (m_clickActive && m_useClickAnimation) { + const u64 elapsedTime_ns = currentTime_ns - m_clickStartTime_ns; + + auto clickAnimationProgress = tsl::style::ListItemHighlightLength * (1.0f - (static_cast(elapsedTime_ns) / 500000000.0f)); + + if (clickAnimationProgress < 0.0f) { + clickAnimationProgress = 0.0f; + } + + if (clickAnimationProgress > 0.0f) { + const u8 saturation = tsl::style::ListItemHighlightSaturation * (float(clickAnimationProgress) / float(tsl::style::ListItemHighlightLength)); + + Color animColor = {0xF, 0xF, 0xF, 0xF}; + if (invertBGClickColor) { + animColor.r = 15 - saturation; + animColor.g = 15 - saturation; + animColor.b = 15 - saturation; + } else { + animColor.r = saturation; + animColor.g = saturation; + animColor.b = saturation; + } + animColor.a = selectionBGColor.a; + renderer->drawRect(this->getX() +22, this->getY(), this->getWidth() -22, this->getHeight(), aWithOpacity(animColor)); + } + } + } + + virtual u8 getIndex() { + return this->m_index; + } + + virtual u8 getProgress() { + return this->m_value; + } + + virtual void setProgress(u8 value) { + this->m_value = value; + } + + void setValueChangedListener(std::function valueChangedListener) { + this->m_valueChangedListener = valueChangedListener; + } + + void setSimpleCallback(SimpleValueChangeCallback callback) { + m_simpleCallback = std::move(callback); + } + + inline void disableClickAnimation() { + m_useClickAnimation = false; + } + + protected: + std::string m_label; + std::string m_packagePath; + std::string m_selection; + s16 m_value = 0; + s16 m_minValue = 0; + s16 m_maxValue = 100; + std::string m_units; + bool m_interactionLocked = false; + bool m_keyRHeld = false; + + std::function m_valueChangedListener = [](u8) {}; + + std::function>&&, const std::string&, const std::string&)> interpretAndExecuteCommands; + std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> getSourceReplacement; + std::vector> commands; + std::string selectedCommand; + + bool m_usingStepTrackbar = false; + bool m_usingNamedStepTrackbar = false; + s16 m_numSteps = 2; + s16 m_index = 0; + bool m_unlockedTrackbar = false; + bool m_executeOnEveryTick = false; + bool touchInSliderBounds = false; + bool triggerClick = false; + std::function m_scriptKeyListener; + + // Instance variables replacing static ones + float m_lastBottomBound = 0.0f; + std::string m_valuePart = ""; + u64 m_clickStartTime_ns = 0; + bool m_clickActive = false; + std::string m_lastLabel = ""; + bool m_holding = false; + u64 m_holdStartTime_ns = 0; + u64 m_prevKeysHeld = 0; + bool m_wasLastHeld = false; + bool m_drawFrameless = false; + + bool m_useClickAnimation = true; + + SimpleValueChangeCallback m_simpleCallback = nullptr; + }; + + + /** + * @brief A customizable analog trackbar going from 0% to 100% but using discrete steps (Like the volume slider) + * + */ + class StepTrackBarV2 : public TrackBarV2 { + public: + + /** + * @brief Constructor + * + * @param icon Icon shown next to the track bar + * @param numSteps Number of steps the track bar has + */ + StepTrackBarV2(std::string label, std::string packagePath, size_t numSteps, s16 minValue, s16 maxValue, std::string units, + std::function>&&, const std::string&, const std::string&)> executeCommands = nullptr, + std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> sourceReplacementFunc = nullptr, + std::vector> cmd = {}, const std::string& selCmd = "", bool usingNamedStepTrackbar = false, bool unlockedTrackbar = false, bool executeOnEveryTick = false) + : TrackBarV2(label, packagePath, minValue, maxValue, units, executeCommands, sourceReplacementFunc, cmd, selCmd, !usingNamedStepTrackbar, usingNamedStepTrackbar, numSteps, unlockedTrackbar, executeOnEveryTick) {} + + virtual ~StepTrackBarV2() {} + + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { + static u32 tick = 0; + static bool holding = false; + static u64 prevKeysHeld = 0; + const u64 keysReleased = prevKeysHeld & ~keysHeld; + prevKeysHeld = keysHeld; + + static bool wasLastHeld = false; + + // Update KEY_R state for visual appearance + m_keyRHeld = (keysHeld & KEY_R) != 0; + + if ((keysHeld & KEY_R)) { + if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Up); + else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ~KEY_R & ALL_KEYS_MASK)) + this->shakeHighlight(FocusDirection::Down); + else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ~KEY_R & ALL_KEYS_MASK)){ + this->shakeHighlight(FocusDirection::Left); + } + else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ~KEY_R & ALL_KEYS_MASK)) { + this->shakeHighlight(FocusDirection::Right); + } + return true; + } + + // Check if KEY_A is pressed to toggle ult::allowSlide + if ((keysDown & KEY_A) && !(keysHeld & ~KEY_A & ALL_KEYS_MASK)) { + + + if (!m_unlockedTrackbar) { + ult::atomicToggle(ult::allowSlide); + m_holding = false; + + if (ult::allowSlide.load(std::memory_order_acquire)) { + triggerRumbleClick.store(true, std::memory_order_release); + triggerOnSound.store(true, std::memory_order_release); + } + } + if (m_unlockedTrackbar || (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire))) { + // Only trigger click animation when unlocked + if (m_unlockedTrackbar || ult::allowSlide.load(std::memory_order_acquire)) { + triggerClick = true; + triggerEnterFeedback(); + } else if (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire)) { + triggerRumbleClick.store(true, std::memory_order_release); + triggerOffSound.store(true, std::memory_order_release); + } + updateAndExecute(); + } + return true; + } + + // Handle SCRIPT_KEY press + if ((keysDown & SCRIPT_KEY) && !(keysHeld & ~SCRIPT_KEY & ALL_KEYS_MASK)) { + if (m_scriptKeyListener) { + m_scriptKeyListener(); + } + return true; + } + + if (ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) { + if (((keysReleased & KEY_LEFT) || (keysReleased & KEY_RIGHT)) || + (wasLastHeld && !(keysHeld & (KEY_LEFT | KEY_RIGHT)))) { + updateAndExecute(); + holding = false; + wasLastHeld = false; + tick = 0; + return true; + } + + if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) { + tick = 0; + return true; + } + + if (keysHeld & (KEY_LEFT | KEY_RIGHT)) { + if (!holding) { + holding = true; + tick = 0; + } + + if ((tick == 0 || tick > 20) && (tick % 3) == 0) { + const float stepSize = static_cast(m_maxValue - m_minValue) / (this->m_numSteps - 1); + if (keysHeld & KEY_LEFT && this->m_index > 0) { + triggerNavigationFeedback(); + + this->m_index--; + this->m_value = static_cast(std::round(m_minValue + m_index * stepSize)); + } else if (keysHeld & KEY_RIGHT && this->m_index < this->m_numSteps-1) { + triggerNavigationFeedback(); + + this->m_index++; + this->m_value = static_cast(std::round(m_minValue + m_index * stepSize)); + } else { + return false; + } + this->m_valueChangedListener(this->getProgress()); + if (m_executeOnEveryTick) + updateAndExecute(false); + wasLastHeld = true; + } + tick++; + return true; + } else { + holding = false; + tick = 0; + } + } + + return false; + } + + + /** + * @brief Gets the current value of the trackbar + * + * @return State + */ + virtual u8 getProgress() override { + return this->m_value / (100 / (this->m_numSteps - 1)); + } + + /** + * @brief Sets the current state of the toggle. Updates the Value + * + * @param state State + */ + virtual void setProgress(u8 value) override { + value = std::min(value, u8(this->m_numSteps - 1)); + this->m_index = value; + + // If using simple callback (modern API), use minValue/maxValue range + // Otherwise use legacy 0-100 range for config.ini compatibility + if (m_simpleCallback) { + const float stepSize = static_cast(m_maxValue - m_minValue) / (this->m_numSteps - 1); + this->m_value = static_cast(std::round(m_minValue + m_index * stepSize)); + } else { + // Legacy behavior for command system + this->m_value = value * (100 / (this->m_numSteps - 1)); + } + } + }; + + + /** + * @brief A customizable trackbar with multiple discrete steps with specific names. Name gets displayed above the bar + * + */ + class NamedStepTrackBarV2 : public StepTrackBarV2 { + public: + u16 trackBarWidth, stepWidth, currentDescIndex; + u32 descWidth, descHeight; + + /** + * @brief Constructor + * + * @param icon Icon shown next to the track bar + * @param stepDescriptions Step names displayed above the track bar + */ + NamedStepTrackBarV2(std::string label, std::string packagePath, std::vector& stepDescriptions, + std::function>&&, const std::string&, const std::string&)> executeCommands = nullptr, + std::function>(const std::vector>&, const std::string&, size_t, const std::string&)> sourceReplacementFunc = nullptr, + std::vector> cmd = {}, const std::string& selCmd = "", bool unlockedTrackbar = false, bool executeOnEveryTick = false) + : StepTrackBarV2(label, packagePath, stepDescriptions.size(), 0, (stepDescriptions.size()-1), "", executeCommands, sourceReplacementFunc, cmd, selCmd, true, unlockedTrackbar, executeOnEveryTick), m_stepDescriptions(stepDescriptions) { + // Initialize the selection with the current index + if (!m_stepDescriptions.empty() && m_index >= 0 && m_index < static_cast(m_stepDescriptions.size())) { + this->m_selection = m_stepDescriptions[m_index]; + currentDescIndex = m_index; + } + } + + virtual ~NamedStepTrackBarV2() {} + + virtual void draw(gfx::Renderer *renderer) override { + // Cache frequently used values + const u16 trackBarWidth = this->getWidth() - 95; + const u16 baseX = this->getX() + 59; + const u16 baseY = this->getY() + 44; // 50 - 3 + const u8 numSteps = this->m_numSteps; + const u8 halfNumSteps = (numSteps - 1) / 2; + const u16 lastStepX = baseX + trackBarWidth - 1; + + // Pre-calculate step spacing + const float stepSpacing = static_cast(trackBarWidth) / (numSteps - 1); + + // Cache color for multiple drawRect calls + const auto stepColor = a(trackBarEmptyColor); + + // Draw step rectangles - optimized loop + u16 stepX; + for (u8 i = 0; i < numSteps; i++) { + + if (i == numSteps - 1) { + // Last step - avoid overshooting + stepX = lastStepX; + } else { + stepX = baseX + static_cast(std::round(i * stepSpacing)); + // Adjust for steps on right side of center + if (i > halfNumSteps) { + stepX -= 1; + } + } + + renderer->drawRect(stepX, baseY, 1, 8, stepColor); + } + + // Update selection (only if index changed - optional optimization) + if (currentDescIndex != this->m_index) { + currentDescIndex = this->m_index; + this->m_selection = this->m_stepDescriptions[currentDescIndex]; + } + + // Draw the parent trackbar + StepTrackBarV2::draw(renderer); + } + + + protected: + std::vector m_stepDescriptions; + + }; + + } + + + // Global state and event system + static inline Event notificationEvent; + static inline std::mutex notificationJsonMutex; + static inline std::atomic notificationGeneration{0}; + + // Max notifications cap (max value of 4 on limited memory, 8 otherwise) + extern int maxNotifications; + + class NotificationPrompt { + public: + NotificationPrompt() + : enabled_(true), + generation_(notificationGeneration.load(std::memory_order_acquire)) + {} + + ~NotificationPrompt() { shutdown(); } + + enum class PromptState : u8 { + Inactive, FadingIn, Visible, FadingOut + }; + + enum class Alignment : u8 { Center = 0, Left = 1, Right = 2 }; + enum class SplitType : u8 { Word = 0, Char = 1 }; + + struct NotifEntry { + std::string text; + std::string title; + char timestamp[10] = {}; + std::string fileName; + u8 fontSize = 28; + u16 durationMs = 3000; + u8 priority = 20; + u64 arrivalNs = 0; + PromptState state = PromptState::Inactive; + u64 expireNs = 0; + u64 stateStartNs = 0; + bool showTime = true; + bool hasIcon = false; + bool iconPending = false; + Alignment alignment = Alignment::Center; + SplitType splitType = SplitType::Word; + }; + + struct NotifCompare { + bool operator()(const NotifEntry& a, const NotifEntry& b) const { + if (a.priority == b.priority) return a.arrivalNs > b.arrivalNs; + return a.priority > b.priority; + } + }; + + struct Lines { + static constexpr u8 MAX_LINES = 10; + std::string buf[MAX_LINES]; + u8 count = 0; + const std::string& operator[](s32 i) const { return buf[i]; } + }; + + static constexpr size_t TITLE_FONT = 18; + static constexpr s32 NOTIF_ICON_DIM = 50; + static constexpr size_t NOTIF_ICON_BYTES = NOTIF_ICON_DIM * NOTIF_ICON_DIM * 2; + static constexpr int MAX_VISIBLE = 8; + static constexpr s32 NOTIF_WIDTH = 448; + static constexpr s32 NOTIF_HEIGHT = 88; + + // ── Public API ─────────────────────────────────────────────────────────── + void show(const std::string& msg, size_t fontSize = 26, u32 priority = 20, + const std::string& fileName = "", const std::string& title = "", + u32 durationMs = 3000, + bool immediately = false, bool resume = false, bool showTime = true, + std::string_view alignment = {}, + std::string_view splitType = {}, + std::string_view timestamp = {}) { + + if (msg.empty()) return; + if (isStale()) return; + + NotifEntry data; + data.text = msg; + data.title = title; + data.fileName = fileName; + data.fontSize = static_cast(std::clamp(fontSize, size_t(8), size_t(48))); + data.durationMs = (durationMs == 0) ? 0 + : static_cast(std::clamp(durationMs, 500u, 30000u)); + data.priority = static_cast(immediately ? 0u : priority); + data.showTime = showTime; + data.alignment = parseAlignment(alignment, !title.empty()); + data.splitType = (!splitType.empty() && splitType[0] == 'c') ? SplitType::Char : SplitType::Word; + data.arrivalNs = ult::nowNs(); + if (!timestamp.empty()) { + const size_t n = std::min(timestamp.size(), sizeof(data.timestamp) - 1); + std::memcpy(data.timestamp, timestamp.data(), n); + data.timestamp[n] = '\0'; + } else { + ult::formatTimestamp(time(nullptr), data.timestamp, sizeof(data.timestamp)); + } + + std::lock_guard lg(state_mutex_); + if (isStale()) return; + + if (immediately) { + bool skipFadeIn = false; + Slot& s0 = slots_[0]; + if (s0.flags & SLOT_ACTIVE) { + if (s0.flags & SLOT_SHOW_NOW) { + evictSlot_NoLock(0); + skipFadeIn = true; + } else { + // Delay bottom-most only if all slots are full + if (slots_[maxNotifications - 1].flags & SLOT_ACTIVE) { + if (pending_queue_.size() < MAX_NOTIFS) + pending_queue_.push(std::move(slots_[maxNotifications - 1].data)); + slots_[maxNotifications - 1] = Slot{}; + } + // Shift all slots down by one to make room at slot 0 + for (int j = maxNotifications - 1; j >= 1; --j) + slots_[j] = std::move(slots_[j - 1]); + slots_[0] = Slot{}; + } + } + placeInSlot_NoLock(0, std::move(data), true, skipFadeIn); + repackSlots_NoLock(ult::nowNs()); + } else { + int freeSlot = -1; + for (int i = 0; i < maxNotifications; ++i) + if (!(slots_[i].flags & SLOT_ACTIVE)) { freeSlot = i; break; } + if (freeSlot >= 0) { + placeInSlot_NoLock(freeSlot, std::move(data), false, resume, resume); + } else { + if (pending_queue_.size() < MAX_NOTIFS) + pending_queue_.push(std::move(data)); + return; + } + } + + eventFire(¬ificationEvent); + #if IS_STATUS_MONITOR_DIRECTIVE + if (isRendering) { + isRendering = false; + wasRendering = true; + leventSignal(&renderingStopEvent); + } + #endif + } + + void showNow(const std::string& msg, size_t fontSize = 26, + const std::string& title = "", + u32 durationMs = 2500, + bool showTime = true, + const std::string& fileName = "", + std::string_view alignment = {}, + std::string_view splitType = {}) { + show(msg, fontSize, 0u, fileName, title, durationMs, true, false, showTime, alignment, splitType); + } + + [[nodiscard]] bool hasActiveFile(std::string_view fname) const; + + void draw(gfx::Renderer* renderer, bool promptOnly = false); + void update(); + [[nodiscard]] bool isActive() const; + [[nodiscard]] int activeCount() const; + void shutdown(); + void forceShutdown() { enabled_.store(false, std::memory_order_release); } + [[nodiscard]] bool hitTest(s32 tx, s32 ty) const; + bool dismissAt(s32 tx, s32 ty); + bool dismissFront(); + + private: + static constexpr size_t MAX_NOTIFS = 30; + static constexpr u32 FADE_DURATION_MS = 83; + static constexpr u32 SLIDE_DURATION_MS = 150; + + static constexpr u8 SLOT_ACTIVE = 1 << 0; + static constexpr u8 SLOT_SHOW_NOW = 1 << 1; + static constexpr u8 SLOT_SLIDING = 1 << 2; + static constexpr u8 SLOT_ICON_LOADED = 1 << 3; + static constexpr u8 SLOT_SOUND_PENDING = 1 << 4; + + struct Slot { + NotifEntry data; + float yCurrent = 0.f; + float yTarget = 0.f; + float ySlideFrom = 0.f; + u64 slideStartNs = 0; + u8 flags = 0; + std::unique_ptr iconBuf; + }; + + Slot slots_[MAX_VISIBLE]; + mutable std::mutex state_mutex_; + std::priority_queue, NotifCompare> pending_queue_; + std::atomic enabled_{true}; + std::atomic generation_{0}; + + bool isStale() const { + return !enabled_.load(std::memory_order_acquire) + || generation_.load(std::memory_order_acquire) + != notificationGeneration.load(std::memory_order_acquire); + } + + // Transition a slot's data into FadingOut state. Caller holds state_mutex_. + static void startFadeOut(NotifEntry& e, u64 now) { + e.state = PromptState::FadingOut; + e.stateStartNs = now; + } + + // Parse alignment string to enum, with a sensible title-aware default. + static Alignment parseAlignment(std::string_view sv, bool hasTitle) { + if (!sv.empty()) { + if (sv[0] == 'l') return Alignment::Left; + if (sv[0] == 'r') return Alignment::Right; + return Alignment::Center; + } + return hasTitle ? Alignment::Left : Alignment::Center; + } + + void evictSlot_NoLock(int i) { + if (!slots_[i].data.fileName.empty()) + remove((ult::NOTIFICATIONS_PATH + slots_[i].data.fileName).c_str()); + slots_[i] = Slot{}; + } + + void clearAll_NoLock() { + for (int i = 0; i < maxNotifications; ++i) slots_[i] = Slot{}; + while (!pending_queue_.empty()) pending_queue_.pop(); + } + + [[nodiscard]] int findHitSlot_NoLock(s32 tx, s32 ty) const; + + // Icon/text-area geometry, computed once and shared between + // getEffectiveHeight and drawSlot. + struct IconGeom { + s32 baseIconPad; + s32 iconColW; + bool hasIconCol; + s32 textAreaX; + s32 textAreaW; + }; + + static IconGeom computeIconGeom(const Slot& slot, s32 x = 0) { + IconGeom g; + g.baseIconPad = (NOTIF_HEIGHT - NOTIF_ICON_DIM) / 2; + g.iconColW = g.baseIconPad + NOTIF_ICON_DIM + g.baseIconPad; + g.hasIconCol = (slot.data.hasIcon && (slot.flags & SLOT_ICON_LOADED)) + || slot.data.iconPending; + g.textAreaW = g.hasIconCol ? NOTIF_WIDTH - g.iconColW : NOTIF_WIDTH; + g.textAreaX = g.hasIconCol ? x + g.iconColW : x; + return g; + } + + // Height contributed by n additional wrapped lines beyond the first: + // n * (lineHeight + 3) + static s32 extraLinesHeight(s32 n, s32 lineHeight) { + return n * (lineHeight + 3); + } + + static constexpr float easeInOut(float t) { + return (t < 0.5f) ? (2*t*t) : (-1 + (4 - 2*t)*t); + } + + static constexpr Color applyAlpha(Color c, float a) { + c.a = static_cast(static_cast(c.a) * a); + return c; + } + + [[gnu::noinline]] + Lines getWrappedLines(const std::string& text, float pixelWidth, + size_t fontSize, u8 maxLines, + SplitType splitType = SplitType::Word) const; + + [[gnu::noinline]] + s32 getEffectiveHeight(const Slot& slot) const; + + [[gnu::noinline]] + void placeInSlot_NoLock(int idx, NotifEntry&& e, bool isShowNow, + bool skipFadeIn, bool suppressSound = false); + + [[gnu::noinline]] + void repackSlots_NoLock(u64 now); + + [[gnu::noinline]] + void applyEllipsis(Lines& lines, u8 maxLines, float pixelWidth, + size_t fontSize, gfx::Renderer* renderer) const; + + [[gnu::noinline]] + void drawSlot(gfx::Renderer* renderer, const Slot& slot, + s32 baseY, float fadeAlpha, bool promptOnly); + + #if IS_LAUNCHER_DIRECTIVE + [[gnu::noinline]] + void drawUltrahandLine(gfx::Renderer* renderer, const std::string& line, + s32 x, s32 y, u32 fontSize, float fadeAlpha, + Color textColor = notificationTextColor); + #endif + }; + + inline NotificationPrompt* notification = nullptr; + + + // GUI + + /** + * @brief The top level Gui class + * @note The main menu and every sub menu are a separate Gui. Create your own Gui class that extends from this one to create your own menus + * + */ + class Gui { + public: + Gui() { + #if !IS_LAUNCHER_DIRECTIVE + { + #if INITIALIZE_IN_GUI_DIRECTIVE // for different project structures + + // Load the bitmap file into memory + ult::loadWallpaperFileWhenSafe(); + #endif + } + #endif + } + + virtual ~Gui() { + if (this->m_topElement != nullptr) + delete this->m_topElement; + + if (this->m_bottomElement != nullptr) + delete this->m_bottomElement; + } + + /** + * @brief Creates all elements present in this Gui + * @note Implement this function and let it return a heap allocated element used as the top level element. This is usually some kind of frame e.g \ref OverlayFrame + * + * @return Top level element + */ + virtual elm::Element* createUI() = 0; + + /** + * @brief Called once per frame to update values + * + */ + virtual void update() {} + + /** + * @brief Called once per frame with the latest HID inputs + * + * @param keysDown Buttons pressed in the last frame + * @param keysHeld Buttons held down longer than one frame + * @param touchInput Last touch position + * @param leftJoyStick Left joystick position + * @param rightJoyStick Right joystick position + * @return Weather or not the input has been consumed + */ + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) { + return false; + } + + /** + * @brief Gets the top level element + * + * @return Top level element + */ + elm::Element* getTopElement() { + return this->m_topElement; + } + + /** + * @brief Gets the bottom level element + * + * @return Bottom level element + */ + elm::Element* getBottomElement() { + return this->m_bottomElement; + } + + /** + * @brief Get the currently focused element + * + * @return Focused element + */ + elm::Element* getFocusedElement() { + return this->m_focusedElement; + } + + /** + * @brief Requests focus to a element + * @note Use this function when focusing a element outside of a element's requestFocus function + * + * @param element Element to focus + * @param direction Focus direction + */ + inline void requestFocus(elm::Element *element, FocusDirection direction, bool shake = true) { + elm::Element *oldFocus = this->m_focusedElement; + + if (element != nullptr) { + this->m_focusedElement = element->requestFocus(oldFocus, direction); + + if (oldFocus != nullptr) + oldFocus->setFocused(false); + + if (this->m_focusedElement != nullptr) { + this->m_focusedElement->setFocused(true); + } + } + + if (shake && oldFocus == this->m_focusedElement && this->m_focusedElement != nullptr) { + if (!tsl::elm::isTableScrolling.load(std::memory_order_acquire)) { + this->m_focusedElement->shakeHighlight(direction); + } + } + } + + /** + * @brief Removes focus from a element + * + * @param element Element to remove focus from. Pass nullptr to remove the focus unconditionally + */ + inline void removeFocus(elm::Element* element = nullptr) { + if (element == nullptr || element == this->m_focusedElement) { + if (this->m_focusedElement != nullptr) { + this->m_focusedElement->setFocused(false); + this->m_focusedElement = nullptr; + } + } + } + + inline void restoreFocus() { + this->m_initialFocusSet = false; + } + + protected: + constexpr static inline auto a = &gfx::Renderer::a; + constexpr static inline auto aWithOpacity = &gfx::Renderer::aWithOpacity; + + private: + elm::Element *m_focusedElement = nullptr; + elm::Element *m_topElement = nullptr; + elm::Element *m_bottomElement = nullptr; + + bool m_initialFocusSet = false; + + friend class Overlay; + friend class gfx::Renderer; + + /** + * @brief Draws the Gui + * + * @param renderer + */ + void draw(gfx::Renderer *renderer) { + if (this->m_topElement != nullptr) + this->m_topElement->draw(renderer); + } + + inline bool initialFocusSet() { + return this->m_initialFocusSet; + } + + inline void markInitialFocusSet() { + this->m_initialFocusSet = true; + } + + }; + + + // Overlay + + /** + * @brief The top level Overlay class + * @note Every Tesla overlay should have exactly one Overlay class initializing services and loading the default Gui + */ + class Overlay { + protected: + /** + * @brief Constructor + * @note Called once when the Overlay gets loaded + */ + Overlay() {} + public: + + /** + * @brief Deconstructor + * @note Called once when the Overlay exits + * + */ + virtual ~Overlay() {} + + + /** + * @brief Initializes services + * @note Called once at the start to initializes services. You have a sm session available during this call, no need to initialize sm yourself + */ + virtual void initServices() {} + + /** + * @brief Exits services + * @note Make sure to exit all services you initialized in \ref Overlay::initServices() here to prevent leaking handles + */ + virtual void exitServices() {} + + /** + * @brief Called before overlay changes from invisible to visible state + * + */ + virtual void onShow() {} + + /** + * @brief Called before overlay changes from visible to invisible state + * + */ + virtual void onHide() {} + + /** + * @brief Loads the default Gui + * @note This function should return the initial Gui to load using the \ref Gui::initially(Args.. args) function + * e.g `return initially();` + * + * @return Default Gui + */ + virtual std::unique_ptr loadInitialGui() = 0; + + /** + * @brief Gets a reference to the current Gui on top of the Gui stack + * + * @return Current Gui reference + */ + std::unique_ptr& getCurrentGui() { + return this->m_guiStack.top(); + } + + /** + * @brief Shows the Gui + * + */ + void show() { + if (ult::useHapticFeedback) { + if (!ult::isHidden.load(std::memory_order_acquire)) { + triggerInitHaptics.store(true, std::memory_order_release); + } + } + + + // reinitialize audio for changes from handheld to docked and vise versa + if (!ult::limitedMemory && ult::useSoundEffects) + reloadIfDockedChangedNow.store(true, std::memory_order_release); + + if (this->m_disableNextAnimation) { + this->m_animationCounter = MAX_ANIMATION_COUNTER; + this->m_disableNextAnimation = false; + } + else { + this->m_fadeInAnimationPlaying = true; + this->m_animationCounter = 0; + } + + this->onShow(); + + ult::isHidden.store(false); + + if (ult::useHapticFeedback) { + triggerRumbleClick.store(true, std::memory_order_release); + } + } + + /** + * @brief Hides the Gui + * + */ + void hide(bool useNoFade = false) { + + + if (useNoFade) { + // Immediately hide overlay + ult::isHidden.store(true); + this->m_shouldHide = true; + return; + } + + + #if IS_STATUS_MONITOR_DIRECTIVE + if (FullMode && !deactivateOriginalFooter) { + + if (this->m_disableNextAnimation) { + this->m_animationCounter = 0; + this->m_disableNextAnimation = false; + } + else { + this->m_fadeOutAnimationPlaying = true; + this->m_animationCounter = MAX_ANIMATION_COUNTER; + } + ult::isHidden.store(true); + this->onHide(); + } + #else + + if (this->m_disableNextAnimation) { + this->m_animationCounter = 0; + this->m_disableNextAnimation = false; + } + else { + this->m_fadeOutAnimationPlaying = true; + this->m_animationCounter = MAX_ANIMATION_COUNTER; + } + ult::isHidden.store(true); + this->onHide(); + #endif + triggerRumbleClick.store(true, std::memory_order_release); + } + + /** + * @brief Returns whether fade animation is playing + * + * @return whether fade animation is playing + */ + bool fadeAnimationPlaying() { + return this->m_fadeInAnimationPlaying || this->m_fadeOutAnimationPlaying; + } + + /** + * @brief Closes the Gui + * @note This makes the Tesla overlay exit and return back to the Tesla-Menu + * + */ + void close(bool forceClose = false) { + if (!forceClose && notification && notification->isActive()) { + this->closeAfter(); + this->hide(true); + return; + } + + this->m_shouldClose = true; + } + + /** + * @brief Closes the Gui + * @note This makes the Tesla overlay exit and return back to the Tesla-Menu + * + */ + void closeAfter() { + this->m_shouldCloseAfter = true; + + } + + /** + * @brief Gets the Overlay instance + * + * @return Overlay instance + */ + static inline Overlay* const get() { + return Overlay::s_overlayInstance; + } + + /** + * @brief Creates the initial Gui of an Overlay and moves the object to the Gui stack + * + * @tparam T + * @tparam Args + * @param args + * @return constexpr std::unique_ptr + */ + template + constexpr inline std::unique_ptr initially(Args&&... args) { + return std::make_unique(args...); + } + + private: + using GuiPtr = std::unique_ptr; + std::stack> m_guiStack; + static inline Overlay *s_overlayInstance = nullptr; + + bool m_fadeInAnimationPlaying = false, m_fadeOutAnimationPlaying = false; + u8 m_animationCounter = 0; + static constexpr int MAX_ANIMATION_COUNTER = 5; // Define the maximum animation counter value + + bool m_shouldHide = false; + bool m_shouldClose = false; + bool m_shouldCloseAfter = false; + + bool m_disableNextAnimation = false; + + bool m_closeOnExit; + + static inline std::atomic isNavigatingBackwards{false}; + bool justNavigated = false; + + /** + * @brief Initializes the Renderer + * + */ + void initScreen() { + gfx::Renderer::get().init(); + } + + /** + * @brief Exits the Renderer + * + */ + void exitScreen() { + gfx::Renderer::get().exit(); + } + + /** + * @brief Weather or not the Gui should get hidden + * + * @return should hide + */ + bool shouldHide() { + return this->m_shouldHide; + } + + /** + * @brief Weather or not hte Gui should get closed + * + * @return should close + */ + bool shouldClose() { + return this->m_shouldClose; + } + + /** + * @brief Weather or not hte Gui should get closed after + * + * @return should close after + */ + bool shouldCloseAfter() { + return this->m_shouldCloseAfter; + } + + + /** + * @brief Quadratic ease-in-out function + * + * @param t Normalized time (0 to 1) + * @return Eased value + */ + float calculateEaseInOut(float t) { + if (t < 0.5) { + return 2 * t * t; + } else { + return -1 + (4 - 2 * t) * t; + } + } + + /** + * @brief Handles fade in and fade out animations of the Overlay + * + */ + void animationLoop() { + + + if (this->m_fadeInAnimationPlaying) { + if (this->m_animationCounter < MAX_ANIMATION_COUNTER) { + this->m_animationCounter++; + } + + if (this->m_animationCounter >= MAX_ANIMATION_COUNTER) { + this->m_fadeInAnimationPlaying = false; + } + } + + if (this->m_fadeOutAnimationPlaying) { + if (this->m_animationCounter > 0) { + this->m_animationCounter--; + } + + if (this->m_animationCounter == 0) { + this->m_fadeOutAnimationPlaying = false; + this->m_shouldHide = true; + } + } + + // Calculate and set the opacity using an easing function + gfx::Renderer::setOpacity(calculateEaseInOut(static_cast(this->m_animationCounter) / MAX_ANIMATION_COUNTER)); + } + + + + /** + * @brief Overlay Main loop + * + */ + void loop(bool promptOnly = false) { + // Early exit check - avoid all work if shutting down + if (ult::launchingOverlay.load(std::memory_order_acquire)) { + return; + } + + // CRITICAL: Initialize to TRUE because stacks are added in init()! + static std::atomic screenshotStacksAdded{true}; + static std::atomic notificationCacheNeedsClearing{false}; + + auto& renderer = gfx::Renderer::get(); + renderer.startFrame(); + + // Handle main UI rendering + if (!promptOnly) { + + // In normal mode, ensure screenshots are enabled + // Only re-add if they were removed AND force-disable is not set + if (!screenshotStacksAdded.load(std::memory_order_acquire) && + !screenshotsAreForceDisabled.load(std::memory_order_acquire)) { + if (!screenshotStacksAdded.exchange(true, std::memory_order_acq_rel)) { + renderer.addScreenshotStacks(false); + } + } + + this->animationLoop(); + this->getCurrentGui()->update(); + this->getCurrentGui()->draw(&renderer); + + } else { + // Prompt-only mode - temporarily remove screenshots + if (screenshotStacksAdded.load(std::memory_order_acquire) && + !screenshotsAreDisabled.load(std::memory_order_acquire) && + !screenshotsAreForceDisabled.load(std::memory_order_acquire)) { + + if (screenshotStacksAdded.exchange(false, std::memory_order_acq_rel)) { + renderer.removeScreenshotStacks(false); + } + } + renderer.clearScreen(); + } + + // Notification handling — safe, consistent, and null-guarded + { + if (notification && notification->isActive()) { + #if IS_STATUS_MONITOR_DIRECTIVE + if (isRendering && !wasRendering) { + isRendering = false; + wasRendering = true; + leventSignal(&renderingStopEvent); + } + #endif + notification->update(); + notification->draw(&renderer, promptOnly); + + // Only set flag if it's not already set + notificationCacheNeedsClearing.exchange(true, std::memory_order_acq_rel); + + } else if (notificationCacheNeedsClearing.exchange(false, std::memory_order_acq_rel)) { + tsl::gfx::FontManager::clearNotificationCache(); + #if IS_STATUS_MONITOR_DIRECTIVE + if (wasRendering) { + pendingExit = false; + wasRendering = false; + isRendering = true; + leventClear(&renderingStopEvent); + } + #endif + } + } + + renderer.endFrame(); + } + + // Calculate transition using ease-in-out curve instead of linear + float easeInOutCubic(float t) { + return t < 0.5f ? 4.0f * t * t * t : 1.0f - pow(-2.0f * t + 2.0f, 3.0f) / 2.0f; + } + + + + void handleInput(u64 keysDown, u64 keysHeld, bool touchDetected, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) { + if (!ult::internalTouchReleased.load(std::memory_order_acquire) || ult::launchingOverlay.load(std::memory_order_acquire)) + return; + + static HidTouchState initialTouchPos = { 0 }; + static HidTouchState oldTouchPos = { 0 }; + static bool oldTouchDetected = false; + static elm::TouchEvent touchEvent, oldTouchEvent; + static u64 buttonPressTime_ns = 0, lastKeyEventTime_ns = 0, keyEventInterval_ns = 67000000ULL; + static bool singlePressHandled = false; + static bool notificationTouchConsumed = false; + static constexpr u64 CLICK_THRESHOLD_NS = 340000000ULL; + static bool hasScrolled = false; + static void* lastGuiPtr = nullptr; + static std::array lastSimulatedTouch = {}; + + auto& currentGui = this->getCurrentGui(); + + if (!currentGui) { + elm::Element::setInputMode(InputMode::Controller); + oldTouchPos = { 0 }; + initialTouchPos = { 0 }; + touchEvent = elm::TouchEvent::None; + ult::stillTouching.store(false, std::memory_order_release); + ult::interruptedTouch.store(false, std::memory_order_release); + return; + } + + auto currentFocus = currentGui->getFocusedElement(); + + // Focus color debounce — snap true immediately, delay false + { + static u64 focusLostTime_ns = 0; + static constexpr u64 UNFOCUS_DELAY_NS = 10'000'000ULL; + if (currentFocus) { + usingUnfocusedColor = true; + focusLostTime_ns = 0; + } else { + if (!bypassUnfocused) { + const u64 now = ult::nowNs(); + if (focusLostTime_ns == 0) focusLostTime_ns = now; + if (now - focusLostTime_ns >= UNFOCUS_DELAY_NS) usingUnfocusedColor = false; + } else { + usingUnfocusedColor = true; + } + } + } + + const bool interpreterIsRunning = ult::runningInterpreter.load(std::memory_order_acquire); + + #if !IS_STATUS_MONITOR_DIRECTIVE + if (interpreterIsRunning) { + const struct { u64 key; FocusDirection dir; } shakes[] = { + {KEY_UP, FocusDirection::Up}, + {KEY_DOWN, FocusDirection::Down}, + {KEY_LEFT, FocusDirection::Left}, + {KEY_RIGHT, FocusDirection::Right}, + }; + for (auto& s : shakes) { + if (keysDown & s.key && !(keysHeld & ~s.key & ALL_KEYS_MASK)) { + currentFocus->shakeHighlight(s.dir); + return; + } + } + } + #endif + + #if IS_STATUS_MONITOR_DIRECTIVE + if (FullMode && !deactivateOriginalFooter) { + if ((keysDown & ALL_KEYS_MASK) && ult::stillTouching && ult::currentForeground.load(std::memory_order_acquire)) { + triggerWallFeedback(); + return; + } + if (ult::simulatedSelect.exchange(false, std::memory_order_acq_rel)) keysDown |= KEY_A; + if (ult::simulatedBack.exchange(false, std::memory_order_acq_rel)) keysDown |= KEY_B; + if (!overrideBackButton) { + if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { + if (!currentGui->handleInput(KEY_B,0,{},{},{})) { + this->goBack(); + if (this->m_guiStack.size() >= 1) triggerExitFeedback(); + } + return; + } + } + } else { + ult::simulatedSelect.exchange(false, std::memory_order_acq_rel); + ult::simulatedBack.exchange(false, std::memory_order_acq_rel); + } + #else + if (ult::simulatedSelect.exchange(false, std::memory_order_acq_rel)) keysDown |= KEY_A; + if (ult::simulatedBack.exchange(false, std::memory_order_acq_rel)) keysDown |= KEY_B; + + if ((keysDown & ALL_KEYS_MASK) && ult::stillTouching && ult::currentForeground.load(std::memory_order_acquire)) { + triggerWallFeedback(); + return; + } + if (!overrideBackButton) { + if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { + if (!currentGui->handleInput(KEY_B,0,{},{},{})) { + this->goBack(); + if (this->m_guiStack.size() >= 1 && !interpreterIsRunning) triggerExitFeedback(); + } + return; + } + } else { + #if IS_LAUNCHER_DIRECTIVE + if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { + if (this->m_guiStack.size() >= 1 && !interpreterIsRunning) triggerExitFeedback(); + } + #endif + } + #endif + + if (currentGui.get() != lastGuiPtr) { + hasScrolled = false; + oldTouchEvent = elm::TouchEvent::None; + oldTouchDetected = false; + oldTouchPos = { 0 }; + initialTouchPos = { 0 }; + lastGuiPtr = currentGui.get(); + } + + auto topElement = currentGui->getTopElement(); + const u64 currentTime_ns = ult::nowNs(); + + if (!currentFocus && !ult::simulatedBack.load(std::memory_order_acquire) && + !ult::stillTouching.load(std::memory_order_acquire) && !oldTouchDetected && !interpreterIsRunning) { + if (!topElement) return; + if (!currentGui->initialFocusSet() && !(keysDown & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT))) { + currentGui->requestFocus(topElement, FocusDirection::None); + currentGui->markInitialFocusSet(); + } + } + + if (isNavigatingBackwards.load(std::memory_order_acquire) && !currentFocus && topElement && + keysDown & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) { + currentGui->requestFocus(topElement, FocusDirection::None); + currentGui->markInitialFocusSet(); + isNavigatingBackwards.store(false, std::memory_order_release); + buttonPressTime_ns = lastKeyEventTime_ns = currentTime_ns; + singlePressHandled = false; + } + + if (!currentFocus && !touchDetected && (!oldTouchDetected || oldTouchEvent == elm::TouchEvent::Scroll)) { + if (!isNavigatingBackwards.load(std::memory_order_acquire) && + !ult::shortTouchAndRelease.load(std::memory_order_acquire) && + !ult::longTouchAndRelease.load(std::memory_order_acquire) && + !ult::simulatedSelect.load(std::memory_order_acquire) && + !ult::simulatedBack.load(std::memory_order_acquire) && + !ult::simulatedNextPage.load(std::memory_order_acquire) && topElement) { + if (oldTouchEvent == elm::TouchEvent::Scroll) hasScrolled = true; + if (!hasScrolled) { + currentGui->removeFocus(); + currentGui->requestFocus(topElement, FocusDirection::None); + } + } else if (ult::longTouchAndRelease.exchange(false, std::memory_order_acq_rel) || + ult::shortTouchAndRelease.exchange(false, std::memory_order_acq_rel)) { + hasScrolled = true; + } + } + + bool handled = false; + for (elm::Element* p = currentFocus; !handled && p; p = p->getParent()) + handled = p->onClick(keysDown) || p->handleInput(keysDown, keysHeld, touchPos, joyStickPosLeft, joyStickPosRight); + + if (currentGui != this->getCurrentGui()) return; + handled |= currentGui->handleInput(keysDown, keysHeld, touchPos, joyStickPosLeft, joyStickPosRight); + + // Directional key release tracking + { + static bool lastDirectionPressed = true; + const bool directionPressed = (keysHeld & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) != 0; + if (!directionPressed && lastDirectionPressed) + tsl::elm::s_directionalKeyReleased.store(true, std::memory_order_release); + else if (directionPressed && lastDirectionPressed) + tsl::elm::s_directionalKeyReleased.store(false, std::memory_order_release); + lastDirectionPressed = directionPressed; + } + + const float currentScrollVelocity = tsl::elm::s_currentScrollVelocity.load(std::memory_order_acquire); + const u64 velMask = currentScrollVelocity != 0.0f ? (KEY_A | KEY_UP) : KEY_UP; + const bool singleArrowKeyPress = + ((keysHeld & KEY_UP) != 0) + ((keysHeld & KEY_DOWN) != 0) + + ((keysHeld & KEY_LEFT) != 0) + ((keysHeld & KEY_RIGHT) != 0) == 1 && + !(keysHeld & ~(velMask | KEY_DOWN | KEY_LEFT | KEY_RIGHT) & ALL_KEYS_MASK); + + if (hasScrolled) { + if (singleArrowKeyPress) { + buttonPressTime_ns = lastKeyEventTime_ns = currentTime_ns; + hasScrolled = false; + isNavigatingBackwards.store(false, std::memory_order_release); + } + } else { + if (!touchDetected && !oldTouchDetected && !handled && currentFocus && + !ult::stillTouching.load(std::memory_order_acquire) && !interpreterIsRunning) { + static bool shouldShake = true; + if (singleArrowKeyPress) { + if (keysDown) { + buttonPressTime_ns = lastKeyEventTime_ns = currentTime_ns; + singlePressHandled = false; + if (keysHeld & KEY_UP && !(keysHeld & ~KEY_UP & ALL_KEYS_MASK)) currentGui->requestFocus(topElement, FocusDirection::Up, shouldShake); + else if (keysHeld & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ALL_KEYS_MASK)) currentGui->requestFocus(currentFocus ? currentFocus->getParent() : topElement, FocusDirection::Down, shouldShake); + else if (keysHeld & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) currentGui->requestFocus(currentFocus ? currentFocus->getParent() : topElement, FocusDirection::Left, shouldShake); + else if (keysHeld & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) currentGui->requestFocus(currentFocus ? currentFocus->getParent() : topElement, FocusDirection::Right, shouldShake); + } + if (keysHeld & ~KEY_DOWN & ~KEY_UP & ~KEY_LEFT & ~KEY_RIGHT & ALL_KEYS_MASK) + buttonPressTime_ns = currentTime_ns; + + const u64 durationSincePress_ns = currentTime_ns - buttonPressTime_ns; + if (!singlePressHandled && durationSincePress_ns >= CLICK_THRESHOLD_NS) + singlePressHandled = true; + + // Compute repeat interval with acceleration + { + const bool tableScroll = tsl::elm::isTableScrolling.load(std::memory_order_acquire); + const u64 tp = tableScroll ? 200000000ULL : 2000000000ULL; + const u64 ini = tableScroll ? 33000000ULL : 67000000ULL; + const u64 sht = tableScroll ? 5000000ULL : 10000000ULL; + const float t = durationSincePress_ns >= tp ? 1.0f : (float)durationSincePress_ns / (float)tp; + keyEventInterval_ns = (u64)((1.0f - t) * ini + t * sht); + } + + if (singlePressHandled && (currentTime_ns - lastKeyEventTime_ns) >= keyEventInterval_ns) { + lastKeyEventTime_ns = currentTime_ns; + const u64 upMask = currentScrollVelocity != 0.0f ? (KEY_A | KEY_UP) : KEY_UP; + const u64 downMask = currentScrollVelocity != 0.0f ? (KEY_A | KEY_DOWN) : KEY_DOWN; + if (keysHeld & KEY_UP && !(keysHeld & ~upMask & ALL_KEYS_MASK)) currentGui->requestFocus(topElement, FocusDirection::Up, false); + else if (keysHeld & KEY_DOWN && !(keysHeld & ~downMask & ALL_KEYS_MASK)) currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Down, false); + else if (keysHeld & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Left, false); + else if (keysHeld & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Right, false); + } + #if !IS_STATUS_MONITOR_DIRECTIVE + } else { + buttonPressTime_ns = lastKeyEventTime_ns = currentTime_ns; + #endif + } + } + } + + #if !IS_STATUS_MONITOR_DIRECTIVE + if (!touchDetected && !interpreterIsRunning && topElement) { + #else + if (!disableJumpTo && !touchDetected && !interpreterIsRunning && topElement) { + #endif + static constexpr u64 INITIAL_HOLD_THRESHOLD_NS = 400000000ULL; + static constexpr u64 HOLD_THRESHOLD_NS = 300000000ULL; + static constexpr u64 RAPID_CLICK_WINDOW_NS = 500000000ULL; + static constexpr u64 RAPID_MODE_TIMEOUT_NS = 1000000000ULL; + static constexpr u64 ACCELERATION_POINT_NS = 1500000000ULL; + static constexpr u64 INITIAL_INTERVAL_NS = 67000000ULL; + static constexpr u64 FAST_INTERVAL_NS = 10000000ULL; + + const bool lKeyPressed = (keysHeld & KEY_L); + const bool rKeyPressed = (keysHeld & KEY_R); + const bool zlKeyPressed = (keysHeld & KEY_ZL); + const bool zrKeyPressed = (keysHeld & KEY_ZR); + const bool notlKeyPressed = (keysHeld & ~KEY_L & ALL_KEYS_MASK); + const bool notrKeyPressed = (keysHeld & ~KEY_R & ALL_KEYS_MASK); + const bool notzlKeyPressed = (keysHeld & ~KEY_ZL & ALL_KEYS_MASK); + const bool notzrKeyPressed = (keysHeld & ~KEY_ZR & ALL_KEYS_MASK); + + struct JumpButtonState { bool keyWasPressed = false, wasIsolated = false; u64 pressStart_ns = 0; }; + static JumpButtonState lState, rState; + + auto handleJumpButton = [&](JumpButtonState& s, bool keyPressed, bool notKeyPressed, std::atomic& jumpSignal) { + if (keyPressed) { + if (!s.keyWasPressed) { s.pressStart_ns = currentTime_ns; s.wasIsolated = !notKeyPressed; } + if (notKeyPressed) s.wasIsolated = false; // another key pressed during hold — cancel + s.keyWasPressed = true; + } else { + if (s.keyWasPressed && s.wasIsolated && !notKeyPressed && + currentTime_ns - s.pressStart_ns < INITIAL_HOLD_THRESHOLD_NS) { + jumpSignal.store(true, std::memory_order_release); + currentGui->requestFocus(topElement, FocusDirection::None); + } + s.keyWasPressed = s.wasIsolated = false; + } + }; + handleJumpButton(lState, lKeyPressed, notlKeyPressed, jumpToTop); + handleJumpButton(rState, rKeyPressed, notrKeyPressed, jumpToBottom); + + struct SkipButtonState { + u64 lastClickTime_ns = 0, firstClickPressStart_ns = 0, buttonPressStart_ns = 0, lastHoldTrigger_ns = 0; + bool keyWasPressed = false, wasIsolated = false, inRapidClickMode = false, holdTriggered = false; + }; + static SkipButtonState zlState, zrState; + + auto handleSkipButton = [&](SkipButtonState& s, bool keyPressed, bool notKeyPressed, std::atomic& skipSignal) { + if (s.inRapidClickMode && (currentTime_ns - s.lastClickTime_ns) > RAPID_MODE_TIMEOUT_NS) + s.inRapidClickMode = false; + if (keyPressed) { + if (!s.keyWasPressed) { + s.wasIsolated = !notKeyPressed; + if (!s.inRapidClickMode) s.firstClickPressStart_ns = currentTime_ns; + if (currentTime_ns - s.lastClickTime_ns <= RAPID_CLICK_WINDOW_NS) s.inRapidClickMode = true; + if (s.inRapidClickMode && s.wasIsolated) { + skipSignal.store(true, std::memory_order_release); + currentGui->requestFocus(topElement, FocusDirection::None); + s.lastClickTime_ns = currentTime_ns; + } + s.buttonPressStart_ns = s.lastHoldTrigger_ns = currentTime_ns; + s.holdTriggered = false; + } + if (notKeyPressed) s.wasIsolated = false; // another key pressed during hold — cancel + if (s.inRapidClickMode && s.wasIsolated) { + const u64 holdDuration = currentTime_ns - s.buttonPressStart_ns; + if (holdDuration >= HOLD_THRESHOLD_NS) { + const float t = holdDuration >= ACCELERATION_POINT_NS ? 1.0f : (float)holdDuration / ACCELERATION_POINT_NS; + const u64 interval = (u64)((1.0f - t) * INITIAL_INTERVAL_NS + t * FAST_INTERVAL_NS); + if (!s.holdTriggered || (currentTime_ns - s.lastHoldTrigger_ns) >= interval) { + skipSignal.store(true, std::memory_order_release); + currentGui->requestFocus(topElement, FocusDirection::None); + s.holdTriggered = true; + s.lastHoldTrigger_ns = s.lastClickTime_ns = currentTime_ns; + } + } + } + s.keyWasPressed = true; + } else { + if (s.keyWasPressed && !s.inRapidClickMode && s.wasIsolated && !notKeyPressed && + currentTime_ns - s.firstClickPressStart_ns < INITIAL_HOLD_THRESHOLD_NS) { + skipSignal.store(true, std::memory_order_release); + currentGui->requestFocus(topElement, FocusDirection::None); + s.lastClickTime_ns = currentTime_ns; + s.inRapidClickMode = true; + } + s.keyWasPressed = s.wasIsolated = false; + } + }; + handleSkipButton(zlState, zlKeyPressed, notzlKeyPressed, skipUp); + handleSkipButton(zrState, zrKeyPressed, notzrKeyPressed, skipDown); + } + + // Notification touch consume + if (!oldTouchDetected && touchDetected) { + if (notification && notification->hitTest(static_cast(touchPos.x), static_cast(touchPos.y))) { + notification->dismissAt(static_cast(touchPos.x), static_cast(touchPos.y)); + notificationTouchConsumed = true; + } + } + if (!touchDetected && oldTouchDetected) notificationTouchConsumed = false; + if (notificationTouchConsumed) { + oldTouchDetected = touchDetected; + oldTouchPos = touchPos; + return; + } + + if (!touchDetected && oldTouchDetected && currentGui && topElement) + topElement->onTouch(elm::TouchEvent::Release, oldTouchPos.x, oldTouchPos.y, oldTouchPos.x, oldTouchPos.y, initialTouchPos.x, initialTouchPos.y); + + // Footer touch regions + const float edgePadding = ult::halfGap.load(std::memory_order_acquire) - 5; + const float backLeftEdge = edgePadding + ult::layerEdge; + const float backRightEdge = backLeftEdge + ult::backWidth.load(std::memory_order_acquire); + const float selectLeftEdge = backRightEdge; + const float selectRightEdge = selectLeftEdge + ult::selectWidth.load(std::memory_order_acquire); + const bool noClickable = ult::noClickableItems.load(std::memory_order_acquire); + const float nextPageLeftEdge = noClickable ? backRightEdge : selectRightEdge; + const float nextPageRightEdge = nextPageLeftEdge + ult::nextPageWidth.load(std::memory_order_acquire); + const float menuRightEdge = 245.0f + ult::layerEdge - 13; + const u32 footerY = cfg::FramebufferHeight - 73U + 1; + + const bool backTouched = (touchPos.x >= backLeftEdge && touchPos.x < backRightEdge && touchPos.y > footerY) && + (initialTouchPos.x >= backLeftEdge && initialTouchPos.x < backRightEdge && initialTouchPos.y > footerY); + const bool selectTouched = !noClickable && + (touchPos.x >= selectLeftEdge && touchPos.x < selectRightEdge && touchPos.y > footerY) && + (initialTouchPos.x >= selectLeftEdge && initialTouchPos.x < selectRightEdge && initialTouchPos.y > footerY); + const bool nextPageTouched = ult::hasNextPageButton.load(std::memory_order_acquire) && + (touchPos.x >= nextPageLeftEdge && touchPos.x < nextPageRightEdge && touchPos.y > footerY) && + (initialTouchPos.x >= nextPageLeftEdge && initialTouchPos.x < nextPageRightEdge && initialTouchPos.y > footerY); + const bool menuTouched = (touchPos.x > ult::layerEdge+7U && touchPos.x <= menuRightEdge && touchPos.y > 10U && touchPos.y <= 83U) && + (initialTouchPos.x > ult::layerEdge+7U && initialTouchPos.x <= menuRightEdge && initialTouchPos.y > 10U && initialTouchPos.y <= 83U); + + bool shouldTriggerRumble = false; + auto checkTouched = [&](bool touched, std::atomic& state) { + if (touched != state.exchange(touched, std::memory_order_acq_rel) && touched) + shouldTriggerRumble = true; + }; + checkTouched(backTouched, ult::touchingBack); + if (usingUnfocusedColor) checkTouched(selectTouched, ult::touchingSelect); + checkTouched(nextPageTouched, ult::touchingNextPage); + if (menuTouched != ult::touchingMenu.exchange(menuTouched, std::memory_order_acq_rel)) { + if (menuTouched && (ult::inMainMenu.load(std::memory_order_acquire) || + (ult::inHiddenMode.load(std::memory_order_acquire) && + !ult::inSettingsMenu.load(std::memory_order_acquire) && + !ult::inSubSettingsMenu.load(std::memory_order_acquire)))) + shouldTriggerRumble = true; + } + if (shouldTriggerRumble) triggerNavigationFeedback(); + + if (touchDetected) { + lastSimulatedTouch = {backTouched, selectTouched, nextPageTouched, menuTouched}; + //const bool touchInFooter = (touchPos.y > static_cast(cfg::FramebufferHeight - 73U + 1)); + ult::interruptedTouch.store(!(touchPos.y > static_cast(cfg::FramebufferHeight - 73U + 1)) && (keysHeld & ALL_KEYS_MASK) != 0, std::memory_order_release); + + const u32 xd = std::abs(static_cast(initialTouchPos.x) - static_cast(touchPos.x)); + const u32 yd = std::abs(static_cast(initialTouchPos.y) - static_cast(touchPos.y)); + if (xd*xd + yd*yd > 1000) { + elm::Element::setInputMode(InputMode::TouchScroll); + touchEvent = elm::TouchEvent::Scroll; + } else if (touchEvent != elm::TouchEvent::Scroll) { + touchEvent = elm::TouchEvent::Hold; + } + + if (!oldTouchDetected) { + initialTouchPos = touchPos; + elm::Element::setInputMode(InputMode::Touch); + if (!interpreterIsRunning) { + ult::touchInBounds = (initialTouchPos.y <= footerY && initialTouchPos.y > 73U && + initialTouchPos.x <= ult::layerEdge + cfg::FramebufferWidth - 30U && + initialTouchPos.x > 40U + ult::layerEdge); + if (ult::touchInBounds) currentGui->removeFocus(); + } + touchEvent = elm::TouchEvent::Touch; + } + + if (currentGui && topElement && !interpreterIsRunning) { + if (touchPos.x > 40U + ult::layerEdge && touchPos.x <= cfg::FramebufferWidth - 30U + ult::layerEdge && + touchPos.y > 73U && touchPos.y <= footerY) + currentGui->removeFocus(); + topElement->onTouch(touchEvent, touchPos.x, touchPos.y, oldTouchPos.x, oldTouchPos.y, initialTouchPos.x, initialTouchPos.y); + } + + oldTouchPos = touchPos; + if ((touchPos.x < ult::layerEdge || touchPos.x > cfg::FramebufferWidth + ult::layerEdge) && + tsl::elm::Element::getInputMode() == tsl::InputMode::Touch) { + oldTouchPos = { 0 }; + initialTouchPos = { 0 }; + #if IS_STATUS_MONITOR_DIRECTIVE + if (FullMode && !deactivateOriginalFooter) this->hide(); + #else + if (!disableHiding) this->hide(); + #endif + } + ult::stillTouching.store(true, std::memory_order_release); + } else { + for (int i = 0; i < 4; ++i) { + if (!lastSimulatedTouch[i]) continue; + if (!ult::interruptedTouch.load(std::memory_order_acquire) && !interpreterIsRunning) { + switch (i) { + case 0: ult::simulatedBack.store(true, std::memory_order_release); break; + case 1: ult::simulatedSelect.store(true, std::memory_order_release); break; + case 2: ult::simulatedNextPage.store(true, std::memory_order_release); break; + case 3: ult::simulatedMenu.store(true, std::memory_order_release); break; + } + } else if (interpreterIsRunning) { + switch (i) { + case 0: this->hide(); break; + case 1: ult::externalAbortCommands.store(true, std::memory_order_release); break; + } + } + } + lastSimulatedTouch.fill(false); + elm::Element::setInputMode(InputMode::Controller); + oldTouchPos = { 0 }; + initialTouchPos = { 0 }; + touchEvent = elm::TouchEvent::None; + ult::stillTouching.store(false, std::memory_order_release); + ult::interruptedTouch.store(false, std::memory_order_release); + } + + oldTouchDetected = touchDetected; + oldTouchEvent = touchEvent; + } + + + /** + * @brief Clears the screen + * + */ + void clearScreen() { + auto& renderer = gfx::Renderer::get(); + + renderer.startFrame(); + renderer.clearScreen(); + renderer.endFrame(); + } + + /** + * @brief Reset hide and close flags that were previously set by \ref Overlay::close() or \ref Overlay::hide() + * + */ + void resetFlags() { + this->m_shouldHide = false; + this->m_shouldClose = false; + this->m_shouldCloseAfter = false; + } + + /** + * @brief Disables the next animation that would play + * + */ + void disableNextAnimation() { + this->m_disableNextAnimation = true; + } + + + /** + * @brief Changes to a different Gui + * + * @param gui Gui to change to + * @return Reference to the Gui + */ + std::unique_ptr& changeTo(std::unique_ptr&& gui, bool clearGlyphCache = false) { + if (this->m_guiStack.top() != nullptr && this->m_guiStack.top()->m_focusedElement != nullptr) + this->m_guiStack.top()->m_focusedElement->resetClickAnimation(); + + isNavigatingBackwards.store(false, std::memory_order_release); + + // cache frame for forward rendering using external list method (to be implemented) + + // Create the top element of the new Gui + gui->m_topElement = gui->createUI(); + + + // Push the new Gui onto the stack + this->m_guiStack.push(std::move(gui)); + + return this->m_guiStack.top(); + } + + + /** + * @brief Creates a new Gui and changes to it + * + * @tparam G Gui to create + * @tparam Args Arguments to pass to the Gui + * @param args Arguments to pass to the Gui + * @return Reference to the newly created Gui + */ + // Template version without clearGlyphCache (for backward compatibility) + template + std::unique_ptr& changeTo(Args&&... args) { + return this->changeTo(std::make_unique(std::forward(args)...), false); + } + + + /** + * @brief Swaps to a different Gui + * + * @param gui Gui to change to + * @return Reference to the Gui + */ + std::unique_ptr& swapTo(std::unique_ptr&& gui, u32 count = 1) { + + isNavigatingBackwards.store(true, std::memory_order_release); + + // Clamp count to available stack size to prevent underflow + const u32 actualCount = std::min(count, static_cast(this->m_guiStack.size())); + + if (actualCount > 1) { + // Pop the specified number of GUIs + for (u32 i = 0; i < actualCount; ++i) { + this->m_guiStack.pop(); + } + } else { + this->m_guiStack.pop(); + } + + + + if (this->m_guiStack.top() != nullptr && this->m_guiStack.top()->m_focusedElement != nullptr) + this->m_guiStack.top()->m_focusedElement->resetClickAnimation(); + + isNavigatingBackwards.store(false, std::memory_order_release); + + // Create the top element of the new Gui + gui->m_topElement = gui->createUI(); + + + // Push the new Gui onto the stack + this->m_guiStack.push(std::move(gui)); + + return this->m_guiStack.top(); + } + + /** + * @brief Creates a new Gui and changes to it + * + * @tparam G Gui to create + * @tparam Args Arguments to pass to the Gui + * @param args Arguments to pass to the Gui + * @return Reference to the newly created Gui + */ + // Template version without clearGlyphCache (for backward compatibility) + template + std::unique_ptr& swapTo(SwapDepth depth, Args&&... args) { + return this->swapTo(std::make_unique(std::forward(args)...), depth.value); + } + + template + std::unique_ptr& swapTo(Args&&... args) { + return this->swapTo(std::make_unique(std::forward(args)...), 1); + } + + /** + * @brief Pops the top Gui(s) from the stack and goes back count number of times + * @param count Number of Guis to pop from the stack (default: 1) + * @note The Overlay gets closed once there are no more Guis on the stack + */ + void goBack(u32 count = 1) { + if (ult::stillTouching && ult::currentForeground.load(std::memory_order_acquire)) { + triggerWallFeedback(); + return; + } + + // If there is exactly one GUI and an active notification, handle that first + if (this->m_guiStack.size() == 1 && notification && notification->isActive()) { + this->close(); + return; + } + + isNavigatingBackwards.store(true, std::memory_order_release); + + // Clamp count to available stack size to prevent underflow + const u32 actualCount = std::min(count, static_cast(this->m_guiStack.size())); + + // Special case: if we don't close on exit and popping everything would leave us with 0 or 1 GUI + if (!this->m_closeOnExit && this->m_guiStack.size() <= actualCount) { + this->hide(); + return; + } + + // Pop the specified number of GUIs + for (u32 i = 0; i < actualCount && !this->m_guiStack.empty(); ++i) { + this->m_guiStack.pop(); + } + + // Close overlay if stack is empty + if (this->m_guiStack.empty()) { + this->close(); + } + + } + + void pop(u32 count = 1) { + + if (ult::stillTouching && ult::currentForeground.load(std::memory_order_acquire)) { + triggerWallFeedback(); + return; + } + + isNavigatingBackwards.store(true, std::memory_order_release); + + // Clamp count to available stack size to prevent underflow + const u32 actualCount = std::min(count, static_cast(this->m_guiStack.size())); + + if (actualCount > 1) { + // Pop the specified number of GUIs + for (u32 i = 0; i < actualCount; ++i) { + this->m_guiStack.pop(); + } + } else { + this->m_guiStack.pop(); + } + } + + + + template + friend std::unique_ptr& changeTo(Args&&... args); + template + friend std::unique_ptr& swapTo(Args&&... args); + + template + friend std::unique_ptr& swapTo(SwapDepth depth, Args&&... args); + + friend void goBack(u32 count); + friend void pop(u32 count); + + template + friend int loop(int argc, char** argv); + + friend class tsl::Gui; + }; + + + namespace impl { + static constexpr const char* TESLA_CONFIG_FILE = "/config/tesla/config.ini"; + static constexpr const char* ULTRAHAND_CONFIG_FILE = "/config/ultrahand/config.ini"; + + /** + * @brief Data shared between the different ult::renderThreads + * + */ + struct SharedThreadData { + std::atomic running = false; + + Event comboEvent = { 0 }; + + std::atomic overlayOpen = false; + + std::mutex dataMutex; + u64 keysDown = 0; + u64 keysDownPending = 0; + u64 keysHeld = 0; + HidTouchScreenState touchState = { 0 }; + HidAnalogStickState joyStickPosLeft = { 0 }, joyStickPosRight = { 0 }; + }; + + + /** + * @brief Extract values from Tesla settings file + * + */ + void parseOverlaySettings(); + + /** + * @brief Update and save launch combo keys + * + * @param keys the new combo keys + */ + static void updateCombo(u64 keys) { + tsl::cfg::launchCombo = keys; + const std::string comboStr = tsl::hlp::keysToComboString(keys); + ult::setIniFileValue(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, ult::KEY_COMBO_STR, comboStr); + ult::setIniFileValue(ult::TESLA_CONFIG_INI_PATH, ult::TESLA_STR, ult::KEY_COMBO_STR, comboStr); + } + + static auto currentUnderscanPixels = std::make_pair(0, 0); + + /** + * @brief Background event polling loop thread + * + * @param args Used to pass in a pointer to a \ref SharedThreadData struct + */ + static void backgroundEventPoller(void *args) { + requiresLNY2 = amsVersionAtLeast(1,10,0); // Detect if using HOS 21+ + + // Initialize the audio service + if (ult::useSoundEffects && !ult::limitedMemory) { + ult::Audio::initialize(); + } + + tsl::hlp::loadEntryKeyCombos(); + ult::launchingOverlay.store(false, std::memory_order_release); + + SharedThreadData *shData = static_cast(args); + + const auto fireLaunch = [&]() __attribute__((noinline)) { + ult::launchingOverlay.store(true, std::memory_order_release); + tsl::Overlay::get()->close(); + eventFire(&shData->comboEvent); + launchComboHasTriggered.store(true, std::memory_order_release); + }; + + // To prevent focus glitchout, close the overlay immediately when the home button gets pressed + Event homeButtonPressEvent = {}; + hidsysAcquireHomeButtonEventHandle(&homeButtonPressEvent, false); + eventClear(&homeButtonPressEvent); + tsl::hlp::ScopeGuard homeButtonEventGuard([&] { eventClose(&homeButtonPressEvent); }); + + // To prevent focus glitchout, close the overlay immediately when the power button gets pressed + Event powerButtonPressEvent = {}; + hidsysAcquireSleepButtonEventHandle(&powerButtonPressEvent, false); + eventClear(&powerButtonPressEvent); + tsl::hlp::ScopeGuard powerButtonEventGuard([&] { eventClose(&powerButtonPressEvent); }); + + + // For handling screenshots color alpha + Event captureButtonPressEvent = {}; + for (int i = 0; i < 2; i++) { + hidsysAcquireCaptureButtonEventHandle(&captureButtonPressEvent, false); + eventClear(&captureButtonPressEvent); + } + tsl::hlp::ScopeGuard captureButtonEventGuard([&] { eventClose(&captureButtonPressEvent); }); + + + // Allow only Player 1 and handheld mode + HidNpadIdType id_list[2] = { HidNpadIdType_No1, HidNpadIdType_Handheld }; + + // Configure HID system to only listen to these IDs + hidSetSupportedNpadIdType(id_list, 2); + + // Configure input for up to 2 supported controllers (P1 + Handheld) + padConfigureInput(2, HidNpadStyleSet_NpadStandard | HidNpadStyleTag_NpadSystemExt); + + // Initialize separate pad states for both controllers + auto pad_p1_ptr = std::make_unique(); + auto pad_handheld_ptr = std::make_unique(); + PadState& pad_p1 = *pad_p1_ptr; + PadState& pad_handheld = *pad_handheld_ptr; + padInitialize(&pad_p1, HidNpadIdType_No1); + padInitialize(&pad_handheld, HidNpadIdType_Handheld); + + // Touch screen init + hidInitializeTouchScreen(); + + // Clear any stale input from both controllers + padUpdate(&pad_p1); + padUpdate(&pad_handheld); + + //ult::initHaptics(); // initialize rumble + + enum WaiterObject { + WaiterObject_HomeButton, + WaiterObject_PowerButton, + WaiterObject_CaptureButton, + WaiterObject_Count + }; + + // Construct waiter + Waiter objects[3] = { + [WaiterObject_HomeButton] = waiterForEvent(&homeButtonPressEvent), + [WaiterObject_PowerButton] = waiterForEvent(&powerButtonPressEvent), + [WaiterObject_CaptureButton] = waiterForEvent(&captureButtonPressEvent), + }; + + u64 currentTouchTick = 0; + auto lastTouchX = 0; + auto lastTouchY = 0; + + // Preset touch boundaries + constexpr int SWIPE_RIGHT_BOUND = 16; // 16 + 80 + constexpr int SWIPE_LEFT_BOUND = (1280 - 16); + constexpr u64 TOUCH_THRESHOLD_NS = 150'000'000ULL; // 150ms in nanoseconds + constexpr u64 FAST_SWAP_THRESHOLD_NS = 150'000'000ULL; + + // Global underscan monitoring - run at most once every 300ms + auto lastUnderscanPixels = std::make_pair(0, 0); + bool firstUnderscanCheck = true; + u64 lastUnderscanCheckNs = 0; // store last execution in nanoseconds + constexpr u64 UNDERSCAN_INTERVAL_NS = 300'000'000ULL; // 300ms in ns + + s32 idx; + Result rc; + + std::string currentTitleID; + + u64 lastPollTick = 0; + u64 resetStartTick = armGetSystemTick(); + const u64 startNs = armTicksToNs(resetStartTick); + + ult::lastTitleID = ult::getTitleIdAsString(); + + // Notification variables + u64 lastNotifCheck = 0; + u64 minusHoldStartTick = 0; + bool minusHoldArmed = false; + + while (shData->running.load(std::memory_order_acquire)) { + + u64 nowTick = armGetSystemTick(); + u64 nowNs = armTicksToNs(nowTick); + + // Scan for input changes from both controllers + padUpdate(&pad_p1); + padUpdate(&pad_handheld); + + // Read in HID values + { + + // Poll Title ID every 1 seconds + if (!ult::resetForegroundCheck.load(std::memory_order_acquire)) { + const u64 elapsedNs = armTicksToNs(nowTick - lastPollTick); + if (elapsedNs >= 1'000'000'000ULL) { + lastPollTick = nowTick; + + currentTitleID = ult::getTitleIdAsString(); + if (currentTitleID != ult::lastTitleID) { + ult::lastTitleID = currentTitleID; + if (currentTitleID != ult::NULL_STR) { + ult::resetForegroundCheck.store(true, std::memory_order_release); + resetStartTick = nowTick; + } + } + } + } + + // If a reset is scheduled, trigger after 3.5s delay + if (ult::resetForegroundCheck.load(std::memory_order_acquire)) { + const u64 resetElapsedNs = armTicksToNs(nowTick - resetStartTick); + if (resetElapsedNs >= 3'500'000'000ULL) { + if (shData->overlayOpen && ult::currentForeground.load(std::memory_order_acquire)) { + #if IS_STATUS_MONITOR_DIRECTIVE + if (!isValidOverlayMode()) + hlp::requestForeground(true, false); + #else + hlp::requestForeground(true, false); + #endif + } + ult::resetForegroundCheck.store(false, std::memory_order_release); + } + } + + if (firstUnderscanCheck || (nowNs - lastUnderscanCheckNs) >= UNDERSCAN_INTERVAL_NS) { + currentUnderscanPixels = tsl::gfx::getUnderscanPixels(); + + if (firstUnderscanCheck || currentUnderscanPixels != lastUnderscanPixels) { + // Update layer dimensions without destroying state + tsl::gfx::Renderer::get().updateLayerSize(); + + lastUnderscanPixels = currentUnderscanPixels; + firstUnderscanCheck = false; + } + + lastUnderscanCheckNs = nowNs; + } + + // Process notification files every 300ms + { + std::lock_guard jsonLock(notificationJsonMutex); + + if (armTicksToNs(nowTick - lastNotifCheck) >= 300'000'000ULL) { + lastNotifCheck = nowTick; + + DIR* dir = opendir(ult::NOTIFICATIONS_PATH.c_str()); + if (dir) { + + if (ult::useNotifications) { + static u32 seenGeneration = UINT32_MAX; + const u32 curGen = notificationGeneration.load(std::memory_order_acquire); + const bool firstPoll = (seenGeneration != curGen); + if (firstPoll) seenGeneration = curGen; + const std::string& notifPath = ult::NOTIFICATIONS_PATH; + + if (!firstPoll && notification && notification->activeCount() >= maxNotifications) { + closedir(dir); + } else { + + // ── Single-pass: stat + JSON read + top-N insertion ───────────── + // No candidates vector — filenames never heap-copied unless they + // beat the current worst slot. Safe on small heap threads. + struct NotifData { + std::string fname, text, title; + struct timespec mtime; + int priority, fontSize; + int duration = 0; + bool showTime; + std::string alignment; + bool splitChar = false; + char timestamp[10] = {}; + }; + static NotifData topSlots[NotificationPrompt::MAX_VISIBLE]; + static int topCount = 0; + topCount = 0; + + const int activeNow = notification ? notification->activeCount() : 0; + const int slotsWanted = firstPoll + ? (maxNotifications - activeNow) + : 1; + + auto isBetter = [](const NotifData& a, const NotifData& b) noexcept { + if (a.priority != b.priority) return a.priority > b.priority; + if (a.mtime.tv_sec != b.mtime.tv_sec) return a.mtime.tv_sec < b.mtime.tv_sec; + return a.mtime.tv_nsec < b.mtime.tv_nsec; + }; + + static std::string fullPath; + struct dirent* entry; + + while ((entry = readdir(dir)) != nullptr) { + if (entry->d_type != DT_REG) continue; + + const char* fname = entry->d_name; + const size_t len = strlen(fname); + + if (len <= 7 || strcmp(fname + len - 7, ".notify") != 0) + continue; + + if (notification && notification->hasActiveFile(fname)) + continue; + + // ── Flag check: suppress & delete if {APP_NAME}.flag exists ────── + { + const char* dash = strchr(fname, '-'); + if (dash) { + static std::string flagPath; + flagPath = ult::NOTIFICATIONS_FLAGS_PATH; + flagPath.append(fname, dash - fname); // extract APP_NAME + flagPath += ".flag"; + + if (ult::isFile(flagPath)) { + fullPath = notifPath; + fullPath += fname; + remove(fullPath.c_str()); + continue; + } + } + } + // ── End flag check ──────────────────────────────────────────────── + + fullPath = notifPath; + fullPath += fname; + + struct stat fileStat; + struct timespec mtime = {0, 0}; + char timestampBuf[10] = {}; + if (stat(fullPath.c_str(), &fileStat) == 0) { + mtime = fileStat.st_mtim; + ult::formatTimestamp(mtime.tv_sec, timestampBuf, sizeof(timestampBuf)); + } + + std::unique_ptr r( + ult::readJsonFromFile(fullPath), ult::JsonDeleter()); + if (!r) continue; + + cJSON* cr = reinterpret_cast(r.get()); + + const cJSON* textObj = cJSON_GetObjectItemCaseSensitive(cr, "text"); + if (!cJSON_IsString(textObj) || !textObj->valuestring || !textObj->valuestring[0]) + continue; + + const cJSON* priorityObj = cJSON_GetObjectItemCaseSensitive(cr, "priority"); + + NotifData nd; + nd.priority = cJSON_IsNumber(priorityObj) ? (int)priorityObj->valuedouble : 20; + nd.mtime = mtime; + + // Prune before copying strings — skip heap allocs for non-qualifiers. + if (topCount == slotsWanted) { + if (!isBetter(nd, topSlots[topCount - 1])) continue; + } + + const cJSON* titleObj = cJSON_GetObjectItemCaseSensitive(cr, "title"); + const cJSON* fontSizeObj = cJSON_GetObjectItemCaseSensitive(cr, "font_size"); + const cJSON* durationObj = cJSON_GetObjectItemCaseSensitive(cr, "duration"); + const cJSON* showTimeObj = cJSON_GetObjectItemCaseSensitive(cr, "show_time"); + const cJSON* alignmentObj = cJSON_GetObjectItemCaseSensitive(cr, "alignment"); + const cJSON* splitTypeObj = cJSON_GetObjectItemCaseSensitive(cr, "split_type"); + + nd.showTime = !(cJSON_IsString(showTimeObj) && showTimeObj->valuestring && strcmp(showTimeObj->valuestring, ult::FALSE_STR.c_str()) == 0); + nd.fname = fname; + nd.text = textObj->valuestring; + nd.title = (cJSON_IsString(titleObj) && titleObj->valuestring) ? titleObj->valuestring : ""; + nd.fontSize = cJSON_IsNumber(fontSizeObj) ? std::clamp((int)fontSizeObj->valuedouble, 8, 48) + : (nd.title.empty() ? 26 : 24); + nd.duration = cJSON_IsNumber(durationObj) + ? ((int)durationObj->valuedouble == 0 ? -1 : std::clamp((int)durationObj->valuedouble, 500, 30000)) + : 0; + + const bool alignmentExplicit = cJSON_IsString(alignmentObj) && alignmentObj->valuestring && alignmentObj->valuestring[0]; + nd.alignment = alignmentExplicit ? alignmentObj->valuestring + : (nd.title.empty() ? "" : ult::LEFT_STR); + nd.splitChar = cJSON_IsString(splitTypeObj) && splitTypeObj->valuestring + && strcmp(splitTypeObj->valuestring, ult::CHAR_STR.c_str()) == 0; + + int pos = topCount; + while (pos > 0 && isBetter(nd, topSlots[pos - 1])) --pos; + + if (pos < slotsWanted) { + if (topCount < slotsWanted) ++topCount; + for (int i = topCount - 1; i > pos; --i) + topSlots[i] = std::move(topSlots[i - 1]); + topSlots[pos] = std::move(nd); + } + } + closedir(dir); + + // ── Dispatch ──────────────────────────────────────────────────── + if (notification) { + for (int i = 0; i < topCount; ++i) { + if (notification->activeCount() >= maxNotifications) break; + const NotifData& nd = topSlots[i]; + // Resume: stagger expiry so earlier slots fade first. + // Slot 0 of N loses (N-1) seconds, slot 1 loses (N-2), …, last loses 0. + const int baseDuration = nd.duration > 0 ? nd.duration : 4000; + const u32 duration = nd.duration == -1 ? 0u + : (firstPoll && topCount > 1) + ? static_cast(std::max(500, baseDuration - (topCount - 1 - i) * 200)) + : static_cast(baseDuration); + notification->show(nd.text, nd.fontSize, nd.priority, + nd.fname, nd.title, duration, + false, firstPoll, nd.showTime, + nd.alignment, + nd.splitChar ? ult::CHAR_STR : ult::WORD_STR, + nd.timestamp); + } + } + + } // end dispatch branch + + } else { + // Notifications disabled: delete all .notify files. + struct dirent* entry; + static std::string fullPath; + + while ((entry = readdir(dir)) != nullptr) { + if (entry->d_type != DT_REG) continue; + + const char* fname = entry->d_name; + const size_t len = strlen(fname); + + if (len > 7 && strcmp(fname + len - 7, ".notify") == 0) { + fullPath.clear(); + fullPath = ult::NOTIFICATIONS_PATH; + fullPath.append(fname, len); + remove(fullPath.c_str()); + } + } + closedir(dir); + } + } + } + } + + // Combine inputs from both controllers + const u64 kDown_p1 = padGetButtonsDown(&pad_p1); + const u64 kHeld_p1 = padGetButtons(&pad_p1); + const u64 kDown_handheld = padGetButtonsDown(&pad_handheld); + const u64 kHeld_handheld = padGetButtons(&pad_handheld); + + // For joysticks, prioritize handheld if available, otherwise use P1 + const HidAnalogStickState leftStick_handheld = padGetStickPos(&pad_handheld, 0); + const HidAnalogStickState rightStick_handheld = padGetStickPos(&pad_handheld, 1); + + // Check if handheld has any stick input (not at center position) + const bool handheldHasInput = (leftStick_handheld.x != 0 || leftStick_handheld.y != 0 || + rightStick_handheld.x != 0 || rightStick_handheld.y != 0); + + // Read touch before acquiring lock (static = BSS, not stack) + static HidTouchScreenState newTouchState; + newTouchState = { 0 }; + const bool hasTouchNow = hidGetTouchScreenStates(&newTouchState, 1) > 0; + const HidTouchState& currentTouch = newTouchState.touches[0]; + + // Swipe detection (uses only local variables, safe outside lock) + if (hasTouchNow) { + const u64 elapsedTime_ns = armTicksToNs(nowTick - currentTouchTick); + if (ult::useSwipeToOpen && elapsedTime_ns <= TOUCH_THRESHOLD_NS) { + if ((lastTouchX != 0 && lastTouchY != 0) && (currentTouch.x != 0 || currentTouch.y != 0)) { + if (ult::layerEdge == 0 && currentTouch.x > SWIPE_RIGHT_BOUND + 84 && lastTouchX <= SWIPE_RIGHT_BOUND) { + eventFire(&shData->comboEvent); + mainComboHasTriggered.store(true, std::memory_order_release); + } + else if (ult::layerEdge > 0 && currentTouch.x < SWIPE_LEFT_BOUND - 84 && lastTouchX >= SWIPE_LEFT_BOUND) { + eventFire(&shData->comboEvent); + mainComboHasTriggered.store(true, std::memory_order_release); + } + } + } + + if (currentTouch.x == 0 && currentTouch.y == 0) { + ult::internalTouchReleased.store(true, std::memory_order_release); + lastTouchX = 0; + lastTouchY = 0; + } else if ((lastTouchX == 0 && lastTouchY == 0) && (currentTouch.x != 0 || currentTouch.y != 0)) { + currentTouchTick = nowTick; + lastTouchX = currentTouch.x; + lastTouchY = currentTouch.y; + } + + if (!shData->overlayOpen) + ult::internalTouchReleased.store(false, std::memory_order_release); + } else { + ult::internalTouchReleased.store(true, std::memory_order_release); + lastTouchX = 0; + lastTouchY = 0; + } + + // Write all shared input state under the mutex + { + std::lock_guard lock(shData->dataMutex); + shData->keysDown = kDown_p1 | kDown_handheld; + shData->keysHeld = kHeld_p1 | kHeld_handheld; + if (handheldHasInput) { + shData->joyStickPosLeft = leftStick_handheld; + shData->joyStickPosRight = rightStick_handheld; + } else { + shData->joyStickPosLeft = padGetStickPos(&pad_p1, 0); + shData->joyStickPosRight = padGetStickPos(&pad_p1, 1); + } + shData->touchState = hasTouchNow ? newTouchState : HidTouchScreenState{ 0 }; + } + + #if IS_STATUS_MONITOR_DIRECTIVE + if (triggerExitNow) { + ult::launchingOverlay.store(true, std::memory_order_release); + ult::setIniFileValue( + ult::ULTRAHAND_CONFIG_INI_PATH, + ult::ULTRAHAND_PROJECT_NAME, + ult::IN_OVERLAY_STR, + ult::FALSE_STR + ); + tsl::setNextOverlay( + ult::OVERLAY_PATH + "ovlmenu.ovl" + ); + tsl::Overlay::get()->close(); + break; + } + #endif + + // KEY_MINUS: dismiss topmost notification, consume key + // Fires whether overlay is open or hidden. + // Skipped if MINUS is (part of) a launch combo, or if + // other buttons are also held (which means it's mid-combo). + if ((shData->keysDown & KEY_MINUS) + && !(shData->keysHeld & ~KEY_MINUS & ALL_KEYS_MASK) + && tsl::cfg::launchCombo != KEY_MINUS + && tsl::cfg::launchCombo2 != KEY_MINUS + && notification && notification->isActive()) { + notification->dismissFront(); + shData->keysDown &= ~KEY_MINUS; + shData->keysHeld &= ~KEY_MINUS; + } + + // KEY_MINUS: hold 3s to toggle notifications + if (ult::useNotificationsHotkey && tsl::cfg::launchCombo != KEY_MINUS + && tsl::cfg::launchCombo2 != KEY_MINUS) { + const bool minusAlone = (shData->keysHeld & KEY_MINUS) + && !(shData->keysHeld & ~KEY_MINUS & ALL_KEYS_MASK); + if (minusAlone) { + if (!minusHoldArmed) { + minusHoldArmed = true; + minusHoldStartTick = nowTick; + } else if (armTicksToNs(nowTick - minusHoldStartTick) >= 3'000'000'000ULL) { + minusHoldArmed = false; + ult::useNotifications = !ult::useNotifications; + ult::setIniFileValue( + ult::ULTRAHAND_CONFIG_INI_PATH, + ult::ULTRAHAND_PROJECT_NAME, + "notifications", + ult::useNotifications ? ult::TRUE_STR : ult::FALSE_STR + ); + if (ult::useNotifications) { + if (!ult::isFile(ult::NOTIFICATIONS_FLAG_FILEPATH)) { + if (FILE* f = std::fopen(ult::NOTIFICATIONS_FLAG_FILEPATH.c_str(), "w")) + std::fclose(f); + } + if (notification) + notification->show(ult::NOTIFY_HEADER+"API notifications enabled.", 22, 0); + } else { + ult::deleteFileOrDirectory(ult::NOTIFICATIONS_FLAG_FILEPATH); + if (notification) + notification->show(ult::NOTIFY_HEADER+"API notifications disabled.", 22, 0); + } + shData->keysDown &= ~KEY_MINUS; + shData->keysHeld &= ~KEY_MINUS; + } + } else { + minusHoldArmed = false; + } + } + + // Check main launch combo first (highest priority) + if ((((shData->keysHeld & tsl::cfg::launchCombo) == tsl::cfg::launchCombo) && shData->keysDown & tsl::cfg::launchCombo)) { + #if IS_LAUNCHER_DIRECTIVE + if (ult::updateMenuCombos) { + ult::setIniFileValue(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, ult::KEY_COMBO_STR , ult::ULTRAHAND_COMBO_STR); + ult::setIniFileValue(ult::TESLA_CONFIG_INI_PATH, ult::TESLA_STR, ult::KEY_COMBO_STR , ult::ULTRAHAND_COMBO_STR); + ult::updateMenuCombos = false; + } + #endif + + #if IS_STATUS_MONITOR_DIRECTIVE + isRendering = false; + leventSignal(&renderingStopEvent); // always — wakes frame limiter immediately + #endif + + if (shData->overlayOpen) { + if (!disableHiding) { + #if IS_STATUS_MONITOR_DIRECTIVE + if (!isValidOverlayMode()) { // only guard the hide + #endif + tsl::Overlay::get()->hide(); + shData->overlayOpen = false; + #if IS_STATUS_MONITOR_DIRECTIVE + } + #endif + } + } + else { + eventFire(&shData->comboEvent); + mainComboHasTriggered.store(true, std::memory_order_release); + } + } + #if IS_LAUNCHER_DIRECTIVE + else if (ult::updateMenuCombos && (((shData->keysHeld & tsl::cfg::launchCombo2) == tsl::cfg::launchCombo2) && shData->keysDown & tsl::cfg::launchCombo2)) { + std::swap(tsl::cfg::launchCombo, tsl::cfg::launchCombo2); // Swap the two launch combos + ult::setIniFileValue(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, ult::KEY_COMBO_STR , ult::TESLA_COMBO_STR); + ult::setIniFileValue(ult::TESLA_CONFIG_INI_PATH, ult::TESLA_STR, ult::KEY_COMBO_STR , ult::TESLA_COMBO_STR); + eventFire(&shData->comboEvent); + mainComboHasTriggered.store(true, std::memory_order_release); + ult::updateMenuCombos = false; + } + else if (ult::overlayLaunchRequested.load(std::memory_order_acquire) && !ult::runningInterpreter.load(std::memory_order_acquire) && ult::settingsInitialized.load(std::memory_order_acquire) && (nowNs - startNs) >= FAST_SWAP_THRESHOLD_NS) { + std::string requestedPath, requestedArgs; + + // Get the request data safely + { + std::lock_guard lock(ult::overlayLaunchMutex); + requestedPath = ult::requestedOverlayPath; + requestedArgs = ult::requestedOverlayArgs; + ult::overlayLaunchRequested.store(false, std::memory_order_release); + } + + if (!requestedPath.empty()) { + + const std::string overlayFileName = ult::getNameFromPath(requestedPath); + + // Set overlay state for ovlmenu.ovl + + // OPTIMIZED: Batch INI file writes + { + ult::setIniFileValue(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, ult::IN_OVERLAY_STR, ult::TRUE_STR); + ult::setIniFileValue(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, "to_packages", ult::TRUE_STR); + } + + // Reset navigation state variables (these control slide navigation) + ult::allowSlide.store(false, std::memory_order_release); + ult::unlockedSlide.store(false, std::memory_order_release); + + // Launch the overlay using the same mechanism as key combos + tsl::setNextOverlay(requestedPath, requestedArgs+" --direct"); + fireLaunch(); + return; + } + } + #endif + // Check overlay key combos (only when overlay is not open, keys are pressed, and not conflicting with main combos) + else if (shData->keysDown != 0 && ult::useLaunchCombos) { + if (shData->keysHeld != tsl::cfg::launchCombo) { + // Lookup both path and optional mode launch args + const auto comboInfo = tsl::hlp::getEntryForKeyCombo(shData->keysHeld); + const std::string& overlayPath = comboInfo.path; + + + #if IS_LAUNCHER_DIRECTIVE + if (!overlayPath.empty() && (shData->keysHeld) && !ult::runningInterpreter.load(std::memory_order_acquire) && ult::settingsInitialized.load(std::memory_order_acquire) && (armTicksToNs(nowTick) - startNs) >= FAST_SWAP_THRESHOLD_NS) { + #else + if (!overlayPath.empty() && (shData->keysHeld) && (nowNs - startNs) >= FAST_SWAP_THRESHOLD_NS) { + #endif + + const std::string& modeArg = comboInfo.launchArg; + const std::string overlayFileName = ult::getNameFromPath(overlayPath); + + // Check HOS21 support before doing anything + if (requiresLNY2 && !usingLNY2(overlayPath)) { + // Skip launch if not supported + const auto forceSupportStatus = ult::parseValueFromIniSection( + ult::OVERLAYS_INI_FILEPATH, overlayFileName, "force_support"); + if (forceSupportStatus != ult::TRUE_STR) { + if (tsl::notification) { + tsl::notification->showNow(ult::NOTIFY_HEADER+ult::INCOMPATIBLE_WARNING, 22); + } + continue; + } + } + + // hideHidden check + if (hideHidden) { + const auto hideStatus = ult::parseValueFromIniSection( + ult::OVERLAYS_INI_FILEPATH, overlayFileName, ult::HIDE_STR); + if (hideStatus == ult::TRUE_STR) { + shData->keysDownPending |= shData->keysDown; + continue; + } + } + + #if IS_STATUS_MONITOR_DIRECTIVE + isRendering = false; + leventSignal(&renderingStopEvent); + #endif + + #if !IS_LAUNCHER_DIRECTIVE + if (lastOverlayFilename == overlayFileName && lastOverlayMode == modeArg) { + #else + if (lastOverlayFilename == overlayFileName && lastOverlayMode == modeArg && lastOverlayMode.find("--package") != std::string::npos) { + #endif + ult::setIniFileValue( + ult::ULTRAHAND_CONFIG_INI_PATH, + ult::ULTRAHAND_PROJECT_NAME, + ult::IN_OVERLAY_STR, + ult::TRUE_STR + ); + + tsl::setNextOverlay(ult::OVERLAY_PATH + "ovlmenu.ovl", "--direct --comboReturn"); + fireLaunch(); + return; + } + + // Compose launch args + std::string finalArgs; + if (!modeArg.empty()) { + finalArgs = modeArg; + } else { + // Only check overlay-specific launch args for non-ovlmenu entries + if (overlayFileName.compare("ovlmenu.ovl") != 0) { + // OPTIMIZED: Single INI read for both values + const std::string useArgs = ult::parseValueFromIniSection(ult::OVERLAYS_INI_FILEPATH, overlayFileName, ult::USE_LAUNCH_ARGS_STR); + const std::string launchArgs = ult::parseValueFromIniSection(ult::OVERLAYS_INI_FILEPATH, overlayFileName, ult::LAUNCH_ARGS_STR); + + if (useArgs == ult::TRUE_STR) { + finalArgs = launchArgs; + ult::removeQuotes(finalArgs); + } + } + } + if (finalArgs.empty()) { + finalArgs = "--direct"; + } else { + finalArgs += " --direct"; + } + + if (overlayFileName.compare("ovlmenu.ovl") == 0) { + finalArgs += " --comboReturn"; + ult::setIniFileValue(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, ult::IN_OVERLAY_STR, ult::TRUE_STR); + } + + tsl::setNextOverlay(overlayPath, finalArgs); + fireLaunch(); + return; + } + } + } + //#endif + + shData->keysDownPending |= shData->keysDown; + } + + //20 ms + //s32 idx = 0; + rc = waitObjects(&idx, objects, WaiterObject_Count, 20'000'000ul); + if (R_SUCCEEDED(rc)) { + + #if IS_STATUS_MONITOR_DIRECTIVE + if (idx == WaiterObject_HomeButton || idx == WaiterObject_PowerButton) { // Changed condition to exclude capture button + if (shData->overlayOpen && !isValidOverlayMode()) { + tsl::Overlay::get()->hide(); + shData->overlayOpen = false; + } + } + #else + if (idx == WaiterObject_HomeButton || idx == WaiterObject_PowerButton) { // Changed condition to exclude capture button + if (shData->overlayOpen) { + tsl::Overlay::get()->hide(); + shData->overlayOpen = false; + } + } + #endif + + switch (idx) { + case WaiterObject_HomeButton: + eventClear(&homeButtonPressEvent); + break; + case WaiterObject_PowerButton: + eventClear(&powerButtonPressEvent); + + // Block feedback thread from touching HID during reinit + hidReinitInProgress.store(true, std::memory_order_seq_cst); + svcSleepThread(20'000'000ULL); // 20ms — let feedback thread finish its current iteration + + // Perform any necessary cleanup + hidExit(); + + // Reinitialize resources + ASSERT_FATAL(hidInitialize()); // Reinitialize HID to reset states + + // Reinitialize both controllers + padInitialize(&pad_p1, HidNpadIdType_No1); + padInitialize(&pad_handheld, HidNpadIdType_Handheld); + hidInitializeTouchScreen(); + + // Update both controllers + padUpdate(&pad_p1); + padUpdate(&pad_handheld); + + // Clear shared input state so wake doesn't see phantom held keys + { + std::lock_guard lock(shData->dataMutex); + shData->keysDown = 0; + shData->keysHeld = 0; + shData->keysDownPending = 0; + shData->touchState = { 0 }; + } + + triggerInitHaptics.store(true, std::memory_order_release); + hidReinitInProgress.store(false, std::memory_order_seq_cst); + break; + + + case WaiterObject_CaptureButton: + if (screenshotsAreDisabled) { + eventClear(&captureButtonPressEvent); + break; + } + + #if IS_STATUS_MONITOR_DIRECTIVE + const bool inOverlayMode = isValidOverlayMode(); + if (inOverlayMode) { + delayUpdate = true; + isRendering = false; + leventSignal(&renderingStopEvent); + } + #endif + + ult::disableTransparency = true; + eventClear(&captureButtonPressEvent); + svcSleepThread(1'500'000'000); + ult::disableTransparency = false; + + #if IS_STATUS_MONITOR_DIRECTIVE + if (inOverlayMode) { + if (notification && notification->isActive()) { + // Notification is still animating — don't re-enable the frame limiter yet. + // Restore wasRendering so the notification draw loop handles re-enabling when done. + wasRendering = true; + } else { + isRendering = true; + leventClear(&renderingStopEvent); + } + delayUpdate = false; + } + #endif + + break; + } + } else if (rc != KERNELRESULT(TimedOut)) { + ASSERT_FATAL(rc); + } + } + //hidExit(); + + } + + /** + * @brief Background event polling loop thread + * + * @param args Used to pass in a pointer to a \ref SharedThreadData struct + */ + static void backgroundFeedbackPoller(void *args) { + while (!feedbackPollerStop.load(std::memory_order_acquire)) { + + if (ult::launchingOverlay.load(std::memory_order_acquire)) + break; + + const u64 nowNs = ult::nowNs(); + + // --- Haptics --- + if (ult::useHapticFeedback && !disableHaptics.load(std::memory_order_acquire) + && !hidReinitInProgress.load(std::memory_order_acquire)) { + if (triggerInitHaptics.exchange(false, std::memory_order_acq_rel)) { + ult::initHaptics(); + } else { + static u64 lastHapticsCheckNs = 0; + if ((nowNs - lastHapticsCheckNs) >= 300'000'000ULL) { + lastHapticsCheckNs = nowNs; + ult::checkAndReinitHaptics(); + } + } + + if (triggerRumbleDoubleClick.exchange(false, std::memory_order_acq_rel)) { + triggerRumbleClick.store(false, std::memory_order_release); + ult::rumbleDoubleClick(); + } else if (triggerRumbleClick.exchange(false, std::memory_order_acq_rel)) { + ult::rumbleClick(); + } + + // Must be called every loop to advance timing state + ult::processRumbleStop(nowNs); + ult::processRumbleDoubleClick(nowNs); + } else { + triggerRumbleClick.store(false, std::memory_order_release); + triggerRumbleDoubleClick.store(false, std::memory_order_release); + } + + // --- Sound --- + if (!ult::limitedMemory) { + if (!ult::useSoundEffects || disableSound.load(std::memory_order_acquire)) { + triggerNavigationSound.store(false, std::memory_order_release); + triggerEnterSound.store(false, std::memory_order_release); + triggerExitSound.store(false, std::memory_order_release); + triggerWallSound.store(false, std::memory_order_release); + triggerOnSound.store(false, std::memory_order_release); + triggerOffSound.store(false, std::memory_order_release); + triggerSettingsSound.store(false, std::memory_order_release); + triggerMoveSound.store(false, std::memory_order_release); + triggerNotificationSound.store(false, std::memory_order_release); + } else { + if (reloadIfDockedChangedNow.exchange(false, std::memory_order_acq_rel)) + ult::Audio::reloadIfDockedChanged(); + if (reloadSoundCacheNow.exchange(false, std::memory_order_acq_rel)) + ult::Audio::reloadAllSounds(); + + if (triggerNavigationSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playNavigateSound(); + else if (triggerEnterSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playEnterSound(); + else if (triggerExitSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playExitSound(); + else if (triggerWallSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playWallSound(); + else if (triggerOnSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playOnSound(); + else if (triggerOffSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playOffSound(); + else if (triggerSettingsSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playSettingsSound(); + else if (triggerMoveSound.exchange(false, std::memory_order_acq_rel)) + ult::Audio::playMoveSound(); + else if (triggerNotificationSound.exchange(false, std::memory_order_acq_rel) && !ult::silenceNotifications) + ult::Audio::playNotificationSound(); + + } + } + + svcSleepThread((ult::useSoundEffects || ult::useHapticFeedback) ? 16'000'000ULL : 160'000'000ULL); + } + } + } + + /** + * @brief Creates a new Gui and changes to it + * + * @tparam G Gui to create + * @tparam Args Arguments to pass to the Gui + * @param args Arguments to pass to the Gui + * @return Reference to the newly created Gui + */ + template + std::unique_ptr& changeTo(Args&&... args) { + return Overlay::get()->changeTo(std::forward(args)...); + } + + template + std::unique_ptr& swapTo(Args&&... args) { + return Overlay::get()->swapTo(std::forward(args)...); + } + + template + std::unique_ptr& swapTo(SwapDepth depth, Args&&... args) { + return Overlay::get()->swapTo(depth, std::forward(args)...); + } + + + /** + * @brief Pops the top Gui from the stack and goes back to the last one + * @note The Overlay gets closed once there are no more Guis on the stack + */ + inline void goBack(u32 count) { + Overlay::get()->goBack(count); + } + + inline void pop(u32 count) { + Overlay::get()->pop(count); + } + + /** + * @brief Shifts focus to a specific UI element + * + * Requests focus on the provided element without directional navigation. + * Uses FocusDirection::None to set focus directly on the target element, + * typically centering it in the viewport without triggering navigation effects. + * + * Useful for jumping to specific items programmatically (e.g., after search, + * restoring saved position, or responding to external events). + * + * @param element The element to receive focus + */ + inline void shiftItemFocus(elm::Element* element) { + if (auto& currentGui = Overlay::get()->getCurrentGui()) { + currentGui->requestFocus(element, FocusDirection::None); + } + } + + inline std::mutex setNextOverlayMutex; + inline std::string nextOverlayName; + + + __attribute__((noinline)) inline void setNextOverlay(const std::string& ovlPath, std::string origArgs) { + std::lock_guard lk(setNextOverlayMutex); + char buffer[1024]; + char* p = buffer; + char* bufferEnd = buffer + sizeof(buffer) - 1; + + const std::string filenameStr = ult::getNameFromPath(ovlPath); + nextOverlayName = filenameStr; + + const char* filename = filenameStr.c_str(); + while (*filename && p < bufferEnd) *p++ = *filename++; + if (p < bufferEnd) *p++ = ' '; + + const char* src = origArgs.c_str(); + const char* end = src + origArgs.length(); + bool hasSkipCombo = false; + + while (src < end && p < bufferEnd) { + while (src < end && *src == ' ' && p < bufferEnd) *p++ = *src++; + if (src >= end || p >= bufferEnd) break; + + if (src[0] == '-' && src[1] == '-') { + if (strncmp(src, "--skipCombo", 11) == 0 && + (src[11] == ' ' || src[11] == '\0')) { + hasSkipCombo = true; + while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; + } + else if (strncmp(src, "--foregroundFix", 15) == 0) { + src += 15; + while (src < end && *src == ' ') src++; + if (src < end && (*src == '0' || *src == '1')) src++; + } + else if (strncmp(src, "--lastTitleID", 13) == 0) { + src += 13; + while (src < end && *src == ' ') src++; + while (src < end && *src != ' ' && *src != '\0') src++; + } + else { + while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; + } + } + else { + while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; + } + } + + if (!hasSkipCombo && (p + 12) < bufferEnd) { + memcpy(p, " --skipCombo", 12); p += 12; + } + + if ((p + 17) < bufferEnd) { + memcpy(p, " --foregroundFix ", 17); p += 17; + if (p < bufferEnd) { + *p++ = (ult::resetForegroundCheck.load(std::memory_order_acquire) || + ult::lastTitleID != ult::getTitleIdAsString()) ? '1' : '0'; + } + } + + if ((p + 15 + (ptrdiff_t)ult::lastTitleID.length()) < bufferEnd) { + memcpy(p, " --lastTitleID ", 15); p += 15; + const char* titleId = ult::lastTitleID.c_str(); + while (*titleId && p < bufferEnd) *p++ = *titleId++; + } + + if (p >= bufferEnd) p = bufferEnd; + *p = '\0'; + + envSetNextLoad(ovlPath.c_str(), buffer); + } + + + + struct option_entry { + const char* name; + u8 len; + u8 action; + }; + + static constexpr struct option_entry options[] = { + {"direct", 6, 1}, + {"skipCombo", 9, 2}, + {"lastTitleID", 11, 3}, + {"foregroundFix", 13, 4}, + {"package", 7, 5}, + {"lastSelectedItem", 16, 6}, + {"comboReturn", 11, 7} // new option + }; + + + /** + * @brief libtesla's main function + * @note Call it directly from main passing in argc and argv and returning it e.g `return tsl::loop(argc, argv);` + * + * @tparam TOverlay Your overlay class + * @tparam launchFlags \ref LaunchFlags + * @param argc argc + * @param argv argv + * @return int result + */ + template + static inline int loop(int argc, char** argv) { + static_assert(std::is_base_of_v, "tsl::loop expects a type derived from tsl::Overlay"); + + #if IS_STATUS_MONITOR_DIRECTIVE + leventClear(&renderingStopEvent); + // Status monitor will load heap settings directly in main, so bypass here in loop + #else + + ult::currentHeapSize = ult::getCurrentHeapSize(); + ult::expandedMemory = ult::currentHeapSize >= ult::OverlayHeapSize::Size_8MB; + ult::limitedMemory = ult::currentHeapSize == ult::OverlayHeapSize::Size_4MB; + + + // Initialize buffer sizes based on expanded memory setting + if (ult::expandedMemory) { + ult::furtherExpandedMemory = ult::currentHeapSize > ult::OverlayHeapSize::Size_8MB; + + if (!ult::furtherExpandedMemory) { + ult::loaderTitle += "+"; + ult::COPY_BUFFER_SIZE = 262144; + ult::HEX_BUFFER_SIZE = 8192; + ult::UNZIP_READ_BUFFER = 262144; + ult::UNZIP_WRITE_BUFFER = 131072; + ult::DOWNLOAD_READ_BUFFER = 131072; + ult::DOWNLOAD_WRITE_BUFFER = 131072; + } else { + ult::loaderTitle += "×"; + ult::COPY_BUFFER_SIZE = 262144*2; + ult::HEX_BUFFER_SIZE = 8192; + ult::UNZIP_READ_BUFFER = 262144*2; + ult::UNZIP_WRITE_BUFFER = 131072*4; + ult::DOWNLOAD_READ_BUFFER = 131072*4; + ult::DOWNLOAD_WRITE_BUFFER = 131072*4; + } + } else if (ult::limitedMemory) { + ult::loaderTitle += "-"; + ult::DOWNLOAD_READ_BUFFER = 16*1024; + ult::UNZIP_READ_BUFFER = 16*1024; + } + #endif + + if (argc > 0) { + lastOverlayFilename = ult::getNameFromPath(argv[0]); + + lastOverlayMode.clear(); + bool skip; + for (u8 arg = 1; arg < argc; arg++) { + const char* s = argv[arg]; + + skip = false; + + if (arg > 1) { + const char* prev = argv[arg - 1]; + if (prev[0] == '-' && prev[1] == '-') { + if (strcmp(prev, "--lastTitleID") == 0 || strcmp(prev, "--foregroundFix") == 0) { + skip = true; + } + } + } + + if (!skip && s[0] == '-' && s[1] == '-') { + if (strcmp(s, "--direct") == 0 || + strcmp(s, "--skipCombo") == 0 || + strcmp(s, "--lastTitleID") == 0 || + strcmp(s, "--foregroundFix") == 0) { + skip = true; + } + } + + if (!skip) { + if (strcmp(s, "--package") == 0) { + lastOverlayMode = "--package"; + arg++; + if (arg < argc) { + lastOverlayMode += " "; + lastOverlayMode += argv[arg]; + arg++; + while (arg < argc && argv[arg][0] != '-') { + lastOverlayMode += " "; + lastOverlayMode += argv[arg]; + arg++; + } + } + } else { + lastOverlayMode = s; + } + break; + } + } + } + + bool skipCombo = false; + #if IS_LAUNCHER_DIRECTIVE + bool comboReturn = false; + bool directMode = true; + #else + bool directMode = false; + #endif + bool usingPackageLauncher = false; + + + for (u8 arg = 0; arg < argc; arg++) { + const char* s = argv[arg]; + if (s[0] != '-' || s[1] != '-') continue; + const char* opt = s + 2; + + for (u8 i = 0; i < 7; i++) { // now 6 instead of 5 + if (memcmp(opt, options[i].name, options[i].len) == 0 && opt[options[i].len] == '\0') { + switch (options[i].action) { + case 1: // direct + directMode = true; + jumpItemName = ""; + jumpItemValue = ""; + jumpItemExactMatch.store(true, std::memory_order_release); + break; + case 2: // skipCombo + skipCombo = true; + ult::firstBoot = false; + break; + case 3: // lastTitleID + if (++arg < argc) { + const char* providedID = argv[arg]; + if (ult::getTitleIdAsString() != providedID) { + ult::resetForegroundCheck.store(true, std::memory_order_release); + } + } + break; + case 4: // foregroundFix + if (++arg < argc) { + ult::resetForegroundCheck.store( + ult::resetForegroundCheck.load(std::memory_order_acquire) || + (argv[arg][0] == '1'), std::memory_order_release); + } + break; + case 5: // package + usingPackageLauncher = true; + break; + case 6: // lastSelectedItem + #if IS_STATUS_MONITOR_DIRECTIVE + lastMode = "returning"; + #endif + break; + case 7: // comboReturn + #if IS_LAUNCHER_DIRECTIVE + comboReturn = true; + #endif + break; + } + } + } + } + + impl::SharedThreadData shData; + shData.running.store(true, std::memory_order_release); + + auto& overlay = tsl::Overlay::s_overlayInstance; + overlay = new TOverlay(); + overlay->m_closeOnExit = (u8(launchFlags) & u8(impl::LaunchFlags::CloseOnExit)) == u8(impl::LaunchFlags::CloseOnExit); + + // Parse Tesla settings + impl::parseOverlaySettings(); + + // Initialize overlay services & screen + tsl::hlp::doWithSmSession([&overlay]{ + overlay->initServices(); + }); + overlay->initScreen(); + + eventCreate(&shData.comboEvent, false); + + Thread backgroundFeedbackThread; + threadCreate(&backgroundFeedbackThread, impl::backgroundFeedbackPoller, nullptr, nullptr, 0x1000, 0x2c, -2); + threadStart(&backgroundFeedbackThread); + + Thread backgroundEventThread; + threadCreate(&backgroundEventThread, impl::backgroundEventPoller, &shData, nullptr, 0x2000, 0x2c, -2); + threadStart(&backgroundEventThread); + + + bool shouldFireEvent = false; + + #if IS_LAUNCHER_DIRECTIVE + + { + auto configData = ult::getParsedDataFromIniFile(ult::ULTRAHAND_CONFIG_INI_PATH); + bool needsUpdate = false; + + // Get reference to project section (create if missing) + auto& project = configData[ult::ULTRAHAND_PROJECT_NAME]; + + // Determine current overlay state + bool inOverlay = true; + auto it = project.find(ult::IN_OVERLAY_STR); + if (it != project.end()) { + inOverlay = (it->second != ult::FALSE_STR); + } + + // Only update the overlay key once, for either firstBoot or skipCombo + if (ult::firstBoot || (inOverlay && skipCombo)) { + project[ult::IN_OVERLAY_STR] = ult::FALSE_STR; + needsUpdate = true; + if (inOverlay && skipCombo) { + shouldFireEvent = true; + } + } + + // Write INI only if we changed something + if (needsUpdate) { + ult::saveIniFileData(ult::ULTRAHAND_CONFIG_INI_PATH, configData); + } + + // Fire event if needed + if (shouldFireEvent) { + eventFire(&shData.comboEvent); + } else { + lastOverlayFilename = ""; + } + } + #else + { + auto configData = ult::getParsedDataFromIniFile(ult::ULTRAHAND_CONFIG_INI_PATH); + + auto projectIt = configData.find(ult::ULTRAHAND_PROJECT_NAME); + if (projectIt != configData.end()) { + auto& project = projectIt->second; + + auto overlayIt = project.find(ult::IN_OVERLAY_STR); + const bool inOverlay = (overlayIt == project.end() || + overlayIt->second != ult::FALSE_STR); + + if (inOverlay && directMode) { + project[ult::IN_OVERLAY_STR] = ult::FALSE_STR; + ult::saveIniFileData(ult::ULTRAHAND_CONFIG_INI_PATH, configData); + } + } + } + + if (skipCombo) { + eventFire(&shData.comboEvent); + shouldFireEvent = true; + } + #endif + + overlay->changeTo(overlay->loadInitialGui()); + overlay->disableNextAnimation(); + + { + const Handle handles[2] = { shData.comboEvent.revent, notificationEvent.revent }; + s32 index = -1; + + bool exitAfterPrompt = false; + bool comboBreakout = false; + bool firstLoop = !ult::firstBoot; + + auto exitLaunching = [&]() __attribute__((noinline)) { + shData.running.store(false, std::memory_order_release); + shData.overlayOpen.store(false, std::memory_order_release); + }; + + while (shData.running.load(std::memory_order_acquire)) { + // Early exit if launching new overlay + if (ult::launchingOverlay.load(std::memory_order_acquire)) { + exitLaunching(); break; + } + + // Wait for events only if no active notification + if (!(notification && notification->isActive())) { + svcWaitSynchronization(&index, handles, 2, UINT64_MAX); + } + eventClear(¬ificationEvent); + eventClear(&shData.comboEvent); + + if ((notification && notification->isActive() && !firstLoop) || index == 1) { + comboBreakout = false; + + while (shData.running.load(std::memory_order_acquire)) { + { + if (ult::launchingOverlay.load(std::memory_order_acquire)) { + exitLaunching(); break; + } + overlay->loop(true); // Draw prompts while hidden + + // ── Notification touch-dismiss while overlay is hidden ────────────── + { + static bool hiddenTouchWasDown = false; + bool touchNow = false; + HidTouchState tp = {}; + + { + std::scoped_lock lock(shData.dataMutex); + touchNow = shData.touchState.count > 0; + if (touchNow) + tp = shData.touchState.touches[0]; + } + // dataMutex released — safe to call notification methods + // which internally acquire state_mutex_ + if (!hiddenTouchWasDown && touchNow) { + if (notification && notification->hitTest( + static_cast(tp.x), static_cast(tp.y))) { + notification->dismissAt( + static_cast(tp.x), static_cast(tp.y)); + } + } + hiddenTouchWasDown = touchNow; + } + // ─────────────────────────────────────────────────────────────────── + } + + if (mainComboHasTriggered.exchange(false, std::memory_order_acq_rel)) { + comboBreakout = true; + exitAfterPrompt = false; + break; + } + + if (launchComboHasTriggered.load(std::memory_order_acquire)) { + exitAfterPrompt = true; + usingPackageLauncher = false; + directMode = false; + break; + } + + if (!(notification && notification->isActive())) { + break; + } + } + + if (!comboBreakout || !shData.running.load(std::memory_order_acquire)) { + { + if (!ult::launchingOverlay.load(std::memory_order_acquire)) { + overlay->clearScreen(); + } + } + if (exitAfterPrompt) { + std::scoped_lock lock(shData.dataMutex); + exitAfterPrompt = false; + exitLaunching(); + ult::launchingOverlay.store(true, std::memory_order_release); + launchComboHasTriggered.store(true, std::memory_order_release); // for isolating sound effect + + if (usingPackageLauncher || directMode) { + tsl::setNextOverlay(ult::OVERLAY_PATH + "ovlmenu.ovl"); + } + + hlp::requestForeground(false); + break; + } + continue; + } + } + + { + if (ult::launchingOverlay.load(std::memory_order_acquire)) { + exitLaunching(); break; + } + firstLoop = false; + shData.overlayOpen.store(true, std::memory_order_release); + + #if IS_STATUS_MONITOR_DIRECTIVE + if (!isValidOverlayMode()) + hlp::requestForeground(true); + #else + hlp::requestForeground(true); + #endif + + overlay->show(); + if (!comboBreakout && !(notification && notification->isActive())) + overlay->clearScreen(); + + { + std::scoped_lock lock(shData.dataMutex); + // Clear derived states that the overlay loop will use + shData.keysDown = 0; + shData.keysHeld = 0; + // Clear any queued pending keys so nothing gets processed one frame late + shData.keysDownPending = 0; + } + } + + while (shData.running.load(std::memory_order_acquire)) { + { + + if (ult::launchingOverlay.load(std::memory_order_acquire)) { + shData.running.store(false, std::memory_order_release); + shData.overlayOpen.store(false, std::memory_order_release); + break; + } + overlay->loop(); + { + std::scoped_lock lock(shData.dataMutex); + if (!overlay->fadeAnimationPlaying()) { + overlay->handleInput(shData.keysDownPending, shData.keysHeld, shData.touchState.count, shData.touchState.touches[0], shData.joyStickPosLeft, shData.joyStickPosRight); + } + shData.keysDownPending = 0; + } + #if IS_LAUNCHER_DIRECTIVE + if (shouldFireEvent) { + shouldFireEvent = false; + + if (!comboReturn) { + triggerExitFeedback(); + } + } + #else + if (!directMode && shouldFireEvent) { + shouldFireEvent = false; + #if IS_STATUS_MONITOR_DIRECTIVE + if (lastMode.compare("returning") == 0) { + triggerExitFeedback(); + } else { + triggerEnterFeedback(); + } + #else + triggerEnterFeedback(); + #endif + } + #endif + } + + #if IS_STATUS_MONITOR_DIRECTIVE + if (pendingExit && wasRendering) { + pendingExit = false; + if (!(notification && notification->isActive())) { + wasRendering = false; + isRendering = true; + leventClear(&renderingStopEvent); + } + } + #endif + + if (overlay->shouldHide()) { + if (overlay->shouldCloseAfter()) { + if (!directMode) { + shData.running.store(false, std::memory_order_release); + shData.overlayOpen.store(false, std::memory_order_release); + break; + } else { + exitAfterPrompt = true; + #if IS_STATUS_MONITOR_DIRECTIVE + pendingExit = true; + #endif + } + } + break; + } + + if (overlay->shouldClose()) { + shData.running.store(false, std::memory_order_release); + shData.overlayOpen.store(false, std::memory_order_release); + + break; + } + } + + if (shData.running.load(std::memory_order_acquire)) { + if (!(notification && notification->isActive())) + overlay->clearScreen(); + overlay->resetFlags(); + hlp::requestForeground(false); + shData.overlayOpen.store(false, std::memory_order_release); + mainComboHasTriggered.store(false, std::memory_order_release); + eventClear(&shData.comboEvent); + } + } + + // Ensure background thread is fully stopped before overlay cleanup + shData.running.store(false, std::memory_order_release); + feedbackPollerStop.store(true, std::memory_order_release); + + threadWaitForExit(&backgroundEventThread); + threadClose(&backgroundEventThread); + + threadWaitForExit(&backgroundFeedbackThread); + threadClose(&backgroundFeedbackThread); + + // Cleanup overlay resources + hlp::requestForeground(false); + overlay->exitScreen(); + overlay->exitServices(); + delete overlay; + + + eventClose(&shData.comboEvent); + + + if (directMode && !launchComboHasTriggered.load(std::memory_order_acquire)) { + if (!disableSound.load(std::memory_order_acquire) && ult::useSoundEffects) + ult::Audio::playExitSound(); + if (ult::useHapticFeedback) { + ult::rumbleDoubleClickStandalone(); + } + } + + return 0; + } + } + +} + + +#ifdef TESLA_INIT_IMPL + +namespace tsl::cfg { + u16 LayerWidth = 0; + u16 LayerHeight = 0; + u16 LayerPosX = 0; + u16 LayerPosY = 0; + u16 FramebufferWidth = 0; + u16 FramebufferHeight = 0; + u64 launchCombo = KEY_ZL | KEY_ZR | KEY_DDOWN; + u64 launchCombo2 = KEY_L | KEY_DDOWN | KEY_RSTICK; +} + +extern "C" void __libnx_init_time(void); + +extern "C" { + + u32 __nx_applet_type = AppletType_None; + u32 __nx_fs_num_sessions = 1; + u32 __nx_nv_transfermem_size = 0x15000; + ViLayerFlags __nx_vi_stray_layer_flags = (ViLayerFlags)0; + + /** + * @brief libtesla service initializing function to override libnx's + * + */ + void __appInit(void) { + ASSERT_FATAL(smInitialize()); // needed to prevent issues with powering device into sleep + + ASSERT_FATAL(fsInitialize()); + ASSERT_FATAL(hidInitialize()); // Controller inputs and Touch + if (hosversionAtLeast(16,0,0)) { + ASSERT_FATAL(plInitialize(PlServiceType_User)); // Font data. Use pl:u for 16.0.0+ + } else { + ASSERT_FATAL(plInitialize(PlServiceType_System)); // Use pl:s for 15.0.1 and below to prevent qlaunch/overlaydisp session exhaustion + } + ASSERT_FATAL(pmdmntInitialize()); // PID querying + ASSERT_FATAL(hidsysInitialize()); // Focus control + ASSERT_FATAL(setsysInitialize()); // Settings querying + + // Time initializations + if R_SUCCEEDED(timeInitialize()) { + __libnx_init_time(); + timeExit(); + } + + #if USING_WIDGET_DIRECTIVE + ult::powerInit(); + i2cInitialize(); + #endif + + fsdevMountSdmc(); + splInitialize(); + spsmInitialize(); + + #if IS_STATUS_MONITOR_DIRECTIVE + Service *plSrv = plGetServiceSession(); + Service plClone; + ASSERT_FATAL(serviceClone(plSrv, &plClone)); + serviceClose(plSrv); + *plSrv = plClone; + #endif + + eventCreate(&tsl::notificationEvent, false); + tsl::notification = new tsl::NotificationPrompt(); + } + + /** + * @brief libtesla service exiting function to override libnx's + * + */ + void __appExit(void) { + delete tsl::notification; + eventClose(&tsl::notificationEvent); + if (!ult::limitedMemory) + ult::Audio::exit(); + + spsmExit(); + splExit(); + fsdevUnmountAll(); + + #if USING_WIDGET_DIRECTIVE + i2cExit(); + ult::powerExit(); + #endif + + fsExit(); + hidExit(); + plExit(); + pmdmntExit(); + hidsysExit(); + setsysExit(); + smExit(); + + // Final cleanup + tsl::gfx::FontManager::cleanup(); + } + +} + +#endif \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libtesla/source/tesla.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/source/tesla.cpp new file mode 100644 index 00000000..cc6236d9 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libtesla/source/tesla.cpp @@ -0,0 +1,1532 @@ +/******************************************************************************** + * Custom Fork Information + * + * File: tesla.cpp + * Author: ppkantorski + * Description: + * This file serves as the core logic for the Ultrahand Overlay project's custom fork + * of libtesla, an overlay executor. Within this file, you will find a collection of + * functions, menu structures, and interaction logic designed to facilitate the + * smooth execution and flexible customization of overlays within the project. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + + +#include + +// --------------------------------------------------------------------------- +// usingLNY2 — defined here, not in the header. +// 69-line file I/O + malloc body: inlining it into every TU would bloat every +// object file that includes tesla.hpp. Called from exactly one place. +// --------------------------------------------------------------------------- +bool usingLNY2(const std::string& filePath) { + FILE* file = fopen(filePath.c_str(), "rb"); + if (!file) + return false; + + // --- Get file size --- + fseek(file, 0, SEEK_END); + const long fileSize = ftell(file); + if (fileSize < (long)(sizeof(NroStart) + sizeof(NroHeader))) { + fclose(file); + return false; + } + const size_t fileSz = (size_t)fileSize; + fseek(file, 0, SEEK_SET); + + // --- Read front chunk (header + MOD0 area) --- + constexpr size_t FRONT_READ_SIZE = 8192; + const size_t frontReadSize = (fileSz < FRONT_READ_SIZE) ? fileSz : FRONT_READ_SIZE; + uint8_t* frontBuf = (uint8_t*)malloc(frontReadSize); + if (!frontBuf) { + fclose(file); + return false; + } + + if (fread(frontBuf, 1, frontReadSize, file) != frontReadSize) { + free(frontBuf); + fclose(file); + return false; + } + + // --- Extract offsets directly (no NroHeader copy needed) --- + const uint32_t mod0_rel = *reinterpret_cast(frontBuf + 0x4); + const uint32_t text_offset = *reinterpret_cast(frontBuf + 0x20); + + bool isNew = false; + + // --- MOD0 detection --- + if (text_offset < fileSz && mod0_rel != 0 && text_offset <= fileSz - mod0_rel) { + const uint32_t mod0_offset = text_offset + mod0_rel; + + // --- MOD0 is inside front buffer --- + if (mod0_offset <= frontReadSize - 60) { + const uint8_t* mod0_ptr = frontBuf + mod0_offset; + if (memcmp(mod0_ptr, "MOD0", 4) == 0 && + memcmp(mod0_ptr + 52, "LNY2", 4) == 0) { + isNew = (*reinterpret_cast(mod0_ptr + 56) >= 1); + } + } + // --- MOD0 must be read separately --- + else if (mod0_offset <= fileSz - 60) { + uint8_t mod0Buf[60]; + fseek(file, mod0_offset, SEEK_SET); + if (fread(mod0Buf, 1, 60, file) == 60) { + if (memcmp(mod0Buf, "MOD0", 4) == 0 && + memcmp(mod0Buf + 52, "LNY2", 4) == 0) { + isNew = (*reinterpret_cast(mod0Buf + 56) >= 1); + } + } + } + } + + free(frontBuf); + fclose(file); + return isNew; +} + +namespace tsl { + +// --------------------------------------------------------------------------- +// Theme color variables +// --------------------------------------------------------------------------- + +Color logoColor1; +Color logoColor2; + +size_t defaultBackgroundAlpha = 0; +Color defaultBackgroundColor; +Color defaultTextColor; +Color notificationTextColor; +Color notificationTitleColor; +Color notificationTimeColor; +Color headerTextColor; +Color headerSeparatorColor; +Color starColor; +Color selectionStarColor; +Color buttonColor; +Color bottomTextColor; +Color bottomSeparatorColor; +Color unfocusedColor; +Color topSeparatorColor; + +Color defaultOverlayColor; +Color defaultPackageColor; +Color defaultScriptColor; +Color clockColor; +Color temperatureColor; +Color batteryColor; +Color batteryChargingColor; +Color batteryLowColor; +size_t widgetBackdropAlpha = 0; +Color widgetBackdropColor; + +Color overlayTextColor; +Color ultOverlayTextColor; +Color packageTextColor; +Color ultPackageTextColor; + +Color bannerVersionTextColor; +Color overlayVersionTextColor; +Color ultOverlayVersionTextColor; +Color packageVersionTextColor; +Color ultPackageVersionTextColor; +Color onTextColor; +Color offTextColor; + +#if IS_LAUNCHER_DIRECTIVE +Color dynamicLogoRGB1; +Color dynamicLogoRGB2; +#endif + +bool invertBGClickColor = false; + +size_t selectionBGAlpha = 0; +Color selectionBGColor; + +Color highlightColor1; +Color highlightColor2; +Color highlightColor3; +Color highlightColor4; + +// Has a meaningful default — initialized to ColorHighlight +Color s_highlightColor = tsl::style::color::ColorHighlight; + +size_t clickAlpha = 0; +Color clickColor; + +size_t progressAlpha = 0; +Color progressColor; + +Color scrollBarColor; +Color scrollBarWallColor; + +size_t separatorAlpha = 0; +Color separatorColor; + +// Constant — initialized once here via RGB888() +const Color edgeSeparatorColor = RGB888("303030"); + +Color textSeparatorColor; + +Color selectedTextColor; +Color selectedValueTextColor; +Color inprogressTextColor; +Color invalidTextColor; +Color clickTextColor; + +size_t tableBGAlpha = 0; +Color tableBGColor; +Color sectionTextColor; +Color infoTextColor; +Color warningTextColor; + +Color healthyRamTextColor; +Color neutralRamTextColor; +Color badRamTextColor; + +Color trackBarSliderColor; +Color trackBarSliderBorderColor; +Color trackBarSliderMalleableColor; +Color trackBarFullColor; +Color trackBarEmptyColor; + + +// Prepare a map of default settings +constexpr ThemeDefault defaultThemeSettings[] = { + // Must stay sorted alphabetically for binary search + {"bad_ram_text_color", "FF0000"}, + {"banner_version_text_color", "AAAAAA"}, + {"battery_charging_color", "00FF00"}, + {"battery_color", "FFFF45"}, + {"battery_low_color", "FF0000"}, + {"bg_alpha", "13"}, + {"bg_color", "000000"}, + {"bottom_button_color", "FFFFFF"}, + {"bottom_separator_color", "FFFFFF"}, + {"bottom_text_color", "FFFFFF"}, + {"unfocused_color", "666666"}, + {"click_alpha", "7"}, + {"click_color", "3E25F7"}, + {"click_text_color", "FFFFFF"}, + {"clock_color", "FFFFFF"}, + {"default_overlay_color", "FFFFFF"}, + {"default_package_color", "FFFFFF"}, + {"default_script_color", "FF33FF"}, + {"dynamic_logo_color_1", "00E669"}, + {"dynamic_logo_color_2", "8080EA"}, + {"header_separator_color", "FFFFFF"}, + {"header_text_color", "FFFFFF"}, + {"healthy_ram_text_color", "00FF00"}, + {"highlight_color_1", "2288CC"}, + {"highlight_color_2", "88FFFF"}, + {"highlight_color_3", "FFFF45"}, + {"highlight_color_4", "F7253E"}, + {"inprogress_text_color", "FFFF45"}, + {"invalid_text_color", "FF0000"}, + {"invert_bg_click_color", "false"}, + {"logo_color_1", "FFFFFF"}, + {"logo_color_2", "FF0000"}, + {"neutral_ram_text_color", "FFAA00"}, + {"notification_text_color", "FFFFFF"}, + {"notification_title_color", "FFFFFF"}, + {"notification_time_color", "AAAAAA"}, + {"off_text_color", "AAAAAA"}, + {"on_text_color", "00FFDD"}, + {"overlay_text_color", "FFFFFF"}, + {"overlay_version_text_color", "AAAAAA"}, + {"package_text_color", "FFFFFF"}, + {"package_version_text_color", "AAAAAA"}, + {"progress_alpha", "7"}, + {"progress_color", "253EF7"}, + {"scrollbar_color", "555555"}, + {"scrollbar_wall_color", "AAAAAA"}, + {"selection_bg_alpha", "11"}, + {"selection_bg_color", "000000"}, + {"selection_star_color", "FFFFFF"}, + {"selection_text_color", "9ED0FF"}, + {"selection_value_text_color", "FF7777"}, + {"separator_alpha", "15"}, + {"separator_color", "404040"}, + {"star_color", "FFFFFF"}, + {"table_bg_alpha", "14"}, + {"table_bg_color", "2C2C2C"}, + {"table_info_text_color", "9ED0FF"}, + {"table_section_text_color", "FFFFFF"}, + {"temperature_color", "FFFFFF"}, + {"text_color", "FFFFFF"}, + {"text_separator_color", "404040"}, + {"top_separator_color", "404040"}, + {"trackbar_empty_color", "404040"}, + {"trackbar_full_color", "00FFDD"}, + {"trackbar_slider_border_color", "505050"}, + {"trackbar_slider_color", "606060"}, + {"trackbar_slider_malleable_color", "A0A0A0"}, + {"ult_overlay_text_color", "9ED0FF"}, + {"ult_overlay_version_text_color", "00FFDD"}, + {"ult_package_text_color", "9ED0FF"}, + {"ult_package_version_text_color", "00FFDD"}, + {"warning_text_color", "FF7777"}, + {"widget_backdrop_alpha", "15"}, + {"widget_backdrop_color", "000000"}, +}; +const size_t defaultThemeSettingsCount = sizeof(defaultThemeSettings) / sizeof(defaultThemeSettings[0]); + +const char* getThemeDefault(const char* key) { + size_t lo = 0, hi = defaultThemeSettingsCount; + while (lo < hi) { + const size_t mid = (lo + hi) / 2; + const int cmp = strcmp(defaultThemeSettings[mid].key, key); + if (cmp == 0) return defaultThemeSettings[mid].value; + if (cmp < 0) lo = mid + 1; + else hi = mid; + } + return ""; +} + + +bool isValidHexColor(std::string_view s) { + if (s.size() != 6) return false; + for (char c : s) if (!isxdigit(c)) return false; + return true; +} + + +// --------------------------------------------------------------------------- +// initializeThemeVars +// Reads theme INI and populates all color vars above. +// Falls through to getThemeDefault() for any missing key so colors are always +// valid even when no theme file exists. +// --------------------------------------------------------------------------- +void initializeThemeVars() { + auto themeData = ult::getParsedDataFromIniFile(ult::THEME_CONFIG_INI_PATH); + + auto getValue = [&](const char* key) -> const char* { + auto sectionIt = themeData.find(ult::THEME_STR); + if (sectionIt != themeData.end()) { + auto it = sectionIt->second.find(key); + if (it != sectionIt->second.end()) return it->second.c_str(); + } + return getThemeDefault(key); + }; + + auto getColor = [&](const char* key, size_t alpha = 15) { + return RGB888(getValue(key), alpha); + }; + + auto getAlpha = [&](const char* key) { + return ult::stoi(getValue(key)); + }; + + + logoColor1 = getColor("logo_color_1"); + logoColor2 = getColor("logo_color_2"); + + #if IS_LAUNCHER_DIRECTIVE + dynamicLogoRGB1 = getColor("dynamic_logo_color_1"); + dynamicLogoRGB2 = getColor("dynamic_logo_color_2"); + #endif + + defaultBackgroundAlpha = getAlpha("bg_alpha"); + defaultBackgroundColor = getColor("bg_color", defaultBackgroundAlpha); + defaultTextColor = getColor("text_color"); + notificationTextColor = getColor("notification_text_color"); + notificationTitleColor = getColor("notification_title_color"); + notificationTimeColor = getColor("notification_time_color"); + headerTextColor = getColor("header_text_color"); + headerSeparatorColor = getColor("header_separator_color"); + starColor = getColor("star_color"); + selectionStarColor = getColor("selection_star_color"); + buttonColor = getColor("bottom_button_color"); + bottomTextColor = getColor("bottom_text_color"); + bottomSeparatorColor = getColor("bottom_separator_color"); + unfocusedColor = getColor("unfocused_color"); + topSeparatorColor = getColor("top_separator_color"); + defaultOverlayColor = getColor("default_overlay_color"); + defaultPackageColor = getColor("default_package_color"); + defaultScriptColor = getColor("default_script_color"); + clockColor = getColor("clock_color"); + temperatureColor = getColor("temperature_color"); + batteryColor = getColor("battery_color"); + batteryChargingColor = getColor("battery_charging_color"); + batteryLowColor = getColor("battery_low_color"); + widgetBackdropAlpha = getAlpha("widget_backdrop_alpha"); + widgetBackdropColor = getColor("widget_backdrop_color", widgetBackdropAlpha); + overlayTextColor = getColor("overlay_text_color"); + ultOverlayTextColor = getColor("ult_overlay_text_color"); + packageTextColor = getColor("package_text_color"); + ultPackageTextColor = getColor("ult_package_text_color"); + bannerVersionTextColor = getColor("banner_version_text_color"); + overlayVersionTextColor = getColor("overlay_version_text_color"); + ultOverlayVersionTextColor = getColor("ult_overlay_version_text_color"); + packageVersionTextColor = getColor("package_version_text_color"); + ultPackageVersionTextColor = getColor("ult_package_version_text_color"); + onTextColor = getColor("on_text_color"); + offTextColor = getColor("off_text_color"); + invertBGClickColor = (getValue("invert_bg_click_color") == ult::TRUE_STR); + selectionBGAlpha = getAlpha("selection_bg_alpha"); + selectionBGColor = getColor("selection_bg_color", selectionBGAlpha); + highlightColor1 = getColor("highlight_color_1"); + highlightColor2 = getColor("highlight_color_2"); + highlightColor3 = getColor("highlight_color_3"); + highlightColor4 = getColor("highlight_color_4"); + clickAlpha = getAlpha("click_alpha"); + clickColor = getColor("click_color", clickAlpha); + progressAlpha = getAlpha("progress_alpha"); + progressColor = getColor("progress_color", progressAlpha); + scrollBarColor = getColor("scrollbar_color"); + scrollBarWallColor = getColor("scrollbar_wall_color"); + separatorAlpha = getAlpha("separator_alpha"); + separatorColor = getColor("separator_color", separatorAlpha); + textSeparatorColor = getColor("text_separator_color"); + selectedTextColor = getColor("selection_text_color"); + selectedValueTextColor = getColor("selection_value_text_color"); + inprogressTextColor = getColor("inprogress_text_color"); + invalidTextColor = getColor("invalid_text_color"); + clickTextColor = getColor("click_text_color"); + tableBGAlpha = getAlpha("table_bg_alpha"); + tableBGColor = getColor("table_bg_color", tableBGAlpha); + sectionTextColor = getColor("table_section_text_color"); + infoTextColor = getColor("table_info_text_color"); + warningTextColor = getColor("warning_text_color"); + healthyRamTextColor = getColor("healthy_ram_text_color"); + neutralRamTextColor = getColor("neutral_ram_text_color"); + badRamTextColor = getColor("bad_ram_text_color"); + trackBarSliderColor = getColor("trackbar_slider_color"); + trackBarSliderBorderColor = getColor("trackbar_slider_border_color"); + trackBarSliderMalleableColor = getColor("trackbar_slider_malleable_color"); + trackBarFullColor = getColor("trackbar_full_color"); + trackBarEmptyColor = getColor("trackbar_empty_color"); +} + + +void initializeTheme(const std::string& themeIniPath) { + auto themeData = ult::getParsedDataFromIniFile(themeIniPath); + auto& themeSection = themeData[ult::THEME_STR]; + bool needsUpdate = false; + + const bool hasThemeSection = ult::isFile(themeIniPath) && (themeData.count(ult::THEME_STR) > 0); + for (size_t i = 0; i < tsl::defaultThemeSettingsCount; ++i) { + const auto& setting = tsl::defaultThemeSettings[i]; + if (!hasThemeSection || themeSection.count(setting.key) == 0) { + themeSection[setting.key] = setting.value; + needsUpdate = true; + } + } + + if (needsUpdate) + ult::saveIniFileData(themeIniPath, themeData); + if (!ult::isDirectory(ult::THEMES_PATH)) + ult::createDirectory(ult::THEMES_PATH); +} + + +namespace gfx { + + // Updated thread-safe calculateStringWidth function + float calculateStringWidth(const std::string& originalString, const float fontSize, const bool monospace) { + if (originalString.empty() || !FontManager::isInitialized()) { + return 0.0f; + } + + // Thread-safe translation cache access + std::string text; + { + std::shared_lock readLock(s_translationCacheMutex); + auto translatedIt = ult::translationCache.find(originalString); + if (translatedIt != ult::translationCache.end()) { + text = translatedIt->second; + } else { + // Don't insert anything, just fallback to original string + text = originalString; + } + } + + // CRITICAL: Use the same data types as drawString + s32 maxWidth = 0; + s32 currentLineWidth = 0; + ssize_t codepointWidth; + u32 currCharacter = 0; + + // Convert fontSize to u32 to match drawString behavior + const u32 fontSizeInt = static_cast(fontSize); + + auto itStrEnd = text.cend(); + auto itStr = text.cbegin(); + + // Fast ASCII check + bool isAsciiOnly = true; + for (unsigned char c : text) { + if (c > 127) { + isAsciiOnly = false; + break; + } + } + + while (itStr != itStrEnd) { + // Decode UTF-8 codepoint + if (isAsciiOnly) { + currCharacter = static_cast(*itStr); + codepointWidth = 1; + } else { + codepointWidth = decode_utf8(&currCharacter, reinterpret_cast(&(*itStr))); + if (codepointWidth <= 0) break; + } + + itStr += codepointWidth; + + // Handle newlines + if (currCharacter == '\n') { + maxWidth = std::max(currentLineWidth, maxWidth); + currentLineWidth = 0; + continue; + } + + // Use u32 fontSize to match drawString - now thread-safe + std::shared_ptr glyph = FontManager::getOrCreateGlyph(currCharacter, monospace, fontSizeInt); + if (!glyph) continue; + + // CRITICAL: Use the same calculation as drawString + currentLineWidth += static_cast(glyph->xAdvance * glyph->currFontSize); + } + + // Final width calculation + maxWidth = std::max(currentLineWidth, maxWidth); + return static_cast(maxWidth); + } +} + +namespace hlp { + + /** + * @brief Toggles focus between the Tesla overlay and the rest of the system + * + * @param enabled Focus Tesla? + */ + void requestForeground(bool enabled, bool updateGlobalFlag) { + if (updateGlobalFlag) + ult::currentForeground.store(enabled, std::memory_order_release); + + u64 applicationAruid = 0, appletAruid = 0; + + for (u64 programId = 0x0100000000001000UL; programId < 0x0100000000001020UL; programId++) { + pmdmntGetProcessId(&appletAruid, programId); + + if (appletAruid != 0) + hidsysEnableAppletToGetInput(!enabled, appletAruid); + } + + + pmdmntGetApplicationProcessId(&applicationAruid); + hidsysEnableAppletToGetInput(!enabled, applicationAruid); + + hidsysEnableAppletToGetInput(true, 0); + } + + namespace ini { + /** + * @brief Unparses ini data into a string + * + * @param iniData Ini data + * @return Ini string + */ + std::string unparseIni(const IniData &iniData) { + std::string result; + bool addSectionGap = false; + + for (const auto §ion : iniData) { + if (addSectionGap) { + result += '\n'; + } + result += '[' + section.first + "]\n"; + for (const auto &keyValue : section.second) { + result += keyValue.first + '=' + keyValue.second + '\n'; + } + addSectionGap = true; + } + + return result; + } + } + + /** + * @brief Encodes key codes into a combo string + * + * @param keys Key codes + * @return Combo string + */ + std::string keysToComboString(u64 keys) { + if (keys == 0) return ""; // Early return for empty input + + std::string result; + bool first = true; + + for (const auto &keyInfo : ult::KEYS_INFO) { + if (keys & keyInfo.key) { + if (!first) { + result += "+"; + } + result += keyInfo.name; + first = false; + } + } + + return result; + } + + // Function to load key combo mappings from both overlays.ini and packages.ini + void loadEntryKeyCombos() { + std::lock_guard lock(comboMutex); + ult::g_entryCombos.clear(); + + // Load overlay combos from overlays.ini + auto overlayData = ult::getParsedDataFromIniFile(ult::OVERLAYS_INI_FILEPATH); + std::string fullPath; + u64 keys; + + std::vector modeList, comboList; + for (auto& [fileName, settings] : overlayData) { + fullPath = ult::OVERLAY_PATH + fileName; + + // 1) main key_combo + if (auto it = settings.find(ult::KEY_COMBO_STR); it != settings.end() && !it->second.empty()) { + keys = hlp::comboStringToKeys(it->second); + if (keys) ult::g_entryCombos[keys] = { fullPath, "" }; + } + + // 2) per-mode combos + auto modesIt = settings.find("mode_args"); + auto argsIt = settings.find("mode_combos"); + if (modesIt != settings.end()) { + modeList = ult::splitIniList(modesIt->second); + comboList = (argsIt != settings.end()) + ? ult::splitIniList(argsIt->second) + : std::vector(); + if (comboList.size() < modeList.size()) + comboList.resize(modeList.size()); + + for (size_t i = 0; i < modeList.size(); ++i) { + const std::string& comboStr = comboList[i]; + if (comboStr.empty()) continue; + keys = hlp::comboStringToKeys(comboStr); + if (!keys) continue; + // launchArg is the *mode* (i.e. modeList[i]) + ult::g_entryCombos[keys] = { fullPath, modeList[i] }; + } + } + } + + // Load package combos from packages.ini + auto packageData = ult::getParsedDataFromIniFile(ult::PACKAGES_INI_FILEPATH); + for (auto& [packageName, settings] : packageData) { + // Only handle main key_combo for packages (no modes for packages) + if (auto it = settings.find(ult::KEY_COMBO_STR); it != settings.end() && !it->second.empty()) { + keys = hlp::comboStringToKeys(it->second); + if (keys) ult::g_entryCombos[keys] = { ult::OVERLAY_PATH + "ovlmenu.ovl", "--package " + packageName}; + } + } + } +} + +namespace impl { + /** + * @brief Extract values from Tesla settings file + * + */ + void parseOverlaySettings() { + const auto section = ult::getKeyValuePairsFromSection( + ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME); + + auto getBool = [&](const char* key, bool def = false) -> bool { + auto it = section.find(key); + if (it == section.end() || it->second.empty()) return def; + return it->second != ult::FALSE_STR; + }; + auto getStr = [&](const char* key, const char* def = "") -> std::string { + auto it = section.find(key); + return (it != section.end() && !it->second.empty()) ? it->second : def; + }; + + // Key combo — ultrahand first, tesla as fallback + u64 decodedKeys = hlp::comboStringToKeys(getStr(ult::KEY_COMBO_STR.c_str())); + if (!decodedKeys) + decodedKeys = hlp::comboStringToKeys( + ult::parseValueFromIniSection(ult::TESLA_CONFIG_INI_PATH, ult::TESLA_STR, ult::KEY_COMBO_STR)); + if (decodedKeys) tsl::cfg::launchCombo = decodedKeys; + + // Datetime format + ult::datetimeFormat = getStr("datetime_format", ult::DEFAULT_DT_FORMAT.c_str()); + ult::removeQuotes(ult::datetimeFormat); + if (ult::datetimeFormat.empty()) ult::datetimeFormat = ult::DEFAULT_DT_FORMAT; + + // Language + std::string lang = getStr(ult::DEFAULT_LANG_STR.c_str(), "en"); + if (lang.empty()) lang = "en"; + + #ifdef UI_OVERRIDE_PATH + { + std::string UI_PATH = UI_OVERRIDE_PATH; + ult::preprocessPath(UI_PATH); + ult::createDirectory(UI_PATH); + const std::string langOverride = UI_PATH + "lang/" + lang + ".json"; + if (ult::isFile(UI_PATH + "theme.ini")) ult::THEME_CONFIG_INI_PATH = UI_PATH + "theme.ini"; + if (ult::isFile(UI_PATH + "wallpaper.rgba")) ult::WALLPAPER_PATH = UI_PATH + "wallpaper.rgba"; + if (ult::isFile(langOverride)) ult::loadTranslationsFromJSON(langOverride); + } + #endif + + // Behavior flags — shared across all overlays + ult::useLaunchCombos = getBool("launch_combos", true); + ult::useNotifications = getBool("notifications", true); + ult::useNotificationsHotkey = getBool("notifications_hotkey", true); + ult::silenceNotifications = getBool("silence_notifications"); + ult::useSoundEffects = getBool("sound_effects", true); + ult::useHapticFeedback = getBool("haptic_feedback"); + ult::useSwipeToOpen = getBool("swipe_to_open", true); + ult::useOpaqueScreenshots = getBool("opaque_screenshots", true); + + // max_notifications — default to 3 so it's always clamped correctly + { + const std::string maxStr = getStr("max_notifications", "3"); + const int cap = ult::limitedMemory ? 4 : tsl::NotificationPrompt::MAX_VISIBLE; + tsl::maxNotifications = std::max(1, std::min(ult::stoi(maxStr), cap)); + } + + // Widget / display flags — shared + ult::hideClock = getBool("hide_clock"); + ult::hideBattery = getBool("hide_battery", true); + ult::hidePCBTemp = getBool("hide_pcb_temp", true); + ult::hideSOCTemp = getBool("hide_soc_temp", true); + ult::dynamicWidgetColors = getBool("dynamic_widget_colors", true); + ult::hideWidgetBackdrop = getBool("hide_widget_backdrop"); + ult::centerWidgetAlignment = getBool("center_widget_alignment", true); + ult::extendedWidgetBackdrop = getBool("extended_widget_backdrop"); + ult::useDynamicLogo = getBool("dynamic_logo", true); + ult::useSelectionBG = getBool("selection_bg", true); + ult::useSelectionText = getBool("selection_text"); + ult::useSelectionValue = getBool("selection_value"); + + #if IS_LAUNCHER_DIRECTIVE + // Launcher-only vars that live in ult:: or global scope — readable here + hideHidden = getBool("hide_hidden"); + ult::usePageSwap = getBool("page_swap"); + ult::useRightAlignment = getBool("right_alignment"); + #endif + + // Notifications flag file + if (ult::useNotifications) { + if (!ult::isFile(ult::NOTIFICATIONS_FLAG_FILEPATH)) + if (FILE* f = fopen(ult::NOTIFICATIONS_FLAG_FILEPATH.c_str(), "w")) fclose(f); + } else { + ult::deleteFileOrDirectory(ult::NOTIFICATIONS_FLAG_FILEPATH); + } + + // Theme and language + const std::string langFile = ult::LANG_PATH + lang + ".json"; + if (ult::isFile(langFile)) ult::parseLanguage(langFile); + else ult::reinitializeLangVars(); + + tsl::initializeTheme(); + tsl::initializeThemeVars(); + } +} + +// Max notifications cap (max value of 4 on limited memory, 8 otherwise) +int maxNotifications = 3; + + + +// Returns true for scripts where every character is a standalone word unit +static bool isWordPerCharScript(u32 cp) { + return (cp >= 0x1100 && cp <= 0x11FF) // Hangul Jamo + || (cp >= 0x2E80 && cp <= 0x2FFF) // CJK radicals, Kangxi + || (cp >= 0x3000 && cp <= 0x303F) // CJK symbols & punctuation + || (cp >= 0x3040 && cp <= 0x30FF) // Hiragana + Katakana + || (cp >= 0x3100 && cp <= 0x318F) // Bopomofo + Hangul compat jamo + || (cp >= 0x3200 && cp <= 0x33FF) // Enclosed/compat CJK + || (cp >= 0x3400 && cp <= 0x4DBF) // CJK extension A + || (cp >= 0x4E00 && cp <= 0x9FFF) // CJK unified ideographs + || (cp >= 0xA000 && cp <= 0xA4FF) // Yi + || (cp >= 0xA960 && cp <= 0xA97F) // Hangul Jamo extended A + || (cp >= 0xAC00 && cp <= 0xD7FF) // Hangul syllables + Jamo extended B + || (cp >= 0xF900 && cp <= 0xFAFF) // CJK compatibility ideographs + || (cp >= 0xFE30 && cp <= 0xFE4F) // CJK compatibility forms + || (cp >= 0x20000 && cp <= 0x2A6DF) // CJK extension B + || (cp >= 0x2A700 && cp <= 0x2CEAF) // CJK extensions C/D/E + || (cp >= 0x2CEB0 && cp <= 0x2EBEF) // CJK extension F + || (cp >= 0x30000 && cp <= 0x3134F); // CJK extension G +} + +static bool isLineStartForbidden(u32 cp) { + switch (cp) { + case 0x3001: case 0x3002: case 0xFF0C: case 0xFF0E: + case 0xFF1A: case 0xFF1B: case 0xFF01: case 0xFF1F: + case 0x30FB: case 0xFF65: case 0xFF09: case 0x3015: + case 0x3011: case 0x3009: case 0x300B: case 0x3003: + case 0x300D: case 0x300F: case 0x2026: case 0x2014: + case 0xFF5D: case 0x30FC: + return true; + default: + return false; + } +} + +std::vector wrapText( + const std::string& text, + float maxWidth, + const std::string& wrappingMode, + bool useIndent, + const std::string& indent, + float indentWidth, + size_t fontSize +) { + if (wrappingMode == "none" || (wrappingMode != "char" && wrappingMode != ult::WORD_STR)) + return { text }; + + std::vector wrappedLines; + bool firstLine = true; + std::string currentLine; + + auto getLeadingSpaces = [&]() -> size_t { + if (wrappedLines.empty()) return 0; + const std::string& s = wrappedLines.back(); + size_t i = 0; + while (i < s.size() && s[i] == ' ') ++i; + return i; + }; + + auto pushLine = [&](const std::string& line) { + if (useIndent && !firstLine) { + wrappedLines.push_back( + wrappedLines.back().substr(0, getLeadingSpaces()) + indent + line + ); + } else { + wrappedLines.push_back(line); + } + }; + + auto currentMaxWidth = [&]() -> float { + if (firstLine) return maxWidth; + if (!useIndent) return maxWidth - indentWidth; + const size_t spaces = getLeadingSpaces(); + const float gapWidth = tsl::gfx::calculateStringWidth( + wrappedLines.empty() ? "" : wrappedLines.back().substr(0, spaces), + fontSize, false + ); + return maxWidth - gapWidth - indentWidth; + }; + + // Shared helper: split a UTF-8 range [begin, end) character-by-character + // with simple trailing-hyphen logic. Used by word mode when a single word + // is too wide to fit on any line. The char-mode path is handled separately + // because it needs script-aware needsHyphen and isLineStartForbidden logic + // that diverges significantly from this simpler version. + auto splitLongWord = [&](std::string::const_iterator begin, + std::string::const_iterator end) { + auto it = begin; + while (it != end) { + u32 cp; + const ssize_t cw = decode_utf8(&cp, reinterpret_cast(&(*it))); + if (cw <= 0) break; + const std::string charStr(it, it + cw); + if (tsl::gfx::calculateStringWidth(currentLine + charStr, fontSize, false) > currentMaxWidth() + && !currentLine.empty()) { + const bool moreRemain = (it + cw) != end; + pushLine(moreRemain ? currentLine + '-' : currentLine); + currentLine = charStr; + firstLine = false; + } else { + currentLine += charStr; + } + it += cw; + } + }; + + if (wrappingMode == "char") { + static constexpr char hyphen = '-'; + u32 prevCharacter = 0; + u32 prevPrevCharacter = 0; + auto itStr = text.cbegin(); + const auto itStrEnd = text.cend(); + + while (itStr != itStrEnd) { + u32 currCharacter; + const ssize_t codepointWidth = decode_utf8(&currCharacter, reinterpret_cast(&(*itStr))); + if (codepointWidth <= 0) break; + + std::string charStr(itStr, itStr + codepointWidth); + const bool overflows = tsl::gfx::calculateStringWidth(currentLine + charStr, fontSize, false) > currentMaxWidth(); + + if (overflows && !currentLine.empty()) { + if (isLineStartForbidden(currCharacter)) { + pushLine(currentLine + charStr); + currentLine.clear(); + } else { + const bool needsHyphen = !useIndent + && (prevCharacter != ' ') + && (currCharacter != ' ') + && !isWordPerCharScript(prevCharacter) + && !isWordPerCharScript(currCharacter); + if (needsHyphen) { + std::string withHyphen = currentLine + hyphen; + if (tsl::gfx::calculateStringWidth(withHyphen, fontSize, false) > currentMaxWidth()) { + // Back off one codepoint to make room for the hyphen + auto it = currentLine.end(); + while (it != currentLine.begin()) { + --it; + if ((*it & 0xC0) != 0x80) break; + } + charStr = std::string(it, currentLine.end()) + charStr; + currentLine.erase(it, currentLine.end()); + withHyphen = (prevPrevCharacter != 0 && prevPrevCharacter != ' ') + ? currentLine + hyphen + : currentLine; + } + pushLine(withHyphen); + } else { + pushLine(currentLine); + } + currentLine = (currCharacter == ' ') ? std::string{} : charStr; + } + firstLine = false; + } else if (!overflows) { + currentLine += charStr; + } else { + // overflows but currentLine is empty — start fresh with this char + currentLine = charStr; + firstLine = false; + } + + prevPrevCharacter = prevCharacter; + prevCharacter = currCharacter; + itStr += codepointWidth; + } + } else { // word mode + ult::StringStream stream(text); + std::string currentWord; + std::string testLine; + + while (stream.getline(currentWord, ' ')) { + u32 firstCp = 0; + decode_utf8(&firstCp, reinterpret_cast(currentWord.c_str())); + + if (isWordPerCharScript(firstCp)) { + // CJK and similar scripts: every character is its own word unit + auto itW = currentWord.cbegin(); + const auto itWEnd = currentWord.cend(); + bool firstChar = true; + while (itW != itWEnd) { + u32 cp; + const ssize_t w = decode_utf8(&cp, reinterpret_cast(&(*itW))); + if (w <= 0) break; + std::string charStr(itW, itW + w); + testLine = currentLine; + if (firstChar && !testLine.empty()) testLine.push_back(' '); + testLine += charStr; + if (tsl::gfx::calculateStringWidth(testLine, fontSize, false) > currentMaxWidth()) { + if (!currentLine.empty()) { + pushLine(isLineStartForbidden(cp) ? currentLine + charStr : currentLine); + currentLine = isLineStartForbidden(cp) ? std::string{} : charStr; + } else { + currentLine = charStr; + } + firstLine = false; + } else { + currentLine = testLine; + } + firstChar = false; + itW += w; + } + } else { + testLine = currentLine; + if (!testLine.empty()) testLine.push_back(' '); + testLine += currentWord; + + if (tsl::gfx::calculateStringWidth(testLine, fontSize, false) > currentMaxWidth()) { + if (!currentLine.empty()) { + pushLine(currentLine); + currentLine.clear(); + firstLine = false; + } + // Word is too wide for any single line — split char-by-char with hyphenation + splitLongWord(currentWord.cbegin(), currentWord.cend()); + } else { + currentLine.swap(testLine); + } + } + } + } + + if (!currentLine.empty()) + pushLine(currentLine); + + return wrappedLines; +} + + +// ── NotificationPrompt out-of-line definitions ─────────────────────────────── + +static const std::string s_emptyStr; + +bool NotificationPrompt::hasActiveFile(std::string_view fname) const { + if (fname.empty()) return false; + if (isStale()) return false; + std::lock_guard lg(state_mutex_); + for (int i = 0; i < maxNotifications; ++i) + if ((slots_[i].flags & SLOT_ACTIVE) && slots_[i].data.fileName == fname) return true; + return false; +} + +int NotificationPrompt::findHitSlot_NoLock(s32 tx, s32 ty) const { + const s32 sx = (ult::useRightAlignment + ? static_cast(tsl::cfg::FramebufferWidth) - NOTIF_WIDTH + : 0) + static_cast(ult::layerEdge); + for (int i = 0; i < maxNotifications; ++i) { + const Slot& slot = slots_[i]; + if (!(slot.flags & SLOT_ACTIVE) || slot.data.state == PromptState::Inactive) continue; + const s32 sy = static_cast(slot.yCurrent); + const s32 sh = getEffectiveHeight(slot); + if (tx >= sx && tx < sx + NOTIF_WIDTH && + ty >= sy && ty < sy + sh) + return i; + } + return -1; +} + +void NotificationPrompt::draw(gfx::Renderer* renderer, bool promptOnly) { + if (isStale()) return; + if (!enabled_.load(std::memory_order_acquire)) return; + + std::lock_guard lg(state_mutex_); + const u64 now = ult::nowNs(); + + for (int i = 0; i < maxNotifications; ++i) { + const Slot& slot = slots_[i]; + if (!(slot.flags & SLOT_ACTIVE) || slot.data.text.empty() || + slot.data.state == PromptState::Inactive) continue; + + float fadeAlpha = 1.0f; + if (slot.data.state != PromptState::Visible) { + const float t = std::min(1.0f, + static_cast((now - slot.data.stateStartNs) / 1'000'000ULL) / FADE_DURATION_MS); + fadeAlpha = easeInOut(slot.data.state == PromptState::FadingIn ? t : 1.0f - t); + } + + drawSlot(renderer, slot, static_cast(slot.yCurrent), fadeAlpha, promptOnly); + } +} + +void NotificationPrompt::update() { + std::lock_guard lg(state_mutex_); + if (isStale()) { clearAll_NoLock(); return; } + if (ult::launchingOverlay.load(std::memory_order_acquire)) return; + + const u64 now = ult::nowNs(); + bool anyCleared = false; + + for (int i = 0; i < maxNotifications; ++i) { + Slot& slot = slots_[i]; + if (!(slot.flags & SLOT_ACTIVE)) continue; + + const bool outOfBounds = static_cast(slot.yTarget) + getEffectiveHeight(slot) + > static_cast(tsl::cfg::FramebufferHeight); + if (outOfBounds) { + slot.data.stateStartNs = now; + if (slot.data.durationMs != 0) + slot.data.expireNs = now + static_cast(slot.data.durationMs) * 1'000'000ULL + + FADE_DURATION_MS * 1'000'000ULL; + } else if (slot.flags & SLOT_SOUND_PENDING) { + slot.flags &= ~SLOT_SOUND_PENDING; + triggerNotificationSound.store(true, std::memory_order_release); + } + + if (slot.data.iconPending) { + slot.data.iconPending = false; + const std::string& fname = slot.data.fileName; + if (!fname.empty()) { + std::string base = fname; + const size_t dot = base.rfind('.'); + if (dot != std::string::npos) base.erase(dot); + const size_t dash = base.rfind('-'); + if (dash != std::string::npos) base.erase(dash); + const std::string iconPath = ult::NOTIFICATIONS_ICONS_PATH + base + ".rgba"; + slot.iconBuf = std::make_unique(NOTIF_ICON_BYTES); + if (ult::loadRGBA8888toRGBA4444(iconPath, slot.iconBuf.get(), + NOTIF_ICON_DIM * NOTIF_ICON_DIM * 4)) { + slot.flags |= SLOT_ICON_LOADED; + slot.data.hasIcon = true; + } else { + slot.iconBuf.reset(); + } + } + } + + if (slot.flags & SLOT_SLIDING) { + const float st = std::min(1.0f, + static_cast((now - slot.slideStartNs) / 1'000'000ULL) / SLIDE_DURATION_MS); + slot.yCurrent = slot.ySlideFrom + (slot.yTarget - slot.ySlideFrom) * easeInOut(st); + if (st >= 1.0f) { slot.yCurrent = slot.yTarget; slot.flags &= ~SLOT_SLIDING; } + } + + const u64 elapsedMs = slot.data.stateStartNs == 0 ? 0 + : (now - slot.data.stateStartNs) / 1'000'000ULL; + if (!outOfBounds) switch (slot.data.state) { + case PromptState::FadingIn: + if (elapsedMs >= FADE_DURATION_MS) { + slot.data.state = PromptState::Visible; + slot.data.stateStartNs = now; + } + break; + case PromptState::Visible: + if (now >= slot.data.expireNs) + startFadeOut(slot.data, now); + break; + case PromptState::FadingOut: + if (elapsedMs >= FADE_DURATION_MS) { + evictSlot_NoLock(i); + anyCleared = true; + } + break; + default: break; + } + } + + if (anyCleared) repackSlots_NoLock(now); + + while (!pending_queue_.empty()) { + int freeSlot = -1; + for (int i = 0; i < maxNotifications; ++i) + if (!(slots_[i].flags & SLOT_ACTIVE)) { freeSlot = i; break; } + if (freeSlot < 0) break; + NotifEntry next = pending_queue_.top(); + pending_queue_.pop(); + placeInSlot_NoLock(freeSlot, std::move(next), false, false); + } +} + +bool NotificationPrompt::isActive() const { + if (isStale()) return false; + std::lock_guard lg(state_mutex_); + for (int i = 0; i < maxNotifications; ++i) + if (slots_[i].flags & SLOT_ACTIVE) return true; + return !pending_queue_.empty(); +} + +int NotificationPrompt::activeCount() const { + if (isStale()) return 0; + std::lock_guard lg(state_mutex_); + int count = 0; + for (int i = 0; i < maxNotifications; ++i) + if (slots_[i].flags & SLOT_ACTIVE) ++count; + return count; +} + +void NotificationPrompt::shutdown() { + enabled_.store(false, std::memory_order_release); + notificationGeneration.fetch_add(1, std::memory_order_acq_rel); + generation_.store(notificationGeneration.load(std::memory_order_acquire), + std::memory_order_release); + std::lock_guard lg(state_mutex_); + clearAll_NoLock(); +} + +bool NotificationPrompt::hitTest(s32 tx, s32 ty) const { + if (isStale()) return false; + std::lock_guard lg(state_mutex_); + return findHitSlot_NoLock(tx, ty) >= 0; +} + +bool NotificationPrompt::dismissAt(s32 tx, s32 ty) { + if (isStale()) return false; + std::lock_guard lg(state_mutex_); + const int idx = findHitSlot_NoLock(tx, ty); + if (idx < 0) return false; + Slot& slot = slots_[idx]; + if (slot.data.state != PromptState::FadingOut) + startFadeOut(slot.data, ult::nowNs()); + return true; +} + +bool NotificationPrompt::dismissFront() { + if (isStale()) return false; + std::lock_guard lg(state_mutex_); + int best = -1; + float bestY = 1.0e9f; + for (int i = 0; i < maxNotifications; ++i) { + const Slot& slot = slots_[i]; + if (!(slot.flags & SLOT_ACTIVE) || slot.data.state == PromptState::FadingOut) continue; + if (slot.yCurrent < bestY) { bestY = slot.yCurrent; best = i; } + } + if (best < 0) return false; + startFadeOut(slots_[best].data, ult::nowNs()); + return true; +} + +NotificationPrompt::Lines +NotificationPrompt::getWrappedLines(const std::string& text, float pixelWidth, + size_t fontSize, u8 maxLines, + SplitType splitType) const { + const std::string& stStr = (splitType == SplitType::Char) ? ult::CHAR_STR : ult::WORD_STR; + + Lines split; + { + size_t start = 0; + while (start < text.size() && split.count < maxLines) { + size_t pos = text.find('\n', start); + const size_t pos2 = text.find("\\n", start); + if (pos2 != std::string::npos && (pos == std::string::npos || pos2 < pos)) pos = pos2; + if (pos == std::string::npos) { split.buf[split.count++] = text.substr(start); break; } + split.buf[split.count++] = text.substr(start, pos - start); + start = pos + (text[pos] == '\n' ? 1 : 2); + } + } + + Lines result; + for (u8 si = 0; si < split.count && result.count < maxLines; ++si) { + const auto wrapped = wrapText(split.buf[si], pixelWidth, + stStr, /*useIndent=*/false, s_emptyStr, 0.f, fontSize); + for (const auto& wl : wrapped) { + if (result.count >= maxLines) break; + result.buf[result.count++] = wl; + } + } + if (result.count == 0 && split.count > 0) + result.buf[result.count++] = ""; + return result; +} + +s32 NotificationPrompt::getEffectiveHeight(const Slot& slot) const { + if (slot.data.text.empty()) return NOTIF_HEIGHT; + + const IconGeom g = computeIconGeom(slot); + const bool hasTitleLayout = !slot.data.title.empty(); + + // Determine wrap width and line cap for the two layout modes + float wrapW; + u8 wrapMax; + if (hasTitleLayout) { + const s32 taw = g.hasIconCol ? g.textAreaW : (NOTIF_WIDTH - 2 * (g.baseIconPad + 2)); + wrapW = g.hasIconCol ? static_cast(taw - g.baseIconPad - 2) + : static_cast(taw); + wrapMax = 4; + } else { + wrapW = static_cast(g.textAreaW - 4); + wrapMax = 9; + } + + const Lines lines = getWrappedLines(slot.data.text, wrapW, slot.data.fontSize, wrapMax, + slot.data.splitType); + if (lines.count <= 1) return NOTIF_HEIGHT; + + const auto fm = tsl::gfx::FontManager::getFontMetricsForCharacter('A', slot.data.fontSize); + return NOTIF_HEIGHT + extraLinesHeight(static_cast(lines.count - 1), fm.lineHeight); +} + +void NotificationPrompt::placeInSlot_NoLock(int idx, NotifEntry&& e, + bool isShowNow, bool skipFadeIn, + bool suppressSound) { + const u64 now = ult::nowNs(); + + float ty = 0.f; + for (int i = 0; i < idx; ++i) + if (slots_[i].flags & SLOT_ACTIVE) ty += static_cast(getEffectiveHeight(slots_[i])); + + Slot& slot = slots_[idx]; + slot.data = std::move(e); + slot.data.state = skipFadeIn ? PromptState::Visible : PromptState::FadingIn; + slot.data.stateStartNs = now; + slot.data.expireNs = (slot.data.durationMs == 0) ? UINT64_MAX + : now + + (skipFadeIn ? 0ULL : FADE_DURATION_MS * 1'000'000ULL) + + slot.data.durationMs * 1'000'000ULL; + slot.data.hasIcon = false; + slot.data.iconPending = !slot.data.fileName.empty(); + slot.yTarget = ty; + slot.yCurrent = ty; + slot.iconBuf.reset(); + const bool placedInBounds = (ty + static_cast(NOTIF_HEIGHT) <= static_cast(tsl::cfg::FramebufferHeight)); + slot.flags = SLOT_ACTIVE + | (isShowNow ? SLOT_SHOW_NOW : 0) + | ((suppressSound && placedInBounds) ? 0 : SLOT_SOUND_PENDING); +} + +void NotificationPrompt::repackSlots_NoLock(u64 now) { + int order[MAX_VISIBLE]; + int count = 0; + + for (int i = 0; i < maxNotifications; ++i) + if ((slots_[i].flags & SLOT_ACTIVE) && (slots_[i].flags & SLOT_SHOW_NOW)) { order[count++] = i; break; } + for (int i = 0; i < maxNotifications && count < maxNotifications; ++i) + if ((slots_[i].flags & SLOT_ACTIVE) && !(slots_[i].flags & SLOT_SHOW_NOW)) order[count++] = i; + + float y = 0.f; + for (int i = 0; i < count; ++i) { + Slot& s = slots_[order[i]]; + if (s.yTarget != y || s.yCurrent != y) { + s.ySlideFrom = s.yCurrent; + s.yTarget = y; + s.slideStartNs = now; + s.flags |= SLOT_SLIDING; + } + y += static_cast(getEffectiveHeight(s)); + } + + for (int i = 0; i < count; ++i) { + if (order[i] == i) continue; + slots_[i] = std::move(slots_[order[i]]); + } + for (int i = count; i < maxNotifications; ++i) + slots_[i] = Slot{}; +} + +void NotificationPrompt::applyEllipsis(Lines& lines, u8 maxLines, + float pixelWidth, size_t fontSize, + gfx::Renderer* renderer) const { + if (maxLines == 0 || lines.count <= maxLines) return; + + std::string overflow = lines.buf[maxLines]; + lines.count = maxLines; + + std::string& last = lines.buf[maxLines - 1]; + last += ' '; + last += overflow; + while (!last.empty()) { + last += "..."; + if (static_cast(renderer->getNotificationTextDimensions(last, false, fontSize).first) <= pixelWidth) + return; + last.resize(last.size() - 4); + } + last = "..."; +} + +void NotificationPrompt::drawSlot(gfx::Renderer* renderer, const Slot& slot, + s32 baseY, float fadeAlpha, bool promptOnly) { + // Precompute all faded colours once — avoids applyAlpha+a2 overhead inside loops + auto fc = [renderer, fadeAlpha](Color c) { + return renderer->a2(applyAlpha(c, fadeAlpha)); + }; + const Color fadedBgColor = fc(defaultBackgroundColor); + const Color fadedTextColor = fc(notificationTextColor); + const Color fadedTitleColor = fc(notificationTitleColor); + const Color fadeTimeColor = fc(notificationTimeColor); + const Color fadedEdgeColor = fc(edgeSeparatorColor); + const Color fadedSeparatorColor = fc(separatorColor); + + // ── Layout geometry ────────────────────────────────────────────────────── + const s32 x = ult::useRightAlignment + ? (tsl::cfg::FramebufferWidth - NOTIF_WIDTH) : 0; + + const IconGeom g = computeIconGeom(slot, x); + const float innerWf = static_cast(g.textAreaW - g.baseIconPad - 2); + const s32 titleTextAreaX = g.hasIconCol ? g.textAreaX : x + (g.baseIconPad + 2); + const s32 titleTextAreaW = g.hasIconCol ? g.textAreaW : NOTIF_WIDTH - 2 * (g.baseIconPad + 2); + const float titleInnerWf = g.hasIconCol ? innerWf : static_cast(titleTextAreaW); + const u8 fontSize = slot.data.fontSize; + const Alignment alignment = slot.data.alignment; + const bool hasTitleIconLayout = !slot.data.text.empty() && !slot.data.title.empty(); + + // ── Line-wrap (single pass shared by height calculation and rendering) ─── + // Lines are wrapped and ellipsised here so effectiveHeight reflects the + // actual rendered line count, not the pre-ellipsis maximum. + Lines lines; + s32 effectiveHeight = NOTIF_HEIGHT; + + if (hasTitleIconLayout) { + lines = getWrappedLines(slot.data.text, titleInnerWf, fontSize, 5, slot.data.splitType); + applyEllipsis(lines, 4, titleInnerWf, fontSize, renderer); + if (lines.count > 1) { + const auto fm = tsl::gfx::FontManager::getFontMetricsForCharacter('A', fontSize); + effectiveHeight += extraLinesHeight(static_cast(lines.count - 1), fm.lineHeight); + } + } else if (!slot.data.text.empty() && g.textAreaW > 0) { + lines = getWrappedLines(slot.data.text, static_cast(g.textAreaW - 4), + fontSize, 9, slot.data.splitType); + applyEllipsis(lines, 8, static_cast(g.textAreaW - 4), fontSize, renderer); + if (lines.count > 1) { + const auto fm = tsl::gfx::FontManager::getFontMetricsForCharacter('A', fontSize); + effectiveHeight += extraLinesHeight(static_cast(lines.count - 1), fm.lineHeight); + } + } + + if (baseY + effectiveHeight > static_cast(tsl::cfg::FramebufferHeight)) return; + + // ── Background ─────────────────────────────────────────────────────────── + renderer->enableScissoring(static_cast(std::max(0, x)), + static_cast(std::max(0, baseY)), + static_cast(NOTIF_WIDTH), + static_cast(effectiveHeight)); + + #if IS_STATUS_MONITOR_DIRECTIVE + renderer->drawRect(x, baseY, NOTIF_WIDTH, effectiveHeight, fadedBgColor); + #else + if (!promptOnly && ult::expandedMemory) + renderer->drawRectMultiThreaded(x, baseY, NOTIF_WIDTH, effectiveHeight, fadedBgColor); + else + renderer->drawRect(x, baseY, NOTIF_WIDTH, effectiveHeight, fadedBgColor); + #endif + + // ── Icon ───────────────────────────────────────────────────────────────── + if (g.hasIconCol && slot.data.hasIcon && (slot.flags & SLOT_ICON_LOADED) && slot.iconBuf) { + const s32 dstX = x + g.baseIconPad; + const s32 iconVertPad = (effectiveHeight - NOTIF_ICON_DIM) / 2; + s32 drawH = NOTIF_ICON_DIM; + if (dstX + NOTIF_ICON_DIM > static_cast(tsl::cfg::FramebufferWidth)) + drawH = 0; + if (iconVertPad + baseY + drawH > static_cast(tsl::cfg::FramebufferHeight)) + drawH = static_cast(tsl::cfg::FramebufferHeight) - iconVertPad - baseY; + if (drawH > 0) + renderer->drawBitmapRGBA4444( + static_cast(dstX), static_cast(iconVertPad + baseY), + static_cast(NOTIF_ICON_DIM), static_cast(drawH), + slot.iconBuf.get(), fadeAlpha); + } + + // ── Text ───────────────────────────────────────────────────────────────── + if (!slot.data.text.empty() && g.textAreaW > 0) { + if (hasTitleIconLayout) { + const auto titleFm = tsl::gfx::FontManager::getFontMetricsForCharacter('A', TITLE_FONT); + const auto messageFm = tsl::gfx::FontManager::getFontMetricsForCharacter('A', fontSize); + const s32 innerW = static_cast(titleInnerWf); + const s32 lineCount = static_cast(lines.count); + const s32 lineStep = messageFm.lineHeight + 3; + static constexpr s32 LINE_GAP = 4; + // blockH = title row + gap + all message lines with inter-line spacing + const s32 blockH = titleFm.lineHeight + LINE_GAP + + (lineCount > 0 + ? lineCount * messageFm.lineHeight + + (lineCount - 1) * 3 + : 0); + const s32 originY = (effectiveHeight - blockH) / 2 + baseY; + const s32 titleY = originY + titleFm.ascent - 3 + 1; + const s32 messageY = originY + titleFm.lineHeight + LINE_GAP + messageFm.ascent + 1+2; + + #if IS_LAUNCHER_DIRECTIVE + if (slot.data.title.find(ult::CAPITAL_ULTRAHAND_PROJECT_NAME) != std::string::npos) + drawUltrahandLine(renderer, slot.data.title, titleTextAreaX, titleY, TITLE_FONT, fadeAlpha, notificationTitleColor); + else { + #endif + renderer->drawNotificationString(slot.data.title, false, + titleTextAreaX, titleY, TITLE_FONT, fadedTitleColor, + 0, true, &fadedSeparatorColor, &s_dividerSpecialChars); + #if IS_LAUNCHER_DIRECTIVE + } + #endif + + if (slot.data.showTime && slot.data.timestamp[0] != '\0') { + const s32 tsW = renderer->getNotificationTextDimensions( + slot.data.timestamp, false, TITLE_FONT).first; + const s32 tsRightEdge = x + NOTIF_WIDTH - g.baseIconPad - 2; + const s32 tsX = tsRightEdge - tsW; + if (tsX > titleTextAreaX) + renderer->drawNotificationString(slot.data.timestamp, false, + tsX, titleY, TITLE_FONT, fadeTimeColor); + } + + for (s32 li = 0; li < lineCount; ++li) { + s32 msgX; + if (alignment == Alignment::Left) { + msgX = titleTextAreaX; + } else { + const s32 lw = renderer->getNotificationTextDimensions(lines[li], false, fontSize).first; + msgX = (alignment == Alignment::Right) + ? titleTextAreaX + innerW - lw + : titleTextAreaX + (innerW - lw) / 2; + } + renderer->drawNotificationString(lines[li], false, msgX, + messageY + li * lineStep, fontSize, fadedTextColor, + 0, true, &fadedSeparatorColor, &s_dividerSpecialChars); + } + + } else { + const auto fm = tsl::gfx::FontManager::getFontMetricsForCharacter('A', fontSize); + const s32 lineCount = static_cast(lines.count); + // total pixel height of the text block including inter-line spacing + const s32 totalTextH = lineCount > 0 + ? lineCount * fm.lineHeight + (lineCount - 1) * 3 + : 0; + const s32 startY = (effectiveHeight - totalTextH) / 2 + fm.ascent + baseY; + const s32 padAdjust = g.hasIconCol ? g.baseIconPad + 2 : 0; + const s32 lineStep = fm.lineHeight + (lineCount > 1 ? 3 : 0); + const bool needsLineWidth = (alignment != Alignment::Left); + + auto alignedX = [&](s32 contentW) -> s32 { + if (alignment == Alignment::Left) return g.textAreaX + 2; + if (alignment == Alignment::Right) return g.textAreaX + g.textAreaW - contentW - padAdjust - 2; + return g.textAreaX + (g.textAreaW - contentW - padAdjust) / 2; + }; + + for (s32 li = 0; li < lineCount; ++li) { + const std::string& line = lines[li]; + const s32 lineY = startY + li * lineStep; + + #if IS_LAUNCHER_DIRECTIVE + const size_t up = line.find(ult::CAPITAL_ULTRAHAND_PROJECT_NAME); + if (up != std::string::npos) { + const std::string before = line.substr(0, up); + const std::string after = line.substr(up + ult::CAPITAL_ULTRAHAND_PROJECT_NAME.length()); + const std::string& hand = ult::SPLIT_PROJECT_NAME_2; + const s32 bw = before.empty() ? 0 : renderer->getNotificationTextDimensions(before, false, fontSize).first; + const s32 aw = after.empty() ? 0 : renderer->getNotificationTextDimensions(after, false, fontSize).first; + const s32 hw = renderer->getNotificationTextDimensions(hand, false, fontSize).first; + const s32 uw = tsl::elm::calculateUltraTextWidth(renderer, fontSize, true); + drawUltrahandLine(renderer, line, alignedX(bw + uw + hw + aw), lineY, fontSize, fadeAlpha); + } else + #endif + { + const s32 lw = needsLineWidth + ? renderer->getNotificationTextDimensions(line, false, fontSize).first + : 0; + renderer->drawNotificationString(line, false, + alignedX(lw), lineY, fontSize, fadedTextColor, + 0, true, &fadedSeparatorColor, &s_dividerSpecialChars); + } + } + } + } + + // ── Border ─────────────────────────────────────────────────────────────── + const s32 edgeX = ult::useRightAlignment ? x : x + NOTIF_WIDTH - 1; + renderer->drawRect(edgeX, baseY, 1, effectiveHeight, fadedEdgeColor); + renderer->drawRect(x, baseY + effectiveHeight - 1, NOTIF_WIDTH, 1, fadedEdgeColor); + renderer->disableScissoring(); +} + +#if IS_LAUNCHER_DIRECTIVE +void NotificationPrompt::drawUltrahandLine(gfx::Renderer* renderer, const std::string& line, + s32 x, s32 y, u32 fontSize, float fadeAlpha, + Color textColor) { + auto fc = [&](Color c) { return applyAlpha(c, fadeAlpha); }; + const size_t up = line.find(ult::CAPITAL_ULTRAHAND_PROJECT_NAME); + if (up == std::string::npos) { + const Color fadedSep = applyAlpha(separatorColor, fadeAlpha); + renderer->drawNotificationString(line, false, x, y, fontSize, fc(textColor), + 0, true, &fadedSep, &s_dividerSpecialChars); + return; + } + const std::string before = line.substr(0, up); + const std::string& hand = ult::SPLIT_PROJECT_NAME_2; + const std::string after = line.substr(up + ult::CAPITAL_ULTRAHAND_PROJECT_NAME.length()); + s32 bw = 0, hw = 0; + if (!before.empty()) bw = renderer->getNotificationTextDimensions(before, false, fontSize).first; + hw = renderer->getNotificationTextDimensions(hand, false, fontSize).first; + s32 curX = x; + if (!before.empty()) { + renderer->drawNotificationString(before, false, curX, y, fontSize, fc(textColor)); + curX += bw; + } + curX = tsl::elm::drawDynamicUltraText(renderer, curX, y, fontSize, fc(logoColor1), true); + renderer->drawNotificationString(hand, false, curX, y, fontSize, fc(logoColor2)); + curX += hw; + if (!after.empty()) + renderer->drawNotificationString(after, false, curX, y, fontSize, fc(textColor)); +} +#endif + +} // namespace tsl \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/LICENSE b/Source/hoc-clk/overlay/lib/libultrahand/libultra/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/README.md b/Source/hoc-clk/overlay/lib/libultrahand/libultra/README.md new file mode 100644 index 00000000..9966139d --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/README.md @@ -0,0 +1,69 @@ +# libultra + +![Ultrahand Logo](https://github.com/ppkantorski/Ultrahand-Overlay/blob/main/.pics/ultrahand.png) + + +## Overview + +`libultra` is a powerful collection of helper functions designed specifically for the Ultrahand Overlay project. This library offers a comprehensive set of utilities aimed at simplifying common tasks and enhancing the efficiency of your projects within the Ultrahand Overlay ecosystem. + +## Features + +### [Ultra Header](/libultra/include/ultra.hpp) + +- **ultra.hpp**: The main header file for the `libultra` library, including all essential functions and declarations for seamless integration into your projects. + +### [Debug Functions](/libultra/include/debug_funcs.hpp) + +- **debug_funcs.hpp**: A collection of functions tailored for debugging purposes, aiding in identifying and resolving issues within your codebase. + +### [Download Functions](/libultra/include/download_funcs.hpp) + +- **download_funcs.hpp**: Utilities for managing file downloads, enabling seamless retrieval of resources from external sources. + +### [Get Functions](/libultra/include/get_funcs.hpp) + +- **get_funcs.hpp**: Functions for retrieving data from various sources, simplifying the process of fetching information within your applications. + +### [Hex Functions](/libultra/include/hex_funcs.hpp) + +- **hex_funcs.hpp**: Tools for working with hexadecimal data, facilitating operations such as conversion and manipulation of hexadecimal values. + +### [INI Functions](/libultra/include/ini_funcs.hpp) + +- **ini_funcs.hpp**: Helper functions for handling INI configuration files, offering a convenient way to manage application settings. + +### [JSON Functions](/libultra/include/json_funcs.hpp) + +- **json_funcs.hpp**: Utilities for parsing and manipulating JSON data, providing easy integration with JSON-based APIs and services. + +### [List Functions](/libultra/include/list_funcs.hpp) + +- **list_funcs.hpp**: Functions for working with lists and arrays, offering essential operations like sorting, searching, and manipulation of list elements. + +### [Mod Functions](/libultra/include/mod_funcs.hpp) + +- **mod_funcs.hpp**: Functions for manipulating game mods, facilitating operations and management tasks related to modifications in gaming environments. + +### [Path Functions](/libultra/include/path_funcs.hpp) + +- **path_funcs.hpp**: Tools for working with file paths and directories, simplifying file system operations within your applications. + +### [String Functions](/libultra/include/string_funcs.hpp) + +- **string_funcs.hpp**: A collection of string manipulation functions, providing utilities for tasks such as formatting, searching, and modification of strings. + + +## Usage + +To build Ultrahand overlays with `libultra` + `libtesla`, simply add the `lib` folder to your project, then import `tesla.hpp`. + +## Contribution + +Contributions to `libultra` are welcome. If you have ideas for additional helper functions or improvements to existing ones, feel free to submit a pull request or open an issue on GitHub. + +## License + +Licensed under both [GPLv2](LICENSE) and [CC-BY-4.0](SUB_LICENSE). + +Copyright (c) 2024 ppkantorski diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE b/Source/hoc-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE new file mode 100644 index 00000000..2f244ac8 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/audio.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/audio.hpp new file mode 100644 index 00000000..e500b4a3 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/audio.hpp @@ -0,0 +1,126 @@ +/******************************************************************************** + * File: audio.hpp + * Author: ppkantorski + * Description: + * This header defines the Audio class and related structures used for + * handling sound playback within the Ultrahand Overlay. It provides interfaces + * for loading, caching, and playing WAV audio through libnx's audout service, + * along with basic sound type management and synchronization support. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2025-2026 ppkantorski + ********************************************************************************/ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include "tsl_utils.hpp" + +namespace ult { + class Audio { + public: + enum class SoundType : uint8_t { + Navigate, + Enter, + Exit, + Wall, + On, + Off, + Settings, + Move, + Notification, + Count + }; + + struct CachedSound { + // Compact raw PCM — native channel count, 16-bit, no volume applied. + // This is the only per-sound allocation. No pre-baked stereo copy is kept. + void* rawBuf = nullptr; + uint32_t rawSize = 0; // actual data bytes + uint32_t rawCap = 0; // allocated (aligned) bytes + uint32_t sampleRate = 48000; // native rate read from WAV header + bool isMono = false; + }; + + static bool initialize(); + static void exit(); + + static inline bool allSoundsExist() { + for (const auto& path : m_soundPaths) + if (!isFile(path)) return false; + return true; + } + + static void playSound(SoundType type); + + static inline void playNavigateSound() { playSound(SoundType::Navigate); } + static inline void playEnterSound() { playSound(SoundType::Enter); } + static inline void playExitSound() { playSound(SoundType::Exit); } + static inline void playWallSound() { playSound(SoundType::Wall); } + static inline void playOnSound() { playSound(SoundType::On); } + static inline void playOffSound() { playSound(SoundType::Off); } + static inline void playSettingsSound() { playSound(SoundType::Settings); } + static inline void playMoveSound() { playSound(SoundType::Move); } + static inline void playNotificationSound() { playSound(SoundType::Notification); } + + static void setMasterVolume(float volume); + static void setEnabled(bool enabled); + static bool isEnabled(); + static bool reloadIfDockedChanged(); + static void reloadAllSounds(); + static void unloadAllSounds(const std::initializer_list& excludeSounds = {}); + static std::mutex m_audioMutex; + + static bool m_initialized; + + private: + static std::atomic m_enabled; + static std::atomic m_masterVolumeFixed; // volume as 0–256 fixed-point + static bool m_lastDockedState; + static std::vector m_cachedSounds; + + // Single shared DMA playback buffer — sized to the largest sound's + // 48 kHz stereo output. Reused on every playSound(); safe because audout + // is always drained before the buffer is written. + static void* m_playBuf; + static uint32_t m_playBufCap; + static AudioOutBuffer m_audoutBuf; + + inline static constexpr const char* m_soundPaths[static_cast(SoundType::Count)] = { + "sdmc:/config/ultrahand/sounds/tick.wav", + "sdmc:/config/ultrahand/sounds/enter.wav", + "sdmc:/config/ultrahand/sounds/exit.wav", + "sdmc:/config/ultrahand/sounds/wall.wav", + "sdmc:/config/ultrahand/sounds/on.wav", + "sdmc:/config/ultrahand/sounds/off.wav", + "sdmc:/config/ultrahand/sounds/settings.wav", + "sdmc:/config/ultrahand/sounds/move.wav", + "sdmc:/config/ultrahand/sounds/notification.wav" + }; + + // Loads WAV into rawBuf (16-bit, native channels, no volume applied). + // Must be called under m_audioMutex. + static bool loadSoundFromWav(SoundType type, const char* path); + + // Ensures m_playBuf is large enough for the largest loaded sound's + // 48 kHz stereo output. Call after any load. Must hold m_audioMutex. + static void growPlayBuf(); + + // Renders rawBuf → m_playBuf on demand: resample to 48 kHz if needed, + // expand mono → stereo, apply current volume + dock attenuation. + // Returns actual output byte count written, or 0 on error. + // Must be called under m_audioMutex. + static uint32_t renderToPlayBuf(const CachedSound& s); + }; +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp new file mode 100644 index 00000000..4fb32836 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp @@ -0,0 +1,45 @@ +/******************************************************************************** + * File: debug_funcs.hpp + * Author: ppkantorski + * Description: + * This header file contains debugging functions for the Ultrahand Overlay project. + * These functions allow logging messages with timestamps to a log file. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include +#include + +namespace ult { + #if USING_LOGGING_DIRECTIVE + + // Specify the log file path + extern const std::string defaultLogFilePath; + + extern std::string logFilePath; // Declare logFilePath as extern + extern bool disableLogging; // Declare disableLogging as extern + + // Global mutex for thread-safe logging + extern std::mutex logMutex; // Declare logMutex as extern + + /** + * @brief Logs a message with a timestamp to a log file in a thread-safe manner. + * + * @param message The message to be logged. + */ + void logMessage(const char* message); + void logMessage(const std::string& message); + #endif +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp new file mode 100644 index 00000000..320b5419 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp @@ -0,0 +1,60 @@ +/******************************************************************************** + * File: download_funcs.hpp + * Author: ppkantorski + * Description: + * This header file contains functions for downloading and extracting files + * using libcurl and miniz. It includes functions for downloading files from URLs, + * writing received data to a file, and extracting files from ZIP archives. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include + +#include +#define CURL_DISABLE_DEFLATE +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +#include "global_vars.hpp" +#include "string_funcs.hpp" +#include "get_funcs.hpp" +#include "path_funcs.hpp" +#include "debug_funcs.hpp" + +namespace ult { + // Constants for buffer sizes + extern size_t DOWNLOAD_READ_BUFFER; + extern size_t DOWNLOAD_WRITE_BUFFER; + extern size_t UNZIP_READ_BUFFER; + extern size_t UNZIP_WRITE_BUFFER; + + // Thread-safe atomic flags for operation control + extern std::atomic abortDownload; + extern std::atomic abortUnzip; + extern std::atomic downloadPercentage; + extern std::atomic unzipPercentage; + + // Main API functions - thread-safe and optimized + bool downloadFile(const std::string& url, const std::string& toDestination, bool noSocketInit=false, bool noPercentagePolling=false); + bool unzipFile(const std::string& zipFilePath, const std::string& extractTo); +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp new file mode 100644 index 00000000..a6ea0a2a --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp @@ -0,0 +1,138 @@ +/******************************************************************************** + * File: get_funcs.hpp + * Author: ppkantorski + * Description: + * This header file contains functions for retrieving information and data + * from various sources, including file system and JSON files. It includes + * functions for obtaining overlay module information, reading file contents, + * and parsing JSON data. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#ifndef GET_FUNCS_HPP +#define GET_FUNCS_HPP + + +#include +#include +#include +#include "debug_funcs.hpp" +#include "string_funcs.hpp" + + +namespace ult { + struct DirCloser { + void operator()(DIR* dir) const { + if (dir) closedir(dir); + } + }; + + + /** + * @brief Concatenates the provided directory and file names to form a destination path. + * + * @param destinationDir The directory where the file should be placed. + * @param fileName The name of the file. + * @return The destination path as a string. + */ + std::string getDestinationPath(const std::string& destinationDir, const std::string& fileName); + + /** + * @brief Extracts the value part from a string line containing a key-value pair. + * + * @param line The string line containing a key-value pair (e.g., "key=value"). + * @return The extracted value as a string. If no value is found, an empty string is returned. + */ + std::string getValueFromLine(const std::string& line); + + + + /** + * @brief Extracts the name from a file path, including handling directories. + * + * @param path The file path from which to extract the name. + * @return The extracted name as a string. If the path indicates a directory, it extracts the last directory name. + * If the path is empty or no name is found, an empty string is returned. + */ + std::string getNameFromPath(const std::string& path); + + + + /** + * @brief Extracts the file name from a full file path. + * + * This function takes a filesystem path and returns only the file name, + * stripping away any directory paths that precede it. + * + * @param path The full path to the file. + * @return The file name extracted from the full path. + */ + std::string getFileName(const std::string& path); + + + + /** + * @brief Extracts the name of the parent directory from a given file path at a specified level. + * + * @param path The file path from which to extract the parent directory name. + * @param level The level of the parent directory to extract (0 for immediate parent, 1 for grandparent, and so on). + * @return The name of the parent directory at the specified level. + */ + std::string getParentDirNameFromPath(const std::string& path, size_t level = 0); + + + + /** + * @brief Extracts the parent directory path from a given file path. + * + * @param path The file path from which to extract the parent directory path. + * @return The parent directory path. + */ + std::string getParentDirFromPath(const std::string& path); + + + + /** + * @brief Gets a list of subdirectories in a directory. + * + * @param directoryPath The path of the directory to search. + * @return A vector of strings containing the names of subdirectories. + */ + std::vector getSubdirectories(const std::string& directoryPath); + + + /** + * @brief Recursively retrieves a list of files from a directory. + * + * @param directoryPath The path of the directory to search. + * @return A vector of strings containing the paths of the files. + */ + std::vector getFilesListFromDirectory(const std::string& directoryPath); + + + + void handleDirectory(const std::string& basePath, const std::vector& parts, size_t partIndex, std::vector& results, bool directoryOnly, size_t maxLines=0); + /** + * @brief Gets a list of files and folders based on a wildcard pattern. + * + * This function searches for files and folders in a directory that match the + * specified wildcard pattern. + * + * @param pathPattern The wildcard pattern to match files and folders. + * @return A vector of strings containing the paths of matching files and folders. + */ + std::vector getFilesListByWildcards(const std::string& pathPattern, size_t maxLines=0); + +} + +#endif \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp new file mode 100644 index 00000000..5b2476a9 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp @@ -0,0 +1,184 @@ +/******************************************************************************** + * File: global_vars.hpp + * Author: ppkantorski + * Description: + * This header file provides the definitions of global constants and paths used + * throughout the Ultrahand Overlay project. These constants are essential for + * file management and configuration settings within the application. + * + * For the latest updates and contributions, visit the project's GitHub repository: + * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay + * + * Note: This notice is integral to the project's documentation and must not be + * altered or removed. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include +#include + +// Auto-detect constexpr std::string support based on C++ version +#if __cplusplus >= 202400L + #define CONSTEXPR_STRING constexpr +#else + #define CONSTEXPR_STRING const +#endif + +namespace ult { + extern const std::string CONFIG_FILENAME; + + extern const std::string ULTRAHAND_PROJECT_NAME; + extern const std::string CAPITAL_ULTRAHAND_PROJECT_NAME; + + extern const std::string ROOT_PATH; + extern const std::string SETTINGS_PATH; + + extern const std::string NX_OVLLOADER_PATH; + extern const std::string OVL_HEAP_CONFIG_PATH; + extern const std::string OVL_EXIT_FLAG_PATH; + + extern const std::string ULTRAHAND_CONFIG_INI_PATH; + extern const std::string TESLA_CONFIG_INI_PATH; + extern const std::string LANG_PATH; + extern const std::string THEMES_PATH; + extern const std::string WALLPAPERS_PATH; + extern const std::string ASSETS_PATH; + extern const std::string SOUNDS_PATH; + extern const std::string LOADED_SOUNDS_PATH; + extern const std::string FLAGS_PATH; + extern const std::string NOTIFICATIONS_PATH; + extern const std::string NOTIFICATIONS_ICONS_PATH; + extern const std::string NOTIFICATIONS_FLAGS_PATH; + + extern const std::string PAYLOADS_PATH; + extern const std::string HB_APPSTORE_JSON; + + // Can be overriden with APPEARANCE_OVERRIDE_PATH directive + extern std::string THEME_CONFIG_INI_PATH; + extern std::string WALLPAPER_PATH; + + extern const std::string SPLIT_PROJECT_NAME_1; + extern const std::string SPLIT_PROJECT_NAME_2; + extern const std::string BOOT_PACKAGE_FILENAME; + extern const std::string EXIT_PACKAGE_FILENAME; + extern const std::string PACKAGE_FILENAME; + + extern const std::string DOWNLOADS_PATH; + + extern const std::string FUSE_DATA_INI_PATH; + extern const std::string PACKAGE_PATH; + extern const std::string OVERLAY_PATH; + extern const std::string OVERLAYS_INI_FILEPATH; + extern const std::string PACKAGES_INI_FILEPATH; + + extern const std::string NOTIFICATIONS_FLAG_FILEPATH; + extern const std::string RELOADING_FLAG_FILEPATH; + + extern const std::set PROTECTED_FILES; + + extern const std::string ULTRAHAND_REPO_URL; + extern const std::string INCLUDED_THEME_FOLDER_URL; + extern const std::string LATEST_RELEASE_INFO_URL; + extern const std::string LATEST_UPDATER_INI_URL; + extern const std::string UPDATER_PAYLOAD_URL; + + extern const std::string LAUNCH_ARGS_STR; + extern const std::string USE_LAUNCH_ARGS_STR; + extern const std::string USE_QUICK_LAUNCH_STR; + extern const std::string USE_BOOT_PACKAGE_STR; + extern const std::string USE_EXIT_PACKAGE_STR; + extern const std::string USE_LOGGING_STR; + + extern const std::string TESLA_COMBO_STR; + extern const std::string ULTRAHAND_COMBO_STR; + + extern const std::string FUSE_STR; + extern const std::string TESLA_STR; + extern const std::string ERISTA_STR; + extern const std::string MARIKO_STR; + extern const std::string HANDHELD_STR; + extern const std::string DOCKED_STR; + extern const std::string KEY_COMBO_STR; + extern const std::string DEFAULT_LANG_STR; + + + extern const std::string LIST_STR; + extern const std::string LIST_FILE_STR; + extern const std::string JSON_STR; + extern const std::string JSON_FILE_STR; + extern const std::string INI_FILE_STR; + extern const std::string HEX_FILE_STR; + extern const std::string PACKAGE_STR; + extern const std::string PACKAGES_STR; + extern const std::string OVERLAY_STR; + extern const std::string OVERLAYS_STR; + extern const std::string IN_OVERLAY_STR; + extern const std::string IN_HIDDEN_OVERLAY_STR; + extern const std::string IN_HIDDEN_PACKAGE_STR; + extern const std::string FILE_STR; + extern const std::string SYSTEM_STR; + extern const std::string MODE_STR; + extern const std::string GROUPING_STR; + extern const std::string FOOTER_STR; + extern const std::string FOOTER_HIGHLIGHT_STR; + extern const std::string TOGGLE_STR; + extern const std::string LEFT_STR; + extern const std::string RIGHT_STR; + extern const std::string CENTER_STR; + extern const std::string CHAR_STR; + extern const std::string WORD_STR; + extern const std::string NONE_STR; + extern const std::string HIDE_STR; + extern const std::string STAR_STR; + extern const std::string PRIORITY_STR; + extern const std::string ON_STR; + extern const std::string OFF_STR; + extern const std::string CAPITAL_ON_STR; + extern const std::string CAPITAL_OFF_STR; + extern const std::string TRUE_STR; + extern const std::string FALSE_STR; + extern const std::string GLOBAL_STR; + extern const std::string DEFAULT_STR; + extern const std::string HOLD_STR; + extern const std::string SLOT_STR; + extern const std::string OPTION_STR; + extern const std::string FORWARDER_STR; + extern const std::string TEXT_STR; + extern const std::string TABLE_STR; + extern const std::string TRACKBAR_STR; + extern const std::string STEP_TRACKBAR_STR; + extern const std::string NAMED_STEP_TRACKBAR_STR; + extern const std::string NULL_STR; + extern const std::string THEME_STR; + extern const std::string NOT_AVAILABLE_STR; + extern const std::string MEMORY_STR; + + // Pre-defined symbols + extern const std::string OPTION_SYMBOL; + extern const std::string DROPDOWN_SYMBOL; + extern const std::string CHECKMARK_SYMBOL; + extern const std::string CROSSMARK_SYMBOL; + extern const std::string DOWNLOAD_SYMBOL; + extern const std::string UNZIP_SYMBOL; + extern const std::string COPY_SYMBOL; + extern const std::string INPROGRESS_SYMBOL; + extern const std::string STAR_SYMBOL; + extern const std::string DIVIDER_SYMBOL; + extern const std::string NOTIFY_HEADER; + extern const std::string HOLD_A_SYMBOL; + + extern const std::vector THROBBER_SYMBOLS; + + extern std::atomic downloadPercentage; + extern std::atomic unzipPercentage; + extern std::atomic copyPercentage; + extern std::atomic displayPercentage; + + void resetPercentages(); +} diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp new file mode 100644 index 00000000..d37943be --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp @@ -0,0 +1,40 @@ +/******************************************************************************** + * File: haptics.hpp + * Author: ppkantorski + * Description: + * This header declares functions and shared flags for managing haptic feedback + * in the Ultrahand Overlay. It includes routines for initializing vibration + * devices, sending rumble and double-click patterns, and controlling timing + * for single and double pulse haptics. Atomic flags ensure safe access across + * threads. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2025-2026 ppkantorski + ********************************************************************************/ + +#pragma once +#include +#include +#include + +namespace ult { + + extern std::atomic clickActive; + extern std::atomic doubleClickActive; + + void initHaptics(); + void deinitHaptics(); + void checkAndReinitHaptics(); + + void rumbleClick(); + void rumbleDoubleClick(); + void processRumbleStop(u64 nowNs); + void processRumbleDoubleClick(u64 nowNs); + void rumbleDoubleClickStandalone(); +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp new file mode 100644 index 00000000..5ca7f2ac --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp @@ -0,0 +1,200 @@ +/******************************************************************************** + * File: hex_funcs.hpp + * Author: ppkantorski + * Description: + * This header file provides functions for working with hexadecimal data in C++. + * It includes functions for converting between ASCII and hexadecimal strings, + * finding hexadecimal data offsets in a file, and editing hexadecimal data in a file. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include +#include // Added for std::memcmp +#include +#include + +#include +#include +#include + + +namespace ult { + extern size_t HEX_BUFFER_SIZE; + + + // For improving the speed of hexing consecutively with the same file and asciiPattern. + extern std::unordered_map hexSumCache; // MOVED TO main.cpp + + // Lookup table for hex characters + inline constexpr char hexLookup[] = "0123456789ABCDEF"; + + + // ULTRA-FAST hex conversion with lookup table + inline constexpr unsigned char hexTable[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,3,4,5,6,7,8,9,0,0,0,0,0,0, + 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,10,11,12,13,14,15,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 + }; + + + extern void clearHexSumCache(); + extern size_t getHexSumCacheSize(); + + /** + * @brief Converts an ASCII string to a hexadecimal string. + * + * This function takes an ASCII string as input and converts it into a hexadecimal string. + * + * @param asciiStr The ASCII string to convert. + * @return The corresponding hexadecimal string. + */ + std::string asciiToHex(const std::string& asciiStr); + + /** + * @brief Converts a decimal string to a hexadecimal string. + * + * This function takes a decimal string as input and converts it into a hexadecimal string. + * + * @param decimalStr The decimal string to convert. + * @return The corresponding hexadecimal string. + */ + std::string decimalToHex(const std::string& decimalStr, int byteGroupSize = 2); + + + /** + * @brief Converts a hexadecimal string to a decimal string. + * + * This function takes a hexadecimal string as input and converts it into a decimal string. + * + * @param hexStr The hexadecimal string to convert. + * @return The corresponding decimal string. + */ + std::string hexToDecimal(const std::string& hexStr); + + + + std::string hexToReversedHex(const std::string& hexadecimal, int order = 2); + + /** + * @brief Converts a decimal string to a reversed hexadecimal string. + * + * This function takes a decimal string as input, converts it into a hexadecimal + * string, and reverses the resulting hexadecimal string in groups of byteGroupSize. + * + * @param decimalStr The decimal string to convert. + * @param byteGroupSize The grouping byteGroupSize for reversing the hexadecimal string. + * @return The reversed hexadecimal string. + */ + std::string decimalToReversedHex(const std::string& decimalStr, int byteGroupSize = 2); + + + + /** + * @brief Finds the offsets of hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and returns the file offsets where the data is found. + * + * @param filePath The path to the binary file. + * @param hexData The hexadecimal data to search for. + * @return A vector of strings containing the file offsets where the data is found. + */ + std::vector findHexDataOffsets(const std::string& filePath, const std::string& hexData); + + + + /** + * @brief Edits hexadecimal data in a file at a specified offset. + * + * This function opens a binary file, seeks to a specified offset, and replaces + * the data at that offset with the provided hexadecimal data. + * + * @param filePath The path to the binary file. + * @param offsetStr The offset in the file to performthe edit. + * @param hexData The hexadecimal data to replace at the offset. + */ + void hexEditByOffset(const std::string& filePath, const std::string& offsetStr, const std::string& hexData); + + /** + * @brief Edits a specific offset in a file with custom hexadecimal data. + * + * This function searches for a custom pattern in the file and calculates a new offset + * based on user-provided offsetStr and the found pattern. It then replaces the data + * at the calculated offset with the provided hexadecimal data. + * + * @param filePath The path to the binary file. + * @param offsetStr The user-provided offset for the edit. + * @param customPattern The custom pattern to search for in the file. + * @param hexDataReplacement The hexadecimal data to replace at the calculated offset. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + void hexEditByCustomOffset(const std::string& filePath, const std::string& customAsciiPattern, const std::string& offsetStr, const std::string& hexDataReplacement, size_t occurrence = 0); + + /** + * @brief Finds and replaces hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and replaces them with a specified hexadecimal replacement data. + * + * @param filePath The path to the binary file. + * @param hexDataToReplace The hexadecimal data to search for and replace. + * @param hexDataReplacement The hexadecimal data to replace with. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + void hexEditFindReplace(const std::string& filePath, const std::string& hexDataToReplace, const std::string& hexDataReplacement, size_t occurrence = 0); + + /** + * @brief Finds and replaces hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and replaces them with a specified hexadecimal replacement data. + * + * @param filePath The path to the binary file. + * @param hexDataToReplace The hexadecimal data to search for and replace. + * @param hexDataReplacement The hexadecimal data to replace with. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + std::string parseHexDataAtCustomOffset(const std::string& filePath, const std::string& customAsciiPattern, const std::string& offsetStr, size_t length, size_t occurrence = 0); + + + + /** + * @brief Finds and replaces hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and replaces them with a specified hexadecimal replacement data. + * + * @param filePath The path to the binary file. + * @param hexDataToReplace The hexadecimal data to search for and replace. + * @param hexDataReplacement The hexadecimal data to replace with. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + + std::string replaceHexPlaceholder(const std::string& arg, const std::string& hexPath); + + + + std::string extractVersionFromBinary(const std::string &filePath); + + + std::string decodeBase64ToString(const std::string& b64); +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp new file mode 100644 index 00000000..b1bc65b3 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp @@ -0,0 +1,342 @@ +/******************************************************************************** + * File: ini_funcs.hpp + * Author: ppkantorski + * Description: + * This header file provides functions for working with INI (Initialization) files + * in C++. It includes functions for reading, parsing, and editing INI files, + * as well as cleaning INI file formatting. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include // For std::string, strlen(), etc. +#include // For std::string +#include // For std::vector +#include // For std::map +#include // For std::remove_if + +#include +#include +#include + +#include "get_funcs.hpp" +#include "path_funcs.hpp" + +namespace ult { + + extern void clearIniMutexCache(); + + extern size_t INI_BUFFER_SIZE; + extern size_t INI_BUFFER_LARGE; + + /** + * @brief Represents a package header structure. + * + * This structure holds information about a package header, including version, + * creator, and description. + */ + struct PackageHeader { + std::string title; + std::string display_title; + std::string version; + std::string creator; + std::string about; + std::string credits; + std::string color; + std::string show_version; + std::string show_widget; + + void clear() { + title.clear(); + display_title.clear(); + version.clear(); + creator.clear(); + about.clear(); + credits.clear(); + color.clear(); + show_version.clear(); + show_widget.clear(); + } + }; + + /** + * @brief Retrieves the package header information from an INI file. + * + * This function parses an INI file and extracts the package header information. + * + * @param filePath The path to the INI file. + * @return The package header structure. + */ + PackageHeader getPackageHeaderFromIni(const std::string& filePath); + + + /** + * @brief Splits a string into a vector of substrings using a specified delimiter. + * + * This function splits a given string into multiple substrings based on the specified delimiter. + * + * @param str The input string to be split. + * @param delim The delimiter character used for splitting (default is space ' '). + * @return A vector of substrings obtained by splitting the input string. + */ + std::vector split(const std::string& str, char delim = ' '); + + + /** + * @brief Parses an INI-formatted string into a map of sections and key-value pairs. + * + * This function parses an INI-formatted string and organizes the data into a map, + * where sections are keys and key-value pairs are stored within each section. + * + * @param str The INI-formatted string to parse. + * @return A map representing the parsed INI data. + */ + std::map> parseIni(const std::string &str); + + + /** + * @brief Parses an INI file and returns its content as a map of sections and key-value pairs. + * + * This function reads the contents of an INI file located at the specified path, + * parses it into a map structure, where section names are keys and key-value pairs + * are stored within each section. + * + * @param configIniPath The path to the INI file to be parsed. + * @return A map representing the parsed INI data. + */ + std::map> getParsedDataFromIniFile(const std::string& configIniPath); + + + /** + * @brief Parses an INI file and retrieves key-value pairs from a specific section. + * + * This function reads the contents of an INI file located at the specified path, + * and returns the key-value pairs within a specific section. + * + * @param configIniPath The path to the INI file to be parsed. + * @param sectionName The name of the section to retrieve key-value pairs from. + * @return A map representing the key-value pairs in the specified section. + */ + std::map getKeyValuePairsFromSection(const std::string& configIniPath, const std::string& sectionName); + + + /** + * @brief Parses sections from an INI file and returns them as a list of strings. + * + * This function reads an INI file and extracts the section names from it. + * + * @param filePath The path to the INI file. + * @return A vector of section names. + */ + std::vector parseSectionsFromIni(const std::string& filePath); + + + + /** + * @brief Parses a specific value from a section and key in an INI file. + * + * @param filePath The path to the INI file. + * @param sectionName The name of the section containing the desired key. + * @param keyName The name of the key whose value is to be retrieved. + * @return The value as a string, or an empty string if the key or section isn't found. + */ + std::string parseValueFromIniSection(const std::string& filePath, const std::string& sectionName, const std::string& keyName); + + + + /** + * @brief Cleans the formatting of an INI file by removing empty lines and standardizing section formatting. + * + * This function takes an INI file located at the specified path, removes empty lines, + * and standardizes the formatting of sections by ensuring that there is a newline + * between each section's closing ']' and the next section's opening '['. + * + * @param filePath The path to the INI file to be cleaned. + */ + void cleanIniFormatting(const std::string& filePath); + + + /** + * @brief Modifies or creates an INI file by adding or updating key-value pairs in the specified section. + * + * This function attempts to open the specified INI file for reading. If the file doesn't exist, + * it creates a new file and adds the specified section and key-value pair. If the file exists, + * it reads its contents, modifies or adds the key-value pair in the specified section, and saves + * the changes back to the original file. + * + * @param fileToEdit The path to the INI file to be modified or created. + * @param desiredSection The name of the section in which the key-value pair should be added or updated. + * @param desiredKey The key for the key-value pair to be added or updated. + * @param desiredValue The new value for the key-value pair. + * @param desiredNewKey (Optional) If provided, the function will rename the key while preserving the original value. + */ + void setIniFile(const std::string& fileToEdit, const std::string& desiredSection, const std::string& desiredKey, const std::string& desiredValue, const std::string& desiredNewKey = "", const std::string& comment = ""); + + + /** + * @brief Sets the value of a key in an INI file within the specified section and cleans the formatting. + * + * This function sets the value of the specified key within the given section of the INI file. + * If the key or section does not exist, it creates them. After updating the INI file, + * it cleans the formatting to ensure proper INI file structure. + * + * @param fileToEdit The path to the INI file to be modified or created. + * @param desiredSection The name of the section in which the key-value pair should be added or updated. + * @param desiredKey The key for the key-value pair to be added or updated. + * @param desiredValue The new value for the key-value pair. + */ + void setIniFileValue(const std::string& fileToEdit, const std::string& desiredSection, const std::string& desiredKey, const std::string& desiredValue, const std::string& comment=""); + + /** + * @brief Sets the key name to a new name in an INI file within the specified section and cleans the formatting. + * + * This function sets the key name to a new name within the given section of the INI file. + * If the key or section does not exist, it creates them. After updating the INI file, + * it cleans the formatting to ensure proper INI file structure. + * + * @param fileToEdit The path to the INI file to be modified or created. + * @param desiredSection The name of the section in which the key-name change should occur. + * @param desiredKey The key name to be changed. + * @param desiredNewKey The new key name to replace the original key name. + */ + void setIniFileKey(const std::string& fileToEdit, const std::string& desiredSection, const std::string& desiredKey, const std::string& desiredNewKey, const std::string& comment=""); + + + + + /** + * @brief Adds a new section to an INI file. + * + * This function adds a new section with the specified name to the INI file located at the + * specified path. If the section already exists, it does nothing. + * + * @param filePath The path to the INI file. + * @param sectionName The name of the section to add. + */ + void addIniSection(const std::string& filePath, const std::string& sectionName); + + + + /** + * @brief Renames a section in an INI file. + * + * This function renames the section with the specified current name to the specified new name + * in the INI file located at the specified path. If the current section does not exist, or if the + * new section name already exists, it does nothing. + * + * @param filePath The path to the INI file. + * @param currentSectionName The name of the section to rename. + * @param newSectionName The new name for the section. + */ + void renameIniSection(const std::string& filePath, const std::string& currentSectionName, const std::string& newSectionName); + + + + + /** + * @brief Removes a section from an INI file. + * + * This function removes the section with the specified name, including all its associated key-value + * pairs, from the INI file located at the specified path. If the section does not exist in the file, + * it does nothing. + * + * @param filePath The path to the INI file. + * @param sectionName The name of the section to remove. + */ + void removeIniSection(const std::string& filePath, const std::string& sectionName); + + + // Removes a key-value pair from an ini accordingly. + void removeIniKey(const std::string& filePath, const std::string& sectionName, const std::string& keyName); + + + bool syncIniValue(std::map>& packageConfigData, + const std::string& packageConfigIniPath, + const std::string& optionName, + const std::string& key, + std::string& value); + + /** + * @brief Parses a command line into individual parts, handling quoted strings. + * + * @param line The command line to parse. + * @return A vector of strings containing the parsed command parts. + */ + std::vector parseCommandLine(const std::string& line); + + + + /** + * @brief Loads and parses options from an INI file. + * + * This function reads and parses options from an INI file, organizing them by section. + * + * @param packageIniPath The path to the INI file. + * @return A vector containing pairs of section names and their associated key-value pairs. + */ + std::vector>>> loadOptionsFromIni(const std::string& packageIniPath); + + /** + * @brief Loads a specific section from an INI file. + * + * This function reads and parses a specific section from an INI file. + * + * @param packageIniPath The path to the INI file. + * @param sectionName The name of the section to load. + * @return A vector of commands within the specified section. + */ + std::vector> loadSpecificSectionFromIni(const std::string& packageIniPath, const std::string& sectionName); + + + + /** + * @brief Saves INI data structure to a file. + * + * This function writes a complete INI data structure to the specified file path. + * The data structure should be organized as sections containing key-value pairs. + * + * @param filePath The path to the INI file to write. + * @param data The complete INI data structure to save. + */ + void saveIniFileData(const std::string& filePath, const std::map>& data); + + + + /** + * @brief Adds a key-value pair to all sections that contain a specified pattern key. + * + * If patternKey is empty, the key-value pair will be added to ALL sections. + * If patternKey is specified, only sections containing that key will be modified. + * + * @param filePath The path to the INI file. + * @param patternKey The key to search for (empty = all sections). + * @param newKey The new key to add. + * @param newValue The value for the new key. + */ + void addKeyToMatchingSections(const std::string& filePath, const std::string& patternKey, + const std::string& newKey, const std::string& newValue); + + /** + * @brief Removes a key from all sections that contain a specified pattern key. + * + * If patternKey is empty, the key will be removed from ALL sections. + * If patternKey is specified, only sections containing that key will have keyToRemove deleted. + * + * @param filePath The path to the INI file. + * @param patternKey The key to search for (empty = all sections). + * @param keyToRemove The key to remove from matching sections. + */ + void removeKeyFromMatchingSections(const std::string& filePath, const std::string& patternKey, + const std::string& keyToRemove); + +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp new file mode 100644 index 00000000..d28c8f72 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp @@ -0,0 +1,102 @@ +/******************************************************************************** + * File: json_funcs.hpp + * Author: ppkantorski + * Description: + * This header file provides functions for working with JSON files in C++ using + * the `cJSON` library. It includes a function to read JSON data from a file. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include +#include "string_funcs.hpp" +#include + +namespace ult { + // Define json_t as an opaque type to maintain API compatibility + typedef void json_t; + + // Define a custom deleter for json_t* + struct JsonDeleter { + void operator()(json_t* json) const { + if (json) { + cJSON_Delete(reinterpret_cast(json)); + } + } + }; + + + /** + * @brief Reads JSON data from a file and returns it as a `json_t` object. + * + * @param filePath The path to the JSON file. + * @return A `json_t` object representing the parsed JSON data. Returns `nullptr` on error. + */ + json_t* readJsonFromFile(const std::string& filePath); + + + /** + * @brief Parses a JSON string into a json_t object. + * + * This function takes a JSON string as input and parses it into a json_t object using cJSON library's `cJSON_Parse` function. + * If parsing fails, it logs the error and returns nullptr. + * + * @param input The input JSON string to parse. + * @return A json_t object representing the parsed JSON, or nullptr if parsing fails. + */ + json_t* stringToJson(const std::string& input); + + + // Function to get a string from a JSON object + std::string getStringFromJson(const json_t* root, const char* key); + + + /** + * @brief Loads a JSON file from the specified path and retrieves a string value for a given key. + * + * This function combines the functionality of loading a JSON file and retrieving a string value associated + * with a given key in a single step. + * + * @param filePath The path to the JSON file. + * @param key The key whose associated string value is to be retrieved. + * @return A string containing the value associated with the given key, or an empty string if the key is not found. + */ + std::string getStringFromJsonFile(const std::string& filePath, const std::string& key); + + + /** + * @brief Sets a value in a JSON file, creating the file if it doesn't exist. + * + * @param filePath The path to the JSON file. + * @param key The key to set. + * @param value The value to set (auto-detected type). + * @param createIfNotExists Whether to create the file if it doesn't exist. + * @return true if successful, false otherwise. + */ + bool setJsonValue(const std::string& filePath, const std::string& key, const std::string& value, bool createIfNotExists = false); + + + /** + * @brief Renames a key in a JSON file. + * + * @param filePath The path to the JSON file. + * @param oldKey The current key name. + * @param newKey The new key name. + * @return true if successful, false otherwise. + */ + bool renameJsonKey(const std::string& filePath, const std::string& oldKey, const std::string& newKey); + + + void pushNotificationJson(const std::string& appID, const std::string& text, size_t fontSize=28); +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp new file mode 100644 index 00000000..29e14ad8 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp @@ -0,0 +1,96 @@ +/******************************************************************************** + * File: list_funcs.hpp + * Author: ppkantorski + * Description: + * This header file contains function declarations and utility functions related + * to working with lists and vectors of strings. These functions are used in the + * Ultrahand Overlay project to perform various operations on lists, such as + * removing entries, filtering, and more. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + + +#pragma once + +#include +#include +#include +#include +#include "debug_funcs.hpp" +#include "string_funcs.hpp" +#include "get_funcs.hpp" + + +namespace ult { + + std::vector splitIniList(const std::string& value); + + + std::string joinIniList(const std::vector& list); + + + + /** + * @brief Removes entries from a vector of strings that match a specified entry. + * + * This function removes entries from the `itemsList` vector of strings that match the `entry`. + * + * @param entry The entry to be compared against the elements in `itemsList`. + * @param itemsList The vector of strings from which matching entries will be removed. + */ + void removeEntryFromList(const std::string& entry, std::vector& itemsList); + + /** + * @brief Filters a list of strings based on a specified filter list. + * + * This function filters a list of strings (`itemsList`) by removing entries that match any + * of the criteria specified in the `filterList`. It uses the `removeEntryFromList` function + * to perform the removal. + * + * @param filterList The list of entries to filter by. Entries in `itemsList` matching any entry in this list will be removed. + * @param itemsList The list of stringsto be filtered. + */ + void filterItemsList(const std::vector& filterList, std::vector& itemsList); + + + // Function to read file into a vector of strings + std::vector readListFromFile(const std::string& filePath, size_t maxLines=0, bool preserveNewlines = false); + + + // Function to get an entry from the list based on the index + std::string getEntryFromListFile(const std::string& listPath, size_t listIndex); + + + /** + * @brief Splits a string into a vector of strings using a delimiter. + * + * This function splits the input string into multiple strings using the specified delimiter. + * + * @param str The input string to split. + * @return A vector of strings containing the split values. + */ + std::vector stringToList(const std::string& str); + + + // Function to read file into a set of strings + std::unordered_set readSetFromFile(const std::string& filePath, const std::string& packagePath = ""); + + + // Function to write a set to a file + void writeSetToFile(const std::unordered_set& fileSet, const std::string& filePath); + + + // Function to compare two file lists and save duplicates to an output file + void compareFilesLists(const std::string& txtFilePath1, const std::string& txtFilePath2, const std::string& outputTxtFilePath); + + + void compareWildcardFilesLists(const std::string& wildcardPatternFilePath, const std::string& txtFilePath, const std::string& outputTxtFilePath); +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp new file mode 100644 index 00000000..e8ee868a --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp @@ -0,0 +1,96 @@ +/******************************************************************************** + * File: mod_funcs.hpp + * Author: ppkantorski + * Description: + * This header file contains function declarations and utility functions for IPS + * binary generations. These functions are used in the Ultrahand Overlay project + * to convert `.pchtxt` mods into `.ips` binaries. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2024-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include "debug_funcs.hpp" +#include "path_funcs.hpp" +#include "hex_funcs.hpp" +#include // Include this header for std::setw and std::setfill + +namespace ult { + inline constexpr const char* IPS32_HEAD_MAGIC = "IPS32"; + inline constexpr const char* IPS32_FOOT_MAGIC = "EEOF"; + + /** + * @brief Checks if a cheat already exists in the cheat file. + * @param cheatFilePath The path to the cheat file. + * @param newCheat The new cheat to check. + * @return True if the cheat exists, otherwise false. + */ + bool cheatExists(const std::string &cheatFilePath, const std::string &newCheat); + + /** + * @brief Appends a new cheat to the cheat file. + * @param cheatFilePath The path to the cheat file. + * @param newCheat The new cheat to append. + */ + void appendCheatToFile(const std::string &cheatFilePath, const std::string &newCheat); + + /** + * @brief Extracts the cheat name from the given file path. + * @param filePath The full file path. + * @return The extracted cheat name. + */ + std::string extractCheatName(const std::string &filePath); + + // Helper function to determine if a string is a valid title ID + bool isValidTitleID(const std::string &str); + + // Function to find the title ID in the text, avoiding the @nsobid- line + std::string findTitleID(const std::string &text); + + /** + * @brief Converts a .pchtxt file to a cheat file. + * @param pchtxtPath The file path to the .pchtxt file. + * @param cheatName The name of the cheat. + * @param outCheatPath The file path for the output cheat file. + * @return True if the conversion was successful, false otherwise. + */ + bool pchtxt2cheat(const std::string &pchtxtPath, std::string cheatName = "", std::string outCheatPath = ""); + + // Corrected helper function to convert values to big-endian format + inline uint32_t toBigEndian(uint32_t value) { + return ((value & 0x000000FF) << 24) | + ((value & 0x0000FF00) << 8) | + ((value & 0x00FF0000) >> 8) | + ((value & 0xFF000000) >> 24); + } + + inline uint16_t toBigEndian(uint16_t value) { + return ((value & 0x00FF) << 8) | + ((value & 0xFF00) >> 8); + } + + + /** + * @brief Converts a .pchtxt file to an IPS file using fstream. + * + * This function reads the contents of a .pchtxt file, extracts the address-value pairs, + * and generates an IPS file with the provided output folder. + * + * @param pchtxtPath The file path to the .pchtxt file. + * @param outputFolder The folder path for the output IPS file. + * @return True if the conversion was successful, false otherwise. + */ + bool pchtxt2ips(const std::string& pchtxtPath, const std::string& outputFolder); +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp new file mode 100644 index 00000000..7c02467a --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp @@ -0,0 +1,277 @@ +/******************************************************************************** + * File: path_funcs.hpp + * Author: ppkantorski + * Description: + * This header file contains function declarations and utility functions related + * to file and directory path manipulation. These functions are used in the + * Ultrahand Overlay project to handle file operations, such as creating + * directories, moving files, and more. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include +#include +#include "global_vars.hpp" +#include "string_funcs.hpp" +#include "get_funcs.hpp" +#include +#include +#include + + +namespace ult { + extern std::atomic abortFileOp; + + extern size_t COPY_BUFFER_SIZE; // Made const for thread safety + extern std::atomic copyPercentage; + + // Mutex for thread-safe logging operations + extern std::mutex logMutex; + + /** + * @brief Checks if a path points to a directory. + * + * This function checks if the specified path points to a directory. + * + * @param path The path to check. + * @return True if the path is a directory, false otherwise. + */ + bool isDirectory(const std::string& path); + + + + /** + * @brief Checks if a path points to a file. + * + * This function checks if the specified path points to a file. + * + * @param path The path to check. + * @return True if the path is a file, false otherwise. + */ + bool isFile(const std::string& path); + + + /** + * @brief Checks if a path points to a file or directory. + * + * This function checks if the specified path points to either a file or a directory. + * + * @param path The path to check. + * @return True if the path points to a file or directory, false otherwise. + */ + bool isFileOrDirectory(const std::string& path); + + + bool isDirectoryEmpty(const std::string& dirPath); + + /** + * @brief Creates a single directory if it doesn't exist. + * + * This function checks if the specified directory exists, and if not, it creates the directory. + * + * @param directoryPath The path of the directory to be created. + */ + void createSingleDirectory(const std::string& directoryPath); + + + /** + * @brief Creates a directory and its parent directories if they don't exist. + * + * This function creates a directory specified by `directoryPath` and also creates any parent directories + * if they don't exist. It handles nested directory creation. + * + * @param directoryPath The path of the directory to be created. + */ + void createDirectory(const std::string& directoryPath); + + + #if !USING_FSTREAM_DIRECTIVE + void writeLog(FILE* logFile, const std::string& line); + #else + void writeLog(std::ofstream& logFile, const std::string& line); + #endif + + /** + * @brief Creates a text file with the specified content. + * + * This function creates a text file specified by `filePath` and writes the given `content` to the file. + * + * @param filePath The path of the text file to be created. + * @param content The content to be written to the text file. + */ + void createTextFile(const std::string& filePath, const std::string& content); + + + + + /** + * @brief Deletes a file or directory. + * + * This function deletes the file or directory specified by `path`. It can delete both files and directories. + * + * @param path The path of the file or directory to be deleted. + */ + void deleteFileOrDirectory(const std::string& pathToDelete, const std::string& logSource = ""); + + + + + /** + * @brief Deletes files or directories that match a specified pattern. + * + * This function deletes files or directories specified by `pathPattern` by matching against a pattern. + * It identifies files or directories that match the pattern and deletes them. + * + * @param pathPattern The pattern used to match and delete files or directories. + */ + void deleteFileOrDirectoryByPattern(const std::string& pathPattern, const std::string& logSourc = "", const std::unordered_set* filterSet = nullptr); + + + void moveDirectory(const std::string& sourcePath, const std::string& destinationPath, + const std::string& logSource = "", const std::string& logDestination = ""); + + + + bool moveFile(const std::string& sourcePath, const std::string& destinationPath, + const std::string& logSource = "", const std::string& logDestination = ""); + + + + + /** + * @brief Moves a file or directory to a new destination. + * + * This function moves a file or directory from the `sourcePath` to the `destinationPath`. It can handle both + * files and directories and ensures that the destination directory exists before moving. + * + * @param sourcePath The path of the source file or directory. + * @param destinationPath The path of the destination where the file or directory will be moved. + */ + void moveFileOrDirectory(const std::string& sourcePath, const std::string& destinationPath, + const std::string& logSource = "", const std::string& logDestination = ""); + + + + /** + * @brief Moves files or directories matching a specified pattern to a destination directory. + * + * This function identifies files or directories that match the `sourcePathPattern` and moves them to the `destinationPath`. + * It processes each matching entry in the source directory pattern and moves them to the specified destination. + * Files/directories in the filterSet will be skipped. + * + * @param sourcePathPattern The pattern used to match files or directories to be moved. + * @param destinationPath The destination directory where matching files or directories will be moved. + * @param logSource Optional log source identifier. + * @param logDestination Optional log destination identifier. + * @param filterSet Optional set of paths to exclude from moving (nullptr to move all). + */ + void moveFilesOrDirectoriesByPattern(const std::string& sourcePathPattern, const std::string& destinationPath, + const std::string& logSource = "", const std::string& logDestination = "", const std::unordered_set* filterSet = nullptr); + + + + /** + * @brief Copies a single file from the source path to the destination path. + * + * This function copies a single file specified by `fromFile` to the location specified by `toFile`. + * + * @param fromFile The path of the source file to be copied. + * @param toFile The path of the destination where the file will be copied. + */ + void copySingleFile(const std::string& fromFile, const std::string& toFile, long long& totalBytesCopied, const long long totalSize, + const std::string& logSource = "", const std::string& logDestination = ""); + + + + /** + * Recursively calculates the total size of the given file or directory. + * @param path The path to the file or directory. + * @return The total size in bytes of all files within the directory or the size of a file. + */ + long long getTotalSize(const std::string& path); + + + /** + * @brief Copies a file or directory from the source path to the destination path. + * + * This function copies a file or directory specified by `fromFileOrDirectory` to the location specified by `toFileOrDirectory`. + * If the source is a regular file, it copies the file to the destination. If the source is a directory, it recursively copies + * the entire directory and its contents to the destination. + * + * @param fromPath The path of the source file or directory to be copied. + * @param toPath The path of the destination where the file or directory will be copied. + */ + void copyFileOrDirectory(const std::string& fromPath, const std::string& toPath, long long* totalBytesCopied = nullptr, long long totalSize = 0, + const std::string& logSource = "", const std::string& logDestination = ""); + + + + + /** + * @brief Copies files or directories matching a specified pattern to a destination directory. + * + * This function identifies files or directories that match the `sourcePathPattern` and copies them to the `toDirectory`. + * It processes each matching entry in the source directory pattern and copies them to the specified destination. + * Files/directories in the filterSet will be skipped. + * + * @param sourcePathPattern The pattern used to match files or directories to be copied. + * @param toDirectory The destination directory where matching files or directories will be copied. + * @param logSource Optional log source identifier. + * @param logDestination Optional log destination identifier. + * @param filterSet Optional set of paths to exclude from copying (nullptr to copy all). + */ + void copyFileOrDirectoryByPattern(const std::string& sourcePathPattern, const std::string& toDirectory, + const std::string& logSource = "", const std::string& logDestination = "", const std::unordered_set* filterSet = nullptr); + + + + + + /** + * @brief Mirrors the deletion of files from a source directory to a target directory. + * + * This function mirrors the deletion of files from a `sourcePath` directory to a `targetPath` directory. + * It deletes corresponding files in the `targetPath` that match the source directory structure. + * + * @param sourcePath The path of the source directory. + * @param targetPath The path of the target directory where files will be mirrored and deleted. + * Default is "sdmc:/". You can specify a different target path if needed. + */ + void mirrorFiles(const std::string& sourcePath, const std::string targetPath, const std::string mode); + + + /** + * @brief For each match of the wildcard pattern, creates an empty text file + * named basename.txt inside the output directory. + * + * @param wildcardPattern A path with a wildcard, such as /some/path/[*]. + * Each match results in a file named after the basename. + * @param outputDir Directory where the output files will be written. + * Created if it doesn't already exist. + */ + void createFlagFiles(const std::string& wildcardPattern, const std::string& outputDir); + + + /** + * @brief Removes all files starting with "._" from a directory and its subdirectories. + * + * This function recursively scans the specified directory and removes all files + * whose names start with "._" (commonly macOS metadata files). It processes + * all subdirectories recursively. + * + * @param sourcePath The path of the directory to clean. + */ + void dotCleanDirectory(const std::string& sourcePath); +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp new file mode 100644 index 00000000..0b3ea9fe --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp @@ -0,0 +1,253 @@ +/******************************************************************************** + * File: string_funcs.hpp + * Author: ppkantorski + * Description: + * This header file contains function declarations and utility functions for string + * manipulation. These functions are used in the Ultrahand Overlay project to + * perform operations like trimming whitespaces, removing quotes, replacing + * multiple slashes, and more. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include "global_vars.hpp" +#include "debug_funcs.hpp" + +namespace ult { + + extern std::string to_string(int value); + extern int stoi(const std::string& str, std::size_t* pos = nullptr, int base = 10); + extern float stof(const std::string& str); + + /** + * @brief A lightweight string stream class that mimics basic functionality of std::istringstream. + */ + class StringStream { + public: + StringStream() : position(0), hexMode(false), validState(true) {} + + + // Add this constructor to accept a string + StringStream(const std::string& input) : data(input), position(0), hexMode(false) {} + + // Set hex mode + StringStream& hex() { + hexMode = true; + return *this; + } + + // Reset hex mode + StringStream& resetHex() { + hexMode = false; + return *this; + } + + // Mimics std::getline() with a delimiter + bool getline(std::string& output, char delimiter); + + // Mimics operator >> to split by whitespace + StringStream& operator>>(std::string& output); + + // Overload the << operator to insert strings and integers + StringStream& operator<<(const std::string& input); + StringStream& operator<<(const char* input); + StringStream& operator<<(char input); + StringStream& operator<<(int input); // Handles int insertion with hex support + StringStream& operator<<(long long input); // for long long + + // Conversion to bool for checking stream state (success/failure) + explicit operator bool() const { + return validState; + } + + std::string str() const; + void clear() { data.clear(); position = 0; } // Add clear function + + private: + std::string data; + size_t position; + bool hexMode; + bool validState; // Track if the stream is in a valid state + }; + + + + /** + * @brief Trims leading and trailing whitespaces from a string. + * + * This function removes leading and trailing whitespaces, tabs, newlines, carriage returns, form feeds, + * and vertical tabs from the input string. + * + * @param str The input string to trim. + * @return The trimmed string. + */ + void trim(std::string& str); + + + + // Function to trim newline characters from the end of a string + void trimNewline(std::string& str); + + + /** + * @brief Removes all white spaces from a string. + * + * This function removes all white spaces, including spaces, tabs, newlines, carriage returns, form feeds, + * and vertical tabs from the input string. + * + * @param str The input string to remove white spaces from. + * @return The string with white spaces removed. + */ + std::string removeWhiteSpaces(const std::string& str); + + /** + * @brief Removes quotes from a string. + * + * This function removes single and double quotes from the beginning and end of the input string. + * + * @param str The input string to remove quotes from. + * @return The string with quotes removed. + */ + void removeQuotes(std::string& str); + + + void resolveDirectoryTraversal(std::string& path); + + /** + * @brief Preprocesses a path string by replacing multiple slashes and adding "sdmc:" prefix. + * + * This function preprocesses a path string by removing multiple consecutive slashes, + * adding the "sdmc:" prefix if not present, and modifying the input string in place. + * + * @param path The input path string to preprocess, passed by reference. + */ + void preprocessPath(std::string& path, const std::string& packagePath = ""); + + /** + * @brief Preprocesses a URL string by adding "https://" prefix. + * + * This function preprocesses a URL string by adding the "https://" prefix if not already present. + * + * @param path The input URL string to preprocess, passed by reference and modified in-place. + */ + void preprocessUrl(std::string& path); + + /** + * @brief Drops the file extension from a filename. + * + * This function removes the file extension (characters after the last dot) from the input filename string. + * + * @param filename The input filename from which to drop the extension, passed by reference and modified in-place. + */ + void dropExtension(std::string& filename); + + /** + * @brief Checks if a string starts with a given prefix. + * + * This function checks if the input string starts with the specified prefix. + * + * @param str The input string to check. + * @param prefix The prefix to check for. + * @return True if the string starts with the prefix, false otherwise. + */ + bool startsWith(const std::string& str, const std::string& prefix); + + + // Helper function to check if a string is a valid integer + bool isValidNumber(const std::string& str); + + // For properly handling placeholder replacements + std::string returnOrNull(const std::string& value); + + + // Function to slice a string from start to end index + std::string sliceString(const std::string& str, size_t start, size_t end); + + + /** + * @brief Converts a string to lowercase. + * + * This function takes a string as input and returns a lowercase version of that string. + * + * @param str The input string to convert to lowercase. + * @return The lowercase version of the input string. + */ + + std::string stringToLowercase(const std::string& str); + + + /** + * @brief Converts a string to uppercase. + * + * This function takes a string as input and returns an uppercase version of that string. + * + * @param str The input string to convert to uppercase. + * @return The uppercase version of the input string. + */ + + std::string stringToUppercase(const std::string& str); + + /** + * @brief Formats a priority string to a desired width. + * + * This function takes a priority string and formats it to a specified desired width by padding with '0's if it's shorter + * or truncating with '9's if it's longer. + * + * @param priority The input priority string to format. + * @param desiredWidth The desired width of the formatted string (default is 4). + * @return A formatted priority string. + */ + std::string formatPriorityString(const std::string& priority, int desiredWidth = 4); + + + + /** + * @brief Removes the part of the string after the first occurrence of '?' character. + * + * This function takes a string and removes the portion of the string that appears after + * the first '?' character, if found. If no '?' character is present, the string remains unchanged. + * + * @param input The input string from which to remove the tag, passed by reference and modified in-place. + */ + void removeTag(std::string &input); + + std::string getFirstLongEntry(const std::string& input, size_t minLength = 8); + + + // This will take a string like "v1.3.5-abasdfasdfa" and output "1.3.5". string could also look like "test-1.3.5-1" or "v1.3.5" and we will only want "1.3.5" + std::string cleanVersionLabel(const std::string& input); + + + std::string extractTitle(const std::string& input); + + + std::vector splitString(const std::string& str, const std::string& delimiter); + + + // Function to split a string by a delimiter and return a specific index + std::string splitStringAtIndex(const std::string& str, const std::string& delimiter, size_t index); + + + std::string customAlign(int number); + + #if IS_LAUNCHER_DIRECTIVE + std::string inputExists(const std::string& input); + #endif +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp new file mode 100644 index 00000000..a9915a9a --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp @@ -0,0 +1,685 @@ +/******************************************************************************** + * File: tsl_utils.hpp + * Author: ppkantorski + * Description: + * 'tsl_utils.hpp' is a central utility header for the Ultrahand Overlay project, + * containing a variety of functions and definitions related to system status, + * input handling, and application-specific behavior on the Nintendo Switch. + * This header provides essential utilities for interacting with the system, + * managing key input, and enhancing overlay functionality. + * + * The utilities defined here are designed to operate independently, facilitating + * robust system interaction capabilities required for custom overlays. + * + * For the latest updates and contributions, visit the project's GitHub repository: + * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay + * + * Note: This notice is integral to the project's documentation and must not be + * altered or removed. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + + +#pragma once + +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +struct OverlayCombo { + std::string path; // full overlay path + std::string launchArg; // empty = use per-overlay launch_args key, otherwise a “mode” arg +}; + +struct SwapDepth { + u32 value; + explicit SwapDepth(u32 v) : value(v) {} +}; + +namespace ult { + + static inline u64 nowNs() { + return armTicksToNs(armGetSystemTick()); + } + + void formatTimestamp(time_t t, char* buf, size_t bufSize); + + // math funcs + double cos(double x); + + extern bool correctFrameSize; // for detecting the correct Overlay display size + + extern u16 DefaultFramebufferWidth; ///< Width of the framebuffer + extern u16 DefaultFramebufferHeight; ///< Height of the framebuffer + + extern std::unordered_map translationCache; + + extern std::unordered_map g_entryCombos; + extern std::atomic launchingOverlay; + extern std::atomic settingsInitialized; + extern std::atomic currentForeground; + + + bool readFileContent(const std::string& filePath, std::string& content); + void parseJsonContent(const std::string& content, std::unordered_map& result); + bool parseJsonToMap(const std::string& filePath, std::unordered_map& result); + + bool loadTranslationsFromJSON(const std::string& filePath); + + // Function to clear the translation cache + void clearTranslationCache(); + + extern u16 activeHeaderHeight; + + bool consoleIsDocked(); + + std::string getBuildIdAsString(); + + std::string getTitleIdAsString(); + + extern std::string lastTitleID; + extern std::atomic resetForegroundCheck; + + + //extern bool isLauncher; + extern std::atomic internalTouchReleased; + extern u32 layerEdge; + extern bool useRightAlignment; + extern bool useSwipeToOpen; + extern bool useLaunchCombos; + extern bool useNotifications; + extern bool useNotificationsHotkey; + extern bool useStartupNotification; + extern bool silenceNotifications; + extern bool useSoundEffects; + extern bool useHapticFeedback; + extern bool usePageSwap; + extern std::atomic noClickableItems; + + extern bool useDynamicLogo; + extern bool useSelectionBG; + extern bool useSelectionText; + extern bool useSelectionValue; + + +#if IS_LAUNCHER_DIRECTIVE + extern std::atomic overlayLaunchRequested; + extern std::string requestedOverlayPath; + extern std::string requestedOverlayArgs; + extern std::mutex overlayLaunchMutex; +#endif + + + + // CUSTOM SECTION START + extern std::atomic backWidth; + extern std::atomic selectWidth; + extern std::atomic nextPageWidth; + extern std::atomic inMainMenu; + extern std::atomic inHiddenMode; + extern std::atomic inSettingsMenu; + extern std::atomic inSubSettingsMenu; + extern std::atomic inOverlaysPage; + extern std::atomic inPackagesPage; + + extern std::atomic hasNextPageButton; + + extern bool firstBoot; // for detecting first boot + extern bool reloadingBoot; // for detedting reloading boots + + // Define an atomic bool for interpreter completion + extern std::atomic threadFailure; + extern std::atomic runningInterpreter; + extern std::atomic shakingProgress; + + extern std::atomic isHidden; + extern std::atomic externalAbortCommands; + + extern bool disableTransparency; + extern bool useOpaqueScreenshots; + + extern std::atomic onTrackBar; + extern std::atomic allowSlide; + extern std::atomic unlockedSlide; + + void atomicToggle(std::atomic& b); + + /** + * @brief Shutdown modes for the Ultrahand-Overlay project. + * + * These macros define the shutdown modes used in the Ultrahand-Overlay project: + * - `SpsmShutdownMode_Normal`: Normal shutdown mode. + * - `SpsmShutdownMode_Reboot`: Reboot mode. + */ + #define SpsmShutdownMode_Normal 0 + #define SpsmShutdownMode_Reboot 1 + + /** + * @brief Key mapping macros for button keys. + * + * These macros define button keys for the Ultrahand-Overlay project to simplify key mappings. + * For example, `KEY_A` represents the `HidNpadButton_A` key. + */ + #define KEY_A HidNpadButton_A + #define KEY_B HidNpadButton_B + #define KEY_X HidNpadButton_X + #define KEY_Y HidNpadButton_Y + #define KEY_L HidNpadButton_L + #define KEY_R HidNpadButton_R + #define KEY_ZL HidNpadButton_ZL + #define KEY_ZR HidNpadButton_ZR + #define KEY_PLUS HidNpadButton_Plus + #define KEY_MINUS HidNpadButton_Minus + #define KEY_DUP HidNpadButton_Up + #define KEY_DDOWN HidNpadButton_Down + #define KEY_DLEFT HidNpadButton_Left + #define KEY_DRIGHT HidNpadButton_Right + #define KEY_SL HidNpadButton_AnySL + #define KEY_SR HidNpadButton_AnySR + #define KEY_LSTICK HidNpadButton_StickL + #define KEY_RSTICK HidNpadButton_StickR + #define KEY_UP HidNpadButton_AnyUp + #define KEY_DOWN HidNpadButton_AnyDown + #define KEY_LEFT HidNpadButton_AnyLeft + #define KEY_RIGHT HidNpadButton_AnyRight + + #define SCRIPT_KEY HidNpadButton_Minus + #define SYSTEM_SETTINGS_KEY HidNpadButton_Plus + #define SETTINGS_KEY HidNpadButton_Y + #define STAR_KEY HidNpadButton_X + + + // Define a mask with all possible key flags + #define ALL_KEYS_MASK (KEY_A | KEY_B | KEY_X | KEY_Y | KEY_DUP | KEY_DDOWN | KEY_DLEFT | KEY_DRIGHT | KEY_L | KEY_R | KEY_ZL | KEY_ZR | KEY_SL | KEY_SR | KEY_LSTICK | KEY_RSTICK | KEY_PLUS | KEY_MINUS) + + + extern bool updateMenuCombos; + + /** + * @brief Ultrahand-Overlay Input Macros + * + * This block of code defines macros for handling input in the Ultrahand-Overlay project. + * These macros simplify the mapping of input events to corresponding button keys and + * provide aliases for touch and joystick positions. + * + * The macros included in this block are: + * + * - `touchPosition`: An alias for a constant `HidTouchState` pointer. + * - `touchInput`: An alias for `&touchPos`, representing touch input. + * - `JoystickPosition`: An alias for `HidAnalogStickState`, representing joystick input. + * + * These macros are utilized within the Ultrahand-Overlay project to manage and interpret + * user input, including touch and joystick events. + */ + #define touchPosition const HidTouchState + #define touchInput &touchPos + #define JoystickPosition HidAnalogStickState + + //void convertComboToUnicode(std::string& combo); + + /** + * @brief Combo key mapping + */ + struct KeyInfo { + u64 key; + const char* name; + const char* glyph; + }; + + /** + * @brief Combo key mappings + * + * Ordered as they should be displayed + */ + extern const std::array KEYS_INFO; + extern std::unordered_map buttonCharMap; + + + void convertComboToUnicode(std::string& combo); + + + // English string definitions + + extern const std::string whiteColor; + extern const std::string blackColor; + extern const std::string greyColor; + + extern std::atomic languageWasChanged; + + inline constexpr double _M_PI = 3.14159265358979323846; // For double precision + inline constexpr double RAD_TO_DEG = 180.0f / _M_PI; + + #if IS_LAUNCHER_DIRECTIVE + extern std::string ENGLISH; + extern std::string SPANISH; + extern std::string FRENCH; + extern std::string GERMAN; + extern std::string JAPANESE; + extern std::string KOREAN; + extern std::string ITALIAN; + extern std::string DUTCH; + extern std::string PORTUGUESE; + extern std::string RUSSIAN; + extern std::string UKRAINIAN; + extern std::string POLISH; + extern std::string SIMPLIFIED_CHINESE; + extern std::string TRADITIONAL_CHINESE; + + extern std::string OVERLAYS; //defined in libTesla now + extern std::string OVERLAYS_ABBR; + extern std::string OVERLAY; + extern std::string HIDDEN_OVERLAYS; + extern std::string PACKAGES; //defined in libTesla now + extern std::string PACKAGE; + extern std::string HIDDEN_PACKAGES; + extern std::string HIDDEN; + extern std::string HIDE_OVERLAY; + extern std::string HIDE_PACKAGE; + extern std::string LAUNCH_ARGUMENTS; + extern std::string FORCE_AMS110_SUPPORT; + extern std::string QUICK_LAUNCH; + extern std::string BOOT_COMMANDS; + extern std::string EXIT_COMMANDS; + extern std::string ERROR_LOGGING; + extern std::string COMMANDS; + extern std::string SETTINGS; + extern std::string FAVORITE; + extern std::string MAIN_SETTINGS; + extern std::string UI_SETTINGS; + + extern std::string WIDGET; + extern std::string WIDGET_ITEMS; + extern std::string WIDGET_SETTINGS; + extern std::string CLOCK; + extern std::string BATTERY; + extern std::string SOC_TEMPERATURE; + extern std::string PCB_TEMPERATURE; + extern std::string BACKDROP; + extern std::string DYNAMIC_COLORS; + extern std::string CENTER_ALIGNMENT; + extern std::string EXTENDED_BACKDROP; + extern std::string MISCELLANEOUS; + extern std::string MENU_SETTINGS; + extern std::string USER_GUIDE; + extern std::string PACKAGES_MENU; + extern std::string SHOW_HIDDEN; + extern std::string SHOW_DELETE; + extern std::string SHOW_UNSUPPORTED; + + extern std::string PAGE_SWAP; + extern std::string RIGHT_SIDE_MODE; + extern std::string OVERLAY_VERSIONS; + extern std::string PACKAGE_VERSIONS; + extern std::string CLEAN_VERSIONS; + extern std::string KEY_COMBO; + extern std::string MODE; + extern std::string LAUNCH_MODES; + extern std::string LANGUAGE; + extern std::string OVERLAY_INFO; + extern std::string SOFTWARE_UPDATE; + extern std::string UPDATE_ULTRAHAND; + extern std::string SYSTEM; + extern std::string DEVICE_INFO; + extern std::string FIRMWARE; + extern std::string BOOTLOADER; + extern std::string HARDWARE; + extern std::string MEMORY; + extern std::string VENDOR; + extern std::string MODEL; + extern std::string STORAGE; + + extern std::string OVERLAY_MEMORY; + extern std::string NOT_ENOUGH_MEMORY; + extern std::string WALLPAPER_SUPPORT_DISABLED; + extern std::string SOUND_SUPPORT_DISABLED; + extern std::string WALLPAPER_SUPPORT_ENABLED; + extern std::string SOUND_SUPPORT_ENABLED; + extern std::string EXIT_OVERLAY_SYSTEM; + + extern std::string ULTRAHAND_ABOUT; + extern std::string ULTRAHAND_CREDITS_START; + extern std::string ULTRAHAND_CREDITS_END; + + extern std::string LOCAL_IP; + extern std::string WALLPAPER; + extern std::string THEME; + extern std::string SOUNDS; + extern std::string DEFAULT; + extern std::string ROOT_PACKAGE; + extern std::string SORT_PRIORITY; + extern std::string OPTIONS; + extern std::string FAILED_TO_OPEN; + + extern std::string LAUNCH_COMBOS; + extern std::string NOTIFICATIONS; + extern std::string NOTIFICATION_SETTINGS; + extern std::string SILENCE_NOTIFICATIONS; + extern std::string STARTUP_NOTIFICATION; + extern std::string MAX_SLOTS; + extern std::string API_NOTIFICATIONS; + extern std::string API_TOGGLE_HOTKEY; + extern std::string DISMISS_NOTIFICATION; + extern std::string API_TOGGLE; + extern std::string CLICK; + extern std::string TAP; + extern std::string HOLD_FOR_4S; + + extern std::string HAPTIC_FEEDBACK; + extern std::string OPAQUE_SCREENSHOTS; + + extern std::string PACKAGE_INFO; + extern std::string _TITLE; + extern std::string _VERSION; + extern std::string _CREATOR; + extern std::string _ABOUT; + extern std::string _CREDITS; + + extern std::string SETTINGS_MENU; + extern std::string SCRIPT_OVERLAY; + extern std::string STAR_FAVORITE; + extern std::string APP_SETTINGS; + extern std::string ON_MAIN_MENU; + extern std::string ON_A_COMMAND; + extern std::string ON_OVERLAY_PACKAGE; + extern std::string FEATURES; + extern std::string SWIPE_TO_OPEN; + + extern std::string THEME_SETTINGS; + extern std::string DYNAMIC_LOGO; + extern std::string SELECTION_BACKGROUND; + extern std::string SELECTION_TEXT; + extern std::string SELECTION_VALUE; + extern std::string LIBULTRAHAND_TITLES; + extern std::string LIBULTRAHAND_VERSIONS; + extern std::string PACKAGE_TITLES; + + extern std::string ULTRAHAND_HAS_STARTED; + extern std::string ULTRAHAND_HAS_RESTARTED; + extern std::string NEW_UPDATE_IS_AVAILABLE; + + extern std::string DELETE_PACKAGE; + extern std::string DELETE_OVERLAY; + extern std::string SELECTION_IS_EMPTY; + extern std::string FORCED_SUPPORT_WARNING; + + extern std::string TASK_IS_COMPLETE; + extern std::string TASK_HAS_FAILED; + + extern std::string REBOOT_TO; + extern std::string REBOOT; + extern std::string SHUTDOWN; + extern std::string BOOT_ENTRY; + #endif + + extern std::string INCOMPATIBLE_WARNING; + extern std::string SYSTEM_RAM; + extern std::string FREE; + + extern std::string UNAVAILABLE_SELECTION; + + extern std::string ON; + extern std::string OFF; + + extern std::string OK; + extern std::string BACK; + extern std::string HIDE; + extern std::string CANCEL; + + extern std::string GAP_1; + extern std::string GAP_2; + extern std::atomic halfGap; + + #if USING_WIDGET_DIRECTIVE + extern std::string SUNDAY; + extern std::string MONDAY; + extern std::string TUESDAY; + extern std::string WEDNESDAY; + extern std::string THURSDAY; + extern std::string FRIDAY; + extern std::string SATURDAY; + + extern std::string JANUARY; + extern std::string FEBRUARY; + extern std::string MARCH; + extern std::string APRIL; + extern std::string MAY; + extern std::string JUNE; + extern std::string JULY; + extern std::string AUGUST; + extern std::string SEPTEMBER; + extern std::string OCTOBER; + extern std::string NOVEMBER; + extern std::string DECEMBER; + + extern std::string SUN; + extern std::string MON; + extern std::string TUE; + extern std::string WED; + extern std::string THU; + extern std::string FRI; + extern std::string SAT; + + extern std::string JAN; + extern std::string FEB; + extern std::string MAR; + extern std::string APR; + extern std::string MAY_ABBR; + extern std::string JUN; + extern std::string JUL; + extern std::string AUG; + extern std::string SEP; + extern std::string OCT; + extern std::string NOV; + extern std::string DEC; + #endif + + // Constant string definitions (English) + void reinitializeLangVars(); + + + void parseLanguage(const std::string& langFile); + + #if USING_WIDGET_DIRECTIVE + void localizeTimeStr(char* timeStr); + #endif + + // Unified function to apply replacements + void applyLangReplacements(std::string& text, bool isValue = false); + + + // Predefined hexMap + inline constexpr std::array hexMap = [] { + std::array map = {0}; + map['0'] = 0; map['1'] = 1; map['2'] = 2; map['3'] = 3; map['4'] = 4; + map['5'] = 5; map['6'] = 6; map['7'] = 7; map['8'] = 8; map['9'] = 9; + map['A'] = 10; map['B'] = 11; map['C'] = 12; map['D'] = 13; map['E'] = 14; map['F'] = 15; + map['a'] = 10; map['b'] = 11; map['c'] = 12; map['d'] = 13; map['e'] = 14; map['f'] = 15; + return map; + }(); + + + extern std::atomic refreshWallpaperNow; + extern std::atomic refreshWallpaper; + extern std::vector wallpaperData; + extern std::atomic inPlot; + + extern std::mutex wallpaperMutex; + extern std::condition_variable cv; + + + + // Function to load the RGBA file into memory and modify wallpaperData directly + bool loadRGBA8888toRGBA4444(const std::string& filePath, u8* dst, size_t srcSize); + void loadWallpaperFile(const std::string& filePath, s32 width = 448, s32 height = 720); + void loadWallpaperFileWhenSafe(); + + void reloadWallpaper(); + + + extern std::atomic themeIsInitialized; + + // Variables for touch commands + extern std::atomic touchingBack; + extern std::atomic touchingSelect; + extern std::atomic touchingNextPage; + extern std::atomic touchingMenu; + extern std::atomic shortTouchAndRelease; + extern std::atomic longTouchAndRelease; + extern std::atomic simulatedBack; + extern std::atomic simulatedSelect; + extern std::atomic simulatedNextPage; + extern std::atomic simulatedMenu; + extern std::atomic stillTouching; + extern std::atomic interruptedTouch; + extern std::atomic touchInBounds; + + +#if USING_WIDGET_DIRECTIVE + // Battery implementation + extern bool powerInitialized; + extern bool powerCacheInitialized; + extern uint32_t powerCacheCharge; + extern bool powerCacheIsCharging; + extern PsmSession powerSession; + + extern std::atomic batteryCharge; + extern std::atomic isCharging; + + bool powerGetDetails(uint32_t *_batteryCharge, bool *_isCharging); + + void powerInit(void); + + void powerExit(void); +#endif + + // Temperature Implementation + extern std::atomic PCB_temperature; + extern std::atomic SOC_temperature; + + /* + I2cReadRegHandler was taken from Switch-OC-Suite source code made by KazushiMe + Original repository link (Deleted, last checked 15.04.2023): https://github.com/KazushiMe/Switch-OC-Suite + */ + + Result I2cReadRegHandler(u8 reg, I2cDevice dev, u16 *out); + + + #define TMP451_SOC_TEMP_REG 0x01 // Register for SOC temperature integer part + #define TMP451_SOC_TMP_DEC_REG 0x10 // Register for SOC temperature decimal part + #define TMP451_PCB_TEMP_REG 0x00 // Register for PCB temperature integer part + #define TMP451_PCB_TMP_DEC_REG 0x15 // Register for PCB temperature decimal part + + // Common helper function to read temperature (integer and fractional parts) + Result ReadTemperature(float *temperature, u8 integerReg, u8 fractionalReg, bool integerOnly); + + // Function to get the SOC temperature + Result ReadSocTemperature(float *temperature, bool integerOnly = true); + + // Function to get the PCB temperature + Result ReadPcbTemperature(float *temperature, bool integerOnly = true); + + + + // Time implementation + + extern const std::string DEFAULT_DT_FORMAT; + extern std::string datetimeFormat; + + + // Widget settings + extern bool hideClock, hideBattery, hidePCBTemp, hideSOCTemp, dynamicWidgetColors; + extern bool hideWidgetBackdrop, centerWidgetAlignment, extendedWidgetBackdrop; + + #if IS_LAUNCHER_DIRECTIVE + void reinitializeWidgetVars(); + #endif + + extern bool cleanVersionLabels, hideOverlayVersions, hidePackageVersions, useLibultrahandTitles, useLibultrahandVersions, usePackageTitles, usePackageVersions; + + + + // nx-ovlloader settings + enum class OverlayHeapSize : u64 { + Size_4MB = 0x400000, + Size_6MB = 0x600000, + Size_8MB = 0x800000 + }; + + // Static cache + struct HeapSizeCache { + bool initialized = false; + OverlayHeapSize cachedSize = OverlayHeapSize::Size_6MB; + u64 customSizeMB = 0; + }; + extern HeapSizeCache heapSizeCache; + + + // Helper function to convert MB to bytes + extern u64 mbToBytes(u32 mb); + + // Helper function to convert bytes to MB + extern u32 bytesToMB(u64 bytes); + + // Implementation + OverlayHeapSize getCurrentHeapSize(); + + extern OverlayHeapSize currentHeapSize; + + bool setOverlayHeapSize(OverlayHeapSize heapSize); + + // Implementation + bool requestOverlayExit(); + + extern const std::string loaderInfo; + extern std::string loaderTitle; + extern bool expandedMemory; + extern bool furtherExpandedMemory; + extern bool limitedMemory; + + extern std::string versionLabel; + + #if IS_LAUNCHER_DIRECTIVE + void reinitializeVersionLabels(); + #endif + + + // Number of renderer threads to use + extern const unsigned numThreads; + extern std::vector renderThreads; + extern const s32 bmpChunkSize; + extern std::atomic currentRow; + + + struct InPlotBarrierCompletion { + void operator()() noexcept; + }; + extern std::barrier inPlotBarrier; + + + void initializeThemeVars(); + + void initializeUltrahandSettings(); + + +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp new file mode 100644 index 00000000..262baaf3 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp @@ -0,0 +1,44 @@ +/******************************************************************************** + * File: ultra.hpp + * Author: ppkantorski + * Description: + * 'ultra.hpp' serves as a central include header for the Ultrahand Overlay project, + * bringing together a comprehensive suite of utility functions essential for the + * development and operation of custom overlays on the Nintendo Switch. This header + * provides consolidated access to functions facilitating debugging, string processing, + * file management, JSON manipulation, and more, enhancing the modularity and + * reusability of code within the project. + * + * These utilities are designed to operate independently, providing robust tools to + * support complex overlay functionalities and interactions. + * + * For the latest updates and contributions, visit the project's GitHub repository: + * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay + * + * Note: This notice is integral to the project's documentation and must not be + * altered or removed. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2024-2026 ppkantorski + ********************************************************************************/ +#pragma once + +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wunused-function" + +// Include all functional headers used in the libUltra library + +#include "global_vars.hpp" +#include "debug_funcs.hpp" +#include "string_funcs.hpp" +#include "get_funcs.hpp" +#include "path_funcs.hpp" +#include "list_funcs.hpp" +#include "json_funcs.hpp" +#include "ini_funcs.hpp" +#include "hex_funcs.hpp" +#include "download_funcs.hpp" +#include "mod_funcs.hpp" +#include "tsl_utils.hpp" +#include "audio.hpp" +#include "haptics.hpp" \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/audio.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/audio.cpp new file mode 100644 index 00000000..d5b8b91c --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/audio.cpp @@ -0,0 +1,410 @@ +/******************************************************************************** + * File: audio.cpp + * Author: ppkantorski + * Description: + * Render-thread-safe audio with a single shared DMA playback buffer. + * Key design: + * - rawBuf : only per-sound allocation — compact native-channel 16-bit PCM, + * native sample rate, no volume. Kept for re-render on vol/dock change. + * - m_playBuf : single shared DMA-ready buffer, sized to the largest sound's + * 48 kHz stereo output. All sounds share this one allocation. + * - renderToPlayBuf() runs inside playSound(): resamples to 48 kHz (linear interp), + * expands mono → L+R, and applies volume in one pass. + * - No per-sound stereo copy is kept — memory cost per sound is rawBuf only. + * - m_playBuf is safe to reuse because audout is always drained before writing. + * - Volume and dock state are read live at render time — no stale tracking needed. + * - Supports any WAV sample rate ≤ 48 kHz (8/11025/16000/22050/32000/44100/48000 Hz). + * Source rates > 48 kHz are rejected at load time. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2025-2026 ppkantorski + ********************************************************************************/ + +#include "audio.hpp" + +namespace ult { + + // ── Static member definitions ───────────────────────────────────────────── + bool Audio::m_initialized = false; + std::atomic Audio::m_enabled{true}; + std::atomic Audio::m_masterVolumeFixed{154}; // 0.6 * 256 ≈ 154 + bool Audio::m_lastDockedState = false; + std::vector Audio::m_cachedSounds; + std::mutex Audio::m_audioMutex; + void* Audio::m_playBuf = nullptr; + uint32_t Audio::m_playBufCap = 0; + AudioOutBuffer Audio::m_audoutBuf = {}; + + // 4 KB — required by Switch audout DMA + static constexpr uint32_t AUDIO_ALIGN = 0x1000; + static constexpr uint32_t TARGET_RATE = 48000; + + // ── initialize ──────────────────────────────────────────────────────────── + bool Audio::initialize() { + std::lock_guard lock(m_audioMutex); + + if (m_initialized) return true; + + if (R_FAILED(audoutInitialize()) || R_FAILED(audoutStartAudioOut())) { + audoutExit(); + return false; + } + + m_initialized = true; + m_cachedSounds.resize(static_cast(SoundType::Count)); + m_lastDockedState = ult::consoleIsDocked(); + + reloadAllSounds(); + + return true; + } + + // ── exit ────────────────────────────────────────────────────────────────── + void Audio::exit() { + std::lock_guard lock(m_audioMutex); + + for (auto& s : m_cachedSounds) { + free(s.rawBuf); + s = CachedSound{}; + } + + free(m_playBuf); + m_playBuf = nullptr; + m_playBufCap = 0; + m_audoutBuf = {}; + + if (m_initialized) { + audoutStopAudioOut(); + audoutExit(); + m_initialized = false; + } + } + + // ── reloadAllSounds ─────────────────────────────────────────────────────── + void Audio::reloadAllSounds() { + for (uint32_t i = 0; i < static_cast(SoundType::Count); ++i) + loadSoundFromWav(static_cast(i), m_soundPaths[i]); + // growPlayBuf() is called inside loadSoundFromWav after each load, + // so m_playBuf is always sized to the current high-water mark. + } + + // ── unloadAllSounds ─────────────────────────────────────────────────────── + void Audio::unloadAllSounds(const std::initializer_list& excludeSounds) { + std::lock_guard lock(m_audioMutex); + if (!m_initialized) return; + + for (uint32_t i = 0; i < m_cachedSounds.size(); ++i) { + const SoundType cur = static_cast(i); + if (std::find(excludeSounds.begin(), excludeSounds.end(), cur) != excludeSounds.end()) + continue; + + CachedSound& s = m_cachedSounds[i]; + free(s.rawBuf); + s = CachedSound{}; + } + // m_playBuf stays allocated — it will be reused when any remaining sound plays. + } + + // ── reloadIfDockedChanged ───────────────────────────────────────────────── + // Volume and dock state are read live in renderToPlayBuf(), so no stale + // marking is needed here — just update m_lastDockedState. + bool Audio::reloadIfDockedChanged() { + if (!m_initialized) return false; + + const bool currentDocked = ult::consoleIsDocked(); + if (currentDocked == m_lastDockedState) return false; + + std::lock_guard lock(m_audioMutex); + m_lastDockedState = currentDocked; + return true; + } + + // ── growPlayBuf ─────────────────────────────────────────────────────────── + // Computes the 48 kHz stereo output size needed for every currently loaded + // sound and grows m_playBuf to cover the largest one. + // Called after each loadSoundFromWav. Must hold m_audioMutex. + void Audio::growPlayBuf() { + uint32_t maxNeeded = 0; + + for (const auto& s : m_cachedSounds) { + if (!s.rawBuf || s.rawSize == 0) continue; + + const uint32_t srcPerChan = s.isMono + ? (s.rawSize / sizeof(s16)) + : (s.rawSize / sizeof(s16)) / 2; + + const uint32_t outPerChan = (s.sampleRate == TARGET_RATE || s.sampleRate == 0) + ? srcPerChan + : static_cast( + ((uint64_t)srcPerChan * TARGET_RATE + s.sampleRate - 1) / s.sampleRate); + + const uint32_t stereoBytes = outPerChan * 2 * sizeof(s16); + const uint32_t needed = (stereoBytes + AUDIO_ALIGN - 1) & ~(AUDIO_ALIGN - 1); + if (needed > maxNeeded) maxNeeded = needed; + } + + if (maxNeeded <= m_playBufCap) return; // already large enough + + free(m_playBuf); + m_playBuf = aligned_alloc(AUDIO_ALIGN, maxNeeded); + if (m_playBuf) { + m_playBufCap = maxNeeded; + } else { + m_playBufCap = 0; + } + } + + // ── renderToPlayBuf ─────────────────────────────────────────────────────── + // Writes rawBuf → m_playBuf: resample to 48 kHz (linear interp if needed), + // expand mono → L+R, apply current volume and dock attenuation. + // Returns actual output byte count written, or 0 on error. + // Must be called under m_audioMutex. + uint32_t Audio::renderToPlayBuf(const CachedSound& s) { + if (!s.rawBuf || s.rawSize == 0 || !m_playBuf) return 0; + + const uint32_t srcSamples = s.rawSize / sizeof(s16); + const uint32_t srcPerChan = s.isMono ? srcSamples : srcSamples / 2; + + const uint32_t outPerChan = (s.sampleRate == TARGET_RATE || s.sampleRate == 0) + ? srcPerChan + : static_cast( + ((uint64_t)srcPerChan * TARGET_RATE + s.sampleRate - 1) / s.sampleRate); + + const uint32_t stereoBytes = outPerChan * 2 * sizeof(s16); + const uint32_t needed = (stereoBytes + AUDIO_ALIGN - 1) & ~(AUDIO_ALIGN - 1); + + if (needed > m_playBufCap) return 0; // shouldn't happen after growPlayBuf() + + // Effective volume: master * 0.5 when docked (TV speaker protection). + // Fixed-point: 0–256 where 256 == 1.0. + int32_t vol = m_masterVolumeFixed.load(std::memory_order_relaxed); + if (m_lastDockedState) vol >>= 1; + + const s16* src = static_cast(s.rawBuf); + s16* dst = static_cast(m_playBuf); + + const bool needsResample = (s.sampleRate != TARGET_RATE && s.sampleRate != 0); + + if (!needsResample) { + // ── Fast path: native 48 kHz — no resampling ───────────────────── + if (s.isMono) { + for (uint32_t i = 0; i < srcSamples; ++i) { + const s16 v = static_cast((static_cast(src[i]) * vol) >> 8); + *dst++ = v; // L + *dst++ = v; // R + } + } else { + for (uint32_t i = 0; i < srcSamples; ++i) + *dst++ = static_cast((static_cast(src[i]) * vol) >> 8); + } + } else { + // ── Resample path: linear interpolation to 48 kHz ──────────────── + // step is source frames per output frame in 16.16 fixed-point. + // For all rates ≤ 48 kHz this is < 1.0 (upsampling). + const uint64_t step = ((uint64_t)s.sampleRate << 16) / TARGET_RATE; + uint64_t srcFixed = 0; + + if (s.isMono) { + for (uint32_t i = 0; i < outPerChan; ++i) { + const uint32_t i0 = static_cast(srcFixed >> 16); + const uint32_t i1 = (i0 + 1 < srcPerChan) ? i0 + 1 : i0; + const int32_t frac = static_cast(srcFixed & 0xFFFF); + const int32_t s0 = src[i0], s1 = src[i1]; + const s16 v = static_cast( + ((s0 + (((s1 - s0) * frac) >> 16)) * vol) >> 8); + *dst++ = v; // L + *dst++ = v; // R + srcFixed += step; + } + } else { + // Stereo interleaved: index [frame*2+0] = L, [frame*2+1] = R + for (uint32_t i = 0; i < outPerChan; ++i) { + const uint32_t i0 = static_cast(srcFixed >> 16); + const uint32_t i1 = (i0 + 1 < srcPerChan) ? i0 + 1 : i0; + const int32_t frac = static_cast(srcFixed & 0xFFFF); + const int32_t l0 = src[i0*2], l1 = src[i1*2]; + const int32_t r0 = src[i0*2 + 1], r1 = src[i1*2 + 1]; + *dst++ = static_cast(((l0 + (((l1-l0)*frac)>>16)) * vol) >> 8); + *dst++ = static_cast(((r0 + (((r1-r0)*frac)>>16)) * vol) >> 8); + srcFixed += step; + } + } + } + + // Zero-fill alignment padding + if (stereoBytes < needed) + memset(static_cast(m_playBuf) + stereoBytes, 0, needed - stereoBytes); + + return stereoBytes; + } + + // ── loadSoundFromWav ────────────────────────────────────────────────────── + // Reads WAV → rawBuf (16-bit, native channels, no volume applied). + // Rejects source rates > 48 kHz. Calls growPlayBuf() after a successful load. + // Must be called under m_audioMutex. + bool Audio::loadSoundFromWav(SoundType type, const char* path) { + const uint32_t idx = static_cast(type); + if (!m_initialized || idx >= static_cast(SoundType::Count)) return false; + + CachedSound& s = m_cachedSounds[idx]; + + free(s.rawBuf); + s = CachedSound{}; // reset all fields + + FILE* f = fopen(path, "rb"); + if (!f) return false; + + // ── RIFF/WAVE header ────────────────────────────────────────────────── + char hdr[12]; + if (fread(hdr, 1, 12, f) != 12 || + memcmp(hdr, "RIFF", 4) || + memcmp(hdr + 8, "WAVE", 4)) { + fclose(f); return false; + } + + u16 fmt = 0, ch = 0, bits = 0; + u32 rate = 0, dSize = 0; + long dPos = 0; + + // ── Chunk scan ──────────────────────────────────────────────────────── + while (fread(hdr, 1, 8, f) == 8) { + const u32 sz = *reinterpret_cast(hdr + 4); + if (!memcmp(hdr, "fmt ", 4)) { + fread(&fmt, 2, 1, f); + fread(&ch, 2, 1, f); + fread(&rate, 4, 1, f); + fseek(f, 6, SEEK_CUR); // skip byte rate + block align + fread(&bits, 2, 1, f); + fseek(f, (long)sz - 16, SEEK_CUR); + } else if (!memcmp(hdr, "data", 4)) { + dSize = sz; + dPos = ftell(f); + break; + } else { + fseek(f, sz, SEEK_CUR); + } + } + + // ── Validate ────────────────────────────────────────────────────────── + // Reject rates above 48 kHz — downsampling would expand rawBuf beyond its + // target-rate output and defeat the purpose of small source files. + if (!dSize || fmt != 1 || ch == 0 || ch > 2 || + (bits != 8 && bits != 16) || rate == 0 || rate > TARGET_RATE) { + fclose(f); return false; + } + + const uint32_t inSamples = dSize / (bits / 8); + const uint32_t rawBytes = inSamples * sizeof(s16); // normalised to 16-bit + const uint32_t rawCap = (rawBytes + AUDIO_ALIGN - 1) & ~(AUDIO_ALIGN - 1); + + void* buf = aligned_alloc(AUDIO_ALIGN, rawCap); + if (!buf) { fclose(f); return false; } + + fseek(f, dPos, SEEK_SET); + s16* out = static_cast(buf); + uint32_t remaining = inSamples; + uint32_t outIdx = 0; + + // ── Chunked read + bit-depth normalisation ──────────────────────────── + constexpr uint32_t CHUNK = 512; + + if (bits == 8) { + u8 chunk[CHUNK]; + while (remaining > 0) { + const uint32_t toRead = std::min(remaining, CHUNK); + if (fread(chunk, 1, toRead, f) != toRead) { + free(buf); fclose(f); return false; + } + for (uint32_t i = 0; i < toRead; ++i) + out[outIdx++] = static_cast((static_cast(chunk[i]) - 128) << 8); + remaining -= toRead; + } + } else { + s16 chunk[CHUNK]; + while (remaining > 0) { + const uint32_t toRead = std::min(remaining, CHUNK); + if (fread(chunk, sizeof(s16), toRead, f) != toRead) { + free(buf); fclose(f); return false; + } + memcpy(out + outIdx, chunk, toRead * sizeof(s16)); + outIdx += toRead; + remaining -= toRead; + } + } + + fclose(f); + + if (rawBytes < rawCap) + memset(static_cast(buf) + rawBytes, 0, rawCap - rawBytes); + + s.rawBuf = buf; + s.rawSize = rawBytes; + s.rawCap = rawCap; + s.sampleRate = rate; + s.isMono = (ch == 1); + + // Grow shared play buffer if this sound's 48 kHz output would exceed it. + growPlayBuf(); + return (m_playBuf != nullptr); + } + + // ── playSound ───────────────────────────────────────────────────────────── + // Drains the audout queue, renders the sound into the shared play buffer, + // then submits. Volume and dock attenuation are applied live inside render. + void Audio::playSound(SoundType type) { + if (!m_enabled.load(std::memory_order_relaxed)) return; + + const uint32_t idx = static_cast(type); + if (idx >= static_cast(SoundType::Count)) return; + + std::lock_guard lock(m_audioMutex); + if (!m_initialized || !m_playBuf) return; + + const CachedSound& s = m_cachedSounds[idx]; + if (!s.rawBuf) return; // sound file not loaded + + // Drain finished buffers so audout's queue stays healthy and so we know + // the shared buffer is no longer in use by a previous submission. + AudioOutBuffer* released = nullptr; + u32 releasedCount = 0; + audoutGetReleasedAudioOutBuffer(&released, &releasedCount); + + const uint32_t outBytes = renderToPlayBuf(s); + if (outBytes == 0) return; + + const uint32_t bufCap = (outBytes + AUDIO_ALIGN - 1) & ~(AUDIO_ALIGN - 1); + + m_audoutBuf = {}; + m_audoutBuf.buffer = m_playBuf; + m_audoutBuf.buffer_size = bufCap; + m_audoutBuf.data_size = outBytes; + m_audoutBuf.data_offset = 0; + m_audoutBuf.next = nullptr; + + AudioOutBuffer* rel = nullptr; + audoutPlayBuffer(&m_audoutBuf, &rel); + } + + // ── Volume / enable accessors ───────────────────────────────────────────── + + // Volume is read live in renderToPlayBuf() — no stale marking needed. + void Audio::setMasterVolume(float v) { + const int32_t fixed = static_cast(std::clamp(v, 0.0f, 1.0f) * 256.0f); + m_masterVolumeFixed.store(fixed, std::memory_order_relaxed); + } + + void Audio::setEnabled(bool e) { + m_enabled.store(e, std::memory_order_relaxed); + } + + bool Audio::isEnabled() { + return m_enabled.load(std::memory_order_relaxed); + } + +} // namespace ult \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp new file mode 100644 index 00000000..f61cfa9c --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp @@ -0,0 +1,52 @@ +/******************************************************************************** + * File: debug_funcs.cpp + * Author: ppkantorski + * Description: + * This source file contains the implementation of debugging functions for the + * Ultrahand Overlay project. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "debug_funcs.hpp" + +namespace ult { + #if USING_LOGGING_DIRECTIVE + // Define static variables + const std::string defaultLogFilePath = "sdmc:/switch/.packages/log.txt"; + std::string logFilePath = defaultLogFilePath; + bool disableLogging = true; + std::mutex logMutex; + + void logMessage(const char* message) { + std::time_t currentTime = std::time(nullptr); + std::tm* timeInfo = std::localtime(¤tTime); + char timestamp[30]; + strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S] ", timeInfo); + + { + std::lock_guard lock(logMutex); + + FILE* file = fopen(logFilePath.c_str(), "a"); + if (file != nullptr) { + fputs(timestamp, file); + fputs(message, file); + fputc('\n', file); + fclose(file); + } + } + } + + // Overload for std::string + void logMessage(const std::string& message) { + logMessage(message.c_str()); + } + #endif +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp new file mode 100644 index 00000000..cf13e673 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp @@ -0,0 +1,754 @@ +/******************************************************************************** + * File: download_funcs.cpp + * Author: ppkantorski + * Description: + * This source file provides implementations for the functions declared in + * download_funcs.hpp. These functions utilize libcurl for downloading files + * from the internet and minizip-ng for extracting ZIP archives with proper + * 64-bit file support. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "download_funcs.hpp" + + +namespace ult { + +// Base loader definitions +size_t DOWNLOAD_READ_BUFFER = 32*1024;//64 * 1024;//4096*10; +size_t DOWNLOAD_WRITE_BUFFER = 16*1024;//64 * 1024; +size_t UNZIP_READ_BUFFER = 32*1024;//131072*2;//4096*4; +size_t UNZIP_WRITE_BUFFER = 16*1024;//131072*2;//4096*4; + +// User agent string for curl requests +static constexpr const char* userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"; + +// Shared atomic flag to indicate whether to abort the download operation +std::atomic abortDownload(false); +// Define an atomic bool for interpreter completion +std::atomic abortUnzip(false); +std::atomic downloadPercentage(-1); +std::atomic unzipPercentage(-1); + +// Thread-safe curl initialization +static std::mutex curlInitMutex; +static std::atomic curlInitialized(false); + + +// Definition of CurlDeleter +struct CurlDeleter { + void operator()(CURL* curl) const noexcept { + if (curl) { + curl_easy_cleanup(curl); + } + } +}; + +struct FileDeleter { + void operator()(FILE* f) const { + if (f) { + fclose(f); + } + } +}; + +// Using stdio.h functions (FILE*, fwrite) +size_t writeCallback(void* ptr, size_t size, size_t nmemb, FILE* stream) { + if (!ptr || !stream) return 0; + return fwrite(ptr, 1, size * nmemb, stream); +} + +// Your C function +int progressCallback(void *ptr, curl_off_t totalToDownload, curl_off_t nowDownloaded, curl_off_t totalToUpload, curl_off_t nowUploaded) { + if (!ptr) return 1; + + auto percentage = static_cast*>(ptr); + + if (totalToDownload > 0) { + percentage->store(static_cast((static_cast(nowDownloaded) / static_cast(totalToDownload)) * 100.0), std::memory_order_release); + } + + if (abortDownload.load(std::memory_order_acquire)) { + percentage->store(-1, std::memory_order_release); + return 1; // Abort the download + } + + return 0; // Continue the download +} + +// Quick connectivity pre-check before spinning up curl +static bool hasInternetAccess() { + if (R_FAILED(nifmInitialize(NifmServiceType_User))) + return false; + NifmInternetConnectionType type; + u32 strength; + NifmInternetConnectionStatus status; + u32 current_addr, subnet_mask, gateway, primary_dns, secondary_dns; + bool connected = R_SUCCEEDED(nifmGetInternetConnectionStatus(&type, &strength, &status)) + && status == NifmInternetConnectionStatus_Connected + && R_SUCCEEDED(nifmGetCurrentIpConfigInfo(¤t_addr, &subnet_mask, &gateway, &primary_dns, &secondary_dns)) + && current_addr != 0 + && primary_dns != 0; + nifmExit(); + return connected; +} + +/** + * @brief Downloads a file from a URL to a specified destination. + * + * @param url The URL of the file to download. + * @param toDestination The destination path where the file should be saved. + * @return True if the download was successful, false otherwise. + */ +bool downloadFile(const std::string& url, const std::string& toDestination, bool noSocketInit, bool noPercentagePolling) { + abortDownload.store(false, std::memory_order_release); + + if (url.find_first_of("{}") != std::string::npos) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Invalid URL: " + url); + #endif + return false; + } + + // Fast pre-flight: ~1.5s max vs curl's unpredictable DNS hang + if (!hasInternetAccess()) { + return false; + } + + std::string destination = toDestination; + if (destination.back() == '/') { + createDirectory(destination); + const size_t lastSlash = url.find_last_of('/'); + if (lastSlash != std::string::npos) { + destination += url.substr(lastSlash + 1); + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Invalid URL: " + url); + #endif + return false; + } + } else { + createDirectory(destination.substr(0, destination.find_last_of('/'))); + } + + const std::string tempFilePath = getParentDirFromPath(destination) + "." + getFileName(destination) + ".tmp"; + + // Alternative method of opening file (depending on your platform, like using POSIX open()) + std::unique_ptr file(fopen(tempFilePath.c_str(), "wb")); + if (!file) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error opening file: " + tempFilePath); + #endif + return false; + } + + // ADD THIS: Set up write buffer for better performance + std::unique_ptr writeBuffer; + if (DOWNLOAD_WRITE_BUFFER > 0) { + writeBuffer = std::make_unique(DOWNLOAD_WRITE_BUFFER); + // _IOFBF = full buffering, _IOLBF = line buffering, _IONBF = no buffering + setvbuf(file.get(), writeBuffer.get(), _IOFBF, DOWNLOAD_WRITE_BUFFER); + } + + static constexpr SocketInitConfig socketInitConfig = { + // TCP buffers + .tcp_tx_buf_size = 16 * 1024, // 16 KB default + .tcp_rx_buf_size = 16 * 1024*2, // 16 KB default + .tcp_tx_buf_max_size = 64 * 1024, // 64 KB default max + .tcp_rx_buf_max_size = 64 * 1024*2, // 64 KB default max + + // UDP buffers + .udp_tx_buf_size = 512, // 512 B default + .udp_rx_buf_size = 512, // 512 B default + + // Socket buffer efficiency + .sb_efficiency = 1, // 0 = default, balanced memory vs CPU + // 1 = prioritize memory efficiency (smaller internal allocations) + .bsd_service_type = BsdServiceType_Auto // Auto-select service + }; + + if (!noSocketInit) { + if (!R_SUCCEEDED(socketInitialize(&socketInitConfig))) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to initialize socket."); + #endif + return false; + } + } + + std::unique_ptr curl(curl_easy_init()); + if (!curl) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error initializing curl."); + #endif + + file.reset(); + writeBuffer.reset(); + return false; + } + + // Only initialize downloadPercentage if we're tracking progress + if (!noPercentagePolling) { + downloadPercentage.store(0, std::memory_order_release); + } + + curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str()); + curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, writeCallback); + curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, file.get()); + + // Conditionally set up progress callback based on noPercentagePolling + if (noPercentagePolling) { + // Disable progress function entirely + curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 1L); + } else { + // Enable progress callback for percentage updates + curl_easy_setopt(curl.get(), CURLOPT_NOPROGRESS, 0L); + curl_easy_setopt(curl.get(), CURLOPT_XFERINFOFUNCTION, progressCallback); + curl_easy_setopt(curl.get(), CURLOPT_XFERINFODATA, &downloadPercentage); + } + + curl_easy_setopt(curl.get(), CURLOPT_USERAGENT, userAgent); + curl_easy_setopt(curl.get(), CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1); // Enable HTTP/2 + curl_easy_setopt(curl.get(), CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); + curl_easy_setopt(curl.get(), CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2); // Force TLS 1.2 + + curl_easy_setopt(curl.get(), CURLOPT_FOLLOWLOCATION, 1L); + curl_easy_setopt(curl.get(), CURLOPT_BUFFERSIZE, DOWNLOAD_READ_BUFFER); // Increase buffer size + + // Add timeout options + curl_easy_setopt(curl.get(), CURLOPT_CONNECTTIMEOUT, 4L); // 10 seconds to connect + curl_easy_setopt(curl.get(), CURLOPT_LOW_SPEED_LIMIT, 1L); // 1 byte/s (virtually any progress) + curl_easy_setopt(curl.get(), CURLOPT_LOW_SPEED_TIME, 60L); // 1 minutes of no progress + + //curl_easy_setopt(curl.get(), CURLOPT_DNS_USE_GLOBAL_CACHE, 0L); + //curl_easy_setopt(curl.get(), CURLOPT_FORBID_REUSE, 1L); + //curl_easy_setopt(curl.get(), CURLOPT_CLOSESOCKETDATA, NULL); // ensure no dangling sockets + //curl_easy_setopt(curl.get(), CURLOPT_TCP_NODELAY, 1L); + + CURLcode result = curl_easy_perform(curl.get()); + + // Check HTTP response code BEFORE closing file/curl + long http_code = 0; + curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code); + + file.reset(); + writeBuffer.reset(); + curl.reset(); + + if (!noSocketInit) { + socketExit(); + } + + // Check for HTTP errors (404, 500, etc.) + if (result == CURLE_OK && (http_code < 200 || http_code >= 300)) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("HTTP error " + std::to_string(http_code) + " downloading: " + url); + #endif + deleteFileOrDirectory(tempFilePath); + if (!noPercentagePolling) { + downloadPercentage.store(-1, std::memory_order_release); + } + return false; + } + + + if (result != CURLE_OK) { + #if USING_LOGGING_DIRECTIVE + if (result == CURLE_ABORTED_BY_CALLBACK) { + if (!disableLogging) + logMessage("Download aborted by user: " + url); + } else if (result == CURLE_OPERATION_TIMEDOUT) { + if (!disableLogging) + logMessage("Download timed out: " + url); + } else if (result == CURLE_COULDNT_CONNECT) { + if (!disableLogging) + logMessage("Could not connect to: " + url); + } else { + if (!disableLogging) + logMessage("Error downloading file: " + std::string(curl_easy_strerror(result))); + } + #endif + deleteFileOrDirectory(tempFilePath); + if (!noPercentagePolling) { + downloadPercentage.store(-1, std::memory_order_release); + } + return false; + } + + // Alternative method for checking if the file is empty (POSIX example) + struct stat fileStat; + if (stat(tempFilePath.c_str(), &fileStat) != 0 || fileStat.st_size == 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error downloading file: Empty file"); + #endif + deleteFileOrDirectory(tempFilePath); + // Only update percentage if we're tracking it + if (!noPercentagePolling) { + downloadPercentage.store(-1, std::memory_order_release); + } + return false; + } + + // Only update percentage if we're tracking it + if (!noPercentagePolling) { + downloadPercentage.store(100, std::memory_order_release); + } + + // CHECK FOR PROTECTED FILES AND ADD .ultra EXTENSION IF NEEDED + if (PROTECTED_FILES.find(destination) != PROTECTED_FILES.end()) { + destination += ".ultra"; + + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Protected file detected, renaming download to: " + destination); + #endif + } + + moveFile(tempFilePath, destination); + + return true; +} + + +/** + * @brief Custom I/O function for opening files with larger buffer + */ +static voidpf ZCALLBACK fopen64_file_func_custom(voidpf opaque, const void* filename, int mode) { + FILE* file = nullptr; + const char* mode_fopen = nullptr; + + if ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ) + mode_fopen = "rb"; + else if (mode & ZLIB_FILEFUNC_MODE_EXISTING) + mode_fopen = "r+b"; + else if (mode & ZLIB_FILEFUNC_MODE_CREATE) + mode_fopen = "wb"; + + if ((filename != nullptr) && (mode_fopen != nullptr)) { + file = fopen((const char*)filename, mode_fopen); + if (file && ((mode & ZLIB_FILEFUNC_MODE_READWRITEFILTER) == ZLIB_FILEFUNC_MODE_READ)) { + // Set 64KB buffer for reading the ZIP file - reduces syscalls + setvbuf(file, nullptr, _IOFBF, UNZIP_READ_BUFFER); + } + } + return file; +} + +static int ZCALLBACK fclose64_file_func_custom(voidpf opaque, voidpf stream) { + int ret = EOF; + if (stream != nullptr) { + ret = fclose((FILE*)stream); + } + return ret; +} + +/** + * @brief Extracts files from a ZIP archive to a specified destination. + * + * Ultra-optimized single-pass extraction with smooth byte-based progress reporting + * using miniz with proper 64-bit file support and streaming extraction. + * Fixed memory leaks with RAII for proper resource cleanup on abort. + * + * @param zipFilePath The path to the ZIP archive file. + * @param toDestination The destination directory where files should be extracted. + * @return True if the extraction was successful, false otherwise. + */ +bool unzipFile(const std::string& zipFilePath, const std::string& toDestination) { + abortUnzip.store(false, std::memory_order_release); + unzipPercentage.store(0, std::memory_order_release); + + // Time-based abort checking - pre-calculated constants + bool success = true; + + // RAII wrapper for unzFile + struct UnzFileManager { + unzFile file = nullptr; + + UnzFileManager(const std::string& path) { + zlib_filefunc64_def ffunc; + fill_fopen64_filefunc(&ffunc); + ffunc.zopen64_file = fopen64_file_func_custom; + ffunc.zclose_file = fclose64_file_func_custom; + file = unzOpen2_64(path.c_str(), &ffunc); + } + + ~UnzFileManager() { + if (file) { + unzClose(file); + file = nullptr; + } + } + + bool is_valid() const { return file != nullptr; } + operator unzFile() const { return file; } + }; + + // RAII wrapper for output file + struct OutputFileManager { + FILE* file = nullptr; + std::unique_ptr buffer; + size_t bufferSize; + + OutputFileManager(size_t bufSize) : bufferSize(bufSize) { + buffer = std::make_unique(bufferSize); + } + + bool open(const std::string& path) { + close(); + file = fopen(path.c_str(), "wb"); + if (file) { + setvbuf(file, buffer.get(), _IOFBF, bufferSize); + } + return file != nullptr; + } + + void close() { + if (file) { + fclose(file); + file = nullptr; + } + } + + bool is_open() const { return file != nullptr; } + + size_t write(const void* data, size_t size) { + return file ? fwrite(data, 1, size, file) : 0; + } + + ~OutputFileManager() { close(); } + }; + + UnzFileManager zipFile(zipFilePath); + if (!zipFile.is_valid()) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open zip file: " + zipFilePath); + #endif + return false; + } + + // Get global info about the ZIP file + unz_global_info64 globalInfo; + if (unzGetGlobalInfo64(zipFile, &globalInfo) != UNZ_OK) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to get zip file info"); + #endif + return false; + } + + const uLong numFiles = globalInfo.number_entry; + if (numFiles == 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("No files found in archive"); + #endif + return false; + } + + // ALWAYS calculate total size for accurate byte-based progress + ZPOS64_T totalUncompressedSize = 0; + char tempFilenameBuffer[512]; + unz_file_info64 fileInfo; + + // First pass: calculate total uncompressed size + int result = unzGoToFirstFile(zipFile); + while (result == UNZ_OK) { + if (abortUnzip.load(std::memory_order_relaxed)) { + unzipPercentage.store(-1, std::memory_order_release); + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Extraction aborted during size calculation"); + #endif + abortUnzip.store(false, std::memory_order_release); + return false; + } + + if (unzGetCurrentFileInfo64(zipFile, &fileInfo, tempFilenameBuffer, sizeof(tempFilenameBuffer), + nullptr, 0, nullptr, 0) == UNZ_OK) { + const size_t nameLen = strlen(tempFilenameBuffer); + if (nameLen > 0 && tempFilenameBuffer[nameLen - 1] != '/') { + totalUncompressedSize += std::max(fileInfo.uncompressed_size, static_cast(1)); + } + } + result = unzGoToNextFile(zipFile); + } + + // Fallback to 1 if no actual data (avoid division by zero) + if (totalUncompressedSize == 0) { + totalUncompressedSize = 1; + } + + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) { + logMessage("Processing " + std::to_string(numFiles) + " files, " + + std::to_string(totalUncompressedSize) + " total bytes from archive"); + } + + #endif + + // Pre-allocate ALL reusable strings and variables outside the main loop + std::string fileName, extractedFilePath, directoryPath; + + // Single large buffer for extraction - reused for all files + const size_t bufferSize = UNZIP_WRITE_BUFFER; + + std::unique_ptr writeBuffer = std::make_unique(bufferSize); + + char filenameBuffer[512]; // Stack allocated for filename reading + + // Progress tracking variables - OPTIMIZED for smooth byte-based tracking + ZPOS64_T totalBytesProcessed = 0; + uLong filesProcessed = 0; + int currentProgress = 0; // Current percentage (0-100) + + // Create output file manager + OutputFileManager outputFile(bufferSize); + + // Loop variables moved outside + bool extractSuccess; + ZPOS64_T fileBytesProcessed; + int bytesRead; + + // String operation variables + const char* filename; + size_t nameLen; + size_t lastSlashPos; + size_t invalid_pos; + size_t start_pos; + + // Ensure destination directory exists + createDirectory(toDestination); + + // Ensure destination ends with '/' - pre-allocate final string + std::string destination; + + destination = toDestination; + if (!destination.empty() && destination.back() != '/') { + destination += '/'; + } + + int newProgress;; + + // Extract files + result = unzGoToFirstFile(zipFile); + while (result == UNZ_OK && success) { + + if (abortUnzip.load(std::memory_order_relaxed)) { + success = false; + break; // RAII will handle cleanup + } + + // Get current file info - reuse fileInfo variable + if (unzGetCurrentFileInfo64(zipFile, &fileInfo, filenameBuffer, sizeof(filenameBuffer), + nullptr, 0, nullptr, 0) != UNZ_OK) { + result = unzGoToNextFile(zipFile); + continue; + } + + filename = filenameBuffer; + + // Quick filename validation + if (!filename || filename[0] == '\0') { + result = unzGoToNextFile(zipFile); + continue; + } + + nameLen = strlen(filename); + if (nameLen > 0 && filename[nameLen - 1] == '/') { // Skip directories + result = unzGoToNextFile(zipFile); + continue; + } + + // Build extraction path - reuse allocated strings + fileName.assign(filename, nameLen); + extractedFilePath = destination; + extractedFilePath += fileName; + + // Optimized character cleaning - only if needed + invalid_pos = extractedFilePath.find_first_of(":*?\"<>|"); + if (invalid_pos != std::string::npos) { + start_pos = std::min(extractedFilePath.find(ROOT_PATH) + 5, extractedFilePath.size()); + auto it = extractedFilePath.begin() + start_pos; + extractedFilePath.erase(std::remove_if(it, extractedFilePath.end(), [](char c) { + return c == ':' || c == '*' || c == '?' || c == '\"' || c == '<' || c == '>' || c == '|'; + }), extractedFilePath.end()); + } + + // CHECK FOR PROTECTED FILES AND ADD .ultra EXTENSION IF NEEDED + if (PROTECTED_FILES.find(extractedFilePath) != PROTECTED_FILES.end()) { + extractedFilePath += ".ultra"; + + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Protected file detected, renaming to: " + extractedFilePath); + #endif + } + + // Open the current file in the ZIP + if (unzOpenCurrentFile(zipFile) != UNZ_OK) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Could not open file in ZIP: " + fileName); + #endif + result = unzGoToNextFile(zipFile); + continue; + } + + // Create directory if needed + lastSlashPos = extractedFilePath.find_last_of('/'); + if (lastSlashPos != std::string::npos) { + directoryPath.assign(extractedFilePath, 0, lastSlashPos + 1); + createDirectory(directoryPath); + } + + // Open output file + if (!outputFile.open(extractedFilePath)) { + unzCloseCurrentFile(zipFile); + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error creating file: " + extractedFilePath); + #endif + result = unzGoToNextFile(zipFile); + continue; + } + + // Extract file data in chunks + extractSuccess = true; + fileBytesProcessed = 0; + + + while ((bytesRead = unzReadCurrentFile(zipFile, writeBuffer.get(), bufferSize)) > 0) { + if (abortUnzip.load(std::memory_order_relaxed)) { + extractSuccess = false; + break; // RAII will handle cleanup + } + + // Write data to file + if (outputFile.write(writeBuffer.get(), bytesRead) != static_cast(bytesRead)) { + extractSuccess = false; + break; + } + + // Update progress tracking + fileBytesProcessed += bytesRead; + totalBytesProcessed += bytesRead; + + // FIXED: Allow progress to reach 100% naturally during processing + if (totalUncompressedSize > 0) { + newProgress = static_cast((totalBytesProcessed * 100) / totalUncompressedSize); + if (newProgress > currentProgress && newProgress <= 100) { + currentProgress = newProgress; + unzipPercentage.store(currentProgress, std::memory_order_release); + + #if USING_LOGGING_DIRECTIVE + // Only log at 10% intervals to avoid spam + if (currentProgress % 10 == 0) { + if (!disableLogging) { + logMessage("Progress: " + std::to_string(currentProgress) + "% (" + + std::to_string(totalBytesProcessed) + "/" + + std::to_string(totalUncompressedSize) + " bytes)"); + } + } + #endif + } + } + } + + // CRITICAL FIX: Handle 0-byte files that don't enter the while loop + if (bytesRead == 0 && fileBytesProcessed == 0 && extractSuccess) { + // This is a 0-byte file - update progress by 1 byte equivalent + totalBytesProcessed += 1; + + // Update progress for 0-byte files + if (totalUncompressedSize > 0) { + newProgress = static_cast((totalBytesProcessed * 100) / totalUncompressedSize); + if (newProgress > currentProgress && newProgress <= 100) { + currentProgress = newProgress; + unzipPercentage.store(currentProgress, std::memory_order_release); + + #if USING_LOGGING_DIRECTIVE + if (currentProgress % 10 == 0) { + if (!disableLogging) + logMessage("Progress: " + std::to_string(currentProgress) + "% (0-byte file processed)"); + } + #endif + } + } + } + + // Check for read errors + if (bytesRead < 0) { + extractSuccess = false; + } + + // Close current file handles + outputFile.close(); + unzCloseCurrentFile(zipFile); + + if (!extractSuccess) { + deleteFileOrDirectory(extractedFilePath); + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to extract: " + fileName); + #endif + + if (abortUnzip.load(std::memory_order_relaxed)) { + success = false; + break; + } + } else { + filesProcessed++; + } + + // Move to next file + result = unzGoToNextFile(zipFile); + } + + writeBuffer.reset(); + + // Check final abort state + if (abortUnzip.load(std::memory_order_relaxed)) { + unzipPercentage.store(-1, std::memory_order_release); + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Extraction aborted by user"); + #endif + abortUnzip.store(false, std::memory_order_release); + return false; + } + + if (success && filesProcessed > 0) { + abortUnzip.store(false, std::memory_order_release); + unzipPercentage.store(100, std::memory_order_release); + + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) { + logMessage("Extraction completed: " + std::to_string(filesProcessed) + " files, " + + std::to_string(totalBytesProcessed) + " bytes"); + } + #endif + + return true; + } else { + abortUnzip.store(false, std::memory_order_release); + unzipPercentage.store(-1, std::memory_order_release); + return false; + } +} +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp new file mode 100644 index 00000000..c072b0dc --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp @@ -0,0 +1,424 @@ +/******************************************************************************** + * File: get_funcs.cpp + * Author: ppkantorski + * Description: + * This source file provides the implementations of functions declared in + * get_funcs.hpp. These functions are responsible for retrieving and handling + * data from the file system and JSON files, including parsing overlay module + * information, reading file contents, and accessing structured data used + * in the Ultrahand Overlay project. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "get_funcs.hpp" + + +namespace ult { + + /** + * @brief Concatenates the provided directory and file names to form a destination path. + * + * @param destinationDir The directory where the file should be placed. + * @param fileName The name of the file. + * @return The destination path as a string. + */ + std::string getDestinationPath(const std::string& destinationDir, + const std::string& fileName) + { + // e.g. "foo/bar" + "/" + "baz.txt" → "foo/bar/baz.txt", but if destinationDir ended in '/', + // you’d get "foo/bar//baz.txt" → collapse again: + std::string combined = destinationDir + "/" + fileName; + preprocessPath(combined); + return combined; + } + + /** + * @brief Extracts the value part from a string line containing a key-value pair. + * + * @param line The string line containing a key-value pair (e.g., "key=value"). + * @return The extracted value as a string. If no value is found, an empty string is returned. + */ + std::string getValueFromLine(const std::string& line) { + const size_t equalsPos = line.rfind('='); + if (equalsPos == std::string::npos || equalsPos + 1 >= line.size()) { + return ""; + } + + // OPTIMIZATION: Find trim boundaries directly - no temporary string + size_t start = equalsPos + 1; + size_t end = line.size() - 1; + + // Skip leading whitespace + while (start <= end && (line[start] == ' ' || line[start] == '\t' || + line[start] == '\n' || line[start] == '\r' || + line[start] == '\f' || line[start] == '\v')) { + ++start; + } + + // Skip trailing whitespace + while (end >= start && (line[end] == ' ' || line[end] == '\t' || + line[end] == '\n' || line[end] == '\r' || + line[end] == '\f' || line[end] == '\v')) { + --end; + } + + // Return trimmed substring directly + return (start <= end) ? line.substr(start, end - start + 1) : ""; + } + + + /** + * @brief Extracts the name from a file path, including handling directories. + * + * @param path The file path from which to extract the name. + * @return The extracted name as a string. If the path indicates a directory, it extracts the last directory name. + * If the path is empty or no name is found, an empty string is returned. + */ + std::string getNameFromPath(const std::string& path) { + const size_t lastNonSlash = path.find_last_not_of('/'); + if (lastNonSlash == std::string::npos) { + return ""; // All slashes, or empty string effectively + } + + const size_t lastSlash = path.find_last_of('/', lastNonSlash); + if (lastSlash == std::string::npos) { + return path.substr(0, lastNonSlash + 1); // No slashes, the entire path is a filename + } + + return path.substr(lastSlash + 1, lastNonSlash - lastSlash); // Standard case, efficiently handled + } + + + + /** + * @brief Extracts the file name from a full file path. + * + * This function takes a filesystem path and returns only the file name, + * stripping away any directory paths that precede it. + * + * @param path The full path to the file. + * @return The file name extracted from the full path. + */ + std::string getFileName(const std::string& path) { + const size_t pos = path.find_last_of('/'); + return (pos != std::string::npos) ? path.substr(pos + 1) : ""; + } + + + /** + * @brief Extracts the name of the parent directory from a given file path at a specified level. + * + * @param path The file path from which to extract the parent directory name. + * @param level The level of the parent directory to extract (0 for immediate parent, 1 for grandparent, and so on). + * @return The name of the parent directory at the specified level. + */ + std::string getParentDirNameFromPath(const std::string& path, size_t level) { + if (path.empty()) return ""; + + // Start from the end of the string and move backwards to find the slashes + size_t endPos = path.find_last_not_of('/'); + if (endPos == std::string::npos) return ""; + + size_t pos = path.rfind('/', endPos); + if (pos == std::string::npos || pos == 0) return ""; + + // Navigate up the specified number of levels + while (level-- > 0 && pos != std::string::npos) { + endPos = pos - 1; + pos = path.rfind('/', endPos); + if (pos == std::string::npos || pos == 0) return ""; + } + + size_t start = path.rfind('/', pos - 1); + if (start == std::string::npos) start = 0; + else start += 1; + + // OPTIMIZATION 1: Use find_first_of instead of manual loop - much faster + const bool hasWhitespace = (path.find_first_of(" \t\n\r\f\v", start, pos - start) != std::string::npos); + + if (hasWhitespace) { + // OPTIMIZATION 2: Pre-allocate exact size and build efficiently + const size_t dirNameLen = pos - start; + std::string result; + result.reserve(dirNameLen + 2); // +2 for quotes + + result = '"'; + result.append(path, start, dirNameLen); + result += '"'; + return result; + } else { + return path.substr(start, pos - start); + } + } + + + + /** + * @brief Extracts the parent directory path from a given file path. + * + * @param path The file path from which to extract the parent directory path. + * @return The parent directory path. + */ + std::string getParentDirFromPath(const std::string& path) { + const size_t lastSlash = path.find_last_of('/'); + if (lastSlash != std::string::npos) { + return path.substr(0, lastSlash + 1); + } + return path; + } + + + /** + * @brief Check if a directory entry is a directory (no caching). + * Fast path for known types, stat() only when necessary. + */ + inline bool isEntryDirectory(struct dirent* entry, const std::string& path) { + // Fast path - most filesystems populate d_type correctly + if (entry->d_type == DT_DIR) { + return true; + } else if (entry->d_type != DT_UNKNOWN) { + return false; // DT_REG, DT_LNK, etc. + } + + // Only stat when d_type is unknown (rare on modern filesystems) + struct stat entryStat; + return (stat(path.c_str(), &entryStat) == 0) && S_ISDIR(entryStat.st_mode); + } + + /** + * @brief Gets a list of subdirectories in a directory. + * + * @param directoryPath The path of the directory to search. + * @return A vector of strings containing the names of subdirectories. + */ + std::vector getSubdirectories(const std::string& directoryPath) { + std::vector subdirectories; + std::unique_ptr dir(opendir(directoryPath.c_str())); + + if (!dir) return subdirectories; + + struct dirent* entry; + while ((entry = readdir(dir.get())) != nullptr) { + const std::string entryName = entry->d_name; + + // Skip . and .. + if (entryName == "." || entryName == "..") continue; + + const std::string fullPath = directoryPath + "/" + entryName; + + if (isEntryDirectory(entry, fullPath)) { + subdirectories.emplace_back(entryName); + } + } + + return subdirectories; + } + + + + /** + * @brief Iteratively retrieves a list of files from a directory. + * + * @param directoryPath The path of the directory to search. + * @return A vector of strings containing the paths of the files. + */ + std::vector getFilesListFromDirectory(const std::string& directoryPath) { + std::vector fileList; + std::vector dirsToProcess; + + // Initialize with the starting directory + dirsToProcess.emplace_back(directoryPath); + + // Pre-allocate string buffer to avoid repeated allocations + std::string fullPath; + std::string currentDir; + + size_t dirIndex = 0; + while (dirIndex < dirsToProcess.size()) { + currentDir = std::move(dirsToProcess[dirIndex]); + dirsToProcess[dirIndex].shrink_to_fit(); + dirIndex++; + + std::unique_ptr dir(opendir(currentDir.c_str())); + if (!dir) continue; + + // Cache directory path info + const bool needsSlash = currentDir.back() != '/'; + + struct dirent* entry; + while ((entry = readdir(dir.get())) != nullptr) { + const char* entryName = entry->d_name; + + // Direct comparison without string creation + if (entryName[0] == '.' && (entryName[1] == '\0' || (entryName[1] == '.' && entryName[2] == '\0'))) { + continue; + } + + // More efficient path building + fullPath.clear(); + fullPath.assign(currentDir); + if (needsSlash) fullPath += '/'; + fullPath += entryName; + + if (entry->d_type == DT_REG) { + // Definitely a regular file + fileList.emplace_back(fullPath); + } else if (isEntryDirectory(entry, fullPath)) { + // Add directory to processing queue + dirsToProcess.emplace_back(fullPath); + } + } + } + + return fileList; + } + + + // Iterative function to handle wildcard directories and file patterns + void handleDirectory(const std::string& basePath, + const std::vector& parts, + size_t partIndex, + std::vector& results, + bool directoryOnly, + size_t maxLines) { + + std::vector> stack; + stack.emplace_back(basePath, partIndex); + + // Pre-declare strings to avoid repeated allocations + std::string fullPath; + std::string result; + std::string currentPath; + + struct stat st; + + bool isDir; + size_t currentPartIndex; + + while (!stack.empty()) { + if (maxLines > 0 && results.size() >= maxLines) return; + + std::tie(currentPath, currentPartIndex) = stack.back(); + stack.pop_back(); + + if (currentPartIndex >= parts.size()) continue; + + DIR* dirPtr = opendir(currentPath.c_str()); + if (!dirPtr) continue; + std::unique_ptr dir(dirPtr); + + const std::string& pattern = parts[currentPartIndex]; + const bool isLastPart = (currentPartIndex == parts.size() - 1); + const bool needsSlash = currentPath.back() != '/'; + + struct dirent* entry; + while ((entry = readdir(dir.get())) != nullptr) { + if (maxLines > 0 && results.size() >= maxLines) return; + + const char* name = entry->d_name; + if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'))) continue; + + if (fnmatch(pattern.c_str(), name, FNM_NOESCAPE) != 0) continue; + + if (entry->d_type != DT_UNKNOWN) { + isDir = (entry->d_type == DT_DIR); + } else { + // More efficient path building for stat check + fullPath.clear(); + fullPath.assign(currentPath); + if (needsSlash) fullPath += '/'; + fullPath += name; + isDir = (stat(fullPath.c_str(), &st) == 0) && S_ISDIR(st.st_mode); + } + + if (isLastPart) { + if (!directoryOnly || isDir) { + // More efficient result building + result.clear(); + result.assign(currentPath); + if (needsSlash) result += '/'; + result += name; + if (isDir) result += '/'; + results.emplace_back(std::move(result)); + if (maxLines > 0 && results.size() >= maxLines) return; + } + } else if (isDir) { + // More efficient path building for stack + fullPath.clear(); + fullPath.assign(currentPath); + if (needsSlash) fullPath += '/'; + fullPath += name; + stack.emplace_back(std::move(fullPath), currentPartIndex + 1); + } + } + } + } + + /** + * @brief Gets a list of files and folders based on a wildcard pattern. + * + * This function searches for files and folders in a directory that match the + * specified wildcard pattern. + * + * @param pathPattern The wildcard pattern to match files and folders. + * @return A vector of strings containing the paths of matching files and folders. + */ + std::vector getFilesListByWildcards(const std::string& pathPattern, size_t maxLines) { + std::vector results; + + if (pathPattern.empty()) return results; + + // Disallow any `/**/` or ending with `/**` + if (pathPattern.find("**") != std::string::npos || pathPattern.find("*null") != std::string::npos || pathPattern.find("null*") != std::string::npos) { + return results; // Exclude invalid patterns + } + + const bool directoryOnly = pathPattern.back() == '/'; + const size_t prefixEnd = pathPattern.find(":/"); + + if (prefixEnd == std::string::npos) return results; + + const std::string basePath = pathPattern.substr(0, prefixEnd + 2); + std::vector parts; + + size_t start = prefixEnd + 2; + size_t pos = start; + const size_t pathLen = pathPattern.length(); + + while (pos <= pathLen) { + if (pos == pathLen || pathPattern[pos] == '/') { + if (pos > start) { + parts.emplace_back(pathPattern.data() + start, pos - start); + } + start = pos + 1; + } + ++pos; + } + + if (start < pathLen && !directoryOnly) { + parts.emplace_back(pathPattern.data() + start, pathLen - start); + } + + // Extra: check parsed parts to disallow "**" + for (size_t i = 0; i + 1 < parts.size(); ++i) { + if (parts[i] == "**" && parts[i + 1] == "**") { + return results; // invalid, exclude + } + } + + if (!parts.empty()) { + handleDirectory(basePath, parts, 0, results, directoryOnly, maxLines); + } + + return results; + } + +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp new file mode 100644 index 00000000..0018335b --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp @@ -0,0 +1,194 @@ +/******************************************************************************** + * File: global_vars.cpp + * Author: ppkantorski + * Description: + * This source file provides the definitions of global constants and paths used + * throughout the Ultrahand Overlay project. These constants are essential for + * file management and configuration settings within the application. + * + * For the latest updates and contributions, visit the project's GitHub repository: + * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay + * + * Note: This notice is integral to the project's documentation and must not be + * altered or removed. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "global_vars.hpp" + +namespace ult { + + // Base paths + const std::string ROOT_PATH = "sdmc:/"; + const std::string BASE_CONFIG_PATH = ROOT_PATH + "config/ultrahand/"; + const std::string TESLA_CONFIG_PATH = ROOT_PATH + "config/tesla/"; + const std::string SWITCH_PATH = ROOT_PATH + "switch/"; + + const std::string NX_OVLLOADER_PATH = ROOT_PATH + "config/nx-ovlloader/"; + const std::string OVL_HEAP_CONFIG_PATH = NX_OVLLOADER_PATH + "heap_size.bin"; + const std::string OVL_EXIT_FLAG_PATH = NX_OVLLOADER_PATH + "exit_flag.bin"; + + // Filenames + CONSTEXPR_STRING std::string CONFIG_FILENAME = "config.ini"; + const std::string BOOT_PACKAGE_FILENAME = "boot_package.ini"; + const std::string EXIT_PACKAGE_FILENAME = "exit_package.ini"; + const std::string PACKAGE_FILENAME = "package.ini"; + const std::string THEME_FILENAME = "theme.ini"; + const std::string WALLPAPER_FILENAME = "wallpaper.rgba"; + const std::string FUSE_FILENAME = "fuse.ini"; + const std::string OVERLAYS_INI_FILENAME = "overlays.ini"; + const std::string PACKAGES_INI_FILENAME = "packages.ini"; + const std::string NOTIFICATIONS_FLAG_FILENAME = "NOTIFICATIONS.flag"; + const std::string RELOADING_FLAG_FILENAME = "RELOADING.flag"; + + // Project names + CONSTEXPR_STRING std::string ULTRAHAND_PROJECT_NAME = "ultrahand"; + CONSTEXPR_STRING std::string CAPITAL_ULTRAHAND_PROJECT_NAME = "Ultrahand"; + CONSTEXPR_STRING std::string SPLIT_PROJECT_NAME_1 = "Ultra"; + CONSTEXPR_STRING std::string SPLIT_PROJECT_NAME_2 = "hand"; + + // Paths + const std::string SETTINGS_PATH = BASE_CONFIG_PATH; + const std::string ULTRAHAND_CONFIG_INI_PATH = BASE_CONFIG_PATH + CONFIG_FILENAME; + const std::string TESLA_CONFIG_INI_PATH = TESLA_CONFIG_PATH + CONFIG_FILENAME; + const std::string LANG_PATH = BASE_CONFIG_PATH + "lang/"; + const std::string THEMES_PATH = BASE_CONFIG_PATH + "themes/"; + const std::string WALLPAPERS_PATH = BASE_CONFIG_PATH + "wallpapers/"; + const std::string ASSETS_PATH = BASE_CONFIG_PATH + "assets/"; + const std::string SOUNDS_PATH = BASE_CONFIG_PATH + ".sounds/"; + const std::string LOADED_SOUNDS_PATH = BASE_CONFIG_PATH + "sounds/"; + const std::string FLAGS_PATH = BASE_CONFIG_PATH + "flags/"; + const std::string NOTIFICATIONS_PATH = BASE_CONFIG_PATH + "notifications/"; + const std::string NOTIFICATIONS_ICONS_PATH = ASSETS_PATH + "notifications/"; + const std::string NOTIFICATIONS_FLAGS_PATH = FLAGS_PATH + "notifications/"; + const std::string PAYLOADS_PATH = BASE_CONFIG_PATH + "payloads/"; + const std::string HB_APPSTORE_JSON = SWITCH_PATH + "appstore/.get/packages/UltrahandOverlay/info.json"; + std::string THEME_CONFIG_INI_PATH = BASE_CONFIG_PATH + THEME_FILENAME; + std::string WALLPAPER_PATH = BASE_CONFIG_PATH + WALLPAPER_FILENAME; + const std::string DOWNLOADS_PATH = BASE_CONFIG_PATH + "downloads/"; + const std::string FUSE_DATA_INI_PATH = BASE_CONFIG_PATH + FUSE_FILENAME; + const std::string PACKAGE_PATH = SWITCH_PATH + ".packages/"; + const std::string OVERLAY_PATH = SWITCH_PATH + ".overlays/"; + const std::string OVERLAYS_INI_FILEPATH = BASE_CONFIG_PATH + OVERLAYS_INI_FILENAME; + const std::string PACKAGES_INI_FILEPATH = BASE_CONFIG_PATH + PACKAGES_INI_FILENAME; + const std::string NOTIFICATIONS_FLAG_FILEPATH = FLAGS_PATH + NOTIFICATIONS_FLAG_FILENAME; + const std::string RELOADING_FLAG_FILEPATH = FLAGS_PATH + RELOADING_FLAG_FILENAME; + + // Protected files + const std::set PROTECTED_FILES = { + ROOT_PATH + "atmosphere/package3", + ROOT_PATH + "atmosphere/stratosphere.romfs" + }; + + // GitHub URLs + const std::string GITHUB_BASE_URL = "https://github.com/ppkantorski/"; + const std::string GITHUB_RAW_BASE_URL = "https://raw.githubusercontent.com/ppkantorski/"; + const std::string ULTRAHAND_REPO_URL = GITHUB_BASE_URL + "Ultrahand-Overlay/"; + const std::string INCLUDED_THEME_FOLDER_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/themes/"; + const std::string LATEST_RELEASE_INFO_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/RELEASE.ini"; + const std::string LATEST_UPDATER_INI_URL = ULTRAHAND_REPO_URL + "releases/latest/download/update.ini"; + const std::string UPDATER_PAYLOAD_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/payloads/ultrahand_updater.bin"; + + // Launch options + const std::string LAUNCH_ARGS_STR = "launch_args"; + const std::string USE_LAUNCH_ARGS_STR = "use_launch_args"; + const std::string USE_QUICK_LAUNCH_STR = "use_quick_launch"; + const std::string USE_BOOT_PACKAGE_STR = "use_boot_package"; + const std::string USE_EXIT_PACKAGE_STR = "use_exit_package"; + const std::string USE_LOGGING_STR = "use_logging"; + + // Combos + CONSTEXPR_STRING std::string TESLA_COMBO_STR = "L+DDOWN+RS"; + CONSTEXPR_STRING std::string ULTRAHAND_COMBO_STR = "ZL+ZR+DDOWN"; + + // System / mode strings + CONSTEXPR_STRING std::string FUSE_STR = "fuse"; + CONSTEXPR_STRING std::string TESLA_STR = "tesla"; + CONSTEXPR_STRING std::string ERISTA_STR = "erista"; + CONSTEXPR_STRING std::string MARIKO_STR = "mariko"; + CONSTEXPR_STRING std::string HANDHELD_STR = "handheld"; + CONSTEXPR_STRING std::string DOCKED_STR = "docked"; + CONSTEXPR_STRING std::string KEY_COMBO_STR = "key_combo"; + CONSTEXPR_STRING std::string DEFAULT_LANG_STR = "default_lang"; + + // Generic strings + CONSTEXPR_STRING std::string LIST_STR = "list"; + CONSTEXPR_STRING std::string LIST_FILE_STR = "list_file"; + CONSTEXPR_STRING std::string JSON_STR = "json"; + CONSTEXPR_STRING std::string JSON_FILE_STR = "json_file"; + CONSTEXPR_STRING std::string INI_FILE_STR = "ini_file"; + CONSTEXPR_STRING std::string HEX_FILE_STR = "hex_file"; + CONSTEXPR_STRING std::string PACKAGE_STR = "package"; + CONSTEXPR_STRING std::string PACKAGES_STR = "packages"; + CONSTEXPR_STRING std::string OVERLAY_STR = "overlay"; + CONSTEXPR_STRING std::string OVERLAYS_STR = "overlays"; + const std::string IN_OVERLAY_STR = "in_overlay"; + const std::string IN_HIDDEN_OVERLAY_STR = "in_hidden_overlay"; + const std::string IN_HIDDEN_PACKAGE_STR = "in_hidden_package"; + CONSTEXPR_STRING std::string FILE_STR = "file"; + CONSTEXPR_STRING std::string SYSTEM_STR = "system"; + CONSTEXPR_STRING std::string MODE_STR = "mode"; + CONSTEXPR_STRING std::string GROUPING_STR = "grouping"; + CONSTEXPR_STRING std::string FOOTER_STR = "footer"; + const std::string FOOTER_HIGHLIGHT_STR = "footer_highlight"; + CONSTEXPR_STRING std::string TOGGLE_STR = "toggle"; + CONSTEXPR_STRING std::string LEFT_STR = "left"; + CONSTEXPR_STRING std::string RIGHT_STR = "right"; + CONSTEXPR_STRING std::string CENTER_STR = "center"; + CONSTEXPR_STRING std::string CHAR_STR = "char"; + CONSTEXPR_STRING std::string WORD_STR = "word"; + CONSTEXPR_STRING std::string NONE_STR = "none"; + CONSTEXPR_STRING std::string HIDE_STR = "hide"; + CONSTEXPR_STRING std::string STAR_STR = "star"; + CONSTEXPR_STRING std::string PRIORITY_STR = "priority"; + CONSTEXPR_STRING std::string ON_STR = "on"; + CONSTEXPR_STRING std::string OFF_STR = "off"; + CONSTEXPR_STRING std::string CAPITAL_ON_STR = "On"; + CONSTEXPR_STRING std::string CAPITAL_OFF_STR = "Off"; + CONSTEXPR_STRING std::string TRUE_STR = "true"; + CONSTEXPR_STRING std::string FALSE_STR = "false"; + CONSTEXPR_STRING std::string GLOBAL_STR = "global"; + CONSTEXPR_STRING std::string DEFAULT_STR = "default"; + CONSTEXPR_STRING std::string HOLD_STR = "hold"; + CONSTEXPR_STRING std::string SLOT_STR = "slot"; + CONSTEXPR_STRING std::string OPTION_STR = "option"; + CONSTEXPR_STRING std::string FORWARDER_STR = "forwarder"; + CONSTEXPR_STRING std::string TEXT_STR = "text"; + CONSTEXPR_STRING std::string TABLE_STR = "table"; + CONSTEXPR_STRING std::string TRACKBAR_STR = "trackbar"; + CONSTEXPR_STRING std::string STEP_TRACKBAR_STR = "step_trackbar"; + const std::string NAMED_STEP_TRACKBAR_STR = "named_step_trackbar"; + CONSTEXPR_STRING std::string NULL_STR = "null"; + CONSTEXPR_STRING std::string THEME_STR = "theme"; + CONSTEXPR_STRING std::string NOT_AVAILABLE_STR = "Not available"; + CONSTEXPR_STRING std::string MEMORY_STR = "memory"; + + // Pre-defined symbols + CONSTEXPR_STRING std::string OPTION_SYMBOL = "\u22EF"; + CONSTEXPR_STRING std::string DROPDOWN_SYMBOL = "\uE14A"; + CONSTEXPR_STRING std::string CHECKMARK_SYMBOL = "\uE14B"; + CONSTEXPR_STRING std::string CROSSMARK_SYMBOL = "\uE14C"; + CONSTEXPR_STRING std::string DOWNLOAD_SYMBOL = "\u2193"; + CONSTEXPR_STRING std::string UNZIP_SYMBOL = "\u2191"; + CONSTEXPR_STRING std::string COPY_SYMBOL = "\u2192"; + CONSTEXPR_STRING std::string INPROGRESS_SYMBOL = "\u25CF"; + CONSTEXPR_STRING std::string STAR_SYMBOL = "\u2605"; + CONSTEXPR_STRING std::string DIVIDER_SYMBOL = ""; + CONSTEXPR_STRING std::string NOTIFY_HEADER = " "; + CONSTEXPR_STRING std::string HOLD_A_SYMBOL = ""; + + const std::vector THROBBER_SYMBOLS = {"", "", "", "", "", "", "", ""}; + + // Atomic variables for progress tracking + std::atomic displayPercentage(0); // for interpreter percentage progress + + void resetPercentages() { + displayPercentage.store(-1, std::memory_order_release); + downloadPercentage.store(-1, std::memory_order_release); + unzipPercentage.store(-1, std::memory_order_release); + copyPercentage.store(-1, std::memory_order_release); + } + +} // namespace ult \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp new file mode 100644 index 00000000..49cc599e --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp @@ -0,0 +1,199 @@ +/******************************************************************************** + * File: haptics.cpp + * Author: ppkantorski + * Description: + * This source file provides implementations for the functions declared in + * haptics.hpp. These functions manage haptic feedback for the Ultrahand Overlay + * using libnx’s vibration interfaces. It includes routines for initializing + * rumble devices, sending vibration patterns, and handling single or double + * click feedback with timing control. Thread safety is maintained through + * atomic operations and synchronization mechanisms. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2025-2026 ppkantorski + ********************************************************************************/ + +#include "haptics.hpp" + +namespace ult { + + // ===== Internal state (private to this file) ===== + static HidVibrationDeviceHandle vibHandheldLeft; + static HidVibrationDeviceHandle vibHandheldRight; + static HidVibrationDeviceHandle vibPlayer1Left; + static HidVibrationDeviceHandle vibPlayer1Right; + static u64 rumbleStartTick = 0; + static u64 doubleClickTick = 0; + static u8 doubleClickPulse = 0; + + static u32 cachedHandheldStyle = 0; + static u32 cachedPlayer1Style = 0; + + // ===== Shared flags (accessible globally) ===== + std::atomic clickActive{false}; + std::atomic doubleClickActive{false}; + + // ===== Constants ===== + static constexpr u64 RUMBLE_DURATION_NS = 30'000'000ULL; + static constexpr u64 DOUBLE_CLICK_PULSE_DURATION_NS = 30'000'000ULL; + static constexpr u64 DOUBLE_CLICK_GAP_NS = 100'000'000ULL; + + + static constexpr HidVibrationValue hapticsPreset = { + .amp_low = 0.20f, + .freq_low = 100.0f, + .amp_high = 0.80f, + .freq_high = 300.0f + }; + + static constexpr HidVibrationValue vibrationStop{0}; + + // ===== Internal helpers ===== + static inline void sendVibration(const HidVibrationValue* value) { + if (cachedHandheldStyle) { + hidSendVibrationValue(vibHandheldLeft, value); + hidSendVibrationValue(vibHandheldRight, value); + } + + if (cachedPlayer1Style) { + hidSendVibrationValue(vibPlayer1Left, value); + hidSendVibrationValue(vibPlayer1Right, value); + } + } + + static inline void sendVibration2x(const HidVibrationValue* value) { + sendVibration(value); + sendVibration(value); + } + + // ===== Public API ===== + void initHaptics() { + const u32 handheldStyle = hidGetNpadStyleSet(HidNpadIdType_Handheld); + const u32 player1Style = hidGetNpadStyleSet(HidNpadIdType_No1); + + vibHandheldLeft = vibHandheldRight = vibPlayer1Left = vibPlayer1Right = + (HidVibrationDeviceHandle)0; + + static HidVibrationDeviceHandle tmp[2]; + + if (handheldStyle) { + hidInitializeVibrationDevices(tmp, 2, HidNpadIdType_Handheld, + (HidNpadStyleTag)handheldStyle); + vibHandheldLeft = tmp[0]; + vibHandheldRight = tmp[1]; + } + + if (player1Style) { + hidInitializeVibrationDevices(tmp, 2, HidNpadIdType_No1, + (HidNpadStyleTag)player1Style); + vibPlayer1Left = tmp[0]; + vibPlayer1Right = tmp[1]; + } + + cachedHandheldStyle = handheldStyle; + cachedPlayer1Style = player1Style; + } + + void checkAndReinitHaptics() { + static u32 lastHandheldStyle = 0; + static u32 lastPlayer1Style = 0; + + const u32 currentHandheldStyle = hidGetNpadStyleSet(HidNpadIdType_Handheld); + const u32 currentPlayer1Style = hidGetNpadStyleSet(HidNpadIdType_No1); + + // Reinitialize only if something changed (appearance/disappearance or style change) + if ((currentHandheldStyle != lastHandheldStyle) || (currentPlayer1Style != lastPlayer1Style)) { + initHaptics(); + } + + // Update last-known styles for change detection + lastHandheldStyle = currentHandheldStyle; + lastPlayer1Style = currentPlayer1Style; + + // Update cached styles used by sendVibration()/rumble paths + cachedHandheldStyle = currentHandheldStyle; + cachedPlayer1Style = currentPlayer1Style; + } + + + void rumbleClick() { + // Use cached style bit instead of querying hid each call + sendVibration(&vibrationStop); + sendVibration2x(&hapticsPreset); + clickActive.store(true, std::memory_order_release); + rumbleStartTick = armGetSystemTick(); + + } + + void rumbleDoubleClick() { + sendVibration(&vibrationStop); + sendVibration2x(&hapticsPreset); + doubleClickActive.store(true, std::memory_order_release); + doubleClickPulse = 1; + doubleClickTick = armGetSystemTick(); // Set ONCE + } + + + void processRumbleStop(u64 nowNs) { + if (clickActive.load(std::memory_order_acquire) && + nowNs - armTicksToNs(rumbleStartTick) >= RUMBLE_DURATION_NS) { + sendVibration(&vibrationStop); + clickActive.store(false, std::memory_order_release); + } + } + + + void processRumbleDoubleClick(u64 nowNs) { + if (!doubleClickActive.load(std::memory_order_acquire)) return; + + const u64 elapsed = nowNs - armTicksToNs(doubleClickTick); // Always from original start + + switch (doubleClickPulse) { + case 1: + if (elapsed >= DOUBLE_CLICK_PULSE_DURATION_NS) { + sendVibration(&vibrationStop); + doubleClickPulse = 2; + // Don't reset tick! + } + break; + + case 2: + if (elapsed >= DOUBLE_CLICK_PULSE_DURATION_NS + DOUBLE_CLICK_GAP_NS) { + sendVibration2x(&hapticsPreset); + doubleClickPulse = 3; + // Don't reset tick! + } + break; + + case 3: + if (elapsed >= (DOUBLE_CLICK_PULSE_DURATION_NS * 2) + DOUBLE_CLICK_GAP_NS) { + sendVibration(&vibrationStop); + doubleClickActive.store(false, std::memory_order_release); + doubleClickPulse = 0; + } + break; + } + } + + + void rumbleDoubleClickStandalone() { + // Standalone uses sleeps, but still use cached style for decision + sendVibration(&vibrationStop); + sendVibration2x(&hapticsPreset); + svcSleepThread(DOUBLE_CLICK_PULSE_DURATION_NS); + + sendVibration(&vibrationStop); + svcSleepThread(DOUBLE_CLICK_GAP_NS); + + sendVibration2x(&hapticsPreset); + svcSleepThread(DOUBLE_CLICK_PULSE_DURATION_NS); + + sendVibration(&vibrationStop); + } +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp new file mode 100644 index 00000000..a96ea595 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp @@ -0,0 +1,773 @@ +/******************************************************************************** + * File: hex_funcs.cpp + * Author: ppkantorski + * Description: + * This source file implements the functions declared in hex_funcs.hpp. + * These functions provide support for manipulating hexadecimal data, + * including conversions between ASCII and hexadecimal strings, + * locating specific hex patterns within files, and editing file contents + * at hex offsets. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "hex_funcs.hpp" + +namespace ult { + size_t HEX_BUFFER_SIZE = 4096;//65536/4; + + // Thread-safe cache and file operation mutexes + std::shared_mutex cacheMutex; // Allows multiple readers, single writer + std::mutex fileWriteMutex; // Protects file write operations + + // For improving the speed of hexing consecutively with the same file and asciiPattern. + std::unordered_map hexSumCache; + + + /** + * @brief Thread-safe cache management functions + */ + void clearHexSumCache() { + std::lock_guard writeLock(cacheMutex); + hexSumCache = {}; + } + + size_t getHexSumCacheSize() { + std::shared_lock readLock(cacheMutex); + return hexSumCache.size(); + } + + /** + * @brief Converts an ASCII string to a hexadecimal string. + * + * This function takes an ASCII string as input and converts it into a hexadecimal string. + * + * @param asciiStr The ASCII string to convert. + * @return The corresponding hexadecimal string. + */ + std::string asciiToHex(const std::string& asciiStr) { + std::string hexStr; + + for (unsigned char c : asciiStr) { + hexStr.push_back(hexLookup[c >> 4]); // High nibble + hexStr.push_back(hexLookup[c & 0x0F]); // Low nibble + } + + return hexStr; + } + + /** + * @brief Converts a decimal string to a fixed-width hexadecimal string. + * + * @param decimalStr The decimal string to convert. + * @param byteGroupSize The number of hex digits to output (must be even for byte alignment). + * @return Hex string of exactly 'byteGroupSize' digits, or empty string if value doesn't fit. + */ + std::string decimalToHex(const std::string& decimalStr, int byteGroupSize) { + const int decimalValue = ult::stoi(decimalStr); + if (decimalValue < 0 || byteGroupSize <= 0 || (byteGroupSize % 2) != 0) { + // Invalid input: negative number, or byteGroupSize <= 0, or odd byteGroupSize + return ""; + } + + // Special case: zero + if (decimalValue == 0) { + return std::string(byteGroupSize, '0'); + } + + // Convert decimalValue to hex (uppercase, minimal length) + std::string hex; + int tempValue = decimalValue; + int remainder; + char hexChar; + while (tempValue > 0) { + remainder = tempValue % 16; + hexChar = (remainder < 10) ? ('0' + remainder) : ('A' + remainder - 10); + hex.insert(hex.begin(), hexChar); + tempValue /= 16; + } + + // Ensure hex length is even by adding leading zero if needed + if (hex.length() % 2 != 0) { + hex.insert(hex.begin(), '0'); + } + + // Minimum size needed to fit hex string + const size_t hexLen = hex.length(); + + // Adjust minimum byteGroupSize to be at least hexLen + size_t minByteGroupSize = std::max(static_cast(byteGroupSize), hexLen); + + // If byteGroupSize was too small, adjust to hex length (must be even) + if (minByteGroupSize % 2 != 0) { + minByteGroupSize++; + } + + // If minByteGroupSize is less than hex length, number doesn't fit + if (minByteGroupSize < hexLen) { + return ""; // can't fit + } + + // Pad with leading zeros to match minByteGroupSize + if (hexLen < minByteGroupSize) { + hex.insert(hex.begin(), minByteGroupSize - hexLen, '0'); + } + + return hex; + } + + + /** + * @brief Converts a hexadecimal string to a decimal string. + * + * This function takes a hexadecimal string as input and converts it into a decimal string. + * + * @param hexStr The hexadecimal string to convert. + * @return The corresponding decimal string. + */ + std::string hexToDecimal(const std::string& hexStr) { + // Convert hexadecimal string to integer + int decimalValue = 0; + const size_t len = hexStr.length(); + + char hexChar; + int value; + + // Iterate over each character in the hexadecimal string + for (size_t i = 0; i < len; ++i) { + hexChar = hexStr[i]; + + // Convert hex character to its decimal value + if (hexChar >= '0' && hexChar <= '9') { + value = hexChar - '0'; + } else if (hexChar >= 'A' && hexChar <= 'F') { + value = 10 + (hexChar - 'A'); + } else if (hexChar >= 'a' && hexChar <= 'f') { + value = 10 + (hexChar - 'a'); + } else { + break; + } + + // Update the decimal value + decimalValue = decimalValue * 16 + value; + } + + // Convert the decimal value to a string + return ult::to_string(decimalValue); + } + + + + std::string hexToReversedHex(const std::string& hexadecimal, int order) { + // Reverse the hexadecimal string in groups of order + std::string reversedHex; + for (int i = hexadecimal.length() - order; i >= 0; i -= order) { + reversedHex += hexadecimal.substr(i, order); + } + + return reversedHex; + } + + /** + * @brief Converts a decimal string to a reversed hexadecimal string. + * + * This function takes a decimal string as input, converts it into a hexadecimal + * string, and reverses the resulting hexadecimal string in groups of byteGroupSize. + * + * @param decimalStr The decimal string to convert. + * @param byteGroupSize The grouping byteGroupSize for reversing the hexadecimal string. + * @return The reversed hexadecimal string. + */ + std::string decimalToReversedHex(const std::string& decimalStr, int byteGroupSize) { + return hexToReversedHex(decimalToHex(decimalStr, byteGroupSize)); + } + + + + /** + * @brief Finds the offsets of hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and returns the file offsets where the data is found. + * + * @param filePath The path to the binary file. + * @param hexData The hexadecimal data to search for. + * @return A vector of strings containing the file offsets where the data is found. + */ + std::vector findHexDataOffsets(const std::string& filePath, const std::string& hexData) { + std::vector offsets; + + FILE* file = fopen(filePath.c_str(), "rb"); + if (!file) { + return offsets; + } + + fseek(file, 0, SEEK_END); + const size_t fileSize = ftell(file); + fseek(file, 0, SEEK_SET); + + if (hexData.length() % 2 != 0) { + fclose(file); + return offsets; + } + + const size_t hexLen = hexData.length(); + const size_t patternLen = hexLen / 2; + + // Use heap allocation for the buffer to avoid stack overflow with large buffer sizes + std::unique_ptr binaryData(new unsigned char[patternLen]); + const unsigned char* hexPtr = reinterpret_cast(hexData.c_str()); + + // Unrolled hex conversion loop + size_t i = 0; + for (; i + 4 <= hexLen; i += 4) { + binaryData[i/2] = (hexTable[hexPtr[i]] << 4) | hexTable[hexPtr[i + 1]]; + binaryData[i/2 + 1] = (hexTable[hexPtr[i + 2]] << 4) | hexTable[hexPtr[i + 3]]; + } + // Handle remaining bytes + for (; i < hexLen; i += 2) { + binaryData[i/2] = (hexTable[hexPtr[i]] << 4) | hexTable[hexPtr[i + 1]]; + } + + // Optimized search variables + const unsigned char* patternPtr = binaryData.get(); + const unsigned char firstByte = patternPtr[0]; + + // Use heap allocation for the buffer to avoid stack overflow with large buffer sizes + std::unique_ptr buffer(new unsigned char[HEX_BUFFER_SIZE]); + size_t bytesRead = 0; + size_t offset = 0; + + + while ((bytesRead = fread(buffer.get(), 1, HEX_BUFFER_SIZE, file)) > 0) { + const unsigned char* bufPtr = buffer.get(); + + // Optimized search with first-byte filtering and loop unrolling + i = 0; + const size_t searchEnd = bytesRead; + + // Process 4 bytes at a time for better cache usage + for (; i + 4 <= searchEnd; i += 4) { + // Check 4 positions at once + if (bufPtr[i] == firstByte) { + if (offset + i + patternLen <= fileSize && + memcmp(bufPtr + i, patternPtr, patternLen) == 0) { + offsets.emplace_back(ult::to_string(offset + i)); + } + } + if (bufPtr[i + 1] == firstByte) { + if (offset + i + 1 + patternLen <= fileSize && + memcmp(bufPtr + i + 1, patternPtr, patternLen) == 0) { + offsets.emplace_back(ult::to_string(offset + i + 1)); + } + } + if (bufPtr[i + 2] == firstByte) { + if (offset + i + 2 + patternLen <= fileSize && + memcmp(bufPtr + i + 2, patternPtr, patternLen) == 0) { + offsets.emplace_back(ult::to_string(offset + i + 2)); + } + } + if (bufPtr[i + 3] == firstByte) { + if (offset + i + 3 + patternLen <= fileSize && + memcmp(bufPtr + i + 3, patternPtr, patternLen) == 0) { + offsets.emplace_back(ult::to_string(offset + i + 3)); + } + } + } + + // Handle remaining bytes + for (; i < searchEnd; ++i) { + if (bufPtr[i] == firstByte) { + if (offset + i + patternLen <= fileSize && + memcmp(bufPtr + i, patternPtr, patternLen) == 0) { + offsets.emplace_back(ult::to_string(offset + i)); + } + } + } + + offset += bytesRead; + } + + fclose(file); + + return offsets; + } + + + + /** + * @brief Edits hexadecimal data in a file at a specified offset. + * + * This function opens a binary file, seeks to a specified offset, and replaces + * the data at that offset with the provided hexadecimal data. + * + * @param filePath The path to the binary file. + * @param offsetStr The offset in the file to perform the edit. + * @param hexData The hexadecimal data to replace at the offset. + */ + void hexEditByOffset(const std::string& filePath, const std::string& offsetStr, const std::string& hexData) { + // Lock file writes to prevent concurrent modifications to the same file + std::lock_guard fileWriteLock(fileWriteMutex); + const std::streampos offset = std::stoll(offsetStr); + + // Open the file for both reading and writing in binary mode + FILE* file = fopen(filePath.c_str(), "rb+"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open the file."); + #endif + return; + } + + // Retrieve the file size + fseek(file, 0, SEEK_END); + const std::streampos fileSize = ftell(file); + + if (offset >= fileSize) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Offset exceeds file size."); + #endif + fclose(file); + return; + } + + // Validate hex data length + const size_t hexLen = hexData.length(); + if (hexLen % 2 != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Invalid hex data length."); + #endif + fclose(file); + return; + } + + // Convert the hex string to binary data using optimized lookup table + const size_t dataLen = hexLen / 2; + std::unique_ptr binaryData(new unsigned char[dataLen]); + const unsigned char* hexPtr = reinterpret_cast(hexData.c_str()); + + // Unrolled hex conversion loop (same as findHexDataOffsets) + size_t i = 0; + for (; i + 4 <= hexLen; i += 4) { + binaryData[i/2] = (hexTable[hexPtr[i]] << 4) | hexTable[hexPtr[i + 1]]; + binaryData[i/2 + 1] = (hexTable[hexPtr[i + 2]] << 4) | hexTable[hexPtr[i + 3]]; + } + // Handle remaining bytes + for (; i < hexLen; i += 2) { + binaryData[i/2] = (hexTable[hexPtr[i]] << 4) | hexTable[hexPtr[i + 1]]; + } + + // Move to the specified offset and write the binary data directly to the file + fseek(file, offset, SEEK_SET); + const size_t bytesWritten = fwrite(binaryData.get(), sizeof(unsigned char), dataLen, file); + if (bytesWritten != dataLen) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to write data to the file."); + #endif + fclose(file); + return; + } + + fclose(file); + } + + + /** + * @brief Edits a specific offset in a file with custom hexadecimal data. + * + * This function searches for a custom pattern in the file and calculates a new offset + * based on user-provided offsetStr and the found pattern. It then replaces the data + * at the calculated offset with the provided hexadecimal data. + * + * @param filePath The path to the binary file. + * @param offsetStr The user-provided offset for the edit. + * @param customPattern The custom pattern to search for in the file. + * @param hexDataReplacement The hexadecimal data to replace at the calculated offset. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + void hexEditByCustomOffset(const std::string& filePath, const std::string& customAsciiPattern, const std::string& offsetStr, const std::string& hexDataReplacement, size_t occurrence) { + + // Create a cache key based on filePath and customAsciiPattern + const std::string cacheKey = filePath + '?' + customAsciiPattern + '?' + ult::to_string(occurrence); + + int hexSum = -1; + + // Thread-safe cache access + { + std::shared_lock readLock(cacheMutex); + const auto cachedResult = hexSumCache.find(cacheKey); + if (cachedResult != hexSumCache.end()) { + hexSum = ult::stoi(cachedResult->second); + } + } + + if (hexSum == -1) { + std::string customHexPattern; + if (customAsciiPattern[0] == '#') { + // remove # + customHexPattern = customAsciiPattern.substr(1); + } else { + // Convert custom ASCII pattern to a custom hex pattern + customHexPattern = asciiToHex(customAsciiPattern); + } + + + // Find hex data offsets in the file + const std::vector offsets = findHexDataOffsets(filePath, customHexPattern); + + if (!offsets.empty()) { + hexSum = ult::stoi(offsets[occurrence]); + + // Thread-safe cache write + { + std::lock_guard writeLock(cacheMutex); + hexSumCache[cacheKey] = ult::to_string(hexSum); + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Offset not found."); + #endif + return; + } + } + + + if (hexSum != -1) { + // Calculate the total offset to seek in the file + hexEditByOffset(filePath, ult::to_string(hexSum + ult::stoi(offsetStr)), hexDataReplacement); + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to find " + customAsciiPattern + "."); + #endif + } + } + + /** + * @brief Finds and replaces hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and replaces them with a specified hexadecimal replacement data. + * + * @param filePath The path to the binary file. + * @param hexDataToReplace The hexadecimal data to search for and replace. + * @param hexDataReplacement The hexadecimal data to replace with. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + void hexEditFindReplace(const std::string& filePath, const std::string& hexDataToReplace, const std::string& hexDataReplacement, size_t occurrence) { + const std::vector offsetStrs = findHexDataOffsets(filePath, hexDataToReplace); + if (!offsetStrs.empty()) { + if (occurrence == 0) { + // Replace all occurrences + for (const std::string& offsetStr : offsetStrs) { + hexEditByOffset(filePath, offsetStr, hexDataReplacement); + } + } else { + // Convert the occurrence string to an integer + if (occurrence > 0 && occurrence <= offsetStrs.size()) { + // Replace the specified occurrence/index + hexEditByOffset(filePath, offsetStrs[occurrence - 1], hexDataReplacement); + } else { + // Invalid occurrence/index specified + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Invalid hex occurrence/index specified."); + #endif + } + } + } + } + + /** + * @brief Finds and replaces hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and replaces them with a specified hexadecimal replacement data. + * + * @param filePath The path to the binary file. + * @param hexDataToReplace The hexadecimal data to search for and replace. + * @param hexDataReplacement The hexadecimal data to replace with. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + std::string parseHexDataAtCustomOffset(const std::string& filePath, const std::string& customAsciiPattern, + const std::string& offsetStr, size_t length, size_t occurrence) { + const std::string cacheKey = filePath + '?' + customAsciiPattern + '?' + ult::to_string(occurrence); + int hexSum = -1; + + // Thread-safe cache read + { + std::shared_lock readLock(cacheMutex); + const auto cachedResult = hexSumCache.find(cacheKey); + if (cachedResult != hexSumCache.end()) { + hexSum = ult::stoi(cachedResult->second); + } + } + + if (hexSum == -1) { + const std::string customHexPattern = asciiToHex(customAsciiPattern); + const std::vector offsets = findHexDataOffsets(filePath, customHexPattern); + + if (!offsets.empty() && offsets.size() > occurrence) { + hexSum = ult::stoi(offsets[occurrence]); + + // Thread-safe cache write + { + std::lock_guard writeLock(cacheMutex); + hexSumCache[cacheKey] = ult::to_string(hexSum); + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Offset not found."); + #endif + return ""; + } + } + + const std::streampos totalOffset = hexSum + std::stoll(offsetStr); + + // Pre-allocate final string size to avoid reallocation + std::string result; + result.reserve(length * 2); + + FILE* file = fopen(filePath.c_str(), "rb"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open the file."); + #endif + return ""; + } + + if (fseek(file, totalOffset, SEEK_SET) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error seeking to offset."); + #endif + fclose(file); + return ""; + } + + // Use heap allocation for the buffer to avoid stack overflow with large buffer sizes + std::unique_ptr buffer(new unsigned char[length]); + const size_t bytesRead = fread(buffer.get(), 1, length, file); + fclose(file); + + if (bytesRead != length) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error reading data from file or end of file reached."); + #endif + return ""; + } + + // Optimized hex conversion - directly build uppercase string + static constexpr char hexDigits[] = "0123456789ABCDEF"; + result.resize(length * 2); + + // Unrolled loop for better performance + size_t i = 0; + for (; i + 4 <= length; i += 4) { + result[i * 2] = hexDigits[(buffer[i] >> 4) & 0xF]; + result[i * 2 + 1] = hexDigits[buffer[i] & 0xF]; + result[i * 2 + 2] = hexDigits[(buffer[i + 1] >> 4) & 0xF]; + result[i * 2 + 3] = hexDigits[buffer[i + 1] & 0xF]; + result[i * 2 + 4] = hexDigits[(buffer[i + 2] >> 4) & 0xF]; + result[i * 2 + 5] = hexDigits[buffer[i + 2] & 0xF]; + result[i * 2 + 6] = hexDigits[(buffer[i + 3] >> 4) & 0xF]; + result[i * 2 + 7] = hexDigits[buffer[i + 3] & 0xF]; + } + // Handle remaining bytes + for (; i < length; ++i) { + result[i * 2] = hexDigits[(buffer[i] >> 4) & 0xF]; + result[i * 2 + 1] = hexDigits[buffer[i] & 0xF]; + } + + + return result; + } + + + + /** + * @brief Finds and replaces hexadecimal data in a file. + * + * This function searches for occurrences of hexadecimal data in a binary file + * and replaces them with a specified hexadecimal replacement data. + * + * @param filePath The path to the binary file. + * @param hexDataToReplace The hexadecimal data to search for and replace. + * @param hexDataReplacement The hexadecimal data to replace with. + * @param occurrence The occurrence/index of the data to replace (default is "0" to replace all occurrences). + */ + + std::string replaceHexPlaceholder(const std::string& arg, const std::string& hexPath) { + std::string replacement = arg; + const std::string searchString = "{hex_file("; + + const size_t startPos = replacement.find(searchString); + const size_t endPos = replacement.find(")}"); + + if (startPos != std::string::npos && endPos != std::string::npos && endPos > startPos) { + const std::string placeholderContent = replacement.substr(startPos + searchString.length(), endPos - startPos - searchString.length()); + + // Split the placeholder content into its components (customAsciiPattern, offsetStr, length) + std::vector components; + + // Use StringStream instead of std::istringstream + StringStream componentStream(placeholderContent); + std::string component; + + while (componentStream.getline(component, ',')) { + trim(component); + components.push_back(component); + } + + if (components.size() == 3) { + // Extract individual components + const std::string customAsciiPattern = components[0]; + const std::string offsetStr = components[1]; + const size_t length = std::stoul(components[2]); + + // Call the parsing function and replace the placeholder + const std::string parsedResult = parseHexDataAtCustomOffset(hexPath, customAsciiPattern, offsetStr, length); + + // Only replace if parsedResult returns a non-empty string + if (!parsedResult.empty()) { + // Replace the entire placeholder with the parsed result + replacement.replace(startPos, endPos - startPos + searchString.length() + 2, parsedResult); + } + } + } + + return replacement; + } + + + + + /** + * @brief Extracts the version string from a binary file. + * + * This function reads a binary file and searches for a version pattern + * in the format "v#.#.#" (e.g., "v1.2.3"). + * + * @param filePath The path to the binary file. + * @return The version string if found; otherwise, an empty string. + */ + std::string extractVersionFromBinary(const std::string &filePath) { + // Step 1: Open the binary file + FILE* file = fopen(filePath.c_str(), "rb"); + if (!file) { + return ""; // Return empty string if file cannot be opened + } + + // Get the file size + fseek(file, 0, SEEK_END); + const std::streamsize size = ftell(file); + fseek(file, 0, SEEK_SET); + + // Read the entire file into a buffer + std::vector buffer(size); + const size_t bytesRead = fread(buffer.data(), sizeof(uint8_t), size, file); + fclose(file); // Close the file after reading + + if (bytesRead != static_cast(size)) { + return ""; // Return empty string if reading fails + } + + // Step 2: Search for the pattern "v#.#.#" + const char* data = reinterpret_cast(buffer.data()); + for (std::streamsize i = 0; i < size; ++i) { + if (data[i] == 'v' && i + 5 < size && + std::isdigit(data[i + 1]) && data[i + 2] == '.' && + std::isdigit(data[i + 3]) && data[i + 4] == '.' && + std::isdigit(data[i + 5])) { + + // Extract the version string + return std::string(data + i, 6); // Return the version string + } + } + + return ""; // Return empty string if no match is found + } + + // 1. Table optimization: Mark as constexpr for compile-time evaluation + static constexpr uint8_t b64_table[256] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,62, 0xFF,0xFF,0xFF,63, + 52,53,54,55,56,57,58,59,60,61,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, + 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF + }; + + // 2. Optimized decode: Pre-calculate output size, reduce bounds checking + static size_t base64_decode(const char* src, uint8_t* out) { + size_t outLen = 0; + const char* p = src; + + // Process 4 chars at a time (unrolled loop for better instruction pipelining) + while (*p) { + uint8_t a = b64_table[static_cast(*p++)]; + if (a == 0xFF) break; + + uint8_t b = b64_table[static_cast(*p++)]; + if (b == 0xFF) break; + + out[outLen++] = (a << 2) | (b >> 4); + + uint8_t cChar = *p++; + if (cChar == '=' || cChar == '\0') break; + + uint8_t c = b64_table[cChar]; + if (c == 0xFF) break; + + out[outLen++] = (b << 4) | (c >> 2); + + uint8_t dChar = *p++; + if (dChar == '=' || dChar == '\0') break; + + uint8_t d = b64_table[dChar]; + if (d == 0xFF) break; + + out[outLen++] = (c << 6) | d; + } + + return outLen; + } + + // 3. Optimized wrapper: Pre-calculate exact output size, avoid vector overhead + std::string decodeBase64ToString(const std::string& b64) { + // Base64 decodes to ~3/4 original size + const size_t maxOutSize = (b64.size() * 3) / 4 + 3; + std::string result(maxOutSize, '\0'); + + const size_t len = base64_decode(b64.c_str(), reinterpret_cast(result.data())); + result.resize(len); + + return result; + } +} diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp new file mode 100644 index 00000000..cf4ba445 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp @@ -0,0 +1,1675 @@ +/******************************************************************************** + * File: ini_funcs.cpp + * Author: ppkantorski + * Description: + * This source file implements the functions declared in ini_funcs.hpp. + * These functions provide support for working with INI (Initialization) files + * in C++. Functionality includes reading and parsing INI files, editing values, + * and cleaning formatting to ensure consistent structure. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include + +namespace ult { + // Thread safety infrastructure + namespace { + std::unordered_map> fileMutexMap; + std::mutex mapMutex; + + std::shared_ptr getFileMutex(const std::string& filePath) { + std::lock_guard lock(mapMutex); + auto it = fileMutexMap.find(filePath); + if (it == fileMutexMap.end()) { + auto mutex = std::make_shared(); + fileMutexMap[filePath] = mutex; + return mutex; + } + return it->second; + } + } + + /** + * @brief Clears unused file mutexes from memory. + * WARNING: Only call this when you're certain NO threads are accessing INI files! + * Best used during application shutdown or maintenance periods. + */ + void clearIniMutexCache() { + std::lock_guard lock(mapMutex); + fileMutexMap.clear(); + } + + + /** + * @brief Retrieves the package header information from an INI file. + * + * This function parses an INI file and extracts the package header information. + * + * @param filePath The path to the INI file. + * @return The package header structure. + */ + PackageHeader getPackageHeaderFromIni(const std::string& filePath) { + auto fileMutex = getFileMutex(filePath); + std::shared_lock lock(*fileMutex); + + PackageHeader packageHeader; + + FILE* file = fopen(filePath.c_str(), "r"); + if (!file) { + return packageHeader; + } + + auto bufferPtr = std::make_unique(1024); + char* buffer = bufferPtr.get(); + std::string line; + + // Create field map once outside the loop + const std::map fieldMap = { + {";title=", &packageHeader.title}, + {";display_title=", &packageHeader.display_title}, + {";version=", &packageHeader.version}, + {";creator=", &packageHeader.creator}, + {";about=", &packageHeader.about}, + {";credits=", &packageHeader.credits}, + {";color=", &packageHeader.color}, + {";show_version=", &packageHeader.show_version}, + {";show_widget=", &packageHeader.show_widget} + }; + + int fieldsFound = 0; + const int totalFields = fieldMap.size(); + + size_t startPos, endPos, first, last; + std::string value; + + size_t len; + while (fgets(buffer, 1024, file) && fieldsFound < totalFields) { + // Reuse line string capacity instead of creating new string + line.assign(buffer); + + // Remove newlines efficiently + len = line.length(); + if (len > 0 && line[len-1] == '\n') { + line.pop_back(); + --len; + if (len > 0 && line[len-1] == '\r') { + line.pop_back(); + } + } + + // Skip empty lines and non-comment lines + if (line.empty() || line[0] != ';') { + line.clear(); // Clear to reuse capacity + continue; + } + + // Process each prefix in the map + for (const auto& [prefix, field] : fieldMap) { + if (line.compare(0, prefix.length(), prefix) == 0) { + startPos = prefix.length(); + endPos = line.find_first_of(";\r\n", startPos); + if (endPos == std::string::npos) { + endPos = line.length(); + } + + // Extract value directly, reusing value string capacity + value.assign(line, startPos, endPos - startPos); + + // Trim whitespace efficiently + first = value.find_first_not_of(" \t"); + if (first == std::string::npos) { + value.clear(); + } else { + last = value.find_last_not_of(" \t"); + if (first != 0 || last != value.length() - 1) { + value.assign(value, first, last - first + 1); + } + } + + // Remove quotes efficiently + if (value.length() >= 2 && + ((value.front() == '"' && value.back() == '"') || + (value.front() == '\'' && value.back() == '\''))) { + value.assign(value, 1, value.length() - 2); + } + + *field = std::move(value); + fieldsFound++; + + // Clear strings to reuse capacity + value.clear(); + break; + } + } + + // Clear line to reuse capacity + line.clear(); + } + + fclose(file); + + return packageHeader; + } + + + + /** + * @brief Splits a string into a vector of substrings using a specified delimiter. + * + * This function splits a given string into multiple substrings based on the specified delimiter. + * + * @param str The input string to be split. + * @param delim The delimiter character used for splitting. + * @return A vector of substrings obtained by splitting the input string. + */ + std::vector split(const std::string& str, char delim) { + std::vector out; + + if (str.empty()) return out; + + const char* data = str.data(); + const char* end = data + str.size(); + const char* start = data; + + while (const char* pos = static_cast(std::memchr(start, delim, end - start))) { + out.emplace_back(start, pos); + start = pos + 1; + } + out.emplace_back(start, end); + + return out; + } + + + /** + * @brief Parses an INI-formatted string into a map of sections and key-value pairs. + * + * This function parses an INI-formatted string and organizes the data into a map, + * where sections are keys and key-value pairs are stored within each section. + * + * @param str The INI-formatted string to parse. + * @return A map representing the parsed INI data. + */ + std::map> parseIni(const std::string &str) { + std::map> iniData; + std::string lastHeader; + lastHeader.reserve(64); + + const char* lineStart = str.c_str(); + const char* lineEnd; + const char* strEnd = lineStart + str.size(); + + auto isWhitespace = [](char c) { + return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v'; + }; + + while (lineStart < strEnd) { + // Find line end + lineEnd = lineStart; + while (lineEnd < strEnd && *lineEnd != '\n') { + lineEnd++; + } + + // Trim whitespace from start + while (lineStart < lineEnd && isWhitespace(*lineStart)) { + lineStart++; + } + + // Trim whitespace from end + while (lineEnd > lineStart && isWhitespace(*(lineEnd-1))) { + lineEnd--; + } + + size_t lineLen = lineEnd - lineStart; + + // Skip empty lines and comments + if (lineLen > 0 && *lineStart != '#') { + if (*lineStart == '[' && *(lineEnd-1) == ']') { + // Section header + lastHeader.assign(lineStart + 1, lineEnd - 1); + iniData[lastHeader]; // Ensure section exists + } else if (!lastHeader.empty()) { + // Key=value pair + const char* eqPos = lineStart; + while (eqPos < lineEnd && *eqPos != '=') { + eqPos++; + } + + if (eqPos < lineEnd) { + // Trim key + const char* keyStart = lineStart; + const char* keyEnd = eqPos; + while (keyStart < keyEnd && isWhitespace(*keyStart)) keyStart++; + while (keyEnd > keyStart && isWhitespace(*(keyEnd-1))) keyEnd--; + + // Trim value + const char* valStart = eqPos + 1; + const char* valEnd = lineEnd; + while (valStart < valEnd && isWhitespace(*valStart)) valStart++; + while (valEnd > valStart && isWhitespace(*(valEnd-1))) valEnd--; + + iniData[lastHeader].emplace( + std::string(keyStart, keyEnd), + std::string(valStart, valEnd) + ); + } + } + } + + // Move to next line + lineStart = lineEnd; + if (lineStart < strEnd && *lineStart == '\n') { + lineStart++; + } + } + + return iniData; + } + + + /** + * @brief Parses an INI file and returns its content as a map of sections and key-value pairs. + * + * This function reads the contents of an INI file located at the specified path, + * parses it into a map structure, where section names are keys and key-value pairs + * are stored within each section. + * + * @param configIniPath The path to the INI file to be parsed. + * @return A map representing the parsed INI data. + */ + std::map> getParsedDataFromIniFile(const std::string& configIniPath) { + auto fileMutex = getFileMutex(configIniPath); + std::shared_lock lock(*fileMutex); + + std::map> parsedData; + + FILE* file = fopen(configIniPath.c_str(), "r"); + if (!file) { + return parsedData; + } + + auto bufferPtr = std::make_unique(1024); + char* buffer = bufferPtr.get(); + std::string key, value; + key.reserve(64); + value.reserve(256); + + std::map* currentSectionMap = nullptr; + + while (fgets(buffer, 1024, file)) { + size_t len = strlen(buffer); + + if (len > 0 && buffer[len-1] == '\n') { + if (--len > 0 && buffer[len-1] == '\r') --len; + } + + if (len == 0) continue; + + const char* start = buffer; + const char* end = buffer + len; + + while (start < end && (*start == ' ' || *start == '\t')) ++start; + while (end > start && (end[-1] == ' ' || end[-1] == '\t')) --end; + + if (start >= end) continue; + + if (*start == '[' && end[-1] == ']') { + if (end - start > 2) { + currentSectionMap = &parsedData[std::string(start + 1, end - 1)]; + } + } else if (currentSectionMap) { + const char* eq = start; + while (eq < end && *eq != '=') ++eq; + + if (eq < end) { + const char* key_end = eq; + while (key_end > start && (key_end[-1] == ' ' || key_end[-1] == '\t')) --key_end; + + if (key_end > start) { + const char* val_start = eq + 1; + while (val_start < end && (*val_start == ' ' || *val_start == '\t')) ++val_start; + + currentSectionMap->emplace( + std::piecewise_construct, + std::forward_as_tuple(start, key_end), + std::forward_as_tuple(val_start, end) + ); + } + } + } + } + + fclose(file); + + return parsedData; + } + + + + /** + * @brief Parses an INI file and retrieves key-value pairs from a specific section. + * + * This function reads the contents of an INI file located at the specified path, + * and returns the key-value pairs within a specific section. Lines starting with + * # or ; are treated as comments and ignored. + * + * @param configIniPath The path to the INI file to be parsed. + * @param sectionName The name of the section to retrieve key-value pairs from. + * @return A map representing the key-value pairs in the specified section. + */ + std::map getKeyValuePairsFromSection(const std::string& configIniPath, const std::string& sectionName) { + auto fileMutex = getFileMutex(configIniPath); + std::shared_lock lock(*fileMutex); + + std::map sectionData; + + + FILE* file = fopen(configIniPath.c_str(), "r"); + if (!file) { + return sectionData; + } + + auto bufferPtr = std::make_unique(1024); + char* buffer = bufferPtr.get(); + std::string line; + line.reserve(256); + + std::string key, value; + key.reserve(64); + value.reserve(128); + + bool inTargetSection = false; + size_t len, delimiterPos; + + while (fgets(buffer, 1024, file)) { + // Remove newline characters + len = strlen(buffer); + if (len > 0 && buffer[len-1] == '\n') { + buffer[--len] = '\0'; + if (len > 0 && buffer[len-1] == '\r') { + buffer[--len] = '\0'; + } + } + + line.assign(buffer); + trim(line); + + if (line.empty()) continue; + + // Skip comment lines + if (line[0] == '#' || line[0] == ';') continue; + + if (line[0] == '[' && line.back() == ']') { + // Compare section directly without extraction + inTargetSection = (line.size() - 2 == sectionName.size() && + line.compare(1, line.size() - 2, sectionName) == 0); + + if (!inTargetSection && !sectionData.empty()) { + break; + } + } else if (inTargetSection) { + delimiterPos = line.find('='); + if (delimiterPos != std::string::npos) { + key.assign(line, 0, delimiterPos); + trim(key); + value.assign(line, delimiterPos + 1, std::string::npos); + trim(value); + sectionData[std::move(key)] = std::move(value); + } + } + } + + fclose(file); + + return sectionData; + } + + + /** + * @brief Parses sections from an INI file and returns them as a list of strings. + * + * This function reads an INI file and extracts the section names from it. + * + * @param filePath The path to the INI file. + * @return A vector of section names. + */ + std::vector parseSectionsFromIni(const std::string& filePath) { + auto fileMutex = getFileMutex(filePath); + std::shared_lock lock(*fileMutex); + + std::vector sections; + + + FILE* file = fopen(filePath.c_str(), "r"); + if (!file) { + return sections; + } + + auto bufferPtr = std::make_unique(1024); + char* buffer = bufferPtr.get(); + std::string line; + //line.reserve(1024); // Add reservation for efficiency + + size_t len; + std::string sectionName; + while (fgets(buffer, 1024, file)) { + // CRITICAL FIX: Remove newlines from fgets + len = strlen(buffer); + if (len > 0 && buffer[len-1] == '\n') { + buffer[len-1] = '\0'; + if (len > 1 && buffer[len-2] == '\r') { + buffer[len-2] = '\0'; + } + } + + line.assign(buffer); // More efficient than string constructor + trim(line); + + // Check if the line contains a section header + if (!line.empty() && line.front() == '[' && line.back() == ']') { + sectionName.assign(line, 1, line.size() - 2); // More efficient + sections.push_back(std::move(sectionName)); // Move for efficiency + } + + // Clear strings to reuse capacity + line.clear(); + sectionName.clear(); + } + + fclose(file); + + return sections; + } + + + + /** + * @brief Parses a specific value from a section and key in an INI file. + * + * @param filePath The path to the INI file. + * @param sectionName The name of the section containing the desired key. + * @param keyName The name of the key whose value is to be retrieved. + * @return The value as a string, or an empty string if the key or section isn't found. + */ + std::string parseValueFromIniSection(const std::string& filePath, const std::string& sectionName, const std::string& keyName) { + auto fileMutex = getFileMutex(filePath); + std::shared_lock lock(*fileMutex); + + std::string value; + + FILE* file = fopen(filePath.c_str(), "r"); + if (!file) { + return value; + } + + auto bufferPtr = std::make_unique(1024); + char* buffer = bufferPtr.get(); + bool inTargetSection = false; + + while (fgets(buffer, 1024, file)) { + size_t len = strlen(buffer); + + // Strip trailing newline/carriage return + if (len > 0 && buffer[len-1] == '\n') { + if (--len > 0 && buffer[len-1] == '\r') --len; + } + + if (len == 0) continue; + + // Trim whitespace + const char* start = buffer; + const char* end = buffer + len; + + while (start < end && (*start == ' ' || *start == '\t')) ++start; + while (end > start && (end[-1] == ' ' || end[-1] == '\t')) --end; + + if (start >= end) continue; + + // Section header + if (*start == '[' && end[-1] == ']') { + if (end - start > 2) { + // Compare directly without constructing string + const size_t sectionLen = end - start - 2; + inTargetSection = (sectionLen == sectionName.length() && + std::memcmp(start + 1, sectionName.data(), sectionLen) == 0); + + // Early exit: left target section without finding key + if (!inTargetSection && value.empty() && sectionLen > 0) { + // We passed a different section; if we already processed target, we're done + // This is implicit - if inTargetSection was true before and now false, we already found it or it doesn't exist + continue; + } + } + } else if (inTargetSection) { + // Find '=' delimiter + const char* eq = start; + while (eq < end && *eq != '=') ++eq; + + if (eq < end) { + // Trim key + const char* key_end = eq; + while (key_end > start && (key_end[-1] == ' ' || key_end[-1] == '\t')) --key_end; + + if (key_end > start) { + const size_t keyLen = key_end - start; + + // Compare directly without constructing string + if (keyLen == keyName.length() && std::memcmp(start, keyName.data(), keyLen) == 0) { + // Trim value + const char* val_start = eq + 1; + while (val_start < end && (*val_start == ' ' || *val_start == '\t')) ++val_start; + + value.assign(val_start, end); + break; // Found it, exit immediately + } + } + } + } + } + + fclose(file); + + return value; + } + + /** + * @brief Cleans the formatting of an INI file by removing empty lines and standardizing section formatting. + * + * This function takes an INI file located at the specified path, removes empty lines, + * and standardizes the formatting of sections by ensuring that there is a newline + * between each section's closing ']' and the next section's opening '['. + * + * @param filePath The path to the INI file to be cleaned. + */ + void cleanIniFormatting(const std::string& filePath) { + auto fileMutex = getFileMutex(filePath); + std::unique_lock lock(*fileMutex); + + const std::string tempPath = filePath + ".tmp"; + + FILE* inputFile = fopen(filePath.c_str(), "r"); + if (!inputFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open the input file: " + filePath); + #endif + return; + } + + FILE* outputFile = fopen(tempPath.c_str(), "w"); + if (!outputFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to create the output file: " + tempPath); + #endif + fclose(inputFile); + return; + } + + // Declare all variables outside the loop + auto linePtr = std::make_unique(1024); + char* line = linePtr.get(); + std::string lineStr; + + bool isNewSection = false; + bool isSection = false; + size_t len = 0; + + while (fgets(line, 1024, inputFile)) { + // Efficient newline removal + len = strlen(line); + if (len > 0 && line[len-1] == '\n') { + line[len-1] = '\0'; + if (len > 1 && line[len-2] == '\r') { + line[len-2] = '\0'; + } + } + + lineStr.assign(line); + trim(lineStr); + + if (!lineStr.empty()) { + isSection = (lineStr[0] == '[' && lineStr.back() == ']'); + + if (isSection) { + if (isNewSection) { + fputc('\n', outputFile); + } + isNewSection = true; + } + + fputs(lineStr.c_str(), outputFile); + fputc('\n', outputFile); + } + // Clear string to reuse capacity + lineStr.clear(); + } + + fclose(inputFile); + fclose(outputFile); + + // Replace the original file with the temp file with error checking + if (std::remove(filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete the original file: " + filePath); + #endif + // Clean up temp file on error + std::remove(tempPath.c_str()); + return; + } + + if (std::rename(tempPath.c_str(), filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to rename the temporary file: " + tempPath); + #endif + } + } + + + /** + * @brief Modifies or creates an INI file by adding or updating key-value pairs in the specified section. + * + * This function attempts to open the specified INI file for reading. If the file doesn't exist, + * it creates a new file and adds the specified section and key-value pair. If the file exists, + * it reads its contents, modifies or adds the key-value pair in the specified section, and saves + * the changes back to the original file. + * + * @param fileToEdit The path to the INI file to be modified or created. + * @param desiredSection The name of the section in which the key-value pair should be added or updated. + * @param desiredKey The key for the key-value pair to be added or updated. + * @param desiredValue The new value for the key-value pair. + * @param desiredNewKey (Optional) If provided, the function will rename the key while preserving the original value. + * @param comment An optional comment to be added (not currently implemented). + */ + void setIniFile(const std::string& fileToEdit, const std::string& desiredSection, const std::string& desiredKey, const std::string& desiredValue, const std::string& desiredNewKey, const std::string& comment) { + auto fileMutex = getFileMutex(fileToEdit); + std::unique_lock lock(*fileMutex); + + std::ios::sync_with_stdio(false); // Disable synchronization between C++ and C I/O. + + if (!isFile(fileToEdit)) { + createDirectory(getParentDirFromPath(fileToEdit)); + } + + FILE* configFile = fopen(fileToEdit.c_str(), "r"); + if (!configFile) { + configFile = fopen(fileToEdit.c_str(), "w"); // Create a new file if it doesn't exist + if (configFile) { + fprintf(configFile, "[%s]\n%s=%s\n", desiredSection.c_str(), desiredKey.c_str(), desiredValue.c_str()); + fclose(configFile); + } + return; + } + + StringStream buffer(""); // Use StringStream to collect results + auto linePtr = std::make_unique(1024); + char* line = linePtr.get(); + bool sectionFound = false; + bool keyFound = false; + bool firstSection = true; // Flag to control new line before first section + std::string currentSection; + std::string lineStr; + std::string key; + + size_t delimiterPos; + size_t len; + const char* start; + const char* end; + + size_t key_start, key_end; + while (fgets(line, 1024, configFile)) { + // More efficient newline removal + len = strlen(line); + if (len > 0 && line[len-1] == '\n') { + line[len-1] = '\0'; + --len; + if (len > 0 && line[len-1] == '\r') { + line[len-1] = '\0'; + --len; + } + } + + // Early exit for empty lines + if (len == 0) continue; + + // Manual trim for better performance + start = line; + while (*start == ' ' || *start == '\t') ++start; + + end = line + len - 1; + while (end >= start && (*end == ' ' || *end == '\t')) --end; + + // Early exit for whitespace-only lines + if (end < start) continue; + + // Calculate trimmed length + len = end - start + 1; + lineStr.assign(start, len); + + if (lineStr[0] == '[' && lineStr.back() == ']') { + if (sectionFound && !keyFound) { + buffer << desiredKey << "=" << desiredValue << '\n'; // Add missing key-value pair + keyFound = true; + } + if (!firstSection) { + buffer << '\n'; // Add a newline before the start of a new section + } + currentSection.assign(lineStr, 1, lineStr.size() - 2); + sectionFound = (currentSection == desiredSection); + buffer << lineStr << '\n'; + firstSection = false; + + // Clear strings to reuse capacity + lineStr.clear(); + currentSection.clear(); + continue; + } + + if (sectionFound && !keyFound) { + delimiterPos = lineStr.find('='); + if (delimiterPos != std::string::npos) { + // Extract and trim key manually for better performance + key_start = 0; + key_end = delimiterPos - 1; + + // Find start of key (skip leading whitespace) + while (key_start < delimiterPos && (lineStr[key_start] == ' ' || lineStr[key_start] == '\t')) { + ++key_start; + } + + // Find end of key (skip trailing whitespace) + while (key_end > key_start && (lineStr[key_end] == ' ' || lineStr[key_end] == '\t')) { + --key_end; + } + + if (key_end >= key_start) { + key.assign(lineStr, key_start, key_end - key_start + 1); + + if (key == desiredKey) { + keyFound = true; + // Build the replacement line more efficiently + lineStr.assign(desiredNewKey.empty() ? desiredKey : desiredNewKey); + lineStr += '='; + lineStr += desiredValue; + } + } + } + } + + buffer << lineStr << '\n'; + + // Clear strings to reuse capacity + lineStr.clear(); + key.clear(); + } + + if (!sectionFound && !keyFound) { + if (!firstSection) buffer << '\n'; // Ensure newline before adding a new section, unless it's the first section + buffer << '[' << desiredSection << ']' << '\n'; + buffer << desiredKey << "=" << desiredValue << '\n'; + } else if (!keyFound) { + buffer << desiredKey << "=" << desiredValue << '\n'; + } + + fclose(configFile); + + // Write to the file again + FILE* outFile = fopen(fileToEdit.c_str(), "w"); + if (outFile) { + fputs(buffer.str().c_str(), outFile); + fclose(outFile); + } + } + + + /** + * @brief Sets the value of a key in an INI file within the specified section and cleans the formatting. + * + * This function sets the value of the specified key within the given section of the INI file. + * If the key or section does not exist, it creates them. After updating the INI file, + * it cleans the formatting to ensure proper INI file structure. + * + * @param fileToEdit The path to the INI file to be modified or created. + * @param desiredSection The name of the section in which the key-value pair should be added or updated. + * @param desiredKey The key for the key-value pair to be added or updated. + * @param desiredValue The new value for the key-value pair. + */ + void setIniFileValue(const std::string& fileToEdit, const std::string& desiredSection, const std::string& desiredKey, const std::string& desiredValue, const std::string& comment) { + setIniFile(fileToEdit, desiredSection, desiredKey, desiredValue, "", comment); + } + + /** + * @brief Sets the key name to a new name in an INI file within the specified section and cleans the formatting. + * + * This function sets the key name to a new name within the given section of the INI file. + * If the key or section does not exist, it creates them. After updating the INI file, + * it cleans the formatting to ensure proper INI file structure. + * + * @param fileToEdit The path to the INI file to be modified or created. + * @param desiredSection The name of the section in which the key-name change should occur. + * @param desiredKey The key name to be changed. + * @param desiredNewKey The new key name to replace the original key name. + */ + void setIniFileKey(const std::string& fileToEdit, const std::string& desiredSection, const std::string& desiredKey, const std::string& desiredNewKey, const std::string& comment) { + setIniFile(fileToEdit, desiredSection, desiredKey, "", desiredNewKey, comment); + } + + + + /** + * @brief Adds a new section to an INI file. + * + * This function adds a new section with the specified name to the INI file located at the + * specified path. If the section already exists, it does nothing. + * + * @param filePath The path to the INI file. + * @param sectionName The name of the section to add. + */ + void addIniSection(const std::string& filePath, const std::string& sectionName) { + auto fileMutex = getFileMutex(filePath); + std::unique_lock lock(*fileMutex); + + FILE* inputFile = fopen(filePath.c_str(), "r"); + if (!inputFile) { + // Create new file with just the section if file doesn't exist + FILE* newFile = fopen(filePath.c_str(), "w"); + if (newFile) { + fprintf(newFile, "[%s]\n", sectionName.c_str()); + fclose(newFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Error: Failed to create new INI file."); + } + #endif + return; + } + + const std::string tempPath = filePath + ".tmp"; + FILE* tempFile = fopen(tempPath.c_str(), "w"); + if (!tempFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Failed to create a temporary file."); + #endif + fclose(inputFile); + return; + } + + // Pre-calculate section comparison values + const size_t sectionNameLen = sectionName.length(); + const size_t fullSectionLen = sectionNameLen + 2; // [ + sectionName + ] + + // Declare all variables outside the loop + auto linePtr = std::make_unique(1024); + char* line = linePtr.get(); + bool sectionExists = false; + size_t len = 0; + const char* end; + + size_t content_len; + + // First pass: check if section exists and copy all content + while (fgets(line, 1024, inputFile)) { + len = strlen(line); + + // Optimize section detection without string copying + if (len >= fullSectionLen && line[0] == '[') { + // Find end of line content (excluding newlines) + end = line + len - 1; + while (end > line && (*end == '\n' || *end == '\r')) --end; + + // Check if this could be our section + if (end > line && *end == ']') { + content_len = end - line + 1; + if (content_len == fullSectionLen) { + // Direct memory comparison - much faster than string creation + if (memcmp(line + 1, sectionName.c_str(), sectionNameLen) == 0) { + sectionExists = true; + // Early optimization: write remaining file and exit loop + fputs(line, tempFile); + + // Copy rest of file efficiently + while (fgets(line, sizeof(line), inputFile)) { + fputs(line, tempFile); + } + break; + } + } + } + } + + // Always write the line as-is + fputs(line, tempFile); + } + + // If the section does not exist, add it at the end + if (!sectionExists) { + // Check if we need a newline before the new section + if (ftell(tempFile) > 0) { + fseek(tempFile, -1, SEEK_END); + char lastChar; + if (fread(&lastChar, 1, 1, tempFile) == 1 && lastChar != '\n') { + fseek(tempFile, 0, SEEK_END); + fputc('\n', tempFile); + } else { + fseek(tempFile, 0, SEEK_END); + } + } + + fprintf(tempFile, "[%s]\n", sectionName.c_str()); + } + + fclose(inputFile); + fclose(tempFile); + + // Replace the original file with the temp file + if (std::remove(filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete the original file: " + filePath); + #endif + // Clean up temp file on error + std::remove(tempPath.c_str()); + return; + } + + if (std::rename(tempPath.c_str(), filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to rename the temporary file: " + tempPath); + #endif + } + } + + + /** + * @brief Renames a section in an INI file. + * + * This function renames the section with the specified current name to the specified new name + * in the INI file located at the specified path. If the current section does not exist, or if the + * new section name already exists, it does nothing. + * + * @param filePath The path to the INI file. + * @param currentSectionName The name of the section to rename. + * @param newSectionName The new name for the section. + */ + void renameIniSection(const std::string& filePath, const std::string& currentSectionName, const std::string& newSectionName) { + auto fileMutex = getFileMutex(filePath); + std::unique_lock lock(*fileMutex); + + FILE* configFile = fopen(filePath.c_str(), "r"); + if (!configFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open the input file: " + filePath); + #endif + return; + } + + const std::string tempPath = filePath + ".tmp"; + FILE* tempFile = fopen(tempPath.c_str(), "w"); + if (!tempFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to create the temporary file: " + tempPath); + #endif + fclose(configFile); + return; + } + + auto linePtr = std::make_unique(1024); + char* line = linePtr.get(); + std::string sectionName; + std::string lineStr; + + while (fgets(line, 1024, configFile)) { + lineStr = line; + trim(lineStr); // Modifying lineStr directly + sectionName.clear(); + + if (!lineStr.empty() && lineStr[0] == '[' && lineStr[lineStr.length() - 2] == ']') { + sectionName = lineStr.substr(1, lineStr.length() - 2); + fprintf(tempFile, "[%s]\n", sectionName == currentSectionName ? newSectionName.c_str() : sectionName.c_str()); + } else { + fprintf(tempFile, "%s\n", line); + } + } + + fclose(configFile); + fclose(tempFile); + + // Replace the original file with the modified temporary file + if (remove(filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete the original file: " + filePath); + #endif + return; + } + + if (rename(tempPath.c_str(), filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to rename the temporary file: " + tempPath); + #endif + } + } + + + /** + * @brief Removes a section from an INI file. + * + * This function removes the section with the specified name, including all its associated key-value + * pairs, from the INI file located at the specified path. If the section does not exist in the file, + * it does nothing. + * + * @param filePath The path to the INI file. + * @param sectionName The name of the section to remove. + */ + void removeIniSection(const std::string& filePath, const std::string& sectionName) { + auto fileMutex = getFileMutex(filePath); + std::unique_lock lock(*fileMutex); + + FILE* configFile = fopen(filePath.c_str(), "r"); + if (!configFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open the input file: " + filePath); + #endif + return; + } + + std::string tempPath = filePath + ".tmp"; + FILE* tempFile = fopen(tempPath.c_str(), "w"); + if (!tempFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to create the temporary file: " + tempPath); + #endif + fclose(configFile); + return; + } + + // Pre-calculate section comparison values + const size_t sectionNameLen = sectionName.length(); + const size_t fullSectionLen = sectionNameLen + 2; // [ + sectionName + ] + + auto linePtr = std::make_unique(1024); + char* line = linePtr.get(); + std::string currentSection; + bool inSectionToRemove = false; + + size_t len; + const char* start; + const char* end; + + size_t trimmed_len; + while (fgets(line, 1024, configFile)) { + len = strlen(line); + + // Early exit for empty lines + if (len == 0) { + if (!inSectionToRemove) { + fprintf(tempFile, "%s", line); + } + continue; + } + + // Manual trim for better performance - find start of non-whitespace + start = line; + while (*start == ' ' || *start == '\t') ++start; + + // Find end of non-whitespace (working backwards from known end) + end = line + len - 1; + while (end >= start && (*end == '\n' || *end == '\r' || *end == ' ' || *end == '\t')) --end; + + // Early exit for whitespace-only lines + if (end < start) { + if (!inSectionToRemove) { + fprintf(tempFile, "%s", line); + } + continue; + } + + // Calculate trimmed length + trimmed_len = end - start + 1; + + // Check if this is a section header + if (trimmed_len >= 3 && *start == '[' && *end == ']') { + // Optimize section detection with direct comparison + if (trimmed_len == fullSectionLen) { + // Direct memory comparison - much faster than string creation + if (memcmp(start + 1, sectionName.c_str(), sectionNameLen) == 0) { + inSectionToRemove = true; + continue; // Skip writing this section header + } + } + + // Different section - not the one to remove + inSectionToRemove = false; + fprintf(tempFile, "%s", line); + } else if (!inSectionToRemove) { + // Write the line as-is to preserve formatting + fprintf(tempFile, "%s", line); + } + // If inSectionToRemove is true, skip writing this line + } + + fclose(configFile); + fclose(tempFile); + + // Replace the original file with the temp file + if (remove(filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete the original file: " + filePath); + #endif + return; + } + + if (rename(tempPath.c_str(), filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to rename the temporary file: " + tempPath); + #endif + } + } + + + /** + * @brief Removes a key-value pair from an INI file. + */ + void removeIniKey(const std::string& filePath, const std::string& sectionName, const std::string& keyName) { + auto fileMutex = getFileMutex(filePath); + std::unique_lock lock(*fileMutex); + + FILE* configFile = fopen(filePath.c_str(), "r"); + if (!configFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open the input file: " + filePath); + #endif + return; + } + + std::string tempPath = filePath + ".tmp"; + FILE* tempFile = fopen(tempPath.c_str(), "w"); + if (!tempFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to create the temporary file: " + tempPath); + #endif + fclose(configFile); + return; + } + + // Declare all variables outside the loop for efficiency + auto linePtr = std::make_unique(1024); + char* line = linePtr.get(); + std::string currentSection; + std::string lineStr; + std::string trimmedLine; + std::string lineKey; + + bool inTargetSection = false; + size_t eqPos; + + while (fgets(line, 1024, configFile)) { + lineStr.assign(line); + + // Create a trimmed copy for parsing + trimmedLine = lineStr; + if (!trimmedLine.empty() && trimmedLine.back() == '\n') { + trimmedLine.pop_back(); + if (!trimmedLine.empty() && trimmedLine.back() == '\r') { + trimmedLine.pop_back(); + } + } + trim(trimmedLine); + + if (!trimmedLine.empty() && trimmedLine.front() == '[' && trimmedLine.back() == ']') { + currentSection.assign(trimmedLine, 1, trimmedLine.length() - 2); + inTargetSection = (currentSection == sectionName); + fprintf(tempFile, "%s", line); // Write original line + } else if (inTargetSection) { + // Check if line starts with the key (handle spaces around =) + eqPos = trimmedLine.find('='); + if (eqPos != std::string::npos) { + lineKey.assign(trimmedLine, 0, eqPos); + trim(lineKey); + if (lineKey == keyName) { + continue; // Skip this line + } + } + fprintf(tempFile, "%s", line); + } else { + fprintf(tempFile, "%s", line); + } + } + + fclose(configFile); + fclose(tempFile); + + // Replace the original file with the temp file + if (remove(filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete the original file: " + filePath); + #endif + return; + } + + if (rename(tempPath.c_str(), filePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to rename the temporary file: " + tempPath); + #endif + } + } + + + bool syncIniValue(std::map>& packageConfigData, + const std::string& packageConfigIniPath, + const std::string& optionName, + const std::string& key, + std::string& value) { + auto optionIt = packageConfigData.find(optionName); + + // Check if option exists and has the key + if (optionIt != packageConfigData.end()) { + auto it = optionIt->second.find(key); + if (it != optionIt->second.end()) { + value = it->second; // Load existing value from config + return false; // Value exists, we're done + } + } + + // Key/section doesn't exist - add it (will be saved later in batch) + packageConfigData[optionName][key] = value; + return true; + } + + + /** + * @brief Parses a command line into individual parts, handling quoted strings. + * + * @param line The command line to parse. + * @return A vector of strings containing the parsed command parts. + */ + std::vector parseCommandLine(const std::string& line) { + std::vector commandParts; + + const char* const data = line.data(); + const char* const end = data + line.length(); + const char* pos = data; + + while (pos < end) { + // Skip leading whitespace + while (pos < end && (*pos == ' ' || *pos == '\t')) { + ++pos; + } + + if (pos >= end) break; + + const char* argStart = pos; + const char* argEnd = pos; + + if (*pos == '\'' || *pos == '"') { + // Quoted argument + const char quoteChar = *pos; + ++pos; // Skip opening quote + argStart = pos; + + // Find closing quote + while (pos < end && *pos != quoteChar) { + ++pos; + } + + argEnd = pos; + if (pos < end) ++pos; // Skip closing quote + } else { + // Unquoted argument + while (pos < end && *pos != ' ' && *pos != '\t' && *pos != '\'' && *pos != '"') { + ++pos; + } + argEnd = pos; + } + + //if (argEnd >= argStart) { + // commandParts.emplace_back(argStart, argEnd - argStart); + //} + + if (argEnd > argStart) { + // Skip standalone "=" — it's the INI assignment separator (key = value), + // never a meaningful command argument. + if (!(argEnd - argStart == 1 && *argStart == '=')) { + commandParts.emplace_back(argStart, argEnd - argStart); + } + } + } + + return commandParts; + } + + + /** + * @brief Loads and parses options from an INI file. + * + * This function reads and parses options from an INI file, organizing them by section. + * + * @param packageIniPath The path to the INI file. + * @return A vector containing pairs of section names and their associated key-value pairs. + */ + std::vector>>> loadOptionsFromIni(const std::string& packageIniPath) { + auto fileMutex = getFileMutex(packageIniPath); + std::shared_lock lock(*fileMutex); + + FILE* packageFile = fopen(packageIniPath.c_str(), "r"); + if (!packageFile) return {}; + + std::vector>>> options; + options.reserve(32); // Reserve reasonable capacity + + auto bufferPtr = std::make_unique(1024); + char* buffer = bufferPtr.get(); + std::string currentSection; + std::vector> sectionCommands; + sectionCommands.reserve(16); + + while (fgets(buffer, 1024, packageFile)) { + size_t len = strlen(buffer); + + // Strip trailing newline/carriage return + if (len > 0 && buffer[len-1] == '\n') { + if (--len > 0 && buffer[len-1] == '\r') --len; + } + + if (len == 0 || buffer[0] == '#') continue; + + // Section header + if (buffer[0] == '[' && buffer[len-1] == ']') { + if (!currentSection.empty()) { + options.emplace_back(std::move(currentSection), std::move(sectionCommands)); + sectionCommands = std::vector>(); + sectionCommands.reserve(16); + } + currentSection.assign(buffer + 1, len - 2); + } else if (!currentSection.empty()) { + // Parse command directly from buffer - avoid string construction + sectionCommands.push_back(parseCommandLine(std::string(buffer, len))); + } + } + + if (!currentSection.empty()) { + options.emplace_back(std::move(currentSection), std::move(sectionCommands)); + } + + fclose(packageFile); + + return options; + } + + /** + * @brief Loads a specific section from an INI file. + * + * This function reads and parses a specific section from an INI file. + * + * @param packageIniPath The path to the INI file. + * @param sectionName The name of the section to load. + * @return A vector of commands within the specified section. + */ + std::vector> loadSpecificSectionFromIni(const std::string& packageIniPath, const std::string& sectionName) { + auto fileMutex = getFileMutex(packageIniPath); + std::shared_lock lock(*fileMutex); + + FILE* packageFile = fopen(packageIniPath.c_str(), "r"); + if (!packageFile) return {}; + + std::vector> sectionCommands; + sectionCommands.reserve(16); + + auto bufferPtr = std::make_unique(1024); + char* buffer = bufferPtr.get(); + bool inTargetSection = false; + + while (fgets(buffer, 1024, packageFile)) { + size_t len = strlen(buffer); + + // Strip trailing newline/carriage return + if (len > 0 && buffer[len-1] == '\n') { + if (--len > 0 && buffer[len-1] == '\r') --len; + } + + if (len == 0 || buffer[0] == '#') continue; + + // Section header + if (buffer[0] == '[' && buffer[len-1] == ']') { + if (len > 2) { + size_t sectionLen = len - 2; + + // Direct comparison without constructing string + bool isTarget = (sectionLen == sectionName.length() && + std::memcmp(buffer + 1, sectionName.data(), sectionLen) == 0); + + // Early exit: found target section and now leaving it + if (inTargetSection && !isTarget) { + break; + } + + inTargetSection = isTarget; + } + } else if (inTargetSection) { + sectionCommands.push_back(parseCommandLine(std::string(buffer, len))); + } + } + + fclose(packageFile); + + return sectionCommands; + } + + + /** + * @brief Saves INI data structure to a file. + * + * This function writes a complete INI data structure to the specified file path. + * The data structure should be organized as sections containing key-value pairs. + * + * @param filePath The path to the INI file to write. + * @param data The complete INI data structure to save. + */ + void saveIniFileData(const std::string& filePath, const std::map>& data) { + auto fileMutex = getFileMutex(filePath); + std::unique_lock lock(*fileMutex); + + FILE* file = fopen(filePath.c_str(), "w"); + if (!file) { + return; + } + + // Use larger buffer for better write performance + auto writeBuffer = std::make_unique(4096); + setvbuf(file, writeBuffer.get(), _IOFBF, 4096); + + std::string buffer; + buffer.reserve(2048); // Pre-allocate buffer + + for (const auto& section : data) { + buffer.clear(); + + // Build section header + buffer += '['; + buffer += section.first; + buffer += "]\n"; + + // Build all key-value pairs for this section + for (const auto& kv : section.second) { + buffer += kv.first; + buffer += '='; + buffer += kv.second; + buffer += '\n'; + } + buffer += '\n'; // Section separator + + // Write entire section at once + fwrite(buffer.data(), 1, buffer.size(), file); + } + + fclose(file); + } + + + + enum class KeyOp { ADD, REMOVE }; + + /** + * @brief Internal helper for pattern-based key operations. + * Section-buffered approach for clean formatting with minimal code size. + */ + void processKeysInMatchingSections(const std::string& filePath, const std::string& patternKey, + const std::string& targetKey, const std::string& value, + KeyOp operation) { + auto fileMutex = getFileMutex(filePath); + std::unique_lock lock(*fileMutex); + + const std::string tempPath = filePath + ".tmp"; + const bool matchAll = patternKey.empty(); + + FILE* in = fopen(filePath.c_str(), "r"); + if (!in) return; + FILE* out = fopen(tempPath.c_str(), "w"); + if (!out) { fclose(in); return; } + + char buf[1024]; + std::vector section; + bool inMatch = matchAll; + size_t patIdx = SIZE_MAX, tgtIdx = SIZE_MAX; + size_t len; + + while (fgets(buf, sizeof(buf), in)) { + len = strlen(buf); + if (len > 0 && buf[len-1] == '\n') buf[--len] = '\0'; + if (len > 0 && buf[len-1] == '\r') buf[--len] = '\0'; + + std::string line(buf), tl = line; + trim(tl); + + if (!tl.empty() && tl[0] == '[' && tl.back() == ']') { + // Flush previous section + if (!section.empty() && inMatch) { + if (operation == KeyOp::ADD) { + // If target exists, update it in place; otherwise insert after pattern + size_t insertAt = (tgtIdx != SIZE_MAX) ? SIZE_MAX : (matchAll ? section.size() : patIdx + 1); + for (size_t i = 0; i < section.size(); ++i) { + if (i == tgtIdx) { + fprintf(out, "%s=%s\n", targetKey.c_str(), value.c_str()); + } else { + fprintf(out, "%s\n", section[i].c_str()); + } + if (i + 1 == insertAt) { + fprintf(out, "%s=%s\n", targetKey.c_str(), value.c_str()); + } + } + } else if (operation == KeyOp::REMOVE) { + for (size_t i = 0; i < section.size(); ++i) { + if (i != tgtIdx) fprintf(out, "%s\n", section[i].c_str()); + } + } + } else { + for (const auto& l : section) fprintf(out, "%s\n", l.c_str()); + } + + section.clear(); + fprintf(out, "%s\n", buf); + inMatch = matchAll; + patIdx = tgtIdx = SIZE_MAX; + continue; + } + + size_t eq = tl.find('='); + if (eq != std::string::npos) { + std::string k(tl, 0, eq); + trim(k); + if (!matchAll && k == patternKey) { inMatch = true; patIdx = section.size(); } + if (k == targetKey) tgtIdx = section.size(); + } + + section.push_back(buf); + } + + // Flush last section + if (!section.empty() && inMatch) { + if (operation == KeyOp::ADD) { + size_t insertAt = (tgtIdx != SIZE_MAX) ? SIZE_MAX : (matchAll ? section.size() : patIdx + 1); + for (size_t i = 0; i < section.size(); ++i) { + if (i == tgtIdx) { + fprintf(out, "%s=%s\n", targetKey.c_str(), value.c_str()); + } else { + fprintf(out, "%s\n", section[i].c_str()); + } + if (i + 1 == insertAt) { + fprintf(out, "%s=%s\n", targetKey.c_str(), value.c_str()); + } + } + } else if (operation == KeyOp::REMOVE) { + for (size_t i = 0; i < section.size(); ++i) { + if (i != tgtIdx) fprintf(out, "%s\n", section[i].c_str()); + } + } + } else { + for (const auto& l : section) fprintf(out, "%s\n", l.c_str()); + } + + fclose(in); + fclose(out); + + std::remove(filePath.c_str()); + std::rename(tempPath.c_str(), filePath.c_str()); + } + + + /** + * @brief Adds a key-value pair to all sections that contain a specified pattern key. + * + * If patternKey is empty, the key-value pair will be added to ALL sections. + * If patternKey is specified, only sections containing that key will be modified. + * + * @param filePath The path to the INI file. + * @param patternKey The key to search for (empty = all sections). + * @param newKey The new key to add. + * @param newValue The value for the new key. + */ + void addKeyToMatchingSections(const std::string& filePath, const std::string& patternKey, + const std::string& newKey, const std::string& newValue) { + processKeysInMatchingSections(filePath, patternKey, newKey, newValue, KeyOp::ADD); + } + + + /** + * @brief Removes a key from all sections that contain a specified pattern key. + * + * If patternKey is empty, the key will be removed from ALL sections. + * If patternKey is specified, only sections containing that key will have keyToRemove deleted. + * + * @param filePath The path to the INI file. + * @param patternKey The key to search for (empty = all sections). + * @param keyToRemove The key to remove from matching sections. + */ + void removeKeyFromMatchingSections(const std::string& filePath, const std::string& patternKey, + const std::string& keyToRemove) { + processKeysInMatchingSections(filePath, patternKey, keyToRemove, "", KeyOp::REMOVE); + } + +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp new file mode 100644 index 00000000..85317dec --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp @@ -0,0 +1,350 @@ +/******************************************************************************** + * File: json_funcs.cpp + * Author: ppkantorski + * Description: + * This source file provides functions for working with JSON files in C++ using + * the `cJSON` library. It includes a function to read JSON data from a file. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "json_funcs.hpp" + + +namespace ult { + + static std::mutex json_access_mutex; + + /** + * @brief Reads JSON data from a file and returns it as a `json_t` object. + * + * @param filePath The path to the JSON file. + * @return A `json_t` object representing the parsed JSON data. Returns `nullptr` on error. + */ + json_t* readJsonFromFile(const std::string& filePath) { + std::lock_guard lock(json_access_mutex); + + FILE* file = fopen(filePath.c_str(), "rb"); + if (!file) { + return nullptr; + } + + // Get file size + fseek(file, 0, SEEK_END); + const long fileSize = ftell(file); + fseek(file, 0, SEEK_SET); + + // Check for reasonable file size + if (fileSize <= 0 || fileSize > 6 * 1024 * 1024) { // 6MB limit + fclose(file); + return nullptr; + } + + // Use vector for better performance and explicit null termination + std::vector buffer; + buffer.resize(static_cast(fileSize) + 1); // +1 for null terminator + + // Read the file in one operation + const size_t bytesRead = fread(buffer.data(), 1, static_cast(fileSize), file); + fclose(file); + + if (bytesRead != static_cast(fileSize)) { + return nullptr; + } + + // Ensure null termination for cJSON + buffer[bytesRead] = '\0'; + + + // Parse the JSON content - pass buffer directly to avoid string copy + cJSON* root = cJSON_Parse(buffer.data()); + if (!root) { + #if USING_LOGGING_DIRECTIVE + const char* error_ptr = cJSON_GetErrorPtr(); + if (error_ptr) { + if (!disableLogging) + logMessage("JSON parsing error: " + std::string(error_ptr)); + } + #endif + return nullptr; + } + + return reinterpret_cast(root); + } + + + /** + * @brief Parses a JSON string into a json_t object. + * + * This function takes a JSON string as input and parses it into a json_t object using cJSON library's `cJSON_Parse` function. + * If parsing fails, it logs the error and returns nullptr. + * + * @param input The input JSON string to parse. + * @return A json_t object representing the parsed JSON, or nullptr if parsing fails. + */ + json_t* stringToJson(const std::string& input) { + cJSON* jsonObj = cJSON_Parse(input.c_str()); + + if (!jsonObj) { + #if USING_LOGGING_DIRECTIVE + const char* error_ptr = cJSON_GetErrorPtr(); + if (error_ptr != nullptr) { + if (!disableLogging) + logMessage("Failed to parse JSON: " + std::string(error_ptr)); + } + #endif + return nullptr; // Return nullptr to indicate failure clearly + } + + return reinterpret_cast(jsonObj); + } + + + + + + // Function to get a string from a JSON object + std::string getStringFromJson(const json_t* root, const char* key) { + const cJSON* croot = reinterpret_cast(root); + const cJSON* value = cJSON_GetObjectItemCaseSensitive(croot, key); + if (value && cJSON_IsString(value) && value->valuestring) { + return value->valuestring; + } else { + return ""; // Key not found or not a string, return empty string/char* + } + } + + + /** + * @brief Loads a JSON file from the specified path and retrieves a string value for a given key. + * + * This function combines the functionality of loading a JSON file and retrieving a string value associated + * with a given key in a single step. + * + * @param filePath The path to the JSON file. + * @param key The key whose associated string value is to be retrieved. + * @return A string containing the value associated with the given key, or an empty string if the key is not found. + */ + std::string getStringFromJsonFile(const std::string& filePath, const std::string& key) { + // Load JSON from file using a smart pointer + std::unique_ptr root(readJsonFromFile(filePath), JsonDeleter()); + if (!root) { + #if USING_LOGGING_DIRECTIVE + logMessage("Failed to load JSON file from path: " + filePath); + #endif + return ""; + } + + // Retrieve the string value associated with the key + cJSON* croot = reinterpret_cast(root.get()); + cJSON* jsonKey = cJSON_GetObjectItemCaseSensitive(croot, key.c_str()); + const char* value = (cJSON_IsString(jsonKey) && jsonKey->valuestring) ? jsonKey->valuestring : nullptr; + + // Check if the value was found and return it + if (value) { + return std::string(value); + } else { + #if USING_LOGGING_DIRECTIVE + logMessage("Key not found or not a string in JSON: " + key); + #endif + return ""; + } + } + + + /** + * @brief Sets a value in a JSON file, creating the file if it doesn't exist. + * + * @param filePath The path to the JSON file. + * @param key The key to set. + * @param value The value to set (auto-detected type). + * @param createIfNotExists Whether to create the file if it doesn't exist. + * @return true if successful, false otherwise. + */ + bool setJsonValue(const std::string& filePath, const std::string& key, const std::string& value, bool createIfNotExists) { + // Try to load existing file + std::unique_ptr root(readJsonFromFile(filePath), JsonDeleter()); + + cJSON* croot = nullptr; + + // If file doesn't exist, create new JSON object if allowed + if (!root) { + if (!createIfNotExists) { + return false; + } + croot = cJSON_CreateObject(); + if (!croot) { + return false; + } + root.reset(reinterpret_cast(croot)); + } else { + croot = reinterpret_cast(root.get()); + } + + // FIXED: Better value type detection + cJSON* jsonValue = nullptr; + + // Remove trimming to preserve leading/trailing spaces for all languages + // std::string trimmedValue = value; + // trimmedValue.erase(0, trimmedValue.find_first_not_of(" \t\n\r")); + // trimmedValue.erase(trimmedValue.find_last_not_of(" \t\n\r") + 1); + + if (value.empty()) { + jsonValue = cJSON_CreateString(""); + } else if (value == "true") { + jsonValue = cJSON_CreateBool(1); + } else if (value == "false") { + jsonValue = cJSON_CreateBool(0); + } else if (value == "null") { + jsonValue = cJSON_CreateNull(); + } else { + // Try parsing as number (integer or float) + char* endPtr = nullptr; + errno = 0; + + // Try as integer first + const long longValue = std::strtol(value.c_str(), &endPtr, 10); + if (endPtr == value.c_str() + value.length() && errno == 0) { + // Successfully parsed as integer + jsonValue = cJSON_CreateNumber(static_cast(longValue)); + } else { + // Try as float + endPtr = nullptr; + errno = 0; + const double doubleValue = std::strtod(value.c_str(), &endPtr); + if (endPtr == value.c_str() + value.length() && errno == 0) { + // Successfully parsed as float + jsonValue = cJSON_CreateNumber(doubleValue); + } else { + // Treat as string + jsonValue = cJSON_CreateString(value.c_str()); + } + } + } + + if (!jsonValue) { + return false; + } + + // Delete existing item if it exists + cJSON_DeleteItemFromObject(croot, key.c_str()); + + // Add the new value + cJSON_AddItemToObject(croot, key.c_str(), jsonValue); + + // Save to file with formatted output for better readability + char* jsonString = cJSON_Print(croot); // Use formatted output instead of PrintUnformatted + if (!jsonString) { + return false; + } + + bool success = false; + { + std::lock_guard lock(json_access_mutex); + + FILE* file = fopen(filePath.c_str(), "w"); // Use text mode for JSON + if (file) { + const size_t jsonLength = std::strlen(jsonString); + const size_t bytesWritten = fwrite(jsonString, 1, jsonLength, file); + success = (bytesWritten == jsonLength); + fclose(file); + } + } + + cJSON_free(jsonString); + return success; + } + + /** + * @brief Renames a key in a JSON file. + * + * @param filePath The path to the JSON file. + * @param oldKey The current key name. + * @param newKey The new key name. + * @return true if successful, false otherwise. + */ + bool renameJsonKey(const std::string& filePath, const std::string& oldKey, const std::string& newKey) { + // Try to load existing file + std::unique_ptr root(readJsonFromFile(filePath), JsonDeleter()); + + if (!root) { + return false; + } + + cJSON* croot = reinterpret_cast(root.get()); + + // Check if old key exists + cJSON* value = cJSON_GetObjectItemCaseSensitive(croot, oldKey.c_str()); + if (!value) { + return false; + } + + // Detach the value from the object + cJSON_DetachItemFromObject(croot, oldKey.c_str()); + + // Add it back with the new key + cJSON_AddItemToObject(croot, newKey.c_str(), value); + + // Save to file + char* jsonString = cJSON_Print(croot); // Use formatted output + if (!jsonString) { + return false; + } + + bool success = false; + + { + std::lock_guard lock(json_access_mutex); + + FILE* file = fopen(filePath.c_str(), "w"); // Use text mode + if (file) { + const size_t jsonLength = std::strlen(jsonString); + const size_t bytesWritten = fwrite(jsonString, 1, jsonLength, file); + success = (bytesWritten == jsonLength); + fclose(file); + } + } + + cJSON_free(jsonString); + return success; + } + + void pushNotificationJson(const std::string& appID, const std::string& text, size_t fontSize) { + u64 tick = armGetSystemTick(); + std::string filename = appID + "-" + std::to_string(tick) + ".notify"; // priority 20 default + + // Build full path + const std::string fullPath = NOTIFICATIONS_PATH + filename; + + // Create JSON object + cJSON* notif = cJSON_CreateObject(); + if (!notif) return; + + cJSON_AddStringToObject(notif, "text", text.c_str()); + cJSON_AddNumberToObject(notif, "font_size", static_cast(fontSize)); + + // Serialize JSON + char* rendered = cJSON_PrintUnformatted(notif); + if (!rendered) { + cJSON_Delete(notif); + return; + } + + // Write to file (C-style) + FILE* file = fopen(fullPath.c_str(), "wb"); + if (file) { + fwrite(rendered, 1, strlen(rendered), file); + fclose(file); + } + + cJSON_free(rendered); + cJSON_Delete(notif); + } +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp new file mode 100644 index 00000000..17fa95a2 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp @@ -0,0 +1,400 @@ +/******************************************************************************** + * File: list_funcs.cpp + * Author: ppkantorski + * Description: + * This source file contains function declarations and utility functions related + * to working with lists and vectors of strings. These functions are used in the + * Ultrahand Overlay project to perform various operations on lists, such as + * removing entries, filtering, and more. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include +#include + +namespace ult { + static constexpr const char* UNABLE_TO_OPEN_FILE = "Unable to open file: "; + + // Thread-safe file access mutex + static std::mutex file_access_mutex; + + std::vector splitIniList(const std::string& value) { + std::vector result; + std::string trimmed = value; + trim(trimmed); + if (trimmed.size() > 2 && trimmed.front() == '(' && trimmed.back() == ')') { + trimmed = trimmed.substr(1, trimmed.size() - 2); + ult::StringStream ss(trimmed); + std::string token; + while (ss.getline(token, ',')) { + trim(token); + result.push_back(token); + } + } + return result; + } + + std::string joinIniList(const std::vector& list) { + std::string result = ""; + for (size_t i = 0; i < list.size(); ++i) { + result += list[i]; + if (i + 1 < list.size()) { + result += ", "; + } + } + return result; + } + + + /** + * @brief Removes entries from a vector of strings that match a specified entry. + * + * This function removes entries from the `itemsList` vector of strings that match the `entry`. + * + * @param entry The entry to be compared against the elements in `itemsList`. + * @param itemsList The vector of strings from which matching entries will be removed. + */ + void removeEntryFromList(const std::string& entry, std::vector& itemsList) { + itemsList.erase(std::remove_if(itemsList.begin(), itemsList.end(), [&](const std::string& item) { + return item.compare(0, entry.length(), entry) == 0; + }), itemsList.end()); + } + + /** + * @brief Filters a list of strings based on a specified filter list. + * + * This function filters a list of strings (`itemsList`) by removing entries that match any + * of the criteria specified in the `filterList`. It uses the `removeEntryFromList` function + * to perform the removal. + * + * @param filterList The list of entries to filter by. Entries in `itemsList` matching any entry in this list will be removed. + * @param itemsList The list of strings to be filtered. + */ + void filterItemsList(const std::vector& filterList, std::vector& itemsList) { + for (const auto& entry : filterList) { + removeEntryFromList(entry, itemsList); + } + } + + + // Function to read file into a vector of strings with optional cap and newline preservation + std::vector readListFromFile(const std::string& filePath, size_t maxLines, bool preserveNewlines) { + std::lock_guard lock(file_access_mutex); + std::vector lines; + + FILE* file = fopen(filePath.c_str(), "r"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + logMessage(UNABLE_TO_OPEN_FILE + filePath); + #endif + return lines; + } + + static constexpr size_t BUFFER_SIZE = 8192; + char buffer[BUFFER_SIZE]; + size_t len; + + while (fgets(buffer, BUFFER_SIZE, file)) { + // Check cap before processing + if (maxLines > 0 && lines.size() >= maxLines) { + break; + } + + if (preserveNewlines) { + // Keep the line as-is, including newlines + lines.emplace_back(buffer); + } else { + // Remove newlines + len = strlen(buffer); + if (len > 0 && buffer[len - 1] == '\n') { + buffer[len - 1] = '\0'; + --len; + // Also remove carriage return if present + if (len > 0 && buffer[len - 1] == '\r') { + buffer[len - 1] = '\0'; + } + } + lines.emplace_back(buffer); + } + } + + fclose(file); + + return lines; + } + + + // Function to get an entry from the list based on the index + std::string getEntryFromListFile(const std::string& listPath, size_t listIndex) { + std::lock_guard lock(file_access_mutex); + + FILE* file = fopen(listPath.c_str(), "r"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + logMessage(UNABLE_TO_OPEN_FILE + listPath); + #endif + return ""; + } + + static constexpr size_t BUFFER_SIZE = 8192; + char buffer[BUFFER_SIZE]; + + // Skip lines until reaching the desired index + for (size_t i = 0; i < listIndex; ++i) { + if (!fgets(buffer, BUFFER_SIZE, file)) { + fclose(file); + return ""; // Index out of bounds + } + } + + // Read the target line + if (!fgets(buffer, BUFFER_SIZE, file)) { + fclose(file); + return ""; // Index out of bounds + } + + fclose(file); + + // Efficiently remove newline character + const size_t len = strlen(buffer); + if (len > 0 && buffer[len - 1] == '\n') { + buffer[len - 1] = '\0'; + if (len > 1 && buffer[len - 2] == '\r') { + buffer[len - 2] = '\0'; + } + } + + return std::string(buffer); + } + + + /** + * @brief Splits a string into a vector of strings using a delimiter. + * + * This function splits the input string into multiple strings using the specified delimiter. + * + * @param str The input string to split. + * @return A vector of strings containing the split values. + */ + std::vector stringToList(const std::string& str) { + std::vector result; + + if (str.empty()) { + return result; + } + + // Check if the input string starts and ends with '(' and ')' or '[' and ']' + if ((str.front() == '(' && str.back() == ')') || (str.front() == '[' && str.back() == ']')) { + // Work directly with the original string using indices instead of creating substring + size_t start = 1; // Skip opening bracket/paren + size_t end = 1; + const size_t values_end = str.size() - 1; // Skip closing bracket/paren + + // Pre-declare item string to avoid repeated allocations + std::string item; + + // Iterate through the string manually to split by commas + while ((end = str.find(',', start)) != std::string::npos && end < values_end) { + // Extract item directly from original string without creating substring + item.assign(str, start, end - start); + + // Trim leading and trailing spaces + trim(item); + + // Remove quotes from each token if necessary + removeQuotes(item); + + result.push_back(std::move(item)); + start = end + 1; + } + + // Handle the last item after the last comma + if (start < values_end) { + item.assign(str, start, values_end - start); + trim(item); + removeQuotes(item); + result.push_back(std::move(item)); + } + } + + return result; + } + + + + // Function to read file into a set of strings + std::unordered_set readSetFromFile(const std::string& filePath, const std::string& packagePath) { + std::lock_guard lock(file_access_mutex); + std::unordered_set lines; + + FILE* file = fopen(filePath.c_str(), "r"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + logMessage(UNABLE_TO_OPEN_FILE + filePath); + #endif + return lines; + } + + static constexpr size_t BUFFER_SIZE = 8192; + char buffer[BUFFER_SIZE]; + size_t len; + while (fgets(buffer, BUFFER_SIZE, file)) { + // Remove trailing newline character if it exists + len = strlen(buffer); + if (len > 0 && buffer[len - 1] == '\n') { + buffer[len - 1] = '\0'; + } + + std::string line = buffer; + if (!packagePath.empty()) { + preprocessPath(line, packagePath); + } + lines.insert(std::move(line)); + } + + fclose(file); + + return lines; + } + + + // Function to write a set to a file + void writeSetToFile(const std::unordered_set& fileSet, const std::string& filePath) { + std::lock_guard lock(file_access_mutex); + + FILE* file = fopen(filePath.c_str(), "w"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + logMessage(UNABLE_TO_OPEN_FILE + filePath); + #endif + return; + } + + for (const auto& entry : fileSet) { + fprintf(file, "%s\n", entry.c_str()); + } + + fclose(file); + } + + // Helper function for streaming comparison + void streamCompareAndWrite(const std::string& streamFilePath, + const std::unordered_set& compareSet, + const std::string& outputTxtFilePath) { + std::lock_guard lock(file_access_mutex); + + FILE* streamFile = fopen(streamFilePath.c_str(), "r"); + if (!streamFile) return; + + FILE* outputFile = fopen(outputTxtFilePath.c_str(), "w"); + if (!outputFile) { + fclose(streamFile); + return; + } + + static constexpr size_t BUFFER_SIZE = 8192; + char buffer[BUFFER_SIZE]; + size_t len; + + while (fgets(buffer, BUFFER_SIZE, streamFile)) { + len = strlen(buffer); + if (len > 0 && buffer[len - 1] == '\n') { + buffer[len - 1] = '\0'; + } + + if (compareSet.count(std::string(buffer))) { + fprintf(outputFile, "%s\n", buffer); + } + } + + fclose(streamFile); + fclose(outputFile); + } + + // Function to compare two file lists and save duplicates to an output file + void compareFilesLists(const std::string& txtFilePath1, const std::string& txtFilePath2, const std::string& outputTxtFilePath) { + // Read files into sets + std::unordered_set fileSet1 = readSetFromFile(txtFilePath1); + std::unordered_set fileSet2 = readSetFromFile(txtFilePath2); + + // Always work with the smaller set for better performance + if (fileSet1.size() <= fileSet2.size()) { + // fileSet1 is smaller or equal - modify it + for (auto it = fileSet1.begin(); it != fileSet1.end();) { + if (fileSet2.count(*it) == 0) { + it = fileSet1.erase(it); + } else { + ++it; + } + } + writeSetToFile(fileSet1, outputTxtFilePath); + } else { + // fileSet2 is smaller - modify it instead + for (auto it = fileSet2.begin(); it != fileSet2.end();) { + if (fileSet1.count(*it) == 0) { + it = fileSet2.erase(it); + } else { + ++it; + } + } + writeSetToFile(fileSet2, outputTxtFilePath); + } + } + + void compareWildcardFilesLists( + const std::string& wildcardPatternFilePath, + const std::string& txtFilePath, + const std::string& outputTxtFilePath + ) { + std::unordered_set targetLines = readSetFromFile(txtFilePath); + std::unordered_set duplicates; + + auto wildcardFiles = getFilesListByWildcards(wildcardPatternFilePath); + + static constexpr size_t BUFFER_SIZE = 8192; + + for (auto& filePath : wildcardFiles) { + if (filePath == txtFilePath || targetLines.empty()) { + filePath = ""; // Clear early + continue; + } + + std::lock_guard lock(file_access_mutex); + + FILE* file = fopen(filePath.c_str(), "r"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + logMessage(UNABLE_TO_OPEN_FILE + filePath); + #endif + continue; + } + + + char buffer[BUFFER_SIZE]; + + while (fgets(buffer, BUFFER_SIZE, file) && !targetLines.empty()) { // Early exit! + char* newlinePos = strchr(buffer, '\n'); + if (newlinePos) *newlinePos = '\0'; + + auto it = targetLines.find(std::string(buffer)); + if (it != targetLines.end()) { + duplicates.emplace(std::move(*it)); // Move instead of copy + targetLines.erase(it); + } + } + fclose(file); + + filePath = ""; // Clear after processing - reduces vector memory footprint + } + + writeSetToFile(duplicates, outputTxtFilePath); + } +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp new file mode 100644 index 00000000..3588a3c0 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp @@ -0,0 +1,530 @@ +/******************************************************************************** + * File: mod_funcs.cpp + * Author: ppkantorski + * Description: + * This source file provides the implementations of functions declared in + * mod_funcs.hpp. These functions handle the conversion of `.pchtxt` mod files + * into `.ips` binary patches used by the Ultrahand Overlay project. This includes + * parsing, validating, and encoding patch data into the IPS format. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2024-2026 ppkantorski + ********************************************************************************/ + +#include + +namespace ult { + + static const std::string CHEAT_TYPE = "04000000"; + static const std::string CHEAT_EXT = ".txt"; + static const std::string CHEAT_ENCODING = "ascii"; + + + /** + * @brief Checks if a cheat already exists in the cheat file. + * @param cheatFilePath The path to the cheat file. + * @param newCheat The new cheat to check. + * @return True if the cheat exists, otherwise false. + */ + bool cheatExists(const std::string& cheatFilePath, const std::string& newCheat) { + #if !USING_FSTREAM_DIRECTIVE + FILE* cheatFile = fopen(cheatFilePath.c_str(), "r"); // Open the cheat file in read mode + if (!cheatFile) { + return false; // Return false if the file cannot be opened + } + + char buffer[1024]; // Buffer to store each line + while (fgets(buffer, sizeof(buffer), cheatFile)) { + // Remove newline character, if present + const size_t len = strlen(buffer); + if (len > 0 && buffer[len - 1] == '\n') { + buffer[len - 1] = '\0'; + } + if (newCheat == buffer) { + fclose(cheatFile); // Close the file before returning + return true; // Cheat exists + } + } + + fclose(cheatFile); // Close the file after processing + return false; // Cheat does not exist + #else + std::ifstream cheatFile(cheatFilePath); + if (!cheatFile) { + return false; // Return false if the file cannot be opened + } + + std::string line; + while (std::getline(cheatFile, line)) { + if (line == newCheat) { + return true; // Cheat exists + } + } + return false; // Cheat does not exist + #endif + } + + /** + * @brief Appends a new cheat to the cheat file. + * @param cheatFilePath The path to the cheat file. + * @param newCheat The new cheat to append. + */ + void appendCheatToFile(const std::string& cheatFilePath, const std::string& newCheat) { + #if !USING_FSTREAM_DIRECTIVE + FILE* cheatFile = fopen(cheatFilePath.c_str(), "a"); // Open the cheat file in append mode + if (!cheatFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open cheat file for appending: " + cheatFilePath); + #endif + return; // Handle the error accordingly + } + + fprintf(cheatFile, "%s\n", newCheat.c_str()); // Write the new cheat followed by a newline + fclose(cheatFile); // Close the file + #else + std::ofstream cheatFile(cheatFilePath, std::ios::app); + if (!cheatFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open cheat file for appending: " + cheatFilePath); + #endif + return; // Handle the error accordingly + } + + cheatFile << newCheat << std::endl; // Write the new cheat + #endif + } + + + /** + * @brief Extracts the cheat name from the given file path. + * @param filePath The full file path. + * @return The extracted cheat name. + */ + std::string extractCheatName(const std::string &filePath) { + const size_t lastSlash = filePath.find_last_of("/\\"); + if (lastSlash == std::string::npos) { + return ""; + } + const size_t secondLastSlash = filePath.find_last_of("/\\", lastSlash - 1); + if (secondLastSlash == std::string::npos) { + return ""; + } + const std::string lastDir = filePath.substr(secondLastSlash + 1, lastSlash - secondLastSlash - 1); + std::string fileName = filePath.substr(lastSlash + 1); + const size_t dotPos = fileName.find_last_of('.'); + if (dotPos != std::string::npos) { + fileName = fileName.substr(0, dotPos); + } + + // If lastDir contains " - ", extract the part after " - " + const size_t dashPos = lastDir.find(" - "); + std::string cheatName = lastDir; + if (dashPos != std::string::npos) { + cheatName = lastDir.substr(dashPos + 3); + } + + return cheatName + " " + fileName; + } + + // Helper function to determine if a string is a valid title ID + bool isValidTitleID(const std::string &str) { + if (str.length() != 16) return false; + for (char c : str) { + if (!std::isxdigit(c)) return false; // Check if each character is a hexadecimal digit + } + return true; + } + + // Function to find the title ID in the text, avoiding the @nsobid- line + std::string findTitleID(const std::string &text) { + const size_t nsobidPos = text.find("@nsobid-"); + const size_t startPos = (nsobidPos != std::string::npos) ? nsobidPos + 40 + 8 : 0; // Skip past @nsobid- and its value + + std::string potentialID; + for (size_t i = startPos; i <= text.length() - 16; ++i) { + potentialID = text.substr(i, 16); + if (isValidTitleID(potentialID)) { + return potentialID; + } + } + return ""; + } + + + /** + * @brief Converts a .pchtxt file to a cheat file. + * @param pchtxtPath The file path to the .pchtxt file. + * @param cheatName The name of the cheat. + * @param outCheatPath The file path for the output cheat file. + * @return True if the conversion was successful, false otherwise. + */ + bool pchtxt2cheat(const std::string &pchtxtPath, std::string cheatName, std::string outCheatPath) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Starting pchtxt2cheat with pchtxtPath: " + pchtxtPath); + #endif + + FILE* pchtxtFile = fopen(pchtxtPath.c_str(), "r"); + if (!pchtxtFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Unable to open file " + pchtxtPath); + #endif + return false; + } + + // Read the entire file into a string + std::string pchtxt; + char buffer[4096]; + while (fgets(buffer, sizeof(buffer), pchtxtFile)) { + pchtxt += buffer; + } + fclose(pchtxtFile); + + const size_t nsobidPos = pchtxt.find("@nsobid-"); + if (nsobidPos == std::string::npos) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Could not find bid in pchtxt file, the file is likely invalid."); + #endif + return false; + } + + const std::string bid = pchtxt.substr(nsobidPos + 8, 40); + const std::string bidShort = bid.substr(0, 16); + + const std::string tid = findTitleID(pchtxt); + if (tid.empty()) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Could not find TID in pchtxt file, the file is likely invalid."); + #endif + return false; + } + + std::string cheatFilePath; + + if (outCheatPath.empty()) { + const std::string folderPath = "sdmc:/atmosphere/contents/" + tid + "/cheats/"; + createDirectory(folderPath); + cheatFilePath = folderPath + bidShort + CHEAT_EXT; + } else { + cheatFilePath = outCheatPath; + } + + FILE* existingCheatFile = fopen(cheatFilePath.c_str(), "r"); + bool cheatNameExists = false; + if (existingCheatFile) { + char line[256]; + while (fgets(line, sizeof(line), existingCheatFile)) { + if (std::string(line) == "[" + cheatName + "]\n") { + cheatNameExists = true; + break; + } + } + fclose(existingCheatFile); + } + + // Open output cheat file + FILE* outCheatFile = fopen(cheatFilePath.c_str(), "a"); + if (!outCheatFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Unable to create cheat file " + cheatFilePath); + #endif + return false; + } + + if (!cheatNameExists) { + fprintf(outCheatFile, "[%s]\n", cheatName.c_str()); + } + + int offset = 0; + bool enabled = true; + int validCheatsProcessed = 0; // ADDED: Track number of valid cheats processed + StringStream iss(pchtxt); // Use your custom StringStream + std::string line; + + std::string addrStr, valStr; + size_t spacePos; + int codeOffset; + std::string cheatLine; + char offsetBuffer[9]; + + // Use your custom getline method instead of std::getline + while (iss.getline(line, '\n')) { // Custom getline with newline as the delimiter + + // strip inline C++-style comments + const auto slashPos = line.find("//"); + if (slashPos != std::string::npos) + line = line.substr(0, slashPos); + + // strip inline hash comments (but leave full-line # for headers) + const auto hashPos = line.find('#'); + if (hashPos != std::string::npos && hashPos > 0) + line = line.substr(0, hashPos); + + trim(line); + if (line.empty() || line[0] == '#') continue; + + if (line.find("@flag offset_shift ") == 0) { + const std::string offsetStr = line.substr(19); + offset = (offsetStr.find("0x") == 0 ? std::strtol(offsetStr.c_str(), nullptr, 16) : std::strtol(offsetStr.c_str(), nullptr, 10)) - 0x100; + continue; + } + + if (line.find("@enabled") == 0) { + enabled = true; + continue; + } + + if (line.find("@disabled") == 0) { + enabled = false; + continue; + } + + if (line.find("@stop") == 0) { + break; + } + + if (!enabled) { + continue; + } + + spacePos = line.find(' '); + if (spacePos == std::string::npos) { + continue; + } + + addrStr = line.substr(0, spacePos); + valStr = line.substr(spacePos + 1); + + if (addrStr.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos || valStr.find_first_not_of("0123456789abcdefABCDEF") != std::string::npos) { + continue; + } + + codeOffset = std::strtol(valStr.c_str(), nullptr, 16) + offset; + snprintf(offsetBuffer, sizeof(offsetBuffer), "%08X", codeOffset); + cheatLine = CHEAT_TYPE + " " + addrStr + " " + hexToReversedHex(offsetBuffer); + + + // Check if cheat already exists + FILE* checkFile = fopen(cheatFilePath.c_str(), "r"); + bool exists = false; + if (checkFile) { + char checkLine[256]; + while (fgets(checkLine, sizeof(checkLine), checkFile)) { + if (std::string(checkLine) == cheatLine + "\n") { + exists = true; + break; + } + } + fclose(checkFile); + } + + if (!exists) { + fprintf(outCheatFile, "%s\n", cheatLine.c_str()); + validCheatsProcessed++; // ADDED: Increment counter for new cheats + } + } + + + fclose(outCheatFile); + + // ADDED: Check if any valid cheats were processed + if (validCheatsProcessed == 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Warning: No valid patch data found to convert to cheats in " + pchtxtPath); + #endif + return false; + } + + return true; + } + + + + /** + * @brief Converts a .pchtxt file to an IPS file using fstream. + * + * This function reads the contents of a .pchtxt file, extracts the address-value pairs, + * and generates an IPS file with the provided output folder. + * + * @param pchtxtPath The file path to the .pchtxt file. + * @param outputFolder The folder path for the output IPS file. + * @return True if the conversion was successful, false otherwise. + */ + bool pchtxt2ips(const std::string& pchtxtPath, const std::string& outputFolder) { + + // Use FILE* for reading + FILE* pchtxtFile = fopen(pchtxtPath.c_str(), "r"); + if (!pchtxtFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Unable to open file " + pchtxtPath); + #endif + return false; + } + + std::vector>> patches; + char lineBuffer[512]; // Fixed: Use char buffer for fgets + std::string line; + uint32_t lineNum = 0; + std::string nsobid; + int offset = 0; // Default offset + bool enabled = true; + + uint32_t address; + uint8_t byte; + std::vector valueBytes; + std::string offsetStr; + + while (fgets(lineBuffer, sizeof(lineBuffer), pchtxtFile) != nullptr) { + line = lineBuffer; // Convert to string + ++lineNum; + if (line.empty() || line.front() == '@' || !enabled) { + if (line.find("@nsobid-") == 0) { + nsobid = line.substr(8); + } + if (line.find("@flag offset_shift ") == 0) { + offsetStr = line.substr(19); + offset = (offsetStr.find("0x") == 0 ? std::strtol(offsetStr.c_str(), nullptr, 16) : std::strtol(offsetStr.c_str(), nullptr, 10)); + } + if (line.find("@enabled") == 0) { + enabled = true; + continue; + } + if (line.find("@disabled") == 0) { + enabled = false; + continue; + } + if (line.find("@stop") == 0) { + break; + } + continue; // Skip empty lines and lines starting with '@' + } + + StringStream iss(line); + std::string addressStr, valueStr; + + if (!(iss >> addressStr >> valueStr)) { + continue; + } + + char* endPtr; + address = std::strtoul(addressStr.c_str(), &endPtr, 16) + offset; // Adjust address by offset + if (*endPtr != '\0') { + continue; + } + + for (size_t i = 0; i < valueStr.length(); i += 2) { + byte = ult::stoi(valueStr.substr(i, 2), nullptr, 16); + valueBytes.push_back(byte); + } + + if (valueBytes.empty()) { + continue; + } + + patches.push_back(std::make_pair(address, valueBytes)); + valueBytes.clear(); + } + + fclose(pchtxtFile); + + // CHECK: Return false if no patches were found + if (patches.empty()) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Warning: No valid patches found in " + pchtxtPath); + #endif + return false; + } + + if (nsobid.empty()) { + nsobid = pchtxtPath.substr(pchtxtPath.find_last_of("/\\") + 1); + nsobid = nsobid.substr(0, nsobid.find_last_of(".")); + } + + // Trim any newline characters from nsobid + trim(nsobid); + trimNewline(nsobid); + + const std::string ipsFileName = nsobid + ".ips"; + const std::string ipsFilePath = outputFolder + ipsFileName; + + + // Use FILE* for writing + FILE* ipsFile = fopen(ipsFilePath.c_str(), "wb"); + if (!ipsFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Unable to create IPS file " + ipsFilePath); + #endif + return false; + } + + fwrite(IPS32_HEAD_MAGIC, sizeof(char), std::strlen(IPS32_HEAD_MAGIC), ipsFile); + + uint16_t valueLength; + uint32_t bigEndianAddress; + + for (const auto& patch : patches) { + bigEndianAddress = toBigEndian(patch.first); // Convert address to big-endian + fwrite(&bigEndianAddress, sizeof(bigEndianAddress), 1, ipsFile); // Write address + + valueLength = toBigEndian(static_cast(patch.second.size())); // Convert length to big-endian + fwrite(&valueLength, sizeof(valueLength), 1, ipsFile); // Write length of value + + fwrite(patch.second.data(), sizeof(uint8_t), patch.second.size(), ipsFile); // Write value + } + + fwrite(IPS32_FOOT_MAGIC, sizeof(char), std::strlen(IPS32_FOOT_MAGIC), ipsFile); + fclose(ipsFile); + + + FILE* _pchtxtFile = fopen(pchtxtPath.c_str(), "r"); + if (!_pchtxtFile) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Unable to open file " + pchtxtPath); + #endif + return false; // Changed: Return false if we can't read the file for title ID + } + + // Read the entire file into a string + std::string pchtxt; + char buffer[4096]; + while (fgets(buffer, sizeof(buffer), _pchtxtFile)) { + pchtxt += buffer; + } + fclose(_pchtxtFile); + + + const std::string tid = findTitleID(pchtxt); + if (!tid.empty()) { + const std::string tidFilePath = outputFolder + tid; + FILE* tidFile = fopen(tidFilePath.c_str(), "w"); + if (tidFile) { + fclose(tidFile); // Creates an empty file + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Warning: Could not find Title ID in " + pchtxtPath); + #endif + } + + return true; + } + +} diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp new file mode 100644 index 00000000..a1d078c3 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp @@ -0,0 +1,1327 @@ +/******************************************************************************** + * File: path_funcs.cpp + * Author: ppkantorski + * Description: + * This source file implements the functions declared in path_funcs.hpp. + * These utility functions are focused on file and directory path manipulation + * for the Ultrahand Overlay project. Functionality includes creating directories, + * checking existence of files or paths, moving or copying files, and normalizing + * file system paths for cross-platform compatibility. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "path_funcs.hpp" + + +namespace ult { + std::atomic abortFileOp(false); + + size_t COPY_BUFFER_SIZE = 8192; // Back to non-const as requested + + std::atomic copyPercentage(-1); + + std::mutex logMutex2; // Mutex for thread-safe logging (defined here, declared as extern in header) + + static std::vector fileList; + + // RAII wrapper for FILE* to ensure proper cleanup + class FileGuard { + private: + FILE* file; + public: + FileGuard(FILE* f) : file(f) {} + ~FileGuard() { if (file) fclose(file); } + FILE* get() { return file; } + FILE* release() { FILE* f = file; file = nullptr; return f; } + }; + + /** + * @brief Checks if a path points to a directory. + * + * This function checks if the specified path points to a directory. + * + * @param path The path to check. + * @return True if the path is a directory, false otherwise. + */ + bool isDirectory(const std::string& path) { + struct stat pathStat; + return (stat(path.c_str(), &pathStat) == 0 && S_ISDIR(pathStat.st_mode)); + } + + /** + * @brief Checks if a path points to a file. + * + * This function checks if the specified path points to a file. + * + * @param path The path to check. + * @return True if the path is a file, false otherwise. + */ + bool isFile(const std::string& path) { + struct stat pathStat; + return (stat(path.c_str(), &pathStat) == 0 && S_ISREG(pathStat.st_mode)); + } + + /** + * @brief Checks if a path points to a file or directory. + * + * This function checks if the specified path points to either a file or a directory. + * + * @param path The path to check. + * @return True if the path points to a file or directory, false otherwise. + */ + bool isFileOrDirectory(const std::string& path) { + struct stat pathStat; + return (stat(path.c_str(), &pathStat) == 0); + } + + // Helper function to check if directory is empty + bool isDirectoryEmpty(const std::string& dirPath) { + DIR* dir = opendir(dirPath.c_str()); + if (!dir) return false; // Can't open, assume not empty + + dirent* entry; + while ((entry = readdir(dir)) != nullptr) { + if (strcmp(entry->d_name, ".") != 0 && strcmp(entry->d_name, "..") != 0) { + closedir(dir); + return false; // Found a file/directory + } + } + closedir(dir); + return true; // Empty directory + } + + + /** + * @brief Creates a single directory if it doesn't exist. + * + * This function checks if the specified directory exists, and if not, it creates the directory. + * + * @param directoryPath The path of the directory to be created. + */ + void createSingleDirectory(const std::string& directoryPath) { + // mkdir is generally thread-safe, returns EEXIST if already exists + if (mkdir(directoryPath.c_str(), 0777) != 0) { + // Only log error if it's not EEXIST + if (errno != EEXIST) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to create directory: " + directoryPath + " - " + std::string(strerror(errno))); + #endif + } + } + } + + /** + * @brief Creates a directory and its parent directories if they don't exist. + * + * This function creates a directory specified by `directoryPath` and also creates any parent directories + * if they don't exist. It handles nested directory creation. + * + * @param directoryPath The path of the directory to be created. + */ + void createDirectory(const std::string& directoryPath) { + const std::string volume = ROOT_PATH; + std::string path = directoryPath; + + // Remove leading "sdmc:/" if present + if (path.compare(0, volume.size(), volume) == 0) { + path = path.substr(volume.size()); + } + + std::string parentPath = volume; + size_t pos = 0, nextPos; + + // Iterate through the path and create each directory level if it doesn't exist + while ((nextPos = path.find('/', pos)) != std::string::npos) { + if (nextPos != pos) { + parentPath.append(path, pos, nextPos - pos); + parentPath += '/'; + createSingleDirectory(parentPath); // Create the parent directory + } + pos = nextPos + 1; + } + + // Create the final directory level if it doesn't exist + if (pos < path.size()) { + parentPath += path.substr(pos); + createSingleDirectory(parentPath); // Create the final directory + } + } + + + void writeLog(FILE* logFile, const std::string& line) { + if (logFile) { + std::lock_guard lock(logMutex2); + fprintf(logFile, "%s\n", line.c_str()); + fflush(logFile); // Ensure data is written immediately + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to write to log file."); + #endif + } + } + + /** + * @brief Creates a text file with the specified content. + * + * This function creates a text file specified by `filePath` and writes the given `content` to the file. + * + * @param filePath The path of the text file to be created. + * @param content The content to be written to the text file. + */ + void createTextFile(const std::string& filePath, const std::string& content) { + // Create parent directory first + createDirectory(getParentDirFromPath(filePath)); + + FileGuard file(fopen(filePath.c_str(), "w")); + if (file.get()) { + fputs(content.c_str(), file.get()); + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Unable to create file " + filePath); + #endif + } + } + + /** + * @brief Deletes a file or directory without using an explicit stack. + * + * This function deletes the file or directory specified by `pathToDelete`. + * It uses a state-machine approach with a current directory pointer instead + * of an explicit stack data structure. + * + * @param pathToDelete The path of the file or directory to be deleted. + * @param logSource The path to the log file where deletions are recorded. + */ + void deleteFileOrDirectory(const std::string& pathToDelete, const std::string& logSource) { + if (pathToDelete.empty()) return; + + std::vector successfulDeletions; + const bool needsLogging = !logSource.empty(); + + // Handle single file case + const bool pathIsFile = pathToDelete.back() != '/'; + + if (pathIsFile) { + if (isFile(pathToDelete)) { + if (remove(pathToDelete.c_str()) == 0) { + if (needsLogging) { + successfulDeletions.push_back(pathToDelete); + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete file: " + pathToDelete); + #endif + } + } + + // Write log for single file deletion if needed + if (needsLogging && !successfulDeletions.empty()) { + createDirectory(getParentDirFromPath(logSource)); + if (FILE* logFile = fopen(logSource.c_str(), "a")) { + writeLog(logFile, pathToDelete); + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open source log file: " + logSource); + } + #endif + } + return; + } + + // Directory deletion - stackless approach + // Normalize root path + std::string rootPath = pathToDelete; + if (rootPath.back() != '/') rootPath += '/'; + + std::string currentDir = rootPath; + struct stat st; + + while (true) { + DIR* directory = opendir(currentDir.c_str()); + if (!directory) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open directory: " + currentDir); + #endif + + // Can't open - either deleted or error. Try to move up. + if (currentDir == rootPath) break; // Done with root + + size_t pos = currentDir.find_last_of('/', currentDir.length() - 2); + if (pos != std::string::npos && pos >= rootPath.length() - 1) { + currentDir = currentDir.substr(0, pos + 1); + } else { + break; + } + continue; + } + + bool foundSubdir = false; + bool foundFile = false; + dirent* entry; + + while ((entry = readdir(directory)) != nullptr) { + const char* name = entry->d_name; + if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) continue; + + std::string childPath = currentDir + name; + if (stat(childPath.c_str(), &st) != 0) continue; + + if (S_ISDIR(st.st_mode)) { + // Found a subdirectory - dive into it + currentDir = childPath + "/"; + foundSubdir = true; + break; + } else if (S_ISREG(st.st_mode)) { + // Delete file immediately + if (remove(childPath.c_str()) == 0) { + if (needsLogging) { + successfulDeletions.push_back(childPath); + } + foundFile = true; + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete file: " + childPath); + #endif + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Unknown file type: " + childPath); + #endif + } + } + closedir(directory); + + if (foundSubdir) { + // Continue with the subdirectory + continue; + } + + if (foundFile) { + // We deleted files, re-scan this directory to check if empty + continue; + } + + // Directory is empty - delete it and move up + if (rmdir(currentDir.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete directory: " + currentDir); + #endif + } + + // Check if we just deleted the root directory + if (currentDir == rootPath) break; + + // Move up, but NEVER go above rootPath + size_t pos = currentDir.find_last_of('/', currentDir.length() - 2); + if (pos != std::string::npos && pos >= rootPath.length() - 1) { + currentDir = currentDir.substr(0, pos + 1); + } else { + break; // Safety: don't go above root + } + } + + // Batch write all successful deletions to log file at the end + if (needsLogging && !successfulDeletions.empty()) { + createDirectory(getParentDirFromPath(logSource)); + if (FILE* logFile = fopen(logSource.c_str(), "a")) { + for (const auto& deletedPath : successfulDeletions) { + writeLog(logFile, deletedPath); + } + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open source log file: " + logSource); + } + #endif + } + } + + /** + * @brief Deletes files or directories that match a specified pattern. + * + * This function deletes files or directories specified by `pathPattern` by matching against a pattern. + * It identifies files or directories that match the pattern and deletes them. + * Files/directories in the filterSet will be skipped. + * + * @param pathPattern The pattern used to match and delete files or directories. + * @param logSource Optional log source identifier. + * @param filterSet Optional set of paths to exclude from deletion (nullptr to delete all). + */ + void deleteFileOrDirectoryByPattern(const std::string& pathPattern, const std::string& logSource, + const std::unordered_set* filterSet) { + + fileList = getFilesListByWildcards(pathPattern); + + for (auto& path : fileList) { + // Check filter before deleting + const bool shouldDelete = !filterSet || filterSet->find(path) == filterSet->end(); + + if (shouldDelete) { + deleteFileOrDirectory(path, logSource); + } + path = ""; + } + + fileList.clear(); + fileList.shrink_to_fit(); + } + + // Helper function to reverse a log file safely + void reverseLogFile(const std::string& logFilePath) { + // First pass: count lines and build offset index + FILE* file = fopen(logFilePath.c_str(), "rb"); + if (!file) return; + + setvbuf(file, nullptr, _IOFBF, 8192); + + std::vector lineOffsets; + + lineOffsets.push_back(0); // First line starts at offset 0 + + static constexpr size_t BUFFER_SIZE = 8192; + char buffer[BUFFER_SIZE]; + long currentOffset = 0; + + while (fgets(buffer, BUFFER_SIZE, file)) { + currentOffset = ftell(file); + lineOffsets.push_back(currentOffset); + } + + // Remove the last offset (it's past EOF) + if (!lineOffsets.empty()) lineOffsets.pop_back(); + + if (lineOffsets.empty()) { + fclose(file); + return; + } + + // Create temp file + std::string tempPath = logFilePath + ".tmp"; + FILE* outFile = fopen(tempPath.c_str(), "wb"); + if (!outFile) { + fclose(file); + return; + } + + setvbuf(outFile, nullptr, _IOFBF, 8192); + + // Second pass: write lines in reverse order + for (auto it = lineOffsets.rbegin(); it != lineOffsets.rend(); ++it) { + fseek(file, *it, SEEK_SET); + if (fgets(buffer, BUFFER_SIZE, file)) { + // Remove trailing newline if present + size_t len = strlen(buffer); + if (len > 0 && buffer[len - 1] == '\n') buffer[len - 1] = '\0'; + + fprintf(outFile, "%s\n", buffer); + } + } + + fflush(outFile); + fclose(outFile); + fclose(file); + + // Replace original with temp + remove(logFilePath.c_str()); + rename(tempPath.c_str(), logFilePath.c_str()); + } + + void moveDirectory(const std::string& sourcePath, const std::string& destinationPath, + const std::string& logSource, const std::string& logDestination) { + + struct stat sourceInfo; + if (stat(sourcePath.c_str(), &sourceInfo) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) logMessage("Source directory doesn't exist: " + sourcePath); + #endif + return; + } + + if (mkdir(destinationPath.c_str(), 0777) != 0 && errno != EEXIST) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) logMessage("Failed to create destination directory: " + destinationPath); + #endif + return; + } + + bool needsLogging = !logSource.empty() || !logDestination.empty(); + + // Open log files once at the start + FILE* logSrcFile = nullptr; + FILE* logDestFile = nullptr; + + if (needsLogging && !logSource.empty()) { + createDirectory(getParentDirFromPath(logSource)); + logSrcFile = fopen(logSource.c_str(), "w"); + if (logSrcFile) setvbuf(logSrcFile, nullptr, _IOFBF, 8192); + } + if (needsLogging && !logDestination.empty()) { + createDirectory(getParentDirFromPath(logDestination)); + logDestFile = fopen(logDestination.c_str(), "w"); + if (logDestFile) setvbuf(logDestFile, nullptr, _IOFBF, 8192); + } + + // Recursive helper that moves files/dirs and logs in post-order (deepest first) + std::function moveRecursive = + [&](const std::string& srcPath, const std::string& dstPath) { + + DIR* dir = opendir(srcPath.c_str()); + if (!dir) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) logMessage("Failed to open source directory: " + srcPath); + #endif + return; + } + + dirent* entry; + + while ((entry = readdir(dir)) != nullptr) { + const char* name = entry->d_name; + if (name[0] == '.' && (name[1] == '\0' || (name[1] == '.' && name[2] == '\0'))) { + continue; + } + + // Build full paths + std::string fullSrcPath = srcPath; + if (!fullSrcPath.empty() && fullSrcPath.back() != '/') fullSrcPath += '/'; + fullSrcPath += name; + + std::string fullDstPath = dstPath; + if (!fullDstPath.empty() && fullDstPath.back() != '/') fullDstPath += '/'; + fullDstPath += name; + + // Use d_type if available + #ifdef _DIRENT_HAVE_D_TYPE + if (entry->d_type == DT_DIR) { + // Create destination directory + if (mkdir(fullDstPath.c_str(), 0777) != 0 && errno != EEXIST) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) logMessage("Failed to create destination directory: " + fullDstPath); + #endif + continue; + } + + // Recurse into subdirectory + moveRecursive(fullSrcPath, fullDstPath); + + // Remove the now-empty source directory + if (rmdir(fullSrcPath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) logMessage("Failed to delete source directory: " + fullSrcPath); + #endif + } + + // Log after processing (post-order) + if (needsLogging) { + if (logSrcFile) { + fprintf(logSrcFile, "%s/\n", fullSrcPath.c_str()); + } + if (logDestFile) { + fprintf(logDestFile, "%s/\n", fullDstPath.c_str()); + } + } + continue; + } else if (entry->d_type != DT_UNKNOWN && entry->d_type != DT_REG) { + // Skip non-regular files (symlinks, devices, etc.) + continue; + } + #endif + // Move regular file + remove(fullDstPath.c_str()); + if (rename(fullSrcPath.c_str(), fullDstPath.c_str()) == 0) { + if (needsLogging) { + if (logSrcFile) { + fprintf(logSrcFile, "%s\n", fullSrcPath.c_str()); + } + if (logDestFile) { + fprintf(logDestFile, "%s\n", fullDstPath.c_str()); + } + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) logMessage("Failed to move: " + fullSrcPath); + #endif + } + } + closedir(dir); + }; + + // Start the recursive move + moveRecursive(sourcePath, destinationPath); + + // Close log files + if (logSrcFile) fclose(logSrcFile); + if (logDestFile) fclose(logDestFile); + + // Remove the top-level source directory + if (rmdir(sourcePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) logMessage("Failed to delete source directory: " + sourcePath); + #endif + } + + // Reverse logs to get shallowest-first order + if (needsLogging) { + if (!logSource.empty()) reverseLogFile(logSource); + if (!logDestination.empty()) reverseLogFile(logDestination); + } + } + + + bool moveFile(const std::string& sourcePath, + const std::string& destinationPath, + const std::string& logSource, + const std::string& logDestination) { + if (!isFileOrDirectory(sourcePath)) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Source file doesn't exist or is not a regular file: " + sourcePath); + #endif + return false; + } + + std::string finalDestPath; + bool moveSuccess = false; + + if (destinationPath.back() == '/') { + // Destination is a directory - construct full destination path + if (!isDirectory(destinationPath)) { + createDirectory(destinationPath); + } + + finalDestPath = destinationPath + getFileName(sourcePath); + remove(finalDestPath.c_str()); + + if (rename(sourcePath.c_str(), finalDestPath.c_str()) == 0) { + moveSuccess = true; + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to move file to directory: " + sourcePath); + #endif + } + } else { + // Destination is a file path - directly rename the file + finalDestPath = destinationPath; + remove(finalDestPath.c_str()); + createDirectory(getParentDirFromPath(finalDestPath)); + + if (rename(sourcePath.c_str(), finalDestPath.c_str()) == 0) { + moveSuccess = true; + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) { + logMessage("Failed to move file: " + sourcePath + " -> " + finalDestPath); + logMessage("Error: " + std::string(strerror(errno))); + } + #endif + } + } + + // Only write to log files if the move was successful + // This is the key optimization - logs are only opened when actually needed! + if (moveSuccess) { + if (!logSource.empty()) { + createDirectory(getParentDirFromPath(logSource)); + if (FILE* logFile = fopen(logSource.c_str(), "a")) { + writeLog(logFile, sourcePath); + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open source log file: " + logSource); + } + #endif + } + + if (!logDestination.empty()) { + createDirectory(getParentDirFromPath(logDestination)); + if (FILE* logFile = fopen(logDestination.c_str(), "a")) { + writeLog(logFile, finalDestPath); + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open destination log file: " + logDestination); + } + #endif + } + } + + return moveSuccess; + } + + /** + * @brief Moves a file or directory to a new destination. + * + * This function moves a file or directory from the `sourcePath` to the `destinationPath`. It can handle both + * files and directories and ensures that the destination directory exists before moving. + * + * @param sourcePath The path of the source file or directory. + * @param destinationPath The path of the destination where the file or directory will be moved. + */ + void moveFileOrDirectory(const std::string& sourcePath, const std::string& destinationPath, + const std::string& logSource, const std::string& logDestination) { + if (sourcePath.back() == '/' && destinationPath.back() == '/') { + moveDirectory(sourcePath, destinationPath, logSource, logDestination); + } else { + moveFile(sourcePath, destinationPath, logSource, logDestination); + } + } + + + /** + * @brief Moves files or directories matching a specified pattern to a destination directory. + * + * This function identifies files or directories that match the `sourcePathPattern` and moves them to the `destinationPath`. + * It processes each matching entry in the source directory pattern and moves them to the specified destination. + * Files/directories in the filterSet will be skipped. + * + * @param sourcePathPattern The pattern used to match files or directories to be moved. + * @param destinationPath The destination directory where matching files or directories will be moved. + * @param logSource Optional log source identifier. + * @param logDestination Optional log destination identifier. + * @param filterSet Optional set of paths to exclude from moving (nullptr to move all). + */ + void moveFilesOrDirectoriesByPattern(const std::string& sourcePathPattern, const std::string& destinationPath, + const std::string& logSource, const std::string& logDestination, const std::unordered_set* filterSet) { + + fileList = getFilesListByWildcards(sourcePathPattern); + + std::string folderName, fixedDestinationPath; + + // Iterate through the file list + for (std::string& sourceFileOrDirectory : fileList) { + // Check filter before moving + const bool shouldMove = !filterSet || filterSet->find(sourceFileOrDirectory) == filterSet->end(); + + if (shouldMove) { + // if sourceFile is a file + if (!isDirectory(sourceFileOrDirectory)) { + moveFileOrDirectory(sourceFileOrDirectory, destinationPath, logSource, logDestination); + } else if (isDirectory(sourceFileOrDirectory)) { + // if sourceFile is a directory + folderName = getNameFromPath(sourceFileOrDirectory); + fixedDestinationPath = destinationPath + folderName + "/"; + moveFileOrDirectory(sourceFileOrDirectory, fixedDestinationPath, logSource, logDestination); + } + } + sourceFileOrDirectory = ""; + } + + fileList.clear(); + fileList.shrink_to_fit(); + } + + /** + * @brief Copies a single file from the source path to the destination path. + * + * This function copies a single file specified by `fromFile` to the location specified by `toFile`. + * + * @param fromFile The path of the source file to be copied. + * @param toFile The path of the destination where the file will be copied. + */ + void copySingleFile(const std::string& fromFile, const std::string& toFile, long long& totalBytesCopied, + const long long totalSize, const std::string& logSource, const std::string& logDestination) { + static constexpr size_t maxRetries = 10; + const size_t bufferSize = COPY_BUFFER_SIZE; + + // Create destination directory once + createDirectory(getParentDirFromPath(toFile)); + + // Use heap allocation for the buffer to avoid stack overflow with large buffer sizes + std::unique_ptr buffer(new char[bufferSize]); + + FILE* srcFile = nullptr; + FILE* destFile = nullptr; + + // Retry loop for file opening + for (size_t retryCount = 0; retryCount <= maxRetries; ++retryCount) { + srcFile = fopen(fromFile.c_str(), "rb"); + if (!srcFile) { + if (retryCount == maxRetries) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Failed to open source file after " + std::to_string(maxRetries) + " retries"); + #endif + return; + } + continue; + } + + destFile = fopen(toFile.c_str(), "wb"); + if (!destFile) { + fclose(srcFile); + if (retryCount == maxRetries) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error: Failed to open destination file after " + std::to_string(maxRetries) + " retries"); + #endif + return; + } + continue; + } + + break; // Both files opened successfully + } + + // RAII cleanup + FileGuard srcGuard(srcFile); + FileGuard destGuard(destFile); + + // Main copy loop - optimized for performance + size_t bytesRead; + char* bufferPtr = buffer.get(); + size_t remainingBytes, written; + while ((bytesRead = fread(bufferPtr, 1, bufferSize, srcFile)) > 0) { + if (abortFileOp.load(std::memory_order_acquire)) { + remove(toFile.c_str()); + copyPercentage.store(-1, std::memory_order_release); + return; + } + + // Write all bytes - handle partial writes + char* writePtr = bufferPtr; + remainingBytes = bytesRead; + + while (remainingBytes > 0) { + written = fwrite(writePtr, 1, remainingBytes, destFile); + if (written == 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error writing to destination file"); + #endif + remove(toFile.c_str()); + copyPercentage.store(-1, std::memory_order_release); + return; + } + writePtr += written; + remainingBytes -= written; + } + + totalBytesCopied += bytesRead; + if (totalSize > 0) { + copyPercentage.store(static_cast(100 * totalBytesCopied / totalSize), std::memory_order_release); + } + } + + // Check for read errors + if (ferror(srcFile)) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error reading from source file"); + #endif + remove(toFile.c_str()); + copyPercentage.store(-1, std::memory_order_release); + return; + } + + // Only open and write to log files if they're needed - this is the key optimization! + if (!logSource.empty()) { + createDirectory(getParentDirFromPath(logSource)); + if (FILE* logFile = fopen(logSource.c_str(), "a")) { + writeLog(logFile, fromFile); + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open source log file: " + logSource); + } + #endif + } + + if (!logDestination.empty()) { + createDirectory(getParentDirFromPath(logDestination)); + if (FILE* logFile = fopen(logDestination.c_str(), "a")) { + writeLog(logFile, toFile); + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open destination log file: " + logDestination); + } + #endif + } + } + + + /** + * Recursively calculates the total size of the given file or directory. + * @param path The path to the file or directory. + * @return The total size in bytes of all files within the directory or the size of a file. + */ + long long getTotalSize(const std::string& path) { + struct stat statbuf; + if (lstat(path.c_str(), &statbuf) != 0) { + return 0; // Cannot stat file + } + + if (S_ISREG(statbuf.st_mode)) { + return statbuf.st_size; + } + + if (S_ISDIR(statbuf.st_mode)) { + long long totalSize = 0; + + DIR* dir = opendir(path.c_str()); + if (!dir) { + return 0; // Cannot open directory + } + + // Calculate base path with slash for efficient concatenation + bool needsSlash = (!path.empty() && path.back() != '/'); + + dirent* entry; + while ((entry = readdir(dir)) != nullptr) { + // Fast check for "." and ".." + if (entry->d_name[0] == '.') { + if (entry->d_name[1] == '\0' || + (entry->d_name[1] == '.' && entry->d_name[2] == '\0')) { + continue; + } + } + + // Build the full path + std::string fullPath = path; + if (needsSlash) fullPath += '/'; + fullPath += entry->d_name; + + // Use d_type if available (much faster than lstat) + #ifdef _DIRENT_HAVE_D_TYPE + if (entry->d_type != DT_UNKNOWN) { + if (entry->d_type == DT_REG) { + // Regular file - get size + if (lstat(fullPath.c_str(), &statbuf) == 0) { + totalSize += statbuf.st_size; + } + } else if (entry->d_type == DT_DIR) { + // Directory - recurse + totalSize += getTotalSize(fullPath); + } + // Ignore other types (symlinks, devices, etc.) + continue; + } + #endif + // Fallback to lstat if d_type unavailable or unknown + if (lstat(fullPath.c_str(), &statbuf) != 0) { + continue; // Cannot stat file, skip it + } + + if (S_ISREG(statbuf.st_mode)) { + totalSize += statbuf.st_size; + } else if (S_ISDIR(statbuf.st_mode)) { + totalSize += getTotalSize(fullPath); + } + } + closedir(dir); + + return totalSize; + } + + return 0; // Non-file/directory entries + } + + /** + * @brief Copies a file or directory from the source path to the destination path. + * + * This function copies a file or directory specified by `fromFileOrDirectory` to the location specified by `toFileOrDirectory`. + * If the source is a regular file, it copies the file to the destination. If the source is a directory, it recursively copies + * the entire directory and its contents to the destination. + * + * @param fromPath The path of the source file or directory to be copied. + * @param toPath The path of the destination where the file or directory will be copied. + */ + void copyFileOrDirectory(const std::string& fromPath, const std::string& toPath, long long* totalBytesCopied, long long totalSize, + const std::string& logSource, const std::string& logDestination) { + bool isTopLevelCall = totalBytesCopied == nullptr; + long long tempBytesCopied = 0; + + bool needsLogging = !logSource.empty() || !logDestination.empty(); + + if (isTopLevelCall) { + totalSize = getTotalSize(fromPath); + totalBytesCopied = &tempBytesCopied; + } + + // Check abort flag + if (abortFileOp.load(std::memory_order_acquire)) { + copyPercentage.store(-1, std::memory_order_release); + return; + } + + struct stat fromStat; + if (stat(fromPath.c_str(), &fromStat) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to get stat of " + fromPath); + #endif + return; + } + + if (S_ISREG(fromStat.st_mode)) { + // It's a regular file + if (toPath.back() == '/') { + // toPath is a directory, copy file into it + std::string filename = getNameFromPath(fromPath); + std::string toFilePath = toPath + filename; + + createDirectory(toPath); + copySingleFile(fromPath, toFilePath, *totalBytesCopied, totalSize, logSource, logDestination); + } else { + // toPath is a file path, copy directly + createDirectory(getParentDirFromPath(toPath)); + copySingleFile(fromPath, toPath, *totalBytesCopied, totalSize, logSource, logDestination); + } + + if (totalSize > 0) { + copyPercentage.store(static_cast((*totalBytesCopied * 100) / totalSize), std::memory_order_release); + } + } else if (S_ISDIR(fromStat.st_mode)) { + // It's a directory + std::string actualToPath = toPath; + + // Ensure toPath ends with / + if (actualToPath.back() != '/') { + actualToPath += '/'; + } + + // Create the destination directory + createDirectory(actualToPath); + + // Open and iterate through the directory + DIR* dir = opendir(fromPath.c_str()); + if (!dir) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open directory: " + fromPath); + #endif + return; + } + + bool hasContent = false; + dirent* entry; + while ((entry = readdir(dir)) != nullptr) { + if (abortFileOp.load(std::memory_order_acquire)) { + closedir(dir); + copyPercentage.store(-1, std::memory_order_release); + return; + } + + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; + + hasContent = true; + + // Build paths for recursion - ensure fromPath has trailing slash + std::string fromWithSlash = fromPath; + if (fromWithSlash.back() != '/') { + fromWithSlash += '/'; + } + + std::string subFromPath = fromWithSlash + entry->d_name; + std::string subToPath = actualToPath + entry->d_name; + + // Check if this entry is a directory and add trailing slash if so + struct stat entryStat; + if (stat(subFromPath.c_str(), &entryStat) == 0 && S_ISDIR(entryStat.st_mode)) { + subToPath += '/'; + } + + // Recursive call - this will write logs in DFS order (deepest first) + copyFileOrDirectory(subFromPath, subToPath, totalBytesCopied, totalSize, logSource, logDestination); + } + closedir(dir); + + // Log this directory AFTER processing its contents (post-order traversal) + if (hasContent && needsLogging) { + std::string logFromPath = fromPath; + if (logFromPath.back() != '/') logFromPath += '/'; + + std::string logToPath = actualToPath; + + if (!logSource.empty()) { + createDirectory(getParentDirFromPath(logSource)); + if (FILE* logFile = fopen(logSource.c_str(), "a")) { + writeLog(logFile, logFromPath); + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open source log file: " + logSource); + } + #endif + } + + if (!logDestination.empty()) { + createDirectory(getParentDirFromPath(logDestination)); + if (FILE* logFile = fopen(logDestination.c_str(), "a")) { + writeLog(logFile, logToPath); + fclose(logFile); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open destination log file: " + logDestination); + } + #endif + } + } + } + + if (isTopLevelCall) { + copyPercentage.store(100, std::memory_order_release); + + // Reverse the log files to match original behavior (shallowest directories first) + if (needsLogging) { + if (!logSource.empty()) { + reverseLogFile(logSource); + } + if (!logDestination.empty()) { + reverseLogFile(logDestination); + } + } + } + } + + + + /** + * @brief Copies files or directories matching a specified pattern to a destination directory. + * + * This function identifies files or directories that match the `sourcePathPattern` and copies them to the `toDirectory`. + * It processes each matching entry in the source directory pattern and copies them to the specified destination. + * Files/directories in the filterSet will be skipped. + * + * @param sourcePathPattern The pattern used to match files or directories to be copied. + * @param toDirectory The destination directory where matching files or directories will be copied. + * @param logSource Optional log source identifier. + * @param logDestination Optional log destination identifier. + * @param filterSet Optional set of paths to exclude from copying (nullptr to copy all). + */ + void copyFileOrDirectoryByPattern(const std::string& sourcePathPattern, const std::string& toDirectory, + const std::string& logSource, const std::string& logDestination, const std::unordered_set* filterSet) { + + fileList = getFilesListByWildcards(sourcePathPattern); + + // Calculate total size only for files that will actually be copied + long long totalSize = 0; + for (const std::string& path : fileList) { + const bool shouldCopy = !filterSet || filterSet->find(path) == filterSet->end(); + if (shouldCopy) { + totalSize += getTotalSize(path); + } + } + + long long totalBytesCopied = 0; + for (std::string& sourcePath : fileList) { + // Check filter before copying + const bool shouldCopy = !filterSet || filterSet->find(sourcePath) == filterSet->end(); + + if (shouldCopy) { + copyFileOrDirectory(sourcePath, toDirectory, &totalBytesCopied, totalSize, logSource, logDestination); + } + sourcePath = ""; + } + + fileList.clear(); + fileList.shrink_to_fit(); + } + + + + /** + * @brief Mirrors the deletion of files from a source directory to a target directory. + * + * This function mirrors the deletion of files from a `sourcePath` directory to a `targetPath` directory. + * It deletes corresponding files in the `targetPath` that match the source directory structure. + * + * @param sourcePath The path of the source directory. + * @param targetPath The path of the target directory where files will be mirrored and deleted. + * Default is "sdmc:/". You can specify a different target path if needed. + */ + void mirrorFiles(const std::string& sourcePath, const std::string targetPath, const std::string mode) { + fileList = getFilesListFromDirectory(sourcePath); + std::string updatedPath; + long long totalSize = 0; + long long totalBytesCopied = 0; + + if (mode == "copy") { + // Calculate total size for progress tracking + for (const auto& path : fileList) { + if (path != targetPath + path.substr(sourcePath.size())) { + totalSize += getTotalSize(path); + } + } + } + + for (auto& path : fileList) { + // Generate the corresponding path in the target directory by replacing the source path + updatedPath = targetPath + path.substr(sourcePath.size()); + if (mode == "delete") + deleteFileOrDirectory(updatedPath); + else if (mode == "copy") { + if (path != updatedPath) + copyFileOrDirectory(path, updatedPath, &totalBytesCopied, totalSize); + } + path = ""; + } + + fileList.clear(); + fileList.shrink_to_fit(); + } + + /** + * @brief For each match of the wildcard pattern, creates an empty text file + * named basename.txt inside the output directory. + * + * @param wildcardPattern A path with a wildcard, such as /some/path/[*]. + * Each match results in a file named after the basename. + * @param outputDir Directory where the output files will be written. + * Created if it doesn't already exist. + */ + void createFlagFiles(const std::string& wildcardPattern, const std::string& outputDir) { + // 1) Gather all matches from the wildcard pattern + fileList = ult::getFilesListByWildcards(wildcardPattern); + if (fileList.empty()) { + return; // No matches, nothing to do + } + + // 2) Ensure the output directory exists + createDirectory(outputDir); + + // 3) Generate empty .txt files for each matched path + std::string outputPrefix = outputDir; + if (!outputPrefix.empty() && outputPrefix.back() != '/') + outputPrefix.push_back('/'); + + std::string baseName, outFile; + for (auto& fullPath : fileList) { + baseName = ult::getNameFromPath(fullPath); + if (baseName.empty()) { + fullPath = ""; + continue; + } + + outFile = outputPrefix + baseName; + + FileGuard fp(std::fopen(outFile.c_str(), "wb")); + // File automatically closed by FileGuard destructor + fullPath = ""; + } + fileList.clear(); + fileList.shrink_to_fit(); + } + + /** + * @brief Removes all files starting with "._" from a directory and its subdirectories. + * + * This function recursively scans the specified directory and removes all files + * whose names start with "._" (commonly macOS metadata files). It processes + * all subdirectories recursively. + * + * @param sourcePath The path of the directory to clean. + */ + void dotCleanDirectory(const std::string& sourcePath) { + DIR* dir = opendir(sourcePath.c_str()); + if (!dir) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Path is not a directory or cannot open: " + sourcePath); + #endif + return; + } + + struct dirent* entry; + struct stat pathStat; + bool needsSlash = (!sourcePath.empty() && sourcePath.back() != '/'); + + while ((entry = readdir(dir)) != nullptr) { + const char* fileName = entry->d_name; + + // Fast skip for "." and ".." + if (fileName[0] == '.' && + (fileName[1] == '\0' || (fileName[1] == '.' && fileName[2] == '\0'))) { + continue; + } + + // Build full path + std::string fullPath = sourcePath; + if (needsSlash) fullPath += '/'; + fullPath += fileName; + + // Handle directories - recurse into them + if (entry->d_type == DT_DIR) { + dotCleanDirectory(fullPath); + continue; + } + + // Only care about "._" files and ".DS_Store" + bool isDotUnderscore = (fileName[0] == '.' && fileName[1] == '_'); + bool isDSStore = (fileName[0] == '.' && fileName[1] == 'D' && fileName[2] == 'S' && + fileName[3] == '_' && fileName[4] == 'S' && fileName[5] == 't' && + fileName[6] == 'o' && fileName[7] == 'r' && fileName[8] == 'e' && + fileName[9] == '\0'); + + if (!isDotUnderscore && !isDSStore) { + continue; + } + + // Process regular files or unknown types + if (entry->d_type == DT_REG) { + if (remove(fullPath.c_str()) == 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Removed dot-underscore file: " + fullPath); + #endif + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to remove dot-underscore file: " + fullPath); + #endif + } + } else if (entry->d_type == DT_UNKNOWN) { + // Verify with stat if type is unknown + if (stat(fullPath.c_str(), &pathStat) == 0 && S_ISREG(pathStat.st_mode)) { + if (remove(fullPath.c_str()) == 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Removed dot-underscore file: " + fullPath); + #endif + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to remove dot-underscore file: " + fullPath); + #endif + } + } + } + } + + closedir(dir); + } +} \ No newline at end of file diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp new file mode 100644 index 00000000..972d9695 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp @@ -0,0 +1,567 @@ +/******************************************************************************** + * File: string_funcs.cpp + * Author: ppkantorski + * Description: + * This source file provides implementations for the string manipulation + * functions declared in string_funcs.hpp. These utility functions support + * operations such as trimming whitespace, removing quotes, normalizing + * slashes, and performing other string cleanup tasks used throughout + * the Ultrahand Overlay project. + * + * For the latest updates and contributions, visit the project's GitHub repository. + * (GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay) + * + * Note: Please be aware that this notice cannot be altered or removed. It is a part + * of the project's documentation and must remain intact. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include "string_funcs.hpp" + +namespace ult { + + + // Custom string conversion methods in place of std:: + std::string to_string(int value) { + char buffer[12]; // Sufficient for 32-bit int + snprintf(buffer, sizeof(buffer), "%d", value); + return std::string(buffer); + } + + int stoi(const std::string& str, std::size_t* pos, int base) { + char* end; + const long result = std::strtol(str.c_str(), &end, base); + + if (pos) { + *pos = end - str.c_str(); // Set the position to the last character processed + } + + // Handle out-of-range or conversion issues here if needed + return static_cast(result); + } + + + float stof(const std::string& str) { + return strtof(str.c_str(), nullptr); + } + + // Mimics std::getline() with a delimiter + bool StringStream::getline(std::string& output, char delimiter) { + if (position >= data.size()) { + return false; + } + + const size_t nextPos = data.find(delimiter, position); + + if (nextPos != std::string::npos) { + output.assign(data, position, nextPos - position); // No temporary string creation + position = nextPos + 1; + } else { + output.assign(data, position, data.size() - position); // No temporary string creation + position = data.size(); + } + + return true; + } + + // Mimics operator >> to split by whitespace + StringStream& StringStream::operator>>(std::string& output) { + // Skip leading whitespace + while (position < data.size() && std::isspace(data[position])) { + ++position; + } + + if (position >= data.size()) { + output.clear(); + validState = false; + return *this; + } + + size_t nextPos = position; + while (nextPos < data.size() && !std::isspace(data[nextPos])) { + ++nextPos; + } + + output.assign(data, position, nextPos - position); // Replace substr() with assign() + position = nextPos; + + validState = true; + return *this; + } + + // Overload << operator for std::string + StringStream& StringStream::operator<<(const std::string& input) { + data += input; + return *this; + } + + // Overload << operator for const char* + StringStream& StringStream::operator<<(const char* input) { + data += input; + return *this; + } + + // Overload << operator for char + StringStream& StringStream::operator<<(char input) { + data += input; + return *this; + } + + // Overload << operator for int (handles hex mode) + StringStream& StringStream::operator<<(int input) { + if (hexMode) { + char buffer[20]; // Buffer large enough for hex conversion + sprintf(buffer, "%x", input); // Convert integer to hex string + data += buffer; + } else { + data += ult::to_string(input); + } + return *this; + } + + // Define the new overload for long long + StringStream& StringStream::operator<<(long long input) { + data += std::to_string(input); + return *this; + } + + // Return the current buffer content + std::string StringStream::str() const { + return data; + } + + + + /** + * @brief Trims leading and trailing whitespaces from a string. + * + * This function removes leading and trailing whitespaces, tabs, newlines, carriage returns, form feeds, + * and vertical tabs from the input string. + * + * @param str The input string to trim. + * @return The trimmed string. + */ + void trim(std::string& str) { + const size_t first = str.find_first_not_of(" \t\n\r\f\v"); + if (first == std::string::npos) { + str.clear(); // Fix: clear all-whitespace strings + return; + } + + const size_t last = str.find_last_not_of(" \t\n\r\f\v"); + + // True in-place modification - no temporary string creation + if (last + 1 < str.length()) { + str.erase(last + 1); // Remove trailing whitespace + } + if (first > 0) { + str.erase(0, first); // Remove leading whitespace + } + } + + + // Function to trim newline characters from the end of a string + void trimNewline(std::string& str) { + const size_t end = str.find_last_not_of("\n"); + if (end == std::string::npos) { + str.clear(); // If the string consists entirely of newlines, clear it + } else { + str.erase(end + 1); // Remove all characters after the last non-newline character + } + } + + + /** + * @brief Removes all white spaces from a string. + * + * This function removes all white spaces, including spaces, tabs, newlines, carriage returns, form feeds, + * and vertical tabs from the input string. + * + * @param str The input string to remove white spaces from. + * @return The string with white spaces removed. + */ + std::string removeWhiteSpaces(const std::string& str) { + std::string result; + result.reserve(str.size()); // Reserve space for the result to avoid reallocations + + std::remove_copy_if(str.begin(), str.end(), std::back_inserter(result), [](unsigned char c) { + return std::isspace(c); + }); + + return result; + } + + + + /** + * @brief Removes quotes from a string. + * + * This function removes single and double quotes from the beginning and end of the input string. + * + * @param str The input string to remove quotes from. + * @return The string with quotes removed. + */ + void removeQuotes(std::string& str) { + const size_t len = str.size(); + if (len >= 2) { + const char front = str[0]; + const char back = str[len - 1]; + + if ((front == '\'' && back == '\'') || (front == '"' && back == '"')) { + std::memmove(&str[0], &str[1], len - 2); + str.resize(len - 2); + } + } + } + + + /** + * @brief Preprocesses a path string by replacing multiple slashes and adding "sdmc:" prefix. + * + * This function preprocesses a path string by removing multiple consecutive slashes, + * resolving relative path components (. and ..), adding the "sdmc:" prefix if not present, + * and modifying the input string in place. + * + * @param path The input path string to preprocess, passed by reference. + * @param packagePath The base package path to resolve relative paths against. + */ + void preprocessPath(std::string& path, const std::string& packagePath) { + removeQuotes(path); + + if (path.empty()) + return; + + // In-place multiple slash removal + size_t writePos = 0; + bool previousSlash = false; + + for (size_t i = 0, len = path.length(); i < len; ++i) { + const char c = path[i]; + if (c == '/') { + if (!previousSlash) { + path[writePos++] = '/'; + previousSlash = true; + } + } else { + path[writePos++] = c; + previousSlash = false; + } + } + path.resize(writePos); + + // Handle "./" replacement if present + if (!packagePath.empty() && path.length() >= 2 && path[0] == '.' && path[1] == '/') { + path.replace(0, 2, packagePath); + } + + // Handle "../" sequences + size_t dotDotPos; + size_t searchEnd; + while ((dotDotPos = path.find("../")) != std::string::npos) { + // Check if there's a trailing slash before "../" + searchEnd = dotDotPos; + if (searchEnd > 0 && path[searchEnd - 1] == '/') { + --searchEnd; + } + + // Find the previous slash + const size_t lastSlash = (searchEnd > 0) ? path.rfind('/', searchEnd - 1) : std::string::npos; + + if (lastSlash != std::string::npos) { + // Erase from after lastSlash to after "../" + path.erase(lastSlash + 1, dotDotPos + 3 - lastSlash - 1); + } else { + // No slash found, replace with root + path.erase(0, dotDotPos); + path.insert(0, "/"); + } + } + + // Check for sdmc: prefix + if (path.length() < 5 || + path[0] != 's' || path[1] != 'd' || path[2] != 'm' || path[3] != 'c' || path[4] != ':') { + path.insert(0, "sdmc:"); + } + } + + + /** + * @brief Preprocesses a URL string by adding "https://" prefix. + * + * This function preprocesses a URL string by adding the "https://" prefix if not already present. + * + * @param path The input URL string to preprocess, passed by reference and modified in-place. + */ + void preprocessUrl(std::string& path) { + removeQuotes(path); + + if (path.size() >= 7 && path[0] == 'h' && path[1] == 't' && + path[2] == 't' && path[3] == 'p') { + if ((path.size() >= 8 && path[4] == 's' && path[5] == ':') || + (path[4] == ':')) { + return; + } + } + + path.insert(0, "https://"); + } + + /** + * @brief Drops the file extension from a filename. + * + * This function removes the file extension (characters after the last dot) from the input filename string. + * + * @param filename The input filename from which to drop the extension, passed by reference and modified in-place. + */ + void dropExtension(std::string& filename) { + const size_t lastDotPos = filename.rfind('.'); + if (lastDotPos != std::string::npos) { + filename.resize(lastDotPos); + } + } + + /** + * @brief Checks if a string starts with a given prefix. + * + * This function checks if the input string starts with the specified prefix. + * + * @param str The input string to check. + * @param prefix The prefix to check for. + * @return True if the string starts with the prefix, false otherwise. + */ + bool startsWith(const std::string& str, const std::string& prefix) { + return str.compare(0, prefix.length(), prefix) == 0; + } + + + + + // Helper function to check if a string is a valid integer + bool isValidNumber(const std::string& str) { + if (str.empty()) { + return false; + } + + size_t start = 0; + if (str[0] == '-' || str[0] == '+') { + if (str.length() == 1) return false; + start = 1; + } + + for (size_t i = start; i < str.length(); ++i) { + if (!std::isdigit(static_cast(str[i]))) { + return false; + } + } + + return true; + } + + std::string returnOrNull(const std::string& value) { + return value.empty() ? NULL_STR : value; + } + + + // Function to slice a string from start to end index + std::string sliceString(const std::string& str, size_t start, size_t end) { + if (start < 0) start = 0; + if (end > static_cast(str.length())) end = str.length(); + if (start > end) start = end; + return str.substr(start, end - start); + } + + + /** + * @brief Converts a string to lowercase. + * + * This function takes a string as input and returns a lowercase version of that string. + * + * @param str The input string to convert to lowercase. + * @return The lowercase version of the input string. + */ + + std::string stringToLowercase(const std::string& str) { + std::string result = str; + for (char& c : result) { + if (c >= 'A' && c <= 'Z') { + c += 32; + } + } + return result; + } + + /** + * @brief Converts a string to uppercase. + * + * This function takes a string as input and returns an uppercase version of that string. + * + * @param str The input string to convert to uppercase. + * @return The uppercase version of the input string. + */ + + std::string stringToUppercase(const std::string& str) { + std::string result = str; + for (char& c : result) { + if (c >= 'a' && c <= 'z') { + c -= 32; + } + } + return result; + } + + + + /** + * @brief Formats a priority string to a desired width. + * + * This function takes a priority string and formats it to a specified desired width by padding with '0's if it's shorter + * or truncating with '9's if it's longer. + * + * @param priority The input priority string to format. + * @param desiredWidth The desired width of the formatted string (default is 4). + * @return A formatted priority string. + */ + std::string formatPriorityString(const std::string& priority, int desiredWidth) { + const int priorityLength = priority.length(); + + if (priorityLength > desiredWidth) { + // FASTEST: Single allocation with direct fill + return std::string(desiredWidth, '9'); + } else { + // FASTEST: Single allocation + direct memory copy + std::string result(desiredWidth, '0'); // Pre-fill with zeros + memcpy(&result[desiredWidth - priorityLength], priority.data(), priorityLength); + return result; + } + } + + + + /** + * @brief Removes the part of the string after the first occurrence of '?' character. + * + * This function takes a string and removes the portion of the string that appears after + * the first '?' character, if found. If no '?' character is present, the string remains unchanged. + * + * @param input The input string from which to remove the tag, passed by reference and modified in-place. + */ + void removeTag(std::string &input) { + const char* pos = static_cast( + std::memchr(input.data(), '?', input.size()) + ); + + if (pos) { + input.resize(pos - input.data()); + } + } + + + std::string getFirstLongEntry(const std::string& input, size_t minLength) { + StringStream iss(input); // Use custom StringStream + std::string word; + + // Split the input string based on spaces and get the first word + if (iss >> word) { + // Check if the first word's length is greater than the specified length + if (word.length() > minLength) { + return word; + } + } + + // Return an empty string if the first word is not longer than minLength + return input; + } + + + // This will take a string like "v1.3.5-abasdfasdfa" and output "1.3.5". string could also look like "test-1.3.5-1" or "v1.3.5" and we will only want "1.3.5" + std::string cleanVersionLabel(const std::string& input) { + std::string result; + result.reserve(input.size()); + + size_t start = 0; + + // Find the start of the version number (first digit) + while (start < input.size() && !std::isdigit(input[start])) { + start++; + } + + if (start == input.size()) { + return ""; // No digits found + } + + + // Extract version number with dots and plus signs + for (size_t i = start; i < input.size(); ++i) { + const char c = input[i]; + if (std::isdigit(c) || c == '.' || c == '+') { + result += c; + } else { + break; // Stop at first character that's not digit, dot, or plus + } + } + + return result; + } + + + std::string extractTitle(const std::string& input) { + const size_t spacePos = input.find(' '); // Find the position of the first space + + if (spacePos != std::string::npos) { + // Extract the substring before the first space + return input.substr(0, spacePos); + } else { + // If no space is found, return the original string + return input; + } + } + + + std::vector splitString(const std::string& str, const std::string& delimiter) { + std::vector tokens; + + // OPTIMIZATION: Pre-allocate space to avoid reallocations + tokens.reserve(str.length() / (delimiter.length() + 1) + 1); + + size_t start = 0; + size_t end = str.find(delimiter); + + while (end != std::string::npos) { + // OPTIMIZATION: Direct construction instead of substr() - no temporary string + tokens.emplace_back(str, start, end - start); + start = end + delimiter.length(); + end = str.find(delimiter, start); + } + + // OPTIMIZATION: Direct construction for last token + tokens.emplace_back(str, start); + + return tokens; + } + + + // Function to split a string by a delimiter and return a specific index + std::string splitStringAtIndex(const std::string& str, const std::string& delimiter, size_t index) { + const std::vector tokens = splitString(str, delimiter); + + if (index < tokens.size()) { + return tokens[index]; + } else { + return ""; // Return empty string if index is out of bounds + } + } + + + std::string customAlign(int number) { + const std::string numStr = ult::to_string(number); + const int paddingSpaces = (4 - numStr.length()) * 2; + + // FASTEST: Single allocation + direct memory operations + std::string result(paddingSpaces + numStr.length(), ' '); + memcpy(&result[paddingSpaces], numStr.data(), numStr.length()); + + return result; + } +} diff --git a/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp new file mode 100644 index 00000000..4f42322a --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp @@ -0,0 +1,1343 @@ +/******************************************************************************** + * File: tsl_utils.cpp + * Author: ppkantorski + * Description: + * 'tsl_utils.cpp' provides the implementation of various utility functions + * defined in 'tsl_utils.hpp' for the Ultrahand Overlay project. This source file + * includes functionality for system checks, input handling, time-based interpolation, + * and other application-specific features essential for operating custom overlays + * on the Nintendo Switch. + * + * For the latest updates and contributions, visit the project's GitHub repository: + * GitHub Repository: https://github.com/ppkantorski/Ultrahand-Overlay + * + * Note: This notice is integral to the project's documentation and must not be + * altered or removed. + * + * Licensed under both GPLv2 and CC-BY-4.0 + * Copyright (c) 2023-2026 ppkantorski + ********************************************************************************/ + +#include + +//#include +extern "C" { // assertion override + void __assert_func(const char *_file, int _line, const char *_func, const char *_expr ) { + abort(); + } +} + +namespace ult { + + void formatTimestamp(time_t t, char* buf, size_t bufSize) { + struct tm tm; + localtime_r(&t, &tm); + int hour12 = tm.tm_hour % 12; + if (hour12 == 0) hour12 = 12; + std::snprintf(buf, bufSize, "%d:%02d %s", + hour12, tm.tm_min, (tm.tm_hour >= 12) ? "PM" : "AM"); + } + + double cos(double x) { + //static constexpr double PI = 3.14159265358979323846; + static constexpr double TWO_PI = 6.28318530717958647692; + static constexpr double HALF_PI = 1.57079632679489661923; + + x = x - TWO_PI * static_cast(x * 0.159154943091895); + if (x < 0) x += TWO_PI; + + int sign = 1; + if (x > _M_PI) { + x -= _M_PI; + sign = -1; + } + if (x > HALF_PI) { + x = _M_PI - x; + sign = -sign; + } + + const double x2 = x * x; + return sign * (1.0 + x2 * (-0.5 + x2 * (0.04166666666666666 + x2 * (-0.001388888888888889 + x2 * (0.0000248015873015873 - x2 * 0.0000002755731922398589))))); + } + + bool correctFrameSize; // for detecting the correct Overlay display size + + u16 DefaultFramebufferWidth = 448; ///< Width of the framebuffer + u16 DefaultFramebufferHeight = 720; ///< Height of the framebuffer + + std::unordered_map translationCache; + + std::unordered_map g_entryCombos; + std::atomic launchingOverlay(false); + std::atomic settingsInitialized(false); + std::atomic currentForeground(false); + + // Helper function to read file content into a string + bool readFileContent(const std::string& filePath, std::string& content) { + FILE* file = fopen(filePath.c_str(), "r"); + if (!file) { + #if USING_LOGGING_DIRECTIVE + logMessage("Failed to open JSON file: " + filePath); + #endif + return false; + } + char buffer[256]; + while (fgets(buffer, sizeof(buffer), file) != nullptr) { + content += buffer; + } + fclose(file); + + return true; + } + + // Helper function to parse JSON-like content into a map + void parseJsonContent(const std::string& content, std::unordered_map& result) { + size_t pos = 0; + size_t keyStart, keyEnd, colonPos, valueStart, valueEnd; + std::string key, value; + + auto normalizeNewlines = [](std::string &s) { + size_t n = 0; + while ((n = s.find("\\n", n)) != std::string::npos) { + s.replace(n, 2, "\n"); + n += 1; + } + }; + + while ((pos = content.find('"', pos)) != std::string::npos) { + keyStart = pos + 1; + keyEnd = content.find('"', keyStart); + if (keyEnd == std::string::npos) break; + + key = content.substr(keyStart, keyEnd - keyStart); + colonPos = content.find(':', keyEnd); + if (colonPos == std::string::npos) break; + + valueStart = content.find('"', colonPos); + valueEnd = content.find('"', valueStart + 1); + if (valueStart == std::string::npos || valueEnd == std::string::npos) break; + + value = content.substr(valueStart + 1, valueEnd - valueStart - 1); + + // Convert escaped newlines (\\n) into real ones + normalizeNewlines(key); + normalizeNewlines(value); + + result[key] = value; + + key.clear(); + value.clear(); + pos = valueEnd + 1; // Move to next pair + } + } + + // Function to parse JSON key-value pairs into a map + bool parseJsonToMap(const std::string& filePath, std::unordered_map& result) { + std::string content; + if (!readFileContent(filePath, content)) { + return false; + } + + parseJsonContent(content, result); + return true; + } + + // Function to load translations from a JSON-like file into the translation cache + bool loadTranslationsFromJSON(const std::string& filePath) { + return parseJsonToMap(filePath, translationCache); + } + + // Function to clear the translation cache + void clearTranslationCache() { + translationCache.clear(); + translationCache.rehash(0); + } + + + u16 activeHeaderHeight = 97; + + bool consoleIsDocked() { + Result rc = apmInitialize(); + if (R_FAILED(rc)) return false; + + ApmPerformanceMode perfMode = ApmPerformanceMode_Invalid; + rc = apmGetPerformanceMode(&perfMode); + apmExit(); + + return R_SUCCEEDED(rc) && (perfMode == ApmPerformanceMode_Boost); + } + + std::string getBuildIdAsString() { + u64 pid = 0; + if (R_FAILED(pmdmntGetApplicationProcessId(&pid)) || R_FAILED(ldrDmntInitialize())) + return NULL_STR; + + LoaderModuleInfo moduleInfos[2]; + s32 count = 0; + Result rc = ldrDmntGetProcessModuleInfo(pid, moduleInfos, 2, &count); + ldrDmntExit(); + + if (R_FAILED(rc) || count == 0) + return NULL_STR; + + u64 buildid; + std::memcpy(&buildid, moduleInfos[1].build_id, sizeof(u64)); + + char buildIdStr[17]; + snprintf(buildIdStr, sizeof(buildIdStr), "%016lX", __builtin_bswap64(buildid)); + return std::string(buildIdStr); + } + + + std::string getTitleIdAsString() { + u64 pid = 0, tid = 0; + if (R_FAILED(pmdmntGetApplicationProcessId(&pid)) || + R_FAILED(pmdmntGetProgramId(&tid, pid))) + return NULL_STR; + + char tidStr[17]; + snprintf(tidStr, sizeof(tidStr), "%016lX", tid); + return std::string(tidStr); + } + + + std::string lastTitleID; + std::atomic resetForegroundCheck(false); // initialize as true + std::atomic internalTouchReleased(true); + + u32 layerEdge = 0; + bool useRightAlignment = false; + bool useSwipeToOpen = true; + bool useLaunchCombos = true; + bool useNotifications = true; + bool useNotificationsHotkey = true; + bool useStartupNotification = true; + bool silenceNotifications = false; + bool useSoundEffects = true; + bool useHapticFeedback = false; + bool usePageSwap = false; + bool useDynamicLogo = true; + bool useSelectionBG = true; + bool useSelectionText = true; + bool useSelectionValue = false; + + std::atomic noClickableItems{false}; + + #if IS_LAUNCHER_DIRECTIVE + std::atomic overlayLaunchRequested{false}; + std::string requestedOverlayPath; + std::string requestedOverlayArgs; + std::mutex overlayLaunchMutex; + #endif + + // CUSTOM SECTION START + std::atomic backWidth; + std::atomic selectWidth; + std::atomic nextPageWidth; + std::atomic inMainMenu{false}; + std::atomic inHiddenMode{false}; + std::atomic inSettingsMenu{false}; + std::atomic inSubSettingsMenu{false}; + std::atomic inOverlaysPage{false}; + std::atomic inPackagesPage{false}; + + std::atomic hasNextPageButton{false}; + + bool firstBoot = true; // for detecting first boot + bool reloadingBoot = false; // for detecting reloading boots + + // Define an atomic bool for interpreter completion + std::atomic threadFailure(false); + std::atomic runningInterpreter(false); + std::atomic shakingProgress(true); + + std::atomic isHidden(false); + std::atomic externalAbortCommands(false); + + bool disableTransparency = false; + bool useOpaqueScreenshots = false; + + std::atomic onTrackBar(false); + std::atomic allowSlide(false); + std::atomic unlockedSlide(false); + + + + void atomicToggle(std::atomic& b) { + bool expected = b.load(std::memory_order_relaxed); + for (;;) { + const bool desired = !expected; + if (b.compare_exchange_weak(expected, desired, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + break; // success + } + // expected has been updated with the current value on failure; loop continues + } + } + + + bool updateMenuCombos = false; + + + const std::array KEYS_INFO = {{ + { HidNpadButton_L, "L", "\uE0E4" }, { HidNpadButton_R, "R", "\uE0E5" }, + { HidNpadButton_ZL, "ZL", "\uE0E6" }, { HidNpadButton_ZR, "ZR", "\uE0E7" }, + { HidNpadButton_AnySL, "SL", "\uE0E8" }, { HidNpadButton_AnySR, "SR", "\uE0E9" }, + { HidNpadButton_Left, "DLEFT", "\uE0ED" }, { HidNpadButton_Up, "DUP", "\uE0EB" }, + { HidNpadButton_Right, "DRIGHT", "\uE0EE" }, { HidNpadButton_Down, "DDOWN", "\uE0EC" }, + { HidNpadButton_A, "A", "\uE0E0" }, { HidNpadButton_B, "B", "\uE0E1" }, + { HidNpadButton_X, "X", "\uE0E2" }, { HidNpadButton_Y, "Y", "\uE0E3" }, + { HidNpadButton_StickL, "LS", "\uE08A" }, { HidNpadButton_StickR, "RS", "\uE08B" }, + { HidNpadButton_Minus, "MINUS", "\uE0B6" }, { HidNpadButton_Plus, "PLUS", "\uE0B5" } + }}; + + static std::unordered_map createButtonCharMap() { + std::unordered_map map; + for (const auto& keyInfo : KEYS_INFO) { + map[keyInfo.name] = keyInfo.glyph; + } + return map; + } + + std::unordered_map buttonCharMap = createButtonCharMap(); + + + void convertComboToUnicode(std::string& combo) { + // Quick check to see if the string contains a '+' + if (combo.find('+') == std::string::npos) { + return; // No '+' found, nothing to modify + } + + // Exit early if the combo contains any spaces + if (combo.find(' ') != std::string::npos) { + return; // Spaces found, return without modifying + } + + std::string unicodeCombo; + bool modified = false; + size_t start = 0; + const size_t length = combo.length(); + size_t end = 0; // Moved outside the loop + std::string token; // Moved outside the loop + auto it = buttonCharMap.end(); // Initialize iterator once outside the loop + + // Iterate through the combo string and split by '+' + for (size_t i = 0; i <= length; ++i) { + if (i == length || combo[i] == '+') { + // Get the current token (trimmed) + end = i; // Reuse the end variable + while (start < end && std::isspace(combo[start])) start++; // Trim leading spaces + while (end > start && std::isspace(combo[end - 1])) end--; // Trim trailing spaces + + token = combo.substr(start, end - start); // Reuse the token variable + it = buttonCharMap.find(token); // Reuse the iterator + + if (it != buttonCharMap.end()) { + unicodeCombo += it->second; // Append the mapped Unicode value + modified = true; + } else { + unicodeCombo += token; // Append the original token if not found + } + + if (i != length) { + unicodeCombo += "+"; // Only append '+' if we're not at the end + } + + start = i + 1; // Move to the next token + } + } + + // If a modification was made, update the original combo + if (modified) { + combo = unicodeCombo; + } + } + + + CONSTEXPR_STRING std::string whiteColor = "FFFFFF"; + CONSTEXPR_STRING std::string blackColor = "000000"; + CONSTEXPR_STRING std::string greyColor = "AAAAAA"; + + std::atomic languageWasChanged{false}; + + // --- Variable declarations (no inline init = no constructor code per-variable) --- + #if IS_LAUNCHER_DIRECTIVE + std::string ENGLISH; + std::string SPANISH; + std::string FRENCH; + std::string GERMAN; + std::string JAPANESE; + std::string KOREAN; + std::string ITALIAN; + std::string DUTCH; + std::string PORTUGUESE; + std::string RUSSIAN; + std::string UKRAINIAN; + std::string POLISH; + std::string SIMPLIFIED_CHINESE; + std::string TRADITIONAL_CHINESE; + std::string OVERLAYS; + std::string OVERLAYS_ABBR; + std::string OVERLAY; + std::string HIDDEN_OVERLAYS; + std::string PACKAGES; + std::string PACKAGE; + std::string HIDDEN_PACKAGES; + std::string HIDDEN; + std::string HIDE_OVERLAY; + std::string HIDE_PACKAGE; + std::string LAUNCH_ARGUMENTS; + std::string FORCE_AMS110_SUPPORT; + std::string QUICK_LAUNCH; + std::string BOOT_COMMANDS; + std::string EXIT_COMMANDS; + std::string ERROR_LOGGING; + std::string COMMANDS; + std::string SETTINGS; + std::string FAVORITE; + std::string MAIN_SETTINGS; + std::string UI_SETTINGS; + std::string WIDGET; + std::string WIDGET_ITEMS; + std::string WIDGET_SETTINGS; + std::string CLOCK; + std::string BATTERY; + std::string SOC_TEMPERATURE; + std::string PCB_TEMPERATURE; + std::string BACKDROP; + std::string DYNAMIC_COLORS; + std::string CENTER_ALIGNMENT; + std::string EXTENDED_BACKDROP; + std::string MISCELLANEOUS; + std::string MENU_SETTINGS; + std::string USER_GUIDE; + std::string PACKAGES_MENU; + std::string SHOW_HIDDEN; + std::string SHOW_DELETE; + std::string SHOW_UNSUPPORTED; + std::string PAGE_SWAP; + std::string RIGHT_SIDE_MODE; + std::string OVERLAY_VERSIONS; + std::string PACKAGE_VERSIONS; + std::string CLEAN_VERSIONS; + std::string KEY_COMBO; + std::string MODE; + std::string LAUNCH_MODES; + std::string LANGUAGE; + std::string OVERLAY_INFO; + std::string SOFTWARE_UPDATE; + std::string UPDATE_ULTRAHAND; + std::string SYSTEM; + std::string DEVICE_INFO; + std::string FIRMWARE; + std::string BOOTLOADER; + std::string HARDWARE; + std::string MEMORY; + std::string VENDOR; + std::string MODEL; + std::string STORAGE; + std::string OVERLAY_MEMORY; + std::string NOT_ENOUGH_MEMORY; + std::string WALLPAPER_SUPPORT_DISABLED; + std::string SOUND_SUPPORT_DISABLED; + std::string WALLPAPER_SUPPORT_ENABLED; + std::string SOUND_SUPPORT_ENABLED; + std::string EXIT_OVERLAY_SYSTEM; + std::string ULTRAHAND_ABOUT; + std::string ULTRAHAND_CREDITS_START; + std::string ULTRAHAND_CREDITS_END; + std::string LOCAL_IP; + std::string WALLPAPER; + std::string THEME; + std::string SOUNDS; + std::string DEFAULT; + std::string ROOT_PACKAGE; + std::string SORT_PRIORITY; + std::string OPTIONS; + std::string FAILED_TO_OPEN; + std::string LAUNCH_COMBOS; + std::string NOTIFICATIONS; + std::string NOTIFICATION_SETTINGS; + std::string SILENCE_NOTIFICATIONS; + std::string STARTUP_NOTIFICATION; + std::string MAX_SLOTS; + std::string API_NOTIFICATIONS; + std::string API_TOGGLE_HOTKEY; + std::string DISMISS_NOTIFICATION; + std::string API_TOGGLE; + std::string CLICK; + std::string TAP; + std::string HOLD_FOR_4S; + + std::string HAPTIC_FEEDBACK; + std::string OPAQUE_SCREENSHOTS; + std::string PACKAGE_INFO; + std::string _TITLE; + std::string _VERSION; + std::string _CREATOR; + std::string _ABOUT; + std::string _CREDITS; + std::string SETTINGS_MENU; + std::string SCRIPT_OVERLAY; + std::string STAR_FAVORITE; + std::string APP_SETTINGS; + std::string ON_MAIN_MENU; + std::string ON_A_COMMAND; + std::string ON_OVERLAY_PACKAGE; + std::string FEATURES; + std::string SWIPE_TO_OPEN; + std::string THEME_SETTINGS; + std::string DYNAMIC_LOGO; + std::string SELECTION_BACKGROUND; + std::string SELECTION_TEXT; + std::string SELECTION_VALUE; + std::string LIBULTRAHAND_TITLES; + std::string LIBULTRAHAND_VERSIONS; + std::string PACKAGE_TITLES; + std::string ULTRAHAND_HAS_STARTED; + std::string ULTRAHAND_HAS_RESTARTED; + std::string NEW_UPDATE_IS_AVAILABLE; + std::string DELETE_PACKAGE; + std::string DELETE_OVERLAY; + std::string SELECTION_IS_EMPTY; + std::string FORCED_SUPPORT_WARNING; + std::string TASK_IS_COMPLETE; + std::string TASK_HAS_FAILED; + std::string REBOOT_TO; + std::string REBOOT; + std::string SHUTDOWN; + std::string BOOT_ENTRY; + #endif + + std::string INCOMPATIBLE_WARNING; + std::string SYSTEM_RAM; + std::string FREE; + std::string UNAVAILABLE_SELECTION; + std::string ON; + std::string OFF; + std::string OK; + std::string BACK; + std::string HIDE; + std::string CANCEL; + std::string GAP_1; + std::string GAP_2; + + std::atomic halfGap = 0.0f; + + #if USING_WIDGET_DIRECTIVE + std::string SUNDAY; + std::string MONDAY; + std::string TUESDAY; + std::string WEDNESDAY; + std::string THURSDAY; + std::string FRIDAY; + std::string SATURDAY; + std::string JANUARY; + std::string FEBRUARY; + std::string MARCH; + std::string APRIL; + std::string MAY; + std::string JUNE; + std::string JULY; + std::string AUGUST; + std::string SEPTEMBER; + std::string OCTOBER; + std::string NOVEMBER; + std::string DECEMBER; + std::string SUN; + std::string MON; + std::string TUE; + std::string WED; + std::string THU; + std::string FRI; + std::string SAT; + std::string JAN; + std::string FEB; + std::string MAR; + std::string APR; + std::string MAY_ABBR; + std::string JUN; + std::string JUL; + std::string AUG; + std::string SEP; + std::string OCT; + std::string NOV; + std::string DEC; + #endif + + + // --- Single source-of-truth table --- + + struct LangEntry { std::string* var; const char* key; const char* defaultVal; }; + + static constexpr LangEntry LANG_TABLE[] = { + #if IS_LAUNCHER_DIRECTIVE + {&ENGLISH, "ENGLISH", "English"}, + {&SPANISH, "SPANISH", "Spanish"}, + {&FRENCH, "FRENCH", "French"}, + {&GERMAN, "GERMAN", "German"}, + {&JAPANESE, "JAPANESE", "Japanese"}, + {&KOREAN, "KOREAN", "Korean"}, + {&ITALIAN, "ITALIAN", "Italian"}, + {&DUTCH, "DUTCH", "Dutch"}, + {&PORTUGUESE, "PORTUGUESE", "Portuguese"}, + {&RUSSIAN, "RUSSIAN", "Russian"}, + {&UKRAINIAN, "UKRAINIAN", "Ukrainian"}, + {&POLISH, "POLISH", "Polish"}, + {&SIMPLIFIED_CHINESE, "SIMPLIFIED_CHINESE", "Simplified Chinese"}, + {&TRADITIONAL_CHINESE, "TRADITIONAL_CHINESE", "Traditional Chinese"}, + {&OVERLAYS, "OVERLAYS", "Overlays"}, + {&OVERLAYS_ABBR, "OVERLAYS_ABBR", "Overlays"}, + {&OVERLAY, "OVERLAY", "Overlay"}, + {&HIDDEN_OVERLAYS, "HIDDEN_OVERLAYS", "Hidden Overlays"}, + {&PACKAGES, "PACKAGES", "Packages"}, + {&PACKAGE, "PACKAGE", "Package"}, + {&HIDDEN_PACKAGES, "HIDDEN_PACKAGES", "Hidden Packages"}, + {&HIDDEN, "HIDDEN", "Hidden"}, + {&HIDE_OVERLAY, "HIDE_OVERLAY", "Hide Overlay"}, + {&HIDE_PACKAGE, "HIDE_PACKAGE", "Hide Package"}, + {&LAUNCH_ARGUMENTS, "LAUNCH_ARGUMENTS", "Launch Arguments"}, + {&FORCE_AMS110_SUPPORT, "FORCE_AMS110_SUPPORT", "Force AMS110+ Support"}, + {&QUICK_LAUNCH, "QUICK_LAUNCH", "Quick Launch"}, + {&BOOT_COMMANDS, "BOOT_COMMANDS", "Boot Commands"}, + {&EXIT_COMMANDS, "EXIT_COMMANDS", "Exit Commands"}, + {&ERROR_LOGGING, "ERROR_LOGGING", "Error Logging"}, + {&COMMANDS, "COMMANDS", "Commands"}, + {&SETTINGS, "SETTINGS", "Settings"}, + {&FAVORITE, "FAVORITE", "Favorite"}, + {&MAIN_SETTINGS, "MAIN_SETTINGS", "Main Settings"}, + {&UI_SETTINGS, "UI_SETTINGS", "UI Settings"}, + {&WIDGET, "WIDGET", "Widget"}, + {&WIDGET_ITEMS, "WIDGET_ITEMS", "Widget Items"}, + {&WIDGET_SETTINGS, "WIDGET_SETTINGS", "Widget Settings"}, + {&CLOCK, "CLOCK", "Clock"}, + {&BATTERY, "BATTERY", "Battery"}, + {&SOC_TEMPERATURE, "SOC_TEMPERATURE", "SOC Temperature"}, + {&PCB_TEMPERATURE, "PCB_TEMPERATURE", "PCB Temperature"}, + {&BACKDROP, "BACKDROP", "Backdrop"}, + {&DYNAMIC_COLORS, "DYNAMIC_COLORS", "Dynamic Colors"}, + {&CENTER_ALIGNMENT, "CENTER_ALIGNMENT", "Center Alignment"}, + {&EXTENDED_BACKDROP, "EXTENDED_BACKDROP", "Extended Backdrop"}, + {&MISCELLANEOUS, "MISCELLANEOUS", "Miscellaneous"}, + {&MENU_SETTINGS, "MENU_SETTINGS", "Menu Settings"}, + {&USER_GUIDE, "USER_GUIDE", "User Guide"}, + {&PACKAGES_MENU, "PACKAGES_MENU", "Packages Menu"}, + {&SHOW_HIDDEN, "SHOW_HIDDEN", "Show Hidden"}, + {&SHOW_DELETE, "SHOW_DELETE", "Show Delete"}, + {&SHOW_UNSUPPORTED, "SHOW_UNSUPPORTED", "Show Unsupported"}, + {&PAGE_SWAP, "PAGE_SWAP", "Page Swap"}, + {&RIGHT_SIDE_MODE, "RIGHT_SIDE_MODE", "Right-side Mode"}, + {&OVERLAY_VERSIONS, "OVERLAY_VERSIONS", "Overlay Versions"}, + {&PACKAGE_VERSIONS, "PACKAGE_VERSIONS", "Package Versions"}, + {&CLEAN_VERSIONS, "CLEAN_VERSIONS", "Clean Versions"}, + {&KEY_COMBO, "KEY_COMBO", "Key Combo"}, + {&MODE, "MODE", "Mode"}, + {&LAUNCH_MODES, "LAUNCH_MODES", "Launch Modes"}, + {&LANGUAGE, "LANGUAGE", "Language"}, + {&OVERLAY_INFO, "OVERLAY_INFO", "Overlay Info"}, + {&SOFTWARE_UPDATE, "SOFTWARE_UPDATE", "Software Update"}, + {&UPDATE_ULTRAHAND, "UPDATE_ULTRAHAND", "Update Ultrahand"}, + {&SYSTEM, "SYSTEM", "System"}, + {&DEVICE_INFO, "DEVICE_INFO", "Device Info"}, + {&FIRMWARE, "FIRMWARE", "Firmware"}, + {&BOOTLOADER, "BOOTLOADER", "Bootloader"}, + {&HARDWARE, "HARDWARE", "Hardware"}, + {&MEMORY, "MEMORY", "Memory"}, + {&VENDOR, "VENDOR", "Vendor"}, + {&MODEL, "MODEL", "Model"}, + {&STORAGE, "STORAGE", "Storage"}, + {&OVERLAY_MEMORY, "OVERLAY_MEMORY", "Overlay Memory"}, + {&NOT_ENOUGH_MEMORY, "NOT_ENOUGH_MEMORY", "Not enough memory."}, + {&WALLPAPER_SUPPORT_DISABLED, "WALLPAPER_SUPPORT_DISABLED", "Wallpaper support disabled."}, + {&SOUND_SUPPORT_DISABLED, "SOUND_SUPPORT_DISABLED", "Sound support disabled."}, + {&WALLPAPER_SUPPORT_ENABLED, "WALLPAPER_SUPPORT_ENABLED", "Wallpaper support enabled."}, + {&SOUND_SUPPORT_ENABLED, "SOUND_SUPPORT_ENABLED", "Sound support enabled."}, + {&EXIT_OVERLAY_SYSTEM, "EXIT_OVERLAY_SYSTEM", "Exit Overlay System"}, + {&ULTRAHAND_ABOUT, "ULTRAHAND_ABOUT", "Ultrahand Overlay is a customizable overlay ecosystem for overlays, commands, hotkeys, and advanced system interaction."}, + {&ULTRAHAND_CREDITS_START, "ULTRAHAND_CREDITS_START", "Special thanks to "}, + {&ULTRAHAND_CREDITS_END, "ULTRAHAND_CREDITS_END", " and many others. ♥"}, + {&LOCAL_IP, "LOCAL_IP", "Local IP"}, + {&WALLPAPER, "WALLPAPER", "Wallpaper"}, + {&THEME, "THEME", "Theme"}, + {&SOUNDS, "SOUNDS", "Sounds"}, + {&DEFAULT, "DEFAULT", "default"}, + {&ROOT_PACKAGE, "ROOT_PACKAGE", "Root Package"}, + {&SORT_PRIORITY, "SORT_PRIORITY", "Sort Priority"}, + {&OPTIONS, "OPTIONS", "Options"}, + {&FAILED_TO_OPEN, "FAILED_TO_OPEN", "Failed to open file"}, + {&LAUNCH_COMBOS, "LAUNCH_COMBOS", "Launch Combos"}, + {&NOTIFICATIONS, "NOTIFICATIONS", "Notifications"}, + {&NOTIFICATION_SETTINGS, "NOTIFICATION_SETTINGS", "Notification Settings"}, + {&SILENCE_NOTIFICATIONS, "SILENCE_NOTIFICATIONS", "Silence Notifications"}, + {&STARTUP_NOTIFICATION, "STARTUP_NOTIFICATION", "Startup Notification"}, + {&MAX_SLOTS, "MAX_SLOTS", "Max Slots"}, + {&API_NOTIFICATIONS, "API_NOTIFICATIONS", "API Notifications"}, + {&API_TOGGLE_HOTKEY, "API_TOGGLE_HOTKEY", "API Toggle Hotkey"}, + {&DISMISS_NOTIFICATION, "DISMISS_NOTIFICATION", "Dismiss Notification"}, + {&API_TOGGLE, "API_TOGGLE", "API Toggle"}, + {&CLICK, "CLICK", "click"}, + {&TAP, "TAP", "tap"}, + {&HOLD_FOR_4S, "HOLD_FOR_4S", "hold for 4s"}, + {&HAPTIC_FEEDBACK, "HAPTIC_FEEDBACK", "Haptic Feedback"}, + {&OPAQUE_SCREENSHOTS, "OPAQUE_SCREENSHOTS", "Opaque Screenshots"}, + {&PACKAGE_INFO, "PACKAGE_INFO", "Package Info"}, + {&_TITLE, "_TITLE", "Title"}, + {&_VERSION, "_VERSION", "Version"}, + {&_CREATOR, "_CREATOR", "Creator(s)"}, + {&_ABOUT, "_ABOUT", "About"}, + {&_CREDITS, "_CREDITS", "Credits"}, + {&SETTINGS_MENU, "SETTINGS_MENU", "Settings Menu"}, + {&SCRIPT_OVERLAY, "SCRIPT_OVERLAY", "Script Overlay"}, + {&STAR_FAVORITE, "STAR_FAVORITE", "Star/Favorite"}, + {&APP_SETTINGS, "APP_SETTINGS", "App Settings"}, + {&ON_MAIN_MENU, "ON_MAIN_MENU", "on Main Menu"}, + {&ON_A_COMMAND, "ON_A_COMMAND", "on a command"}, + {&ON_OVERLAY_PACKAGE, "ON_OVERLAY_PACKAGE", "on overlay/package"}, + {&FEATURES, "FEATURES", "Features"}, + {&SWIPE_TO_OPEN, "SWIPE_TO_OPEN", "Swipe to Open"}, + {&THEME_SETTINGS, "THEME_SETTINGS", "Theme Settings"}, + {&DYNAMIC_LOGO, "DYNAMIC_LOGO", "Dynamic Logo"}, + {&SELECTION_BACKGROUND, "SELECTION_BACKGROUND", "Selection Background"}, + {&SELECTION_TEXT, "SELECTION_TEXT", "Selection Text"}, + {&SELECTION_VALUE, "SELECTION_VALUE", "Selection Value"}, + {&LIBULTRAHAND_TITLES, "LIBULTRAHAND_TITLES", "libultrahand Titles"}, + {&LIBULTRAHAND_VERSIONS, "LIBULTRAHAND_VERSIONS", "libultrahand Versions"}, + {&PACKAGE_TITLES, "PACKAGE_TITLES", "Package Titles"}, + {&ULTRAHAND_HAS_STARTED, "ULTRAHAND_HAS_STARTED", "Ultrahand has started."}, + {&ULTRAHAND_HAS_RESTARTED, "ULTRAHAND_HAS_RESTARTED", "Ultrahand has restarted."}, + {&NEW_UPDATE_IS_AVAILABLE, "NEW_UPDATE_IS_AVAILABLE", "New update is available!"}, + {&DELETE_PACKAGE, "DELETE_PACKAGE", "Delete Package"}, + {&DELETE_OVERLAY, "DELETE_OVERLAY", "Delete Overlay"}, + {&SELECTION_IS_EMPTY, "SELECTION_IS_EMPTY", "Selection is empty!"}, + {&FORCED_SUPPORT_WARNING, "FORCED_SUPPORT_WARNING", "Forcing support can be dangerous."}, + {&TASK_IS_COMPLETE, "TASK_IS_COMPLETE", "Task is complete!"}, + {&TASK_HAS_FAILED, "TASK_HAS_FAILED", "Task has failed."}, + {&REBOOT_TO, "REBOOT_TO", "Reboot To"}, + {&REBOOT, "REBOOT", "Reboot"}, + {&SHUTDOWN, "SHUTDOWN", "Shutdown"}, + {&BOOT_ENTRY, "BOOT_ENTRY", "Boot Entry"}, + #endif + + {&INCOMPATIBLE_WARNING, "INCOMPATIBLE_WARNING", "Incompatible on AMS v1.10+"}, + {&SYSTEM_RAM, "SYSTEM_RAM", "System RAM"}, + {&FREE, "FREE", "free"}, + {&UNAVAILABLE_SELECTION, "UNAVAILABLE_SELECTION", "Not available"}, + {&ON, "ON", "On"}, + {&OFF, "OFF", "Off"}, + {&OK, "OK", "OK"}, + {&BACK, "BACK", "Back"}, + {&HIDE, "HIDE", "Hide"}, + {&CANCEL, "CANCEL", "Cancel"}, + {&GAP_1, "GAP_1", " "}, + {&GAP_2, "GAP_2", " "}, + + #if USING_WIDGET_DIRECTIVE + {&SUNDAY, "SUNDAY", "Sunday"}, + {&MONDAY, "MONDAY", "Monday"}, + {&TUESDAY, "TUESDAY", "Tuesday"}, + {&WEDNESDAY, "WEDNESDAY", "Wednesday"}, + {&THURSDAY, "THURSDAY", "Thursday"}, + {&FRIDAY, "FRIDAY", "Friday"}, + {&SATURDAY, "SATURDAY", "Saturday"}, + {&JANUARY, "JANUARY", "January"}, + {&FEBRUARY, "FEBRUARY", "February"}, + {&MARCH, "MARCH", "March"}, + {&APRIL, "APRIL", "April"}, + {&MAY, "MAY", "May"}, + {&JUNE, "JUNE", "June"}, + {&JULY, "JULY", "July"}, + {&AUGUST, "AUGUST", "August"}, + {&SEPTEMBER, "SEPTEMBER", "September"}, + {&OCTOBER, "OCTOBER", "October"}, + {&NOVEMBER, "NOVEMBER", "November"}, + {&DECEMBER, "DECEMBER", "December"}, + {&SUN, "SUN", "Sun"}, + {&MON, "MON", "Mon"}, + {&TUE, "TUE", "Tue"}, + {&WED, "WED", "Wed"}, + {&THU, "THU", "Thu"}, + {&FRI, "FRI", "Fri"}, + {&SAT, "SAT", "Sat"}, + {&JAN, "JAN", "Jan"}, + {&FEB, "FEB", "Feb"}, + {&MAR, "MAR", "Mar"}, + {&APR, "APR", "Apr"}, + {&MAY_ABBR, "MAY_ABBR", "May"}, + {&JUN, "JUN", "Jun"}, + {&JUL, "JUL", "Jul"}, + {&AUG, "AUG", "Aug"}, + {&SEP, "SEP", "Sep"}, + {&OCT, "OCT", "Oct"}, + {&NOV, "NOV", "Nov"}, + {&DEC, "DEC", "Dec"}, + #endif + }; + + static constexpr size_t LANG_TABLE_SIZE = sizeof(LANG_TABLE) / sizeof(LANG_TABLE[0]); + + + // --- reinitializeLangVars: just a loop now --- + void reinitializeLangVars() { + for (size_t i = 0; i < LANG_TABLE_SIZE; ++i) + *LANG_TABLE[i].var = LANG_TABLE[i].defaultVal; + } + + + // --- parseLanguage: same loop, different source --- + void parseLanguage(const std::string& langFile) { + std::unordered_map jsonMap; + if (!parseJsonToMap(langFile, jsonMap)) { + #if USING_LOGGING_DIRECTIVE + logMessage("Failed to parse language file: " + langFile); + #endif + return; + } + for (size_t i = 0; i < LANG_TABLE_SIZE; ++i) { + auto it = jsonMap.find(LANG_TABLE[i].key); + *LANG_TABLE[i].var = (it != jsonMap.end()) ? it->second : LANG_TABLE[i].defaultVal; + } + } + + + // --- localizeTimeStr and applyLangReplacements unchanged --- + #if USING_WIDGET_DIRECTIVE + void localizeTimeStr(char* timeStr) { + static const struct { const char* key; std::string* val; } mappings[] = { + {"Sunday", &SUNDAY}, {"Monday", &MONDAY}, {"Tuesday", &TUESDAY}, + {"Wednesday", &WEDNESDAY}, {"Thursday", &THURSDAY}, {"Friday", &FRIDAY}, + {"Saturday", &SATURDAY}, + {"January", &JANUARY}, {"February", &FEBRUARY}, {"March", &MARCH}, + {"April", &APRIL}, {"June", &JUNE}, {"July", &JULY}, + {"August", &AUGUST}, {"September", &SEPTEMBER}, {"October", &OCTOBER}, + {"November", &NOVEMBER}, {"December", &DECEMBER}, + {"Sun", &SUN}, {"Mon", &MON}, {"Tue", &TUE}, {"Wed", &WED}, + {"Thu", &THU}, {"Fri", &FRI}, {"Sat", &SAT}, + {"Jan", &JAN}, {"Feb", &FEB}, {"Mar", &MAR}, {"Apr", &APR}, + {"May", &MAY_ABBR}, {"Jun", &JUN}, {"Jul", &JUL}, {"Aug", &AUG}, + {"Sep", &SEP}, {"Oct", &OCT}, {"Nov", &NOV}, {"Dec", &DEC}, + }; + + std::string result = timeStr; + for (const auto& m : mappings) { + size_t pos = 0; + const size_t keyLen = strlen(m.key); + while ((pos = result.find(m.key, pos)) != std::string::npos) { + result.replace(pos, keyLen, *m.val); + pos += m.val->size(); + } + } + strcpy(timeStr, result.c_str()); + } + #endif + + void applyLangReplacements(std::string& text, bool isValue) { + if (isValue) { + if (text.length() == 2 && text[0] == 'O' && text[1] == 'n') { text = ON; return; } + if (text.length() == 3 && text[0] == 'O' && text[1] == 'f' && text[2] == 'f') { text = OFF; return; } + } + #if IS_LAUNCHER_DIRECTIVE + else { + switch (text.length()) { + case 6: if (text == "Reboot") { text = REBOOT; } break; + case 8: if (text == "Shutdown") { text = SHUTDOWN; } break; + case 9: if (text == "Reboot To") { text = REBOOT_TO; } break; + case 10: if (text == "Boot Entry"){ text = BOOT_ENTRY;} break; + } + } + #endif + } + + + + std::atomic refreshWallpaperNow(false); + std::atomic refreshWallpaper(false); + std::vector wallpaperData; + std::atomic inPlot(false); + + std::mutex wallpaperMutex; + std::condition_variable cv; + + bool loadRGBA8888toRGBA4444(const std::string& filePath, u8* dst, size_t srcSize) { + FILE* f = fopen(filePath.c_str(), "rb"); + if (!f) return false; + + const uint8x8_t mask = vdup_n_u8(0xF0); + constexpr size_t chunkBytes = 128 * 1024; + uint8_t chunkBuffer[chunkBytes]; + size_t totalRead = 0; + + setvbuf(f, nullptr, _IOFBF, chunkBytes); + + while (totalRead < srcSize) { + const size_t toRead = std::min(srcSize - totalRead, chunkBytes); + const size_t bytesRead = fread(chunkBuffer, 1, toRead, f); + if (bytesRead == 0) { fclose(f); return false; } + + const uint8_t* src = chunkBuffer; + size_t i = 0; + for (; i + 16 <= bytesRead; i += 16) { + uint8x16_t data = vld1q_u8(src + i); + uint8x8x2_t sep = vuzp_u8(vget_low_u8(data), vget_high_u8(data)); + vst1_u8(dst, vorr_u8(vand_u8(sep.val[0], mask), vshr_n_u8(sep.val[1], 4))); + dst += 8; + } + for (; i + 1 < bytesRead; i += 2) + *dst++ = (src[i] & 0xF0) | (src[i+1] >> 4); + + totalRead += bytesRead; + } + + fclose(f); + return true; + } + + + void loadWallpaperFile(const std::string& filePath, s32 width, s32 height) { + const size_t srcSize = width * height * 4; + wallpaperData.resize(srcSize / 2); + if (!isFile(filePath) || + !loadRGBA8888toRGBA4444(filePath, wallpaperData.data(), srcSize)) + wallpaperData.clear(); + } + + + void loadWallpaperFileWhenSafe() { + if (expandedMemory && !inPlot.load(std::memory_order_acquire) && !refreshWallpaper.load(std::memory_order_acquire)) { + std::unique_lock lock(wallpaperMutex); + cv.wait(lock, [] { return !inPlot.load(std::memory_order_acquire) && !refreshWallpaper.load(std::memory_order_acquire); }); + if (wallpaperData.empty() && isFile(WALLPAPER_PATH)) { + loadWallpaperFile(WALLPAPER_PATH); + } + } + } + + + void reloadWallpaper() { + // Signal that wallpaper is being refreshed + refreshWallpaper.store(true, std::memory_order_release); + + // Lock the mutex for condition waiting + std::unique_lock lock(wallpaperMutex); + + // Wait for inPlot to be false before reloading the wallpaper + cv.wait(lock, [] { return !inPlot.load(std::memory_order_acquire); }); + + // Clear the current wallpaper data + wallpaperData.clear(); + + // Reload the wallpaper file + if (isFile(WALLPAPER_PATH)) { + loadWallpaperFile(WALLPAPER_PATH); + } + + // Signal that wallpaper has finished refreshing + refreshWallpaper.store(false, std::memory_order_release); + + // Notify any waiting threads + cv.notify_all(); + } + + + std::atomic themeIsInitialized(false); // for loading the theme once in OverlayFrame / HeaderOverlayFrame + + // Variables for touch commands + std::atomic touchingBack(false); + std::atomic touchingSelect(false); + std::atomic touchingNextPage(false); + std::atomic touchingMenu(false); + std::atomic shortTouchAndRelease(false); + std::atomic longTouchAndRelease(false); + std::atomic simulatedBack(false); + std::atomic simulatedSelect(false); + std::atomic simulatedNextPage(false); + std::atomic simulatedMenu(false); + std::atomic stillTouching(false); + std::atomic interruptedTouch(false); + std::atomic touchInBounds(false); + + +#if USING_WIDGET_DIRECTIVE + // Battery implementation + bool powerInitialized = false; + bool powerCacheInitialized; + uint32_t powerCacheCharge; + bool powerCacheIsCharging; + PsmSession powerSession; + + std::atomic batteryCharge{0}; + std::atomic isCharging{false}; + + bool powerGetDetails(uint32_t *_batteryCharge, bool *_isCharging) { + static uint64_t last_call_ns = 0; + + // Ensure power system is initialized + if (!powerInitialized) { + return false; + } + + // Get the current time in nanoseconds + const uint64_t now_ns = nowNs(); + + // 3 seconds in nanoseconds + static constexpr uint64_t min_delay_ns = 3000000000ULL; + + // Check if enough time has elapsed or if cache is not initialized + const bool useCache = (now_ns - last_call_ns <= min_delay_ns) && powerCacheInitialized; + if (!useCache) { + PsmChargerType charger = PsmChargerType_Unconnected; + Result rc = psmGetBatteryChargePercentage(_batteryCharge); + bool hwReadsSucceeded = R_SUCCEEDED(rc); + + if (hwReadsSucceeded) { + rc = psmGetChargerType(&charger); + hwReadsSucceeded &= R_SUCCEEDED(rc); + *_isCharging = (charger != PsmChargerType_Unconnected); + + if (hwReadsSucceeded) { + // Update cache + powerCacheCharge = *_batteryCharge; + powerCacheIsCharging = *_isCharging; + powerCacheInitialized = true; + last_call_ns = now_ns; // Update last call time after successful hardware read + return true; + } + } + + // Use cached values if the hardware read fails + if (powerCacheInitialized) { + *_batteryCharge = powerCacheCharge; + *_isCharging = powerCacheIsCharging; + return hwReadsSucceeded; // Return false if hardware read failed but cache is valid + } + + // Return false if cache is not initialized and hardware read failed + return false; + } + + // Use cached values if not enough time has passed + *_batteryCharge = powerCacheCharge; + *_isCharging = powerCacheIsCharging; + return true; // Return true as cache is used + } + + + void powerInit(void) { + uint32_t charge = 0; + bool charging = false; + + powerCacheInitialized = false; + powerCacheCharge = 0; + powerCacheIsCharging = false; + + if (!powerInitialized) { + Result rc = psmInitialize(); + if (R_SUCCEEDED(rc)) { + rc = psmBindStateChangeEvent(&powerSession, 1, 1, 1); + + if (R_FAILED(rc)) + psmExit(); + + if (R_SUCCEEDED(rc)) { + powerInitialized = true; + ult::powerGetDetails(&charge, &charging); + ult::batteryCharge.store(charge, std::memory_order_release); + ult::isCharging.store(charging, std::memory_order_release); + } + } + } + } + + void powerExit(void) { + if (powerInitialized) { + psmUnbindStateChangeEvent(&powerSession); + psmExit(); + powerInitialized = false; + powerCacheInitialized = false; + } + } +#endif + + + // Temperature Implementation + std::atomic PCB_temperature{0.0f}; + std::atomic SOC_temperature{0.0f}; + + /* + I2cReadRegHandler was taken from Switch-OC-Suite source code made by KazushiMe + Original repository link (Deleted, last checked 15.04.2023): https://github.com/KazushiMe/Switch-OC-Suite + */ + + Result I2cReadRegHandler(u8 reg, I2cDevice dev, u16 *out) { + struct readReg { + u8 send; + u8 sendLength; + u8 sendData; + u8 receive; + u8 receiveLength; + }; + + I2cSession _session; + + Result res = i2cOpenSession(&_session, dev); + if (res) + return res; + + u16 val; + + struct readReg readRegister = { + .send = 0 | (I2cTransactionOption_Start << 6), + .sendLength = sizeof(reg), + .sendData = reg, + .receive = 1 | (I2cTransactionOption_All << 6), + .receiveLength = sizeof(val), + }; + + res = i2csessionExecuteCommandList(&_session, &val, sizeof(val), &readRegister, sizeof(readRegister)); + if (res) { + i2csessionClose(&_session); + return res; + } + + *out = val; + i2csessionClose(&_session); + return 0; + } + + + // Common helper function to read temperature (integer and fractional parts) + Result ReadTemperature(float *temperature, u8 integerReg, u8 fractionalReg, bool integerOnly) { + u16 rawValue; + u8 val; + s32 integerPart = 0; + float fractionalPart = 0.0f; // Change this to a float to retain fractional precision + + // Read the integer part of the temperature + Result res = I2cReadRegHandler(integerReg, I2cDevice_Tmp451, &rawValue); + if (R_FAILED(res)) { + return res; // Error during I2C read + } + + val = (u8)rawValue; // Cast the value to an 8-bit unsigned integer + integerPart = val; // Integer part of temperature in Celsius + + if (integerOnly) + { + *temperature = static_cast(integerPart); // Ensure it's treated as a float + return 0; // Return only integer part if requested + } + + // Read the fractional part of the temperature + res = I2cReadRegHandler(fractionalReg, I2cDevice_Tmp451, &rawValue); + if (R_FAILED(res)) { + return res; // Error during I2C read + } + + val = (u8)rawValue; // Cast the value to an 8-bit unsigned integer + fractionalPart = static_cast(val >> 4) * 0.0625f; // Convert upper 4 bits into fractional part + + // Combine integer and fractional parts + *temperature = static_cast(integerPart) + fractionalPart; + + return 0; + } + + // Function to get the SOC temperature + Result ReadSocTemperature(float *temperature, bool integerOnly) { + return ReadTemperature(temperature, TMP451_SOC_TEMP_REG, TMP451_SOC_TMP_DEC_REG, integerOnly); + } + + // Function to get the PCB temperature + Result ReadPcbTemperature(float *temperature, bool integerOnly) { + return ReadTemperature(temperature, TMP451_PCB_TEMP_REG, TMP451_PCB_TMP_DEC_REG, integerOnly); + } + + + // Time implementation + CONSTEXPR_STRING std::string DEFAULT_DT_FORMAT = "%a %T"; + std::string datetimeFormat = DEFAULT_DT_FORMAT; + + + // Widget settings + bool hideClock, hideBattery, hidePCBTemp, hideSOCTemp, dynamicWidgetColors; + bool hideWidgetBackdrop, centerWidgetAlignment, extendedWidgetBackdrop; + + #if IS_LAUNCHER_DIRECTIVE + void reinitializeWidgetVars() { + // Load INI data once instead of 8 separate file reads + auto ultrahandSection = getKeyValuePairsFromSection(ULTRAHAND_CONFIG_INI_PATH, ULTRAHAND_PROJECT_NAME); + + // Helper lambda to safely get boolean values with proper defaults + auto getBoolValue = [&](const std::string& key, bool defaultValue = false) -> bool { + if (ultrahandSection.count(key) > 0) { + return (ultrahandSection.at(key) != FALSE_STR); + } + return defaultValue; + }; + + // Set all values from the loaded section with correct defaults (matching initialization) + hideClock = getBoolValue("hide_clock", false); // FALSE_STR default + hideBattery = getBoolValue("hide_battery", true); // TRUE_STR default + hideSOCTemp = getBoolValue("hide_soc_temp", true); // TRUE_STR default + hidePCBTemp = getBoolValue("hide_pcb_temp", true); // TRUE_STR default + dynamicWidgetColors = getBoolValue("dynamic_widget_colors", true); // TRUE_STR default + hideWidgetBackdrop = getBoolValue("hide_widget_backdrop", false); // FALSE_STR default + centerWidgetAlignment = getBoolValue("center_widget_alignment", true); // TRUE_STR default + extendedWidgetBackdrop = getBoolValue("extended_widget_backdrop", false); // FALSE_STR default + } + #endif + + bool cleanVersionLabels, hideOverlayVersions, hidePackageVersions, useLibultrahandTitles, useLibultrahandVersions, usePackageTitles, usePackageVersions; + + + + + // Helper function to convert MB to bytes + u64 mbToBytes(u32 mb) { + return static_cast(mb) * 0x100000; + } + + // Helper function to convert bytes to MB + u32 bytesToMB(u64 bytes) { + return static_cast(bytes / 0x100000); + } + + + + // Helper function to get version-appropriate default heap size + static OverlayHeapSize getDefaultHeapSize() { + if (hosversionAtLeast(21, 0, 0)) { + return OverlayHeapSize::Size_4MB; // HOS 21.0.0+ + } else if (hosversionAtLeast(20, 0, 0)) { + return OverlayHeapSize::Size_6MB; // HOS 20.0.0+ + } else { + return OverlayHeapSize::Size_8MB; // Older versions + } + } + + // Implementation + OverlayHeapSize getCurrentHeapSize() { + // Fast path: return cached value if already loaded + if (heapSizeCache.initialized) { + return heapSizeCache.cachedSize; + } + + // Slow path: read from file (only happens once) + FILE* f = fopen(ult::OVL_HEAP_CONFIG_PATH.c_str(), "rb"); + if (!f) { + // No config file - use version-specific default + heapSizeCache.cachedSize = getDefaultHeapSize(); + heapSizeCache.initialized = true; + return heapSizeCache.cachedSize; + } + + u64 size; + if (fread(&size, sizeof(size), 1, f) == 1) { + constexpr u64 twoMB = 0x200000; + // Only accept multiples of 2MB, excluding 2MB itself + if (size != twoMB && size % twoMB == 0) { + heapSizeCache.cachedSize = static_cast(size); + fclose(f); + heapSizeCache.initialized = true; + return heapSizeCache.cachedSize; + } + } + + // Invalid or no data in config - use version-specific default + fclose(f); + heapSizeCache.cachedSize = getDefaultHeapSize(); + heapSizeCache.initialized = true; + return heapSizeCache.cachedSize; + } + + // Update the global default too + HeapSizeCache heapSizeCache; + OverlayHeapSize currentHeapSize = getDefaultHeapSize(); + + bool setOverlayHeapSize(OverlayHeapSize heapSize) { + ult::createDirectory(ult::NX_OVLLOADER_PATH); + + FILE* f = fopen(ult::OVL_HEAP_CONFIG_PATH.c_str(), "wb"); + if (!f) return false; + + const u64 size = static_cast(heapSize); + const bool success = (fwrite(&size, sizeof(size), 1, f) == 1); + fclose(f); + + // Update cache on successful write + if (success) { + heapSizeCache.cachedSize = heapSize; + heapSizeCache.initialized = true; + + // Create reloading flag to indicate this was an intentional restart + ult::createDirectory(ult::FLAGS_PATH); + f = fopen(ult::RELOADING_FLAG_FILEPATH.c_str(), "wb"); + if (f) { + fclose(f); // Empty file, just needs to exist + } + } + + return success; + } + + + // Implementation + bool requestOverlayExit() { + ult::createDirectory(ult::NX_OVLLOADER_PATH); + + FILE* f = fopen(ult::OVL_EXIT_FLAG_PATH.c_str(), "wb"); + if (!f) return false; + + // Write a single byte (flag file just needs to exist) + u8 flag = 1; + bool success = (fwrite(&flag, 1, 1, f) == 1); + fclose(f); + + deleteFileOrDirectory(NOTIFICATIONS_FLAG_FILEPATH); + + return success; + } + + + const std::string loaderInfo = envGetLoaderInfo(); + std::string loaderTitle = extractTitle(loaderInfo); + + bool expandedMemory = false; + bool furtherExpandedMemory = false; + bool limitedMemory = false; + + std::string versionLabel; + + #if IS_LAUNCHER_DIRECTIVE + void reinitializeVersionLabels() { + // Load INI data once instead of 6 separate file reads + auto ultrahandSection = getKeyValuePairsFromSection(ULTRAHAND_CONFIG_INI_PATH, ULTRAHAND_PROJECT_NAME); + + // Helper lambda to safely get boolean values with proper defaults + auto getBoolValue = [&](const std::string& key, bool defaultValue = false) -> bool { + if (ultrahandSection.count(key) > 0) { + return (ultrahandSection.at(key) != FALSE_STR); + } + return defaultValue; + }; + + // Set all values from the loaded section with correct defaults (matching initialization) + cleanVersionLabels = getBoolValue("clean_version_labels", false); // FALSE_STR default + hideOverlayVersions = getBoolValue("hide_overlay_versions", false); // FALSE_STR default + hidePackageVersions = getBoolValue("hide_package_versions", false); // FALSE_STR default + } + #endif + + + // Number of renderer threads to use + const unsigned numThreads = 4;//expandedMemory ? 4 : 0; + std::vector renderThreads(numThreads); + + void InPlotBarrierCompletion::operator()() noexcept { + inPlot.store(false, std::memory_order_release); + } + std::barrier inPlotBarrier(numThreads); + + const s32 bmpChunkSize = ((720 + numThreads - 1) / numThreads); + std::atomic currentRow; +} diff --git a/Source/hoc-clk/overlay/lib/libultrahand/ultrahand.mk b/Source/hoc-clk/overlay/lib/libultrahand/ultrahand.mk new file mode 100644 index 00000000..4baf3c63 --- /dev/null +++ b/Source/hoc-clk/overlay/lib/libultrahand/ultrahand.mk @@ -0,0 +1,31 @@ +#--------------------------------------------------------------------------------- +# Ultrahand Library Configuration +# Auto-detects libultrahand directory location +#--------------------------------------------------------------------------------- + +# Assume TOPDIR is the root project directory where you run make +TOPDIR ?= $(CURDIR) + +# Get the absolute path of this .mk file directory +ULTRA_ABS := $(patsubst %/,%,$(dir $(lastword $(MAKEFILE_LIST)))) + +# Convert absolute path to relative path from TOPDIR +ULTRA_DIR := $(subst $(TOPDIR)/,,$(ULTRA_ABS)) + +# If ULTRA_DIR equals ULTRA_ABS, then ULTRA_ABS is outside TOPDIR, +# fallback to just ULTRA_ABS (rare case) +ifeq ($(ULTRA_DIR),$(ULTRA_ABS)) + ULTRA_DIR := $(ULTRA_ABS) +endif + + +# Now add folder paths relative to TOPDIR (or absolute if fallback) +SOURCES += \ + $(ULTRA_DIR)/common \ + $(ULTRA_DIR)/libultra/source \ + $(ULTRA_DIR)/libtesla/source + +INCLUDES += \ + $(ULTRA_DIR)/common \ + $(ULTRA_DIR)/libultra/include \ + $(ULTRA_DIR)/libtesla/include diff --git a/Source/sys-clk/.gitignore b/Source/sys-clk/.gitignore deleted file mode 100644 index cc543c0e..00000000 --- a/Source/sys-clk/.gitignore +++ /dev/null @@ -1,5 +0,0 @@ -/dist -.DS_Store -Thumbs.db -desktop.ini -.vscode \ No newline at end of file diff --git a/Source/sys-clk/.gitlab-ci.yml b/Source/sys-clk/.gitlab-ci.yml deleted file mode 100644 index 80ebec89..00000000 --- a/Source/sys-clk/.gitlab-ci.yml +++ /dev/null @@ -1,17 +0,0 @@ -image: $CI_SERVER_HOST:4567/libretro/infrastructure/libretro-build-libnx-devkitpro:latest - -variables: - PACKAGE_FOLDER: "sys-clk" - -stages: - - package - -nightly: - stage: package - script: - - bash build.sh $PACKAGE_FOLDER - artifacts: - name: $PACKAGE_FOLDER - expire_in: 24 hours - paths: - - $PACKAGE_FOLDER diff --git a/Source/sys-clk/.gitmodules b/Source/sys-clk/.gitmodules deleted file mode 100644 index 3db71a4d..00000000 --- a/Source/sys-clk/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "overlay/lib/libultrahand"] - path = overlay/lib/libultrahand - url = https://github.com/ppkantorski/libultrahand diff --git a/Source/sys-clk/LICENSE b/Source/sys-clk/LICENSE deleted file mode 100644 index 72648e0e..00000000 --- a/Source/sys-clk/LICENSE +++ /dev/null @@ -1,7 +0,0 @@ --------------------------------------------------------------------------- -"THE BEER-WARE LICENSE" (Revision 42): -, , -wrote this file. As long as you retain this notice you can do whatever you -want with this stuff. If you meet any of us some day, and you think this -stuff is worth it, you can buy us a beer in return. - The sys-clk authors --------------------------------------------------------------------------- diff --git a/Source/sys-clk/README.md b/Source/sys-clk/README.md deleted file mode 100644 index aeb88c8c..00000000 --- a/Source/sys-clk/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# hoc-clk - -Switch sysmodule allowing you to set cpu/gpu/mem clocks according to the running application and docked state. -Modified for Horizon OC - -Support is only provided for FW 16.0.0+. This MAY work on older firmwares but support is NOT guaranteed \ No newline at end of file diff --git a/Source/sys-clk/bitmap.py b/Source/sys-clk/bitmap.py deleted file mode 100644 index bdf81362..00000000 --- a/Source/sys-clk/bitmap.py +++ /dev/null @@ -1,53 +0,0 @@ -from PIL import Image -import argparse -import os - -def image_to_rgba8888_array(image_path, output_path): - # Open and convert to RGBA - img = Image.open(image_path).convert('RGBA') - width, height = img.size - - # Get pixel data - pixels = img.tobytes() - - # Write as C header file - with open(output_path, 'w') as f: - f.write('// This is a automatically generated file, do not edit manually.\n') - f.write(f'// {os.path.basename(image_path)} - {width}x{height}\n') - f.write(f'const unsigned int IMG_WIDTH = {width};\n') - f.write(f'const unsigned int IMG_HEIGHT = {height};\n') - f.write('const unsigned char IMG_DATA[] = {\n ') - - for i, byte in enumerate(pixels): - f.write(f'0x{byte:02X}') - if i < len(pixels) - 1: - f.write(', ') - if (i + 1) % 12 == 0: - f.write('\n ') - - f.write('\n};\n') - - print(f'Converted: {width}x{height} -> {len(pixels)} bytes') - print(f'Output: {output_path}') - -def main(): - parser = argparse.ArgumentParser( - description='PNG to RGB8888 script' - ) - parser.add_argument('input', help='Input image file (e.g. cat.png)') - parser.add_argument( - '-o', '--output', - help='Output header file (default: .h)' - ) - - args = parser.parse_args() - - output_path = args.output - if not output_path: - base, _ = os.path.splitext(args.input) - output_path = base + '.h' - - image_to_rgba8888_array(args.input, output_path) - -if __name__ == '__main__': - main() diff --git a/Source/sys-clk/build.sh b/Source/sys-clk/build.sh deleted file mode 100644 index f8be9fa3..00000000 --- a/Source/sys-clk/build.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/bash -set -e - -ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" -DIST_DIR="$ROOT_DIR/dist" -CORES="$(nproc --all)" - -if [[ -n "$1" ]]; then - DIST_DIR="$1" -fi - -echo "DIST_DIR: $DIST_DIR" -echo "CORES: $CORES" - -echo "*** sysmodule ***" -TITLE_ID="$(grep -oP '"title_id":\s*"0x\K(\w+)' "$ROOT_DIR/sysmodule/perms.json")" - -pushd "$ROOT_DIR/sysmodule" -make -j$CORES -popd > /dev/null - -mkdir -p "$DIST_DIR/atmosphere/contents/$TITLE_ID/flags" -cp -vf "$ROOT_DIR/sysmodule/out/horizon-oc.nsp" "$DIST_DIR/atmosphere/contents/$TITLE_ID/exefs.nsp" ->"$DIST_DIR/atmosphere/contents/$TITLE_ID/flags/boot2.flag" -cp -vf "$ROOT_DIR/sysmodule/toolbox.json" "$DIST_DIR/atmosphere/contents/$TITLE_ID/toolbox.json" - -echo "*** overlay ***" -pushd "$ROOT_DIR/overlay" -make -j$CORES -popd > /dev/null - -mkdir -p "$DIST_DIR/switch/.overlays" -cp -vf "$ROOT_DIR/overlay/out/horizon-oc-overlay.ovl" "$DIST_DIR/switch/.overlays/horizon-oc-overlay.ovl" - -echo "*** assets ***" -mkdir -p "$DIST_DIR/config/horizon-oc" -cp -vf "$ROOT_DIR/config.ini.template" "$DIST_DIR/config/horizon-oc/config.ini.template" -cp -vf "$ROOT_DIR/../../README.md" "$DIST_DIR/README.md" - -echo "*** lang ***" - -cp -r "$ROOT_DIR/overlay/lang/" "$DIST_DIR/config/horizon-oc/" diff --git a/Source/sys-clk/common/include/SaltyNX.h b/Source/sys-clk/common/include/SaltyNX.h deleted file mode 100644 index 06ebc50b..00000000 --- a/Source/sys-clk/common/include/SaltyNX.h +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright (c) MasaGratoR - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once -#include "ipc.h" - -Handle saltysd_orig; - -Result SaltySD_Connect() { - for (int i = 0; i < 200; i++) { - if (!svcConnectToNamedPort(&saltysd_orig, "SaltySD")) - return 0; - svcSleepThread(1000*1000); - } - return 1; -} - -Result SaltySD_Term() -{ - Result ret; - IpcCommand c; - - ipcInitialize(&c); - ipcSendPid(&c); - - struct input - { - u64 magic; - u64 cmd_id; - u64 zero; - u64 reserved[2]; - } *raw; - - raw = (input*)ipcPrepareHeader(&c, sizeof(*raw)); - - raw->magic = SFCI_MAGIC; - raw->cmd_id = 0; - raw->zero = 0; - - ret = ipcDispatch(saltysd_orig); - - if (R_SUCCEEDED(ret)) - { - IpcParsedCommand r; - ipcParse(&r); - - struct output { - u64 magic; - u64 result; - } *resp = (output*)r.Raw; - - ret = resp->result; - } - - // Session terminated works too. - svcCloseHandle(saltysd_orig); - if (ret == 0xf601) return 0; - - return ret; -} - -Result SaltySD_CheckIfSharedMemoryAvailable(ptrdiff_t *offset, u64 size) -{ - Result ret = 0; - - // Send a command - IpcCommand c; - ipcInitialize(&c); - ipcSendPid(&c); - - struct input { - u64 magic; - u64 cmd_id; - u64 size; - u32 reserved[2]; - } *raw; - - raw = (input*)ipcPrepareHeader(&c, sizeof(*raw)); - - raw->magic = SFCI_MAGIC; - raw->cmd_id = 6; - raw->size = size; - - ret = ipcDispatch(saltysd_orig); - - if (R_SUCCEEDED(ret)) { - IpcParsedCommand r; - ipcParse(&r); - - struct output { - u64 magic; - u64 result; - u64 offset; - } *resp = (output*)r.Raw; - - ret = resp->result; - - if (!ret) - { - *offset = resp->offset; - } - } - - return ret; -} - -Result SaltySD_GetSharedMemoryHandle(Handle *retrieve) -{ - Result ret = 0; - - // Send a command - IpcCommand c; - ipcInitialize(&c); - ipcSendPid(&c); - - struct input { - u64 magic; - u64 cmd_id; - u32 reserved[4]; - } *raw; - - raw = (input*)ipcPrepareHeader(&c, sizeof(*raw)); - - raw->magic = SFCI_MAGIC; - raw->cmd_id = 7; - - ret = ipcDispatch(saltysd_orig); - - if (R_SUCCEEDED(ret)) { - IpcParsedCommand r; - ipcParse(&r); - - struct output { - u64 magic; - u64 result; - u64 reserved[2]; - } *resp = (output*)r.Raw; - - ret = resp->result; - - if (!ret) - { - *retrieve = r.Handles[0]; - } - } - - return ret; -} - -Result SaltySD_GetDisplayRefreshRate(uint8_t* refreshRate) -{ - Result ret = 0; - - // Send a command - IpcCommand c; - ipcInitialize(&c); - ipcSendPid(&c); - - struct input { - u64 magic; - u64 cmd_id; - u64 zero; - u64 reserved; - } *raw; - - raw = (input*)ipcPrepareHeader(&c, sizeof(*raw)); - - raw->magic = SFCI_MAGIC; - raw->cmd_id = 10; - raw->zero = 0; - - ret = ipcDispatch(saltysd_orig); - - if (R_SUCCEEDED(ret)) { - IpcParsedCommand r; - ipcParse(&r); - - struct output { - u64 magic; - u64 result; - u64 refreshRate; - u64 reserved; - } *resp = (output*)r.Raw; - - ret = resp->result; - - if (!ret) - { - *refreshRate = (uint8_t)(resp->refreshRate); - } - } - - return ret; -} - -Result SaltySD_SetDisplayRefreshRate(uint8_t refreshRate) -{ - Result ret = 0; - - // Send a command - IpcCommand c; - ipcInitialize(&c); - ipcSendPid(&c); - - struct input { - u64 magic; - u64 cmd_id; - u64 refreshRate; - u64 reserved; - } *raw; - - raw = (input*)ipcPrepareHeader(&c, sizeof(*raw)); - - raw->magic = SFCI_MAGIC; - raw->cmd_id = 11; - raw->refreshRate = refreshRate; - - ret = ipcDispatch(saltysd_orig); - - if (R_SUCCEEDED(ret)) { - IpcParsedCommand r; - ipcParse(&r); - - struct output { - u64 magic; - u64 result; - u64 reserved[2]; - } *resp = (output*)r.Raw; - - ret = resp->result; - } - - return ret; -} \ No newline at end of file diff --git a/Source/sys-clk/common/include/battery.h b/Source/sys-clk/common/include/battery.h deleted file mode 100644 index dff0b08b..00000000 --- a/Source/sys-clk/common/include/battery.h +++ /dev/null @@ -1,252 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once -#include -#include -#include -typedef enum { - BatteryFlag_NoHub = BIT(0), // Hub is disconnected - BatteryFlag_Rail = BIT(8), // At least one Joy-con is charging from rail - BatteryFlag_SPDSRC = BIT(12), // OTG - BatteryFlag_ACC = BIT(16) // Accessory -} BatteryChargeFlags; - -typedef enum { - PDState_NewPDO = 1, // Received new Power Data Object - PDState_NoPD = 2, // No Power Delivery source is detected - PDState_AcceptedRDO = 3 // Received and accepted Request Data Object -} BatteryPDControllerState; - -// Charger type detection -typedef enum { - ChargerType_None = 0, - ChargerType_PD = 1, - ChargerType_TypeC_1500mA = 2, - ChargerType_TypeC_3000mA = 3, - ChargerType_DCP = 4, // Dedicated Charging Port - ChargerType_CDP = 5, // Charging Downstream Port - ChargerType_SDP = 6, // Standard Downstream Port - ChargerType_Apple_500mA = 7, - ChargerType_Apple_1000mA = 8, - ChargerType_Apple_2000mA = 9 -} BatteryChargerType; -typedef enum { - PowerRole_Sink = 1, // Device is receiving power - PowerRole_Source = 2 // Device is providing power -} BatteryPowerRole; - -typedef struct { - int32_t InputCurrentLimit; // Input (Sink) current limit in mA - int32_t VBUSCurrentLimit; // Output (Source/VBUS/OTG) current limit in mA - int32_t ChargeCurrentLimit; // Battery charging current limit in mA - int32_t ChargeVoltageLimit; // Battery charging voltage limit in mV - int32_t unk_x10; // Unknown field (possibly enum) - int32_t unk_x14; // Unknown field (possibly flags) - BatteryPDControllerState PDControllerState; // PD Controller State - int32_t BatteryTemperature; // Battery temperature in milli-Celsius - int32_t RawBatteryCharge; // Battery charge in percentmille - int32_t VoltageAvg; // Average voltage in mV - int32_t BatteryAge; // Battery health (capacity full/design) in pcm - BatteryPowerRole PowerRole; // Current power role - BatteryChargerType ChargerType; // Type of charger connected - int32_t ChargerVoltageLimit; // Charger voltage limit in mV - int32_t ChargerCurrentLimit; // Charger current limit in mA - BatteryChargeFlags Flags; // Various status flags -} BatteryChargeInfo; - -#define IS_BATTERY_CHARGING_ENABLED(info) (((info)->unk_x14 >> 8) & 1) - -Result batteryInfoInitialize(void); - -void batteryInfoExit(void); - -Result batteryInfoGetChargeInfo(BatteryChargeInfo *out); - -Result batteryInfoGetChargePercentage(u32 *out); - -Result batteryInfoIsEnoughPowerSupplied(bool *out); - -Result batteryInfoEnableCharging(void); -Result batteryInfoDisableCharging(void); -Result batteryInfoEnableFastCharging(void); -Result batteryInfoDisableFastCharging(void); - -const char* batteryInfoGetChargerTypeString(BatteryChargerType type); -const char* batteryInfoGetPowerRoleString(BatteryPowerRole role); -const char* batteryInfoGetPDStateString(BatteryPDControllerState state); - -static inline int batteryInfoGetTemperatureMiliCelsius(BatteryChargeInfo *info) { - return info->BatteryTemperature; -} - -static inline float batteryInfoGetChargePercent(BatteryChargeInfo *info) { - return (float)info->RawBatteryCharge / 1000.0f; -} - -static inline float batteryInfoGetBatteryHealthPercent(BatteryChargeInfo *info) { - return (float)info->BatteryAge / 1000.0f; -} - -static inline bool batteryInfoIsCharging(BatteryChargeInfo *info) { - return IS_BATTERY_CHARGING_ENABLED(info); -} - -static const char* s_chargerTypeStrings[] = { - "None", - "Power Delivery", - "USB-C @ 1.5A", - "USB-C @ 3.0A", - "USB-DCP", - "USB-CDP", - "USB-SDP", - "Apple @ 0.5A", - "Apple @ 1.0A", - "Apple @ 2.0A", -}; - -static const char* s_powerRoleStrings[] = { - "Unknown", - "Sink", - "Source", -}; - -static const char* s_pdStateStrings[] = { - "Unknown", - "New PDO Received", - "No PD Source", - "RDO Accepted" -}; - -// Internal PSM service handle -static Service g_psmService = {0}; -static bool g_batteryInfoInitialized = false; - -// Internal PSM command implementations -static Result psmGetBatteryChargeInfoFields(BatteryChargeInfo *out) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatchOut(&g_psmService, 17, *out); -} - -static Result psmEnableBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 2); -} - -static Result psmDisableBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 3); -} - -static Result psmEnableFastBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 10); -} - -static Result psmDisableFastBatteryCharging_internal(void) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return serviceDispatch(&g_psmService, 11); -} - -Result batteryInfoInitialize(void) { - if (g_batteryInfoInitialized) - return 0; - - Result rc = psmInitialize(); - if (R_SUCCEEDED(rc)) { - memcpy(&g_psmService, psmGetServiceSession(), sizeof(Service)); - g_batteryInfoInitialized = true; - } - - return rc; -} - -void batteryInfoExit(void) { - if (g_batteryInfoInitialized) { - psmExit(); - memset(&g_psmService, 0, sizeof(Service)); - g_batteryInfoInitialized = false; - } -} - -Result batteryInfoGetChargeInfo(BatteryChargeInfo *out) { - if (!out) - return MAKERESULT(Module_Libnx, LibnxError_BadInput); - - return psmGetBatteryChargeInfoFields(out); -} - -Result batteryInfoGetChargePercentage(u32 *out) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return psmGetBatteryChargePercentage(out); -} - -Result batteryInfoIsEnoughPowerSupplied(bool *out) { - if (!g_batteryInfoInitialized) - return MAKERESULT(Module_Libnx, LibnxError_NotInitialized); - - return psmIsEnoughPowerSupplied(out); -} - -Result batteryInfoEnableCharging(void) { - return psmEnableBatteryCharging_internal(); -} - -Result batteryInfoDisableCharging(void) { - return psmDisableBatteryCharging_internal(); -} - -Result batteryInfoEnableFastCharging(void) { - return psmEnableFastBatteryCharging_internal(); -} - -Result batteryInfoDisableFastCharging(void) { - return psmDisableFastBatteryCharging_internal(); -} - -const char* batteryInfoGetChargerTypeString(BatteryChargerType type) { - if (type < 0 || type > ChargerType_Apple_2000mA) - return "Unknown"; - - return s_chargerTypeStrings[type]; -} - -const char* batteryInfoGetPowerRoleString(BatteryPowerRole role) { - if (role < PowerRole_Sink || role > PowerRole_Source) - return s_powerRoleStrings[0]; - - return s_powerRoleStrings[role]; -} - -const char* batteryInfoGetPDStateString(BatteryPDControllerState state) { - if (state < PDState_NewPDO || state > PDState_AcceptedRDO) - return s_pdStateStrings[0]; - - return s_pdStateStrings[state]; -} \ No newline at end of file diff --git a/Source/sys-clk/common/include/cpp_util.hpp b/Source/sys-clk/common/include/cpp_util.hpp deleted file mode 100644 index 2e367ede..00000000 --- a/Source/sys-clk/common/include/cpp_util.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) meha3945 (hanai3bi) - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#include - -template -class ScopeGuard { -public: - ScopeGuard(F&& f) - : f(f), engaged(true) {}; - - ~ScopeGuard() { - if (engaged) - f(); - }; - - ScopeGuard(ScopeGuard&& rhs) - : f(std::move(rhs.f)) {}; - - void dismiss() { engaged = false; } - -private: - F f; - bool engaged; -}; - -struct MakeScopeExit { - template - ScopeGuard operator+=(F&& f) { - return ScopeGuard(std::move(f)); - }; -}; - -#define STRING_CAT2(x, y) x##y -#define STRING_CAT(x, y) STRING_CAT2(x, y) -#define SCOPE_GUARD MakeScopeExit() += [&]() __attribute__((always_inline)) -#define SCOPE_EXIT auto STRING_CAT(scope_exit_, __LINE__) = SCOPE_GUARD \ No newline at end of file diff --git a/Source/sys-clk/common/include/crc32.h b/Source/sys-clk/common/include/crc32.h deleted file mode 100644 index 67539c7d..00000000 --- a/Source/sys-clk/common/include/crc32.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once -#include -#include - -uint32_t crc32(const uint8_t *data, size_t length) { - uint32_t crc = 0xFFFFFFFF; - - for (size_t i = 0; i < length; i++) { - crc ^= data[i]; - for (int j = 0; j < 8; j++) { - crc = (crc >> 1) ^ (0xEDB88320 & -(crc & 1)); - } - } - return ~crc; -} - -uint32_t checksum_file(const char *filename) { - FILE *file = fopen(filename, "rb"); - if (!file) { - perror("[crc32] Error opening file"); - return 0; - } - - uint8_t buffer[1024]; - uint32_t crc = 0xFFFFFFFF; - size_t bytes_read; - - while ((bytes_read = fread(buffer, 1, sizeof(buffer), file)) > 0) { - for (size_t i = 0; i < bytes_read; i++) { - crc ^= buffer[i]; - for (int j = 0; j < 8; j++) { - crc = (crc >> 1) ^ (0xEDB88320 & -(crc & 1)); - } - } - } - - fclose(file); - return ~crc; -} \ No newline at end of file diff --git a/Source/sys-clk/common/include/display_refresh_rate.h b/Source/sys-clk/common/include/display_refresh_rate.h deleted file mode 100644 index add49b3a..00000000 --- a/Source/sys-clk/common/include/display_refresh_rate.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) Souldbminer, based on reasearch by MasaGratoR and Cooler3D - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#include -#include -#include - -typedef struct { - uint16_t hFrontPorch; - uint8_t hSyncWidth; - uint8_t hBackPorch; - uint8_t vFrontPorch; - uint8_t vSyncWidth; - uint8_t vBackPorch; - uint8_t VIC; - uint32_t pixelClock_kHz; -} DockedTimings; - -typedef struct { - uint8_t hSyncWidth; - uint16_t hFrontPorch; - uint8_t hBackPorch; - uint8_t vSyncWidth; - uint16_t vFrontPorch; - uint8_t vBackPorch; - uint32_t pixelClock_kHz; -} HandheldTimings; - -typedef struct { - uint8_t min; - uint8_t max; -} MinMaxRefreshRate; - -typedef struct { - uint32_t unk0; - uint32_t hActive; - uint32_t vActive; - uint32_t hSyncWidth; - uint32_t vSyncWidth; - uint32_t hFrontPorch; - uint32_t vFrontPorch; - uint32_t hBackPorch; - uint32_t vBackPorch; - uint32_t pclkKHz; - uint32_t bitsPerPixel; - uint32_t vmode; - uint32_t sync; - uint32_t unk1; - uint32_t reserved; -} NvdcMode2; - -typedef struct { - NvdcMode2 modes[201]; - uint32_t num_modes; -} NvdcModeDB2; - -typedef struct { - unsigned int PLLD_DIVM: 8; - unsigned int reserved_1: 3; - unsigned int PLLD_DIVN: 8; - unsigned int reserved_2: 1; - unsigned int PLLD_DIVP: 3; - unsigned int CSI_CLK_SRC: 1; - unsigned int reserved_3: 1; - unsigned int PLL_D: 1; - unsigned int reserved_4: 1; - unsigned int PLLD_LOCK: 1; - unsigned int reserved_5: 1; - unsigned int PLLD_REF_DIS: 1; - unsigned int PLLD_ENABLE: 1; - unsigned int PLLD_BYPASS: 1; -} PLLD_BASE; - -typedef struct { - signed int PLLD_SDM_DIN: 16; - unsigned int PLLD_EN_SDM: 1; - unsigned int PLLD_LOCK_OVERRIDE: 1; - unsigned int PLLD_EN_LCKDET: 1; - unsigned int PLLD_FREQLOCK: 1; - unsigned int PLLD_IDDQ: 1; - unsigned int PLLD_ENABLE_CLK: 1; - unsigned int PLLD_KVCO: 1; - unsigned int PLLD_KCP: 2; - unsigned int PLLD_PTS: 2; - unsigned int PLLD_LDPULSE_ADJ: 3; - unsigned int reserved: 2; -} PLLD_MISC; - -typedef struct { - uint64_t clkVirtAddr; - uint64_t dsiVirtAddr; - bool isDocked; - bool isLite; - bool isRetroSUPER; - bool isPossiblySpoofedRetro; - bool dontForce60InDocked; - bool matchLowestDocked; - bool displaySync; - bool displaySyncOutOfFocus60; - bool displaySyncDocked; - bool displaySyncDockedOutOfFocus60; -} DisplayRefreshConfig; -bool DisplayRefresh_Initialize(const DisplayRefreshConfig* config); -void DisplayRefresh_SetDockedState(bool isDocked); -bool DisplayRefresh_SetRate(uint32_t new_refreshRate); -bool DisplayRefresh_GetRate(uint32_t* out_refreshRate, bool internal); -uint8_t DisplayRefresh_GetDockedHighestAllowed(void); -void DisplayRefresh_CorrectOledGamma(uint32_t refresh_rate); -void DisplayRefresh_SetAllowedDockedRatesIPC(uint32_t refreshRates, bool is720p); -void DisplayRefresh_Shutdown(void); diff --git a/Source/sys-clk/common/include/fuse.h b/Source/sys-clk/common/include/fuse.h deleted file mode 100644 index 107cebd2..00000000 --- a/Source/sys-clk/common/include/fuse.h +++ /dev/null @@ -1,314 +0,0 @@ -/* - * Copyright (c) 2018 naehrwert - * Copyright (c) 2018 shuffle2 - * Copyright (c) 2018 balika011 - * Copyright (c) 2019-2025 CTCaer - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - */ - -#ifndef _FUSE_H_ -#define _FUSE_H_ - -#ifndef BIT -#define BIT(n) (1U<<(n)) -#endif - -/*! Fuse registers. */ -#define FUSE_CTRL 0x0 -#define FUSE_ADDR 0x4 -#define FUSE_RDATA 0x8 -#define FUSE_WDATA 0xC -#define FUSE_TIME_RD1 0x10 -#define FUSE_TIME_RD2 0x14 -#define FUSE_TIME_PGM1 0x18 -#define FUSE_TIME_PGM2 0x1C -#define FUSE_PRIV2INTFC 0x20 -#define FUSE_PRIV2INTFC_START_DATA BIT(0) -#define FUSE_PRIV2INTFC_SKIP_RECORDS BIT(1) -#define FUSE_FUSEBYPASS 0x24 -#define FUSE_PRIVATEKEYDISABLE 0x28 -#define FUSE_PRIVKEY_DISABLE BIT(0) -#define FUSE_PRIVKEY_TZ_STICKY_BIT BIT(4) -#define FUSE_DISABLEREGPROGRAM 0x2C -#define FUSE_WRITE_ACCESS_SW 0x30 -#define FUSE_PWR_GOOD_SW 0x34 -#define FUSE_PRIV2RESHIFT 0x3C -#define FUSE_FUSETIME_RD0 0x40 -#define FUSE_FUSETIME_RD1 0x44 -#define FUSE_FUSETIME_RD2 0x48 -#define FUSE_FUSETIME_RD3 0x4C -#define FUSE_PRIVATE_KEY0_NONZERO 0x80 -#define FUSE_PRIVATE_KEY1_NONZERO 0x84 -#define FUSE_PRIVATE_KEY2_NONZERO 0x88 -#define FUSE_PRIVATE_KEY3_NONZERO 0x8C -#define FUSE_PRIVATE_KEY4_NONZERO 0x90 - -/*! Fuse Cached registers */ -#define FUSE_RESERVED_ODM8_B01 0x98 // FUSE_READ_TZ Group 0. -#define FUSE_RESERVED_ODM9_B01 0x9C // FUSE_READ_TZ Group 0. -#define FUSE_RESERVED_ODM10_B01 0xA0 // FUSE_READ_TZ Group 0. -#define FUSE_RESERVED_ODM11_B01 0xA4 // FUSE_READ_TZ Group 0. -#define FUSE_RESERVED_ODM12_B01 0xA8 // FUSE_READ_TZ Group 1? Is value -1? -#define FUSE_RESERVED_ODM13_B01 0xAC // FUSE_READ_TZ Group 1? Is value -1? -#define FUSE_RESERVED_ODM14_B01 0xB0 // FUSE_READ_TZ Group 1? Is value -1? -#define FUSE_RESERVED_ODM15_B01 0xB4 // FUSE_READ_TZ Group 1? Is value -1? -#define FUSE_RESERVED_ODM16_B01 0xB8 // FUSE_READ_TZ Group 2? Is value -1? -#define FUSE_RESERVED_ODM17_B01 0xBC // FUSE_READ_TZ Group 2? Is value -1? -#define FUSE_RESERVED_ODM18_B01 0xC0 // FUSE_READ_TZ Group 2. -#define FUSE_RESERVED_ODM19_B01 0xC4 // FUSE_READ_TZ Group 2. -#define FUSE_RESERVED_ODM20_B01 0xC8 // FUSE_READ_TZ Group 3. -#define FUSE_RESERVED_ODM21_B01 0xCC // FUSE_READ_TZ Group 3. -#define FUSE_KEK00_B01 0xD0 -#define FUSE_KEK01_B01 0xD4 -#define FUSE_KEK02_B01 0xD8 -#define FUSE_KEK03_B01 0xDC -#define FUSE_BEK00_B01 0xE0 -#define FUSE_BEK01_B01 0xE4 -#define FUSE_BEK02_B01 0xE8 -#define FUSE_BEK03_B01 0xEC -#define FUSE_OPT_RAM_RTSEL_TSMCSP_PO4SVT_B01 0xF0 -#define FUSE_OPT_RAM_WTSEL_TSMCSP_PO4SVT_B01 0xF4 -#define FUSE_OPT_RAM_RTSEL_TSMCPDP_PO4SVT_B01 0xF8 -#define FUSE_OPT_RAM_MTSEL_TSMCPDP_PO4SVT_B01 0xFC - -#define FUSE_PRODUCTION_MODE 0x100 -#define FUSE_JTAG_SECUREID_VALID 0x104 -#define FUSE_ODM_LOCK 0x108 -#define FUSE_OPT_OPENGL_EN 0x10C -#define FUSE_SKU_INFO 0x110 -#define FUSE_CPU_SPEEDO_0_CALIB 0x114 -#define FUSE_CPU_IDDQ_CALIB 0x118 - -#define FUSE_RESERVED_ODM22_B01 0x11C // FUSE_READ_TZ Group 3. -#define FUSE_RESERVED_ODM23_B01 0x120 // FUSE_READ_TZ Group 3. -#define FUSE_RESERVED_ODM24_B01 0x124 // FUSE_READ_TZ Group 4. - -#define FUSE_OPT_FT_REV 0x128 -#define FUSE_CPU_SPEEDO_1_CALIB 0x12C -#define FUSE_CPU_SPEEDO_2_CALIB 0x130 -#define FUSE_SOC_SPEEDO_0_CALIB 0x134 -#define FUSE_SOC_SPEEDO_1_CALIB 0x138 -#define FUSE_SOC_SPEEDO_2_CALIB 0x13C -#define FUSE_SOC_IDDQ_CALIB 0x140 - -#define FUSE_RESERVED_ODM25_B01 0x144 // FUSE_READ_TZ Group 4. - -#define FUSE_FA 0x148 -#define FUSE_RESERVED_PRODUCTION 0x14C -#define FUSE_HDMI_LANE0_CALIB 0x150 -#define FUSE_HDMI_LANE1_CALIB 0x154 -#define FUSE_HDMI_LANE2_CALIB 0x158 -#define FUSE_HDMI_LANE3_CALIB 0x15C -#define FUSE_ENCRYPTION_RATE 0x160 -#define FUSE_PUBLIC_KEY0 0x164 -#define FUSE_PUBLIC_KEY1 0x168 -#define FUSE_PUBLIC_KEY2 0x16C -#define FUSE_PUBLIC_KEY3 0x170 -#define FUSE_PUBLIC_KEY4 0x174 -#define FUSE_PUBLIC_KEY5 0x178 -#define FUSE_PUBLIC_KEY6 0x17C -#define FUSE_PUBLIC_KEY7 0x180 -#define FUSE_TSENSOR1_CALIB 0x184 // CPU1. -#define FUSE_TSENSOR2_CALIB 0x188 // CPU2. - -#define FUSE_OPT_SECURE_SCC_DIS_B01 0x18C - -#define FUSE_OPT_CP_REV 0x190 // FUSE style revision - ATE. 0x101 0x100 -#define FUSE_OPT_PFG 0x194 -#define FUSE_TSENSOR0_CALIB 0x198 // CPU0. -#define FUSE_FIRST_BOOTROM_PATCH_SIZE 0x19C -#define FUSE_SECURITY_MODE 0x1A0 -#define FUSE_PRIVATE_KEY0 0x1A4 -#define FUSE_PRIVATE_KEY1 0x1A8 -#define FUSE_PRIVATE_KEY2 0x1AC -#define FUSE_PRIVATE_KEY3 0x1B0 -#define FUSE_PRIVATE_KEY4 0x1B4 -#define FUSE_ARM_JTAG_DIS 0x1B8 -#define FUSE_BOOT_DEVICE_INFO 0x1BC -#define FUSE_RESERVED_SW 0x1C0 -#define FUSE_OPT_VP9_DISABLE 0x1C4 - -#define FUSE_RESERVED_ODM0 0x1C8 -#define FUSE_RESERVED_ODM1 0x1CC -#define FUSE_RESERVED_ODM2 0x1D0 -#define FUSE_RESERVED_ODM3 0x1D4 -#define FUSE_RESERVED_ODM4 0x1D8 -#define FUSE_RESERVED_ODM5 0x1DC -#define FUSE_RESERVED_ODM6 0x1E0 -#define FUSE_RESERVED_ODM7 0x1E4 - -#define FUSE_OBS_DIS 0x1E8 - -#define FUSE_OPT_NVJTAG_PROTECTION_ENABLE_B01 0x1EC - -#define FUSE_USB_CALIB 0x1F0 -#define FUSE_SKU_DIRECT_CONFIG 0x1F4 -#define FUSE_KFUSE_PRIVKEY_CTRL 0x1F8 -#define FUSE_PACKAGE_INFO 0x1FC // 1: MID, 2: DSC. -#define FUSE_OPT_VENDOR_CODE 0x200 -#define FUSE_OPT_FAB_CODE 0x204 -#define FUSE_OPT_LOT_CODE_0 0x208 -#define FUSE_OPT_LOT_CODE_1 0x20C -#define FUSE_OPT_WAFER_ID 0x210 -#define FUSE_OPT_X_COORDINATE 0x214 -#define FUSE_OPT_Y_COORDINATE 0x218 -#define FUSE_OPT_SEC_DEBUG_EN 0x21C -#define FUSE_OPT_OPS_RESERVED 0x220 -#define FUSE_SATA_CALIB 0x224 - -#define FUSE_SPARE_REGISTER_ODM_B01 0x224 - -#define FUSE_GPU_IDDQ_CALIB 0x228 -#define FUSE_TSENSOR3_CALIB 0x22C // CPU3. -#define FUSE_CLOCK_BONDOUT0 0x230 -#define FUSE_CLOCK_BONDOUT1 0x234 - -#define FUSE_RESERVED_ODM26_B01 0x238 // FUSE_READ_TZ Group 4. -#define FUSE_RESERVED_ODM27_B01 0x23C // FUSE_READ_TZ Group 4. -#define FUSE_RESERVED_ODM28_B01 0x240 // MAX77812 phase configuration. FUSE_READ_TZ Group 5. - -#define FUSE_OPT_SAMPLE_TYPE 0x244 -#define FUSE_OPT_SUBREVISION 0x248 // "", "p", "q", "r". e.g: A01p. -#define FUSE_OPT_SW_RESERVED_0 0x24C -#define FUSE_OPT_SW_RESERVED_1 0x250 -#define FUSE_TSENSOR4_CALIB 0x254 // GPU. -#define FUSE_TSENSOR5_CALIB 0x258 // MEM0. -#define FUSE_TSENSOR6_CALIB 0x25C // MEM1. -#define FUSE_TSENSOR7_CALIB 0x260 // PLLX. -#define FUSE_OPT_PRIV_SEC_DIS 0x264 -#define FUSE_PKC_DISABLE 0x268 - -#define FUSE_BOOT_SECURITY_INFO_B01 0x268 -#define FUSE_OPT_RAM_RTSEL_TSMCSP_PO4HVT_B01 0x26C -#define FUSE_OPT_RAM_WTSEL_TSMCSP_PO4HVT_B01 0x270 -#define FUSE_OPT_RAM_RTSEL_TSMCPDP_PO4HVT_B01 0x274 -#define FUSE_OPT_RAM_MTSEL_TSMCPDP_PO4HVT_B01 0x278 - -#define FUSE_FUSE2TSEC_DEBUG_DISABLE 0x27C -#define FUSE_TSENSOR_COMMON 0x280 -#define FUSE_OPT_CP_BIN 0x284 -#define FUSE_OPT_GPU_DISABLE 0x288 -#define FUSE_OPT_FT_BIN 0x28C -#define FUSE_OPT_DONE_MAP 0x290 - -#define FUSE_RESERVED_ODM29_B01 0x294 // FUSE_READ_TZ Group 5? Is value -1? - -#define FUSE_APB2JTAG_DISABLE 0x298 -#define FUSE_ODM_INFO 0x29C // Debug features disable. -#define FUSE_ARM_CRYPT_DE_FEATURE 0x2A8 - -#define FUSE_OPT_RAM_WTSEL_TSMCPDP_PO4SVT_B01 0x2B0 -#define FUSE_OPT_RAM_RCT_TSMCDP_PO4SVT_B01 0x2B4 -#define FUSE_OPT_RAM_WCT_TSMCDP_PO4SVT_B01 0x2B8 -#define FUSE_OPT_RAM_KP_TSMCDP_PO4SVT_B01 0x2BC - -#define FUSE_WOA_SKU_FLAG 0x2C0 -#define FUSE_ECO_RESERVE_1 0x2C4 -#define FUSE_GCPLEX_CONFIG_FUSE 0x2C8 -#define FUSE_GPU_VPR_AUTO_FETCH_DIS BIT(0) -#define FUSE_GPU_VPR_ENABLED BIT(1) -#define FUSE_GPU_WPR_ENABLED BIT(2) -#define FUSE_PRODUCTION_MONTH 0x2CC -#define FUSE_RAM_REPAIR_INDICATOR 0x2D0 -#define FUSE_TSENSOR9_CALIB 0x2D4 // AOTAG. -#define FUSE_VMIN_CALIBRATION 0x2DC -#define FUSE_AGING_SENSOR_CALIBRATION 0x2E0 -#define FUSE_DEBUG_AUTHENTICATION 0x2E4 -#define FUSE_SECURE_PROVISION_INDEX 0x2E8 -#define FUSE_SECURE_PROVISION_INFO 0x2EC -#define FUSE_OPT_GPU_DISABLE_CP1 0x2F0 -#define FUSE_SPARE_ENDIS 0x2F4 -#define FUSE_ECO_RESERVE_0 0x2F8 // AID. -#define FUSE_RESERVED_CALIB0 0x304 // GPCPLL ADC Calibration. -#define FUSE_RESERVED_CALIB1 0x308 -#define FUSE_OPT_GPU_TPC0_DISABLE 0x30C -#define FUSE_OPT_GPU_TPC0_DISABLE_CP1 0x310 -#define FUSE_OPT_CPU_DISABLE 0x314 -#define FUSE_OPT_CPU_DISABLE_CP1 0x318 -#define FUSE_TSENSOR10_CALIB 0x31C -#define FUSE_TSENSOR10_CALIB_AUX 0x320 -#define FUSE_OPT_RAM_SVOP_DP 0x324 -#define FUSE_OPT_RAM_SVOP_PDP 0x328 -#define FUSE_OPT_RAM_SVOP_REG 0x32C -#define FUSE_OPT_RAM_SVOP_SP 0x330 -#define FUSE_OPT_RAM_SVOP_SMPDP 0x334 - -#define FUSE_OPT_RAM_WTSEL_TSMCPDP_PO4HVT_B01 0x324 -#define FUSE_OPT_RAM_RCT_TSMCDP_PO4HVT_B01 0x328 -#define FUSE_OPT_RAM_WCT_TSMCDP_PO4HVT_B01 0x32c -#define FUSE_OPT_RAM_KP_TSMCDP_PO4HVT_B01 0x330 -#define FUSE_OPT_RAM_SVOP_SP_B01 0x334 - -#define FUSE_OPT_GPU_TPC0_DISABLE_CP2 0x338 -#define FUSE_OPT_GPU_TPC1_DISABLE 0x33C -#define FUSE_OPT_GPU_TPC1_DISABLE_CP1 0x340 -#define FUSE_OPT_GPU_TPC1_DISABLE_CP2 0x344 -#define FUSE_OPT_CPU_DISABLE_CP2 0x348 -#define FUSE_OPT_GPU_DISABLE_CP2 0x34C -#define FUSE_USB_CALIB_EXT 0x350 -#define FUSE_RESERVED_FIELD 0x354 // RMA. -#define FUSE_SPARE_REALIGNMENT_REG 0x37C -#define FUSE_SPARE_BIT_0 0x380 -//... -#define FUSE_SPARE_BIT_31 0x3FC - -/*! Fuse commands. */ -#define FUSE_IDLE 0x0 -#define FUSE_READ 0x1 -#define FUSE_WRITE 0x2 -#define FUSE_SENSE 0x3 -#define FUSE_CMD_MASK 0x3 - -/*! Fuse status. */ -#define FUSE_STATUS_RESET 0 -#define FUSE_STATUS_POST_RESET 1 -#define FUSE_STATUS_LOAD_ROW0 2 -#define FUSE_STATUS_LOAD_ROW1 3 -#define FUSE_STATUS_IDLE 4 -#define FUSE_STATUS_READ_SETUP 5 -#define FUSE_STATUS_READ_STROBE 6 -#define FUSE_STATUS_SAMPLE_FUSES 7 -#define FUSE_STATUS_READ_HOLD 8 -#define FUSE_STATUS_FUSE_SRC_SETUP 9 -#define FUSE_STATUS_WRITE_SETUP 10 -#define FUSE_STATUS_WRITE_ADDR_SETUP 11 -#define FUSE_STATUS_WRITE_PROGRAM 12 -#define FUSE_STATUS_WRITE_ADDR_HOLD 13 -#define FUSE_STATUS_FUSE_SRC_HOLD 14 -#define FUSE_STATUS_LOAD_RIR 15 -#define FUSE_STATUS_READ_BEFORE_WRITE_SETUP 16 -#define FUSE_STATUS_READ_DEASSERT_PD 17 - -/*! Fuse cache registers. */ -#define FUSE_RESERVED_ODMX(x) (0x1C8 + 4 * (x)) - -#define FUSE_ARRAY_WORDS_NUM 192 -#define FUSE_ARRAY_WORDS_NUM_B01 256 - -enum -{ - FUSE_NX_HW_TYPE_ICOSA, - FUSE_NX_HW_TYPE_IOWA, - FUSE_NX_HW_TYPE_HOAG, - FUSE_NX_HW_TYPE_AULA -}; - -enum -{ - FUSE_NX_HW_STATE_PROD, - FUSE_NX_HW_STATE_DEV -}; - -#endif diff --git a/Source/sys-clk/common/include/i2c.h b/Source/sys-clk/common/include/i2c.h deleted file mode 100644 index feb7c9fb..00000000 --- a/Source/sys-clk/common/include/i2c.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) 2023 KazushiMe - * Licensed under the GPLv2 - */ - -#pragma once - -#include - -// To use i2c service, sm and i2c should be intialized via smInitialize() and i2cInitialize(). - -Result I2cSet_U8(I2cDevice dev, u8 reg, u8 val); - -Result I2cRead_OutU8(I2cDevice dev, u8 reg, u8 *out); -Result I2cRead_OutU16(I2cDevice dev, u8 reg, u16 *out); - -// Max17050 fuel gauge -float I2c_Max17050_GetBatteryCurrent(); - -const u8 MAX17050_CURRENT_REG = 0x0A; - -// Buck Converter -typedef enum I2c_BuckConverter_Reg { - I2c_Max77620_SD1VOLT_REG = 0x17, // Used for Erista DDR VDDQ+VDD2 / Mariko VDD2 - I2c_Max77621_VOLT_REG = 0x00, - I2c_Max77812_CPUVOLT_REG = 0x26, - I2c_Max77812_GPUVOLT_REG = 0x23, - I2c_Max77812_MEMVOLT_REG = 0x25, // Master 3 (GPU 1 + 2, DRAM 3, CPU 4), used for Mariko VDDQ -} I2c_BuckConverter_Reg; - -typedef struct I2c_BuckConverter_Domain { - I2cDevice device; - I2c_BuckConverter_Reg reg; - u8 volt_mask; - u32 uv_step; - u32 uv_min; - u32 uv_max; - u8 por_val; -} I2c_BuckConverter_Domain; - -const I2c_BuckConverter_Domain I2c_Erista_CPU = { I2cDevice_Max77621Cpu, I2c_Max77621_VOLT_REG, 0x7F, 6250, 606250, 1400000, }; -const I2c_BuckConverter_Domain I2c_Erista_GPU = { I2cDevice_Max77621Gpu, I2c_Max77621_VOLT_REG, 0x7F, 6250, 606250, 1400000, }; -const I2c_BuckConverter_Domain I2c_Erista_DRAM = { I2cDevice_Max77620Pmic, I2c_Max77620_SD1VOLT_REG, 0x7F, 12500, 600000, 1250000, }; -const I2c_BuckConverter_Domain I2c_Mariko_CPU = { I2cDevice_Max77812_2, I2c_Max77812_CPUVOLT_REG, 0xFF, 5000, 250000, 1525000, 0x78 }; -const I2c_BuckConverter_Domain I2c_Mariko_GPU = { I2cDevice_Max77812_2, I2c_Max77812_GPUVOLT_REG, 0xFF, 5000, 250000, 1525000, 0x78 }; -const I2c_BuckConverter_Domain I2c_Mariko_DRAM_VDDQ = { I2cDevice_Max77812_2, I2c_Max77812_MEMVOLT_REG, 0xFF, 5000, 250000, 700000, 0x78 }; -const I2c_BuckConverter_Domain I2c_Mariko_DRAM_VDD2 = { I2cDevice_Max77620Pmic, I2c_Max77620_SD1VOLT_REG, 0x7F, 12500, 600000, 1250000, }; - -u32 I2c_BuckConverter_GetMvOut(const I2c_BuckConverter_Domain* domain); -Result I2c_BuckConverter_SetMvOut(const I2c_BuckConverter_Domain* domain, u32 mvolt); - -// Bq24193 Battery management -u32 I2c_Bq24193_Convert_Raw_mA(u8 raw); -u8 I2c_Bq24193_Convert_mA_Raw(u32 ma); - -Result I2c_Bq24193_GetFastChargeCurrentLimit(u32 *ma); -Result I2c_Bq24193_SetFastChargeCurrentLimit(u32 ma); - -const u32 MA_RANGE_MIN = 512; -const u32 MA_RANGE_MAX = 4544; - -const u8 BQ24193_CHARGE_CURRENT_CONTROL_REG = 0x2; \ No newline at end of file diff --git a/Source/sys-clk/common/include/ipc.h b/Source/sys-clk/common/include/ipc.h deleted file mode 100644 index 3015af32..00000000 --- a/Source/sys-clk/common/include/ipc.h +++ /dev/null @@ -1,756 +0,0 @@ -/** - * @file ipc.h - * @brief Inter-process communication handling - * @author plutoo - * @copyright libnx Authors (ISC License) - */ -#pragma once -#include - -/// IPC input header magic -#define SFCI_MAGIC 0x49434653 -/// IPC output header magic -#define SFCO_MAGIC 0x4f434653 - -/// IPC invalid object ID -#define IPC_INVALID_OBJECT_ID UINT32_MAX - -///@name IPC request building -///@{ - -/// IPC command (request) structure. -#define IPC_MAX_BUFFERS 8 -#define IPC_MAX_OBJECTS 8 - -typedef enum { - BufferType_Normal=0, ///< Regular buffer. - BufferType_Type1=1, ///< Allows ProcessMemory and shared TransferMemory. - BufferType_Invalid=2, - BufferType_Type3=3 ///< Same as Type1 except remote process is not allowed to use device-mapping. -} BufferType; - -typedef enum { - BufferDirection_Send=0, - BufferDirection_Recv=1, - BufferDirection_Exch=2, -} BufferDirection; - -typedef enum { - IpcCommandType_Invalid = 0, - IpcCommandType_LegacyRequest = 1, - IpcCommandType_Close = 2, - IpcCommandType_LegacyControl = 3, - IpcCommandType_Request = 4, - IpcCommandType_Control = 5, - IpcCommandType_RequestWithContext = 6, - IpcCommandType_ControlWithContext = 7, -} IpcCommandType; - -typedef enum { - DomainMessageType_Invalid = 0, - DomainMessageType_SendMessage = 1, - DomainMessageType_Close = 2, -} DomainMessageType; - -/// IPC domain message header. -typedef struct { - u8 Type; - u8 NumObjectIds; - u16 Length; - u32 ThisObjectId; - u32 Pad[2]; -} DomainMessageHeader; - -/// IPC domain response header. -typedef struct { - u32 NumObjectIds; - u32 Pad[3]; -} DomainResponseHeader; - - -typedef struct { - size_t NumSend; // A - size_t NumRecv; // B - size_t NumExch; // W - const void* Buffers[IPC_MAX_BUFFERS]; - size_t BufferSizes[IPC_MAX_BUFFERS]; - BufferType BufferTypes[IPC_MAX_BUFFERS]; - - size_t NumStaticIn; // X - size_t NumStaticOut; // C - const void* Statics[IPC_MAX_BUFFERS]; - size_t StaticSizes[IPC_MAX_BUFFERS]; - u8 StaticIndices[IPC_MAX_BUFFERS]; - - bool SendPid; - size_t NumHandlesCopy; - size_t NumHandlesMove; - Handle Handles[IPC_MAX_OBJECTS]; - - size_t NumObjectIds; - u32 ObjectIds[IPC_MAX_OBJECTS]; -} IpcCommand; - -/** - * @brief Initializes an IPC command structure. - * @param cmd IPC command structure. - */ -static inline void ipcInitialize(IpcCommand* cmd) { - *cmd = (IpcCommand){}; -} - -/// IPC buffer descriptor. -typedef struct { - u32 Size; ///< Size of the buffer. - u32 Addr; ///< Lower 32-bits of the address of the buffer - u32 Packed; ///< Packed data (including higher bits of the address) -} IpcBufferDescriptor; - -/// IPC static send-buffer descriptor. -typedef struct { - u32 Packed; ///< Packed data (including higher bits of the address) - u32 Addr; ///< Lower 32-bits of the address -} IpcStaticSendDescriptor; - -/// IPC static receive-buffer descriptor. -typedef struct { - u32 Addr; ///< Lower 32-bits of the address of the buffer - u32 Packed; ///< Packed data (including higher bits of the address) -} IpcStaticRecvDescriptor; - -/** - * @brief Adds a buffer to an IPC command structure. - * @param cmd IPC command structure. - * @param buffer Address of the buffer. - * @param size Size of the buffer. - * @param type Buffer type. - */ -static inline void ipcAddSendBuffer(IpcCommand* cmd, const void* buffer, size_t size, BufferType type) { - size_t off = cmd->NumSend; - cmd->Buffers[off] = buffer; - cmd->BufferSizes[off] = size; - cmd->BufferTypes[off] = type; - cmd->NumSend++; -} - -/** - * @brief Adds a receive-buffer to an IPC command structure. - * @param cmd IPC command structure. - * @param buffer Address of the buffer. - * @param size Size of the buffer. - * @param type Buffer type. - */ -static inline void ipcAddRecvBuffer(IpcCommand* cmd, void* buffer, size_t size, BufferType type) { - size_t off = cmd->NumSend + cmd->NumRecv; - cmd->Buffers[off] = buffer; - cmd->BufferSizes[off] = size; - cmd->BufferTypes[off] = type; - cmd->NumRecv++; -} - -/** - * @brief Adds an exchange-buffer to an IPC command structure. - * @param cmd IPC command structure. - * @param buffer Address of the buffer. - * @param size Size of the buffer. - * @param type Buffer type. - */ -static inline void ipcAddExchBuffer(IpcCommand* cmd, void* buffer, size_t size, BufferType type) { - size_t off = cmd->NumSend + cmd->NumRecv + cmd->NumExch; - cmd->Buffers[off] = buffer; - cmd->BufferSizes[off] = size; - cmd->BufferTypes[off] = type; - cmd->NumExch++; -} - -/** - * @brief Adds a static-buffer to an IPC command structure. - * @param cmd IPC command structure. - * @param buffer Address of the buffer. - * @param size Size of the buffer. - * @param index Index of buffer. - */ -static inline void ipcAddSendStatic(IpcCommand* cmd, const void* buffer, size_t size, u8 index) { - size_t off = cmd->NumStaticIn; - cmd->Statics[off] = buffer; - cmd->StaticSizes[off] = size; - cmd->StaticIndices[off] = index; - cmd->NumStaticIn++; -} - -/** - * @brief Adds a static-receive-buffer to an IPC command structure. - * @param cmd IPC command structure. - * @param buffer Address of the buffer. - * @param size Size of the buffer. - * @param index Index of buffer. - */ -static inline void ipcAddRecvStatic(IpcCommand* cmd, void* buffer, size_t size, u8 index) { - size_t off = cmd->NumStaticIn + cmd->NumStaticOut; - cmd->Statics[off] = buffer; - cmd->StaticSizes[off] = size; - cmd->StaticIndices[off] = index; - cmd->NumStaticOut++; -} - -/** - * @brief Adds a smart-buffer (buffer + static-buffer pair) to an IPC command structure. - * @param cmd IPC command structure. - * @param pointer_buffer_size Pointer buffer size. - * @param buffer Address of the buffer. - * @param size Size of the buffer. - * @param index Index of buffer. - */ -static inline void ipcAddSendSmart(IpcCommand* cmd, size_t pointer_buffer_size, const void* buffer, size_t size, u8 index) { - if (pointer_buffer_size != 0 && size <= pointer_buffer_size) { - ipcAddSendBuffer(cmd, NULL, 0, BufferType_Normal); - ipcAddSendStatic(cmd, buffer, size, index); - } else { - ipcAddSendBuffer(cmd, buffer, size, BufferType_Normal); - ipcAddSendStatic(cmd, NULL, 0, index); - } -} - -/** - * @brief Adds a smart-receive-buffer (buffer + static-receive-buffer pair) to an IPC command structure. - * @param cmd IPC command structure. - * @param pointer_buffer_size Pointer buffer size. - * @param buffer Address of the buffer. - * @param size Size of the buffer. - * @param index Index of buffer. - */ -static inline void ipcAddRecvSmart(IpcCommand* cmd, size_t pointer_buffer_size, void* buffer, size_t size, u8 index) { - if (pointer_buffer_size != 0 && size <= pointer_buffer_size) { - ipcAddRecvBuffer(cmd, NULL, 0, BufferType_Normal); - ipcAddRecvStatic(cmd, buffer, size, index); - } else { - ipcAddRecvBuffer(cmd, buffer, size, BufferType_Normal); - ipcAddRecvStatic(cmd, NULL, 0, index); - } -} - -/** - * @brief Tags an IPC command structure to send the PID. - * @param cmd IPC command structure. - */ -static inline void ipcSendPid(IpcCommand* cmd) { - cmd->SendPid = true; -} - -/** - * @brief Adds a copy-handle to be sent through an IPC command structure. - * @param cmd IPC command structure. - * @param h Handle to send. - * @remark The receiving process gets a copy of the handle. - */ -static inline void ipcSendHandleCopy(IpcCommand* cmd, Handle h) { - cmd->Handles[cmd->NumHandlesCopy++] = h; -} - -/** - * @brief Adds a move-handle to be sent through an IPC command structure. - * @param cmd IPC command structure. - * @param h Handle to send. - * @remark The sending process loses ownership of the handle, which is transferred to the receiving process. - */ -static inline void ipcSendHandleMove(IpcCommand* cmd, Handle h) { - cmd->Handles[cmd->NumHandlesCopy + cmd->NumHandlesMove++] = h; -} - -/** - * @brief Prepares the header of an IPC command structure. - * @param cmd IPC command structure. - * @param sizeof_raw Size in bytes of the raw data structure to embed inside the IPC request - * @return Pointer to the raw embedded data structure in the request, ready to be filled out. - */ -static inline void* ipcPrepareHeader(IpcCommand* cmd, size_t sizeof_raw) { - u32* buf = (u32*)armGetTls(); - size_t i; - *buf++ = IpcCommandType_Request | (cmd->NumStaticIn << 16) | (cmd->NumSend << 20) | (cmd->NumRecv << 24) | (cmd->NumExch << 28); - - u32* fill_in_size_later = buf; - - if (cmd->NumStaticOut > 0) { - *buf = (cmd->NumStaticOut + 2) << 10; - } - else { - *buf = 0; - } - - if (cmd->SendPid || cmd->NumHandlesCopy > 0 || cmd->NumHandlesMove > 0) { - *buf++ |= 0x80000000; - *buf++ = (!!cmd->SendPid) | (cmd->NumHandlesCopy << 1) | (cmd->NumHandlesMove << 5); - - if (cmd->SendPid) - buf += 2; - - for (i=0; i<(cmd->NumHandlesCopy + cmd->NumHandlesMove); i++) - *buf++ = cmd->Handles[i]; - } - else { - buf++; - } - - for (i=0; iNumStaticIn; i++, buf+=2) { - IpcStaticSendDescriptor* desc = (IpcStaticSendDescriptor*) buf; - - uintptr_t ptr = (uintptr_t) cmd->Statics[i]; - desc->Addr = ptr; - desc->Packed = cmd->StaticIndices[i] | (cmd->StaticSizes[i] << 16) | - (((ptr >> 32) & 15) << 12) | (((ptr >> 36) & 15) << 6); - } - - for (i=0; i<(cmd->NumSend + cmd->NumRecv + cmd->NumExch); i++, buf+=3) { - IpcBufferDescriptor* desc = (IpcBufferDescriptor*) buf; - desc->Size = cmd->BufferSizes[i]; - - uintptr_t ptr = (uintptr_t) cmd->Buffers[i]; - desc->Addr = ptr; - desc->Packed = cmd->BufferTypes[i] | - (((ptr >> 32) & 15) << 28) | ((ptr >> 36) << 2); - } - - u32 padding = ((16 - (((uintptr_t) buf) & 15)) & 15) / 4; - u32* raw = (u32*) (buf + padding); - - size_t raw_size = (sizeof_raw/4) + 4; - buf += raw_size; - - u16* buf_u16 = (u16*) buf; - - for (i=0; iNumStaticOut; i++) { - size_t off = cmd->NumStaticIn + i; - size_t sz = (uintptr_t) cmd->StaticSizes[off]; - - buf_u16[i] = (sz > 0xFFFF) ? 0 : sz; - } - - size_t u16s_size = ((2*cmd->NumStaticOut) + 3)/4; - buf += u16s_size; - raw_size += u16s_size; - - *fill_in_size_later |= raw_size; - - for (i=0; iNumStaticOut; i++, buf+=2) { - IpcStaticRecvDescriptor* desc = (IpcStaticRecvDescriptor*) buf; - size_t off = cmd->NumStaticIn + i; - - uintptr_t ptr = (uintptr_t) cmd->Statics[off]; - desc->Addr = ptr; - desc->Packed = (ptr >> 32) | (cmd->StaticSizes[off] << 16); - } - - return (void*) raw; -} - -/** - * @brief Dispatches an IPC request. - * @param session IPC session handle. - * @return Result code. - */ -static inline Result ipcDispatch(Handle session) { - return svcSendSyncRequest(session); -} - -///@} - -///@name IPC response parsing -///@{ - -/// IPC parsed command (response) structure. -typedef struct { - IpcCommandType CommandType; ///< Type of the command - - bool HasPid; ///< true if the 'Pid' field is filled out. - u64 Pid; ///< PID included in the response (only if HasPid is true) - - size_t NumHandles; ///< Number of handles copied. - Handle Handles[IPC_MAX_OBJECTS]; ///< Handles. - bool WasHandleCopied[IPC_MAX_OBJECTS]; ///< true if the handle was moved, false if it was copied. - - bool IsDomainRequest; ///< true if the the message is a Domain message. - DomainMessageType InMessageType; ///< Type of the domain message. - u32 InMessageLength; ///< Size of rawdata (for domain messages). - u32 InThisObjectId; ///< Object ID to call the command on (for domain messages). - size_t InNumObjectIds; ///< Number of object IDs (for domain messages). - u32 InObjectIds[IPC_MAX_OBJECTS]; ///< Object IDs (for domain messages). - - bool IsDomainResponse; ///< true if the the message is a Domain response. - size_t OutNumObjectIds; ///< Number of object IDs (for domain responses). - u32 OutObjectIds[IPC_MAX_OBJECTS]; ///< Object IDs (for domain responses). - - size_t NumBuffers; ///< Number of buffers in the response. - void* Buffers[IPC_MAX_BUFFERS]; ///< Pointers to the buffers. - size_t BufferSizes[IPC_MAX_BUFFERS]; ///< Sizes of the buffers. - BufferType BufferTypes[IPC_MAX_BUFFERS]; ///< Types of the buffers. - BufferDirection BufferDirections[IPC_MAX_BUFFERS]; ///< Direction of each buffer. - - size_t NumStatics; ///< Number of statics in the response. - void* Statics[IPC_MAX_BUFFERS]; ///< Pointers to the statics. - size_t StaticSizes[IPC_MAX_BUFFERS]; ///< Sizes of the statics. - u8 StaticIndices[IPC_MAX_BUFFERS]; ///< Indices of the statics. - - size_t NumStaticsOut; ///< Number of output statics available in the response. - - void* Raw; ///< Pointer to the raw embedded data structure in the response. - void* RawWithoutPadding; ///< Pointer to the raw embedded data structure, without padding. - size_t RawSize; ///< Size of the raw embedded data. -} IpcParsedCommand; - -/** - * @brief Parse an IPC command response into an IPC parsed command structure. - * @param r IPC parsed command structure to fill in. - * @return Result code. - */ -static inline Result ipcParse(IpcParsedCommand* r) { - u32* buf = (u32*)armGetTls(); - u32 ctrl0 = *buf++; - u32 ctrl1 = *buf++; - size_t i; - - r->IsDomainRequest = false; - r->IsDomainResponse = false; - - r->CommandType = (IpcCommandType) (ctrl0 & 0xffff); - r->HasPid = false; - r->RawSize = (ctrl1 & 0x1ff) * 4; - r->NumHandles = 0; - - r->NumStaticsOut = (ctrl1 >> 10) & 15; - if (r->NumStaticsOut >> 1) r->NumStaticsOut--; // Value 2 -> Single descriptor - if (r->NumStaticsOut >> 1) r->NumStaticsOut--; // Value 3+ -> (Value - 2) descriptors - - if (ctrl1 & 0x80000000) { - u32 ctrl2 = *buf++; - - if (ctrl2 & 1) { - r->HasPid = true; - r->Pid = *buf++; - r->Pid |= ((u64)(*buf++)) << 32; - } - - size_t num_handles_copy = ((ctrl2 >> 1) & 15); - size_t num_handles_move = ((ctrl2 >> 5) & 15); - - size_t num_handles = num_handles_copy + num_handles_move; - u32* buf_after_handles = buf + num_handles; - - if (num_handles > IPC_MAX_OBJECTS) - num_handles = IPC_MAX_OBJECTS; - - for (i=0; iHandles[i] = *(buf+i); - r->WasHandleCopied[i] = (i < num_handles_copy); - } - - r->NumHandles = num_handles; - buf = buf_after_handles; - } - - size_t num_statics = (ctrl0 >> 16) & 15; - u32* buf_after_statics = buf + num_statics*2; - - if (num_statics > IPC_MAX_BUFFERS) - num_statics = IPC_MAX_BUFFERS; - - for (i=0; iPacked; - - r->Statics[i] = (void*) (desc->Addr | (((packed >> 12) & 15) << 32) | (((packed >> 6) & 15) << 36)); - r->StaticSizes[i] = packed >> 16; - r->StaticIndices[i] = packed & 63; - } - - r->NumStatics = num_statics; - buf = buf_after_statics; - - size_t num_bufs_send = (ctrl0 >> 20) & 15; - size_t num_bufs_recv = (ctrl0 >> 24) & 15; - size_t num_bufs_exch = (ctrl0 >> 28) & 15; - - size_t num_bufs = num_bufs_send + num_bufs_recv + num_bufs_exch; - r->Raw = (void*)(((uintptr_t)(buf + num_bufs*3) + 15) &~ 15); - r->RawWithoutPadding = (void*)((uintptr_t)(buf + num_bufs*3)); - - if (num_bufs > IPC_MAX_BUFFERS) - num_bufs = IPC_MAX_BUFFERS; - - for (i=0; iPacked; - - r->Buffers[i] = (void*) (desc->Addr | ((packed >> 28) << 32) | (((packed >> 2) & 15) << 36)); - r->BufferSizes[i] = desc->Size; - r->BufferTypes[i] = (BufferType) (packed & 3); - - if (i < num_bufs_send) - r->BufferDirections[i] = BufferDirection_Send; - else if (i < (num_bufs_send + num_bufs_recv)) - r->BufferDirections[i] = BufferDirection_Recv; - else - r->BufferDirections[i] = BufferDirection_Exch; - } - - r->NumBuffers = num_bufs; - return 0; -} - -/** - * @brief Queries the size of an IPC pointer buffer. - * @param session IPC session handle. - * @param size Output variable in which to store the size. - * @return Result code. - */ -static inline Result ipcQueryPointerBufferSize(Handle session, size_t *size) { - u32* buf = (u32*)armGetTls(); - - buf[0] = IpcCommandType_Control; - buf[1] = 8; - buf[2] = 0; - buf[3] = 0; - buf[4] = SFCI_MAGIC; - buf[5] = 0; - buf[6] = 3; - buf[7] = 0; - - Result rc = ipcDispatch(session); - - if (R_SUCCEEDED(rc)) { - IpcParsedCommand r; - ipcParse(&r); - - struct ipcQueryPointerBufferSizeResponse { - u64 magic; - u64 result; - u32 size; - } *raw = (struct ipcQueryPointerBufferSizeResponse*)r.Raw; - - rc = raw->result; - - if (R_SUCCEEDED(rc)) { - *size = raw->size & 0xffff; - } - } - - return rc; -} - -/** - * @brief Closes the IPC session with proper clean up. - * @param session IPC session handle. - * @return Result code. - */ -static inline Result ipcCloseSession(Handle session) { - u32* buf = (u32*)armGetTls(); - buf[0] = IpcCommandType_Close; - buf[1] = 0; - return ipcDispatch(session); -} - -/** - * @brief Clones an IPC session. - * @param session IPC session handle. - * @param unk Unknown. - * @param new_session_out Output cloned IPC session handle. - * @return Result code. - */ -static inline Result ipcCloneSession(Handle session, u32 unk, Handle* new_session_out) { - u32* buf = (u32*)armGetTls(); - - buf[0] = IpcCommandType_Control; - buf[1] = 9; - buf[2] = 0; - buf[3] = 0; - buf[4] = SFCI_MAGIC; - buf[5] = 0; - buf[6] = 4; - buf[7] = 0; - buf[8] = unk; - - Result rc = ipcDispatch(session); - - if (R_SUCCEEDED(rc)) { - IpcParsedCommand r; - ipcParse(&r); - - struct ipcCloneSessionResponse { - u64 magic; - u64 result; - } *raw = (struct ipcCloneSessionResponse*)r.Raw; - - rc = raw->result; - - if (R_SUCCEEDED(rc) && new_session_out) { - *new_session_out = r.Handles[0]; - } - } - - return rc; -} - -///@} - -///@name IPC domain handling -///@{ - -/** - * @brief Converts an IPC session handle into a domain. - * @param session IPC session handle. - * @param object_id_out Output variable in which to store the object ID. - * @return Result code. - */ -static inline Result ipcConvertSessionToDomain(Handle session, u32* object_id_out) { - u32* buf = (u32*)armGetTls(); - - buf[0] = IpcCommandType_Control; - buf[1] = 8; - buf[4] = SFCI_MAGIC; - buf[5] = 0; - buf[6] = 0; - buf[7] = 0; - - Result rc = ipcDispatch(session); - - if (R_SUCCEEDED(rc)) { - IpcParsedCommand r; - ipcParse(&r); - - struct ipcConvertSessionToDomainResponse { - u64 magic; - u64 result; - u32 object_id; - } *raw = (struct ipcConvertSessionToDomainResponse*)r.Raw; - - rc = raw->result; - - if (R_SUCCEEDED(rc)) { - *object_id_out = raw->object_id; - } - } - - return rc; -} - -/** - * @brief Adds an object ID to be sent through an IPC domain command structure. - * @param cmd IPC domain command structure. - * @param object_id Object ID to send. - */ -static inline void ipcSendObjectId(IpcCommand* cmd, u32 object_id) { - cmd->ObjectIds[cmd->NumObjectIds++] = object_id; -} - -/** - * @brief Prepares the header of an IPC command structure (domain version). - * @param cmd IPC command structure. - * @param sizeof_raw Size in bytes of the raw data structure to embed inside the IPC request - * @param object_id Domain object ID. - * @return Pointer to the raw embedded data structure in the request, ready to be filled out. - */ -static inline void* ipcPrepareHeaderForDomain(IpcCommand* cmd, size_t sizeof_raw, u32 object_id) { - void* raw = ipcPrepareHeader(cmd, sizeof_raw + sizeof(DomainMessageHeader) + cmd->NumObjectIds*sizeof(u32)); - DomainMessageHeader* hdr = (DomainMessageHeader*) raw; - u32 *object_ids = (u32*)(((uintptr_t) raw) + sizeof(DomainMessageHeader) + sizeof_raw); - - hdr->Type = DomainMessageType_SendMessage; - hdr->NumObjectIds = (u8)cmd->NumObjectIds; - hdr->Length = sizeof_raw; - hdr->ThisObjectId = object_id; - hdr->Pad[0] = hdr->Pad[1] = 0; - - for(size_t i = 0; i < cmd->NumObjectIds; i++) - object_ids[i] = cmd->ObjectIds[i]; - return (void*)(((uintptr_t) raw) + sizeof(DomainMessageHeader)); -} - -/** - * @brief Parse an IPC command request into an IPC parsed command structure (domain version). - * @param r IPC parsed command structure to fill in. - * @return Result code. - */ -static inline Result ipcParseDomainRequest(IpcParsedCommand* r) { - Result rc = ipcParse(r); - DomainMessageHeader *hdr; - u32 *object_ids; - if(R_FAILED(rc)) - return rc; - - hdr = (DomainMessageHeader*) r->Raw; - object_ids = (u32*)(((uintptr_t) hdr) + sizeof(DomainMessageHeader) + hdr->Length); - r->Raw = (void*)(((uintptr_t) r->Raw) + sizeof(DomainMessageHeader)); - - r->IsDomainRequest = true; - r->InMessageType = (DomainMessageType)(hdr->Type); - switch (r->InMessageType) { - case DomainMessageType_SendMessage: - case DomainMessageType_Close: - break; - default: - return MAKERESULT(Module_Libnx, LibnxError_DomainMessageUnknownType); - } - - r->InThisObjectId = hdr->ThisObjectId; - r->InNumObjectIds = hdr->NumObjectIds > 8 ? 8 : hdr->NumObjectIds; - if ((uintptr_t)object_ids + sizeof(u32) * r->InNumObjectIds - (uintptr_t)armGetTls() >= 0x100) { - return MAKERESULT(Module_Libnx, LibnxError_DomainMessageTooManyObjectIds); - } - for(size_t i = 0; i < r->InNumObjectIds; i++) - r->InObjectIds[i] = object_ids[i]; - - return rc; -} - -/** - * @brief Parse an IPC command response into an IPC parsed command structure (domain version). - * @param r IPC parsed command structure to fill in. - * @param sizeof_raw Size in bytes of the raw data structure. - * @return Result code. - */ -static inline Result ipcParseDomainResponse(IpcParsedCommand* r, size_t sizeof_raw) { - Result rc = ipcParse(r); - DomainResponseHeader *hdr; - u32 *object_ids; - if(R_FAILED(rc)) - return rc; - - hdr = (DomainResponseHeader*) r->Raw; - r->Raw = (void*)(((uintptr_t) r->Raw) + sizeof(DomainResponseHeader)); - object_ids = (u32*)(((uintptr_t) r->Raw) + sizeof_raw);//Official sw doesn't align this. - - r->IsDomainResponse = true; - - r->OutNumObjectIds = hdr->NumObjectIds > 8 ? 8 : hdr->NumObjectIds; - if ((uintptr_t)object_ids + sizeof(u32) * r->OutNumObjectIds - (uintptr_t)armGetTls() >= 0x100) { - return MAKERESULT(Module_Libnx, LibnxError_DomainMessageTooManyObjectIds); - } - for(size_t i = 0; i < r->OutNumObjectIds; i++) - r->OutObjectIds[i] = object_ids[i]; - - return rc; -} - -/** - * @brief Closes a domain object by ID. - * @param session IPC session handle. - * @param object_id ID of the object to close. - * @return Result code. - */ -static inline Result ipcCloseObjectById(Handle session, u32 object_id) { - IpcCommand c; - DomainMessageHeader* hdr; - - ipcInitialize(&c); - hdr = (DomainMessageHeader*)ipcPrepareHeader(&c, sizeof(DomainMessageHeader)); - - hdr->Type = DomainMessageType_Close; - hdr->NumObjectIds = 0; - hdr->Length = 0; - hdr->ThisObjectId = object_id; - hdr->Pad[0] = hdr->Pad[1] = 0; - - return ipcDispatch(session); // this command has no associated response -} - -///@} \ No newline at end of file diff --git a/Source/sys-clk/common/include/memmem.h b/Source/sys-clk/common/include/memmem.h deleted file mode 100644 index 0f791c1b..00000000 --- a/Source/sys-clk/common/include/memmem.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - MIT License - - Copyright (c) 2024 Roy Merkel - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -#ifndef MEMMEM_IMPL_H -#define MEMMEM_IMPL_H - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void *memmem_impl(const void *haystack, size_t haystacklen, - const void *needle, size_t needlelen); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/Source/sys-clk/common/include/notification.h b/Source/sys-clk/common/include/notification.h deleted file mode 100644 index a6389b6f..00000000 --- a/Source/sys-clk/common/include/notification.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) ppkantorski (bord2death) - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#include -#include -#include - -static void writeNotification(const std::string& message) { - static const char* flagPath = "sdmc:/config/ultrahand/flags/NOTIFICATIONS.flag"; - - FILE* flagFile = fopen(flagPath, "r"); - if (!flagFile) { - return; - } - fclose(flagFile); - - std::string filename = "Horizon OC -" + std::to_string(std::time(nullptr)) + ".notify"; - std::string fullPath = "sdmc:/config/ultrahand/notifications/" + filename; - - FILE* file = fopen(fullPath.c_str(), "w"); - if (file) { - fprintf(file, "{\n"); - fprintf(file, " \"text\": \"%s\",\n", message.c_str()); - fprintf(file, " \"fontSize\": 28\n"); - fprintf(file, "}\n"); - fclose(file); - } - } diff --git a/Source/sys-clk/common/include/pcv_types.h b/Source/sys-clk/common/include/pcv_types.h deleted file mode 100644 index 03899f35..00000000 --- a/Source/sys-clk/common/include/pcv_types.h +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright (c) ppkantorski (bord2death) - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -/* - * SDx actual min is 625 mV. Multipliers 0/1 reserved. - * SD0 max is 1400 mV - * SD1 max is 1550 mV - * SD2 max is 3787.5 mV - * SD3 max is 3787.5 mV - */ - -/* -* Switch Power domains (max77620): -* Name | Usage | uV step | uV min | uV default | uV max | Init -*-------+---------------+---------+--------+------------+---------+------------------ -* sd0 | SoC | 12500 | 600000 | 625000 | 1400000 | 1.125V (pkg1.1) -* sd1 | SDRAM | 12500 | 600000 | 1125000 | 1125000 | 1.1V (pkg1.1) -* sd2 | ldo{0-1, 7-8} | 12500 | 600000 | 1325000 | 1350000 | 1.325V (pcv) -* sd3 | 1.8V general | 12500 | 600000 | 1800000 | 1800000 | -* ldo0 | Display Panel | 25000 | 800000 | 1200000 | 1200000 | 1.2V (pkg1.1) -* ldo1 | XUSB, PCIE | 25000 | 800000 | 1050000 | 1050000 | 1.05V (pcv) -* ldo2 | SDMMC1 | 50000 | 800000 | 1800000 | 3300000 | -* ldo3 | GC ASIC | 50000 | 800000 | 3100000 | 3100000 | 3.1V (pcv) -* ldo4 | RTC | 12500 | 800000 | 850000 | 850000 | 0.85V (AO, pcv) -* ldo5 | GC Card | 50000 | 800000 | 1800000 | 1800000 | 1.8V (pcv) -* ldo6 | Touch, ALS | 50000 | 800000 | 2900000 | 2900000 | 2.9V (pcv) -* ldo7 | XUSB | 50000 | 800000 | 1050000 | 1050000 | 1.05V (pcv) -* ldo8 | XUSB, DP, MCU | 50000 | 800000 | 1050000 | 2800000 | 1.05V/2.8V (pcv) -*/ - - -// GPIOs T210: 3: 3.3V, 5: CPU PMIC, 6: GPU PMIC, 7: DSI/VI 1.2V powered by ldo0. - -/* - * OTP: T210 - T210B01: - * SD0: 1.0V 1.05V - SoC. EN Based on FPSSRC. - * SD1: 1.15V 1.1V - DRAM for T210. EN Based on FPSSRC. - * SD2: 1.35V 1.35V - * SD3: 1.8V 1.8V - * All powered off? - * LDO0: -- -- - Display - * LDO1: 1.05V 1.05V - * LDO2: -- -- - SD - * LDO3: 3.1V 3.1V - GC ASIC - * LDO4: 1.0V 0.8V - Needed for RTC domain on T210. - * LDO5: 3.1V 3.1V - * LDO6: 2.8V 2.9V - Touch. - * LDO7: 1.05V 1.0V - * LDO8: 1.05V 1.0V - */ - -/* -* MAX77620_AME_GPIO: control GPIO modes (bits 0 - 7 correspond to GPIO0 - GPIO7); 0 -> GPIO, 1 -> alt-mode -* MAX77620_REG_GPIOx: 0x9 sets output and enable -*/ - -typedef enum { - PcvPowerDomain_Max77620_Sd0 = 0, - PcvPowerDomain_Max77620_Sd1 = 1, - PcvPowerDomain_Max77620_Sd2 = 2, - PcvPowerDomain_Max77620_Sd3 = 3, - PcvPowerDomain_Max77620_Ldo0 = 4, - PcvPowerDomain_Max77620_Ldo1 = 5, - PcvPowerDomain_Max77620_Ldo2 = 6, - PcvPowerDomain_Max77620_Ldo3 = 7, - PcvPowerDomain_Max77620_Ldo4 = 8, - PcvPowerDomain_Max77620_Ldo5 = 9, - PcvPowerDomain_Max77620_Ldo6 = 10, - PcvPowerDomain_Max77620_Ldo7 = 11, - PcvPowerDomain_Max77620_Ldo8 = 12, - PcvPowerDomain_Max77621_Cpu = 13, - PcvPowerDomain_Max77621_Gpu = 14, - PcvPowerDomain_Max77812_Cpu = 15, - PcvPowerDomain_Max77812_Gpu = 16, - PcvPowerDomain_Max77812_Dram = 17, -} PowerDomain; - -typedef enum { - PcvPowerDomainId_Max77620_Sd0 = 0x3A000080, - PcvPowerDomainId_Max77620_Sd1 = 0x3A000081, // vdd2 - PcvPowerDomainId_Max77620_Sd2 = 0x3A000082, - PcvPowerDomainId_Max77620_Sd3 = 0x3A000083, - PcvPowerDomainId_Max77620_Ldo0 = 0x3A0000A0, - PcvPowerDomainId_Max77620_Ldo1 = 0x3A0000A1, - PcvPowerDomainId_Max77620_Ldo2 = 0x3A0000A2, - PcvPowerDomainId_Max77620_Ldo3 = 0x3A0000A3, - PcvPowerDomainId_Max77620_Ldo4 = 0x3A0000A4, - PcvPowerDomainId_Max77620_Ldo5 = 0x3A0000A5, - PcvPowerDomainId_Max77620_Ldo6 = 0x3A0000A6, - PcvPowerDomainId_Max77620_Ldo7 = 0x3A0000A7, - PcvPowerDomainId_Max77620_Ldo8 = 0x3A0000A8, - PcvPowerDomainId_Max77621_Cpu = 0x3A000003, - PcvPowerDomainId_Max77621_Gpu = 0x3A000004, - PcvPowerDomainId_Max77812_Cpu = 0x3A000003, - PcvPowerDomainId_Max77812_Gpu = 0x3A000004, - PcvPowerDomainId_Max77812_Dram = 0x3A000005, // vddq -} PowerDomainId; \ No newline at end of file diff --git a/Source/sys-clk/common/include/pwm.h b/Source/sys-clk/common/include/pwm.h deleted file mode 100644 index ccc24e02..00000000 --- a/Source/sys-clk/common/include/pwm.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) MasaGratoR - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - Service s; -} PwmChannelSession; - -Result pwmInitialize(void); -void pwmExit(void); -Service* pwmGetServiceSession(void); -Result pwmOpenSession2(PwmChannelSession *out, u32 device_code); -Result pwmChannelSessionGetDutyCycle(PwmChannelSession *c, double* out); -void pwmChannelSessionClose(PwmChannelSession *c); - -#ifdef __cplusplus -} // extern "C" -#endif \ No newline at end of file diff --git a/Source/sys-clk/common/include/registers.h b/Source/sys-clk/common/include/registers.h deleted file mode 100644 index 82977371..00000000 --- a/Source/sys-clk/common/include/registers.h +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * Copyright (c) Linux 4 Tegra & Linux 4 Switch contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#define EMC_INTSTATUS_0 0x0 -#define EMC_INTMASK_0 0x4 -#define EMC_DBG_0 0x8 -#define EMC_CFG_0 0xC -#define EMC_ADR_CFG_0 0x10 -#define EMC_REFCTRL_0 0x20 -#define EMC_PIN_0 0x24 -#define EMC_TIMING_CONTROL_0 0x28 -#define EMC_RC_0 0x2C -#define EMC_RFC_0 0x30 -#define EMC_RAS_0 0x34 -#define EMC_RP_0 0x38 -#define EMC_R2W_0 0x3C -#define EMC_W2R_0 0x40 -#define EMC_R2P_0 0x44 -#define EMC_W2P_0 0x48 -#define EMC_RD_RCD_0 0x4C -#define EMC_WR_RCD_0 0x50 -#define EMC_RRD_0 0x54 -#define EMC_REXT_0 0x58 -#define EMC_WDV_0 0x5C -#define EMC_QUSE_0 0x60 -#define EMC_QRST_0 0x64 -#define EMC_QSAFE_0 0x68 -#define EMC_RDV_0 0x6C -#define EMC_REFRESH_0 0x70 -#define EMC_BURST_REFRESH_NUM_0 0x74 -#define EMC_PDEX2WR_0 0x78 -#define EMC_PDEX2RD_0 0x7C -#define EMC_PCHG2PDEN_0 0x80 -#define EMC_ACT2PDEN_0 0x84 -#define EMC_AR2PDEN_0 0x88 -#define EMC_RW2PDEN_0 0x8C -#define EMC_TXSR_0 0x90 -#define EMC_TCKE_0 0x94 -#define EMC_TFAW_0 0x98 -#define EMC_TRPAB_0 0x9C -#define EMC_TCLKSTABLE_0 0xA0 -#define EMC_TCLKSTOP_0 0xA4 -#define EMC_TREFBW_0 0xA8 -#define EMC_TPPD_0 0xAC -#define EMC_ODT_WRITE_0 0xB0 -#define EMC_PDEX2MRR_0 0xB4 -#define EMC_WEXT_0 0xB8 -#define EMC_RFC_SLR_0 0xC0 -#define EMC_MRS_WAIT_CNT2_0 0xC4 -#define EMC_MRS_WAIT_CNT_0 0xC8 -#define EMC_MRS_0 0xCC -#define EMC_EMRS_0 0xD0 -#define EMC_REF_0 0xD4 -#define EMC_PRE_0 0xD8 -#define EMC_NOP_0 0xDC -#define EMC_SELF_REF_0 0xE0 -#define EMC_DPD_0 0xE4 -#define EMC_MRW_0 0xE8 -#define EMC_MRR_0 0xEC -#define EMC_CMDQ_0 0xF0 -#define EMC_MC2EMCQ_0 0xF4 -#define EMC_FBIO_SPARE_0 0x100 -#define EMC_FBIO_CFG5_0 0x104 -#define EMC_FBIO_CFG6_0 0x114 -#define EMC_PDEX2CKE_0 0x118 -#define EMC_CKE2PDEN_0 0x11C -#define EMC_CFG_RSV_0 0x120 -#define EMC_ACPD_CONTROL_0 0x124 -#define EMC_MPC_0 0x128 -#define EMC_EMRS2_0 0x12C -#define EMC_EMRS3_0 0x130 -#define EMC_MRW2_0 0x134 -#define EMC_MRW3_0 0x138 -#define EMC_MRW4_0 0x13C -#define EMC_CLKEN_OVERRIDE_0 0x140 -#define EMC_R2R_0 0x144 -#define EMC_W2W_0 0x148 -#define EMC_EINPUT_0 0x14C -#define EMC_EINPUT_DURATION_0 0x150 -#define EMC_PUTERM_EXTRA_0 0x154 -#define EMC_TCKESR_0 0x158 -#define EMC_TPD_0 0x15C -#define EMC_AUTO_CAL_CONFIG_0 0x2A4 -#define EMC_AUTO_CAL_INTERVAL_0 0x2A8 -#define EMC_AUTO_CAL_STATUS_0 0x2AC -#define EMC_REQ_CTRL_0 0x2B0 -#define EMC_EMC_STATUS_0 0x2B4 -#define EMC_CFG_2_0 0x2B8 -#define EMC_CFG_DIG_DLL_0 0x2BC -#define EMC_CFG_DIG_DLL_PERIOD_0 0x2C0 -#define EMC_DIG_DLL_STATUS_0 0x2C4 -#define EMC_CFG_DIG_DLL_1_0 0x2C8 -#define EMC_RDV_MASK_0 0x2CC -#define EMC_WDV_MASK_0 0x2D0 -#define EMC_RDV_EARLY_MASK_0 0x2D4 -#define EMC_RDV_EARLY_0 0x2D8 -#define EMC_AUTO_CAL_CONFIG8_0 0x2DC -#define EMC_ZCAL_INTERVAL_0 0x2E0 -#define EMC_ZCAL_WAIT_CNT_0 0x2E4 -#define EMC_ZCAL_MRW_CMD_0 0x2E8 -#define EMC_ZQ_CAL_0 0x2EC -#define EMC_XM2COMPPADCTRL3_0 0x2F4 -#define EMC_AUTO_CAL_VREF_SEL_0_0 0x2F8 -#define EMC_AUTO_CAL_VREF_SEL_1_0 0x300 -#define EMC_XM2COMPPADCTRL_0 0x30C -#define EMC_FDPD_CTRL_DQ_0 0x310 -#define EMC_FDPD_CTRL_CMD_0 0x314 -#define EMC_PMACRO_CMD_BRICK_CTRL_FDPD_0 0x318 -#define EMC_PMACRO_DATA_BRICK_CTRL_FDPD_0 0x31C -#define EMC_SCRATCH0_0 0x324 -#define EMC_PMACRO_BRICK_CTRL_RFU1_0 0x330 -#define EMC_PMACRO_BRICK_CTRL_RFU2_0 0x334 -#define EMC_CMD_MAPPING_CMD0_0_0 0x380 -#define EMC_CMD_MAPPING_CMD0_1_0 0x384 -#define EMC_CMD_MAPPING_CMD0_2_0 0x388 -#define EMC_CMD_MAPPING_CMD1_0_0 0x38C -#define EMC_CMD_MAPPING_CMD1_1_0 0x390 -#define EMC_CMD_MAPPING_CMD1_2_0 0x394 -#define EMC_CMD_MAPPING_CMD2_0_0 0x398 -#define EMC_CMD_MAPPING_CMD2_1_0 0x39C -#define EMC_CMD_MAPPING_CMD2_2_0 0x3A0 -#define EMC_CMD_MAPPING_CMD3_0_0 0x3A4 -#define EMC_CMD_MAPPING_CMD3_1_0 0x3A8 -#define EMC_CMD_MAPPING_CMD3_2_0 0x3AC -#define EMC_CMD_MAPPING_BYTE_0 0x3B0 -#define EMC_TR_TIMING_0_0 0x3B4 -#define EMC_TR_CTRL_0_0 0x3B8 -#define EMC_TR_CTRL_1_0 0x3BC -#define EMC_SWITCH_BACK_CTRL_0 0x3C0 -#define EMC_TR_RDV_0 0x3C4 -#define EMC_STALL_THEN_EXE_BEFORE_CLKCHANGE_0 0x3C8 -#define EMC_STALL_THEN_EXE_AFTER_CLKCHANGE_0 0x3CC -#define EMC_UNSTALL_RW_AFTER_CLKCHANGE_0 0x3D0 -#define EMC_AUTO_CAL_ 0x3D4 -#define EMC_SEL_DPD_CTRL_0 0x3D8 -#define EMC_PRE_REFRESH_REQ_CNT_0 0x3DC -#define EMC_DYN_SELF_REF_CONTROL_0 0x3E0 -#define EMC_TXSRDLL_0 0x3E4 -#define EMC_CCFIFO_ADDR_0 0x3E8 -#define EMC_CCFIFO_DATA_0 0x3EC -#define EMC_CCFIFO_STATUS_0 0x3F0 -#define EMC_TR_QPOP_0 0x3F4 -#define EMC_TR_RDV_MASK_0 0x3F8 -#define EMC_TR_QSAFE_0 0x3FC -#define EMC_TR_QRST_0 0x400 -#define EMC_SWIZZLE_RANK0_BYTE0_0 0x404 -#define EMC_SWIZZLE_RANK0_BYTE1_0 0x408 -#define EMC_SWIZZLE_RANK0_BYTE2_0 0x40C -#define EMC_SWIZZLE_RANK0_BYTE3_0 0x410 -#define EMC_SWIZZLE_RANK1_BYTE0_0 0x418 -#define EMC_SWIZZLE_RANK1_BYTE1_0 0x41C -#define EMC_SWIZZLE_RANK1_BYTE2_0 0x420 -#define EMC_SWIZZLE_RANK1_BYTE3_0 0x424 -#define EMC_ISSUE_QRST_0 0x428 -#define EMC_PMC_SCRATCH1_0 0x440 -#define EMC_PMC_SCRATCH2_0 0x444 -#define EMC_PMC_SCRATCH3_0 0x448 -#define EMC_AUTO_CAL_CONFIG2_0 0x458 -#define EMC_AUTO_CAL_CONFIG3_0 0x45C -#define EMC_TR_DVFS_0 0x460 -#define EMC_AUTO_CAL_CHANNEL_0 0x464 -#define EMC_IBDLY_0 0x468 -#define EMC_OBDLY_0 0x46C -#define EMC_TXDSRVTTGEN_0 0x480 -#define EMC_WE_DURATION_0 0x48C -#define EMC_WS_DURATION_0 0x490 -#define EMC_WEV_0 0x494 -#define EMC_WSV_0 0x498 -#define EMC_CFG_3_0 0x49C -#define EMC_MRW5_0 0x4A0 -#define EMC_MRW6_0 0x4A4 -#define EMC_MRW7_0 0x4A8 -#define EMC_MRW8_0 0x4AC -#define EMC_MRW9_0 0x4B0 -#define EMC_MRW10_0 0x4B4 -#define EMC_MRW11_0 0x4B8 -#define EMC_MRW12_0 0x4BC -#define EMC_MRW13_0 0x4C0 -#define EMC_MRW14_0 0x4C4 -#define EMC_MRW15_0 0x4D0 -#define EMC_CFG_SYNC_0 0x4D4 -#define EMC_FDPD_CTRL_CMD_NO_RAMP_0 0x4D8 -#define EMC_WDV_CHK_0 0x4E0 -#define EMC_CFG_PIPE_2_0 0x554 -#define EMC_CFG_PIPE_CLK_0 0x558 -#define EMC_CFG_PIPE_1_0 0x55C -#define EMC_CFG_PIPE_0 0x560 -#define EMC_QPOP_0 0x564 -#define EMC_QUSE_WIDTH_0 0x568 -#define EMC_PUTERM_WIDTH_0 0x56C -#define EMC_BGBIAS_CTL0_0 0x570 -#define EMC_AUTO_CAL_CONFIG7_0 0x574 -#define EMC_XM2COMPPADCTRL2_0 0x578 -#define EMC_COMP_PAD_SW_CTRL_0 0x57C -#define EMC_REFCTRL2_0 0x580 -#define EMC_FBIO_CFG7_0 0x584 -#define EMC_DATA_BRLSHFT_0_0 0x588 -#define EMC_DATA_BRLSHFT_1_0 0x58C -#define EMC_RFCPB_0 0x590 -#define EMC_DQS_BRLSHFT_0_0 0x594 -#define EMC_DQS_BRLSHFT_1_0 0x598 -#define EMC_CMD_BRLSHFT_0_0 0x59C -#define EMC_CMD_BRLSHFT_1_0 0x5A0 -#define EMC_CMD_BRLSHFT_2_0 0x5A4 -#define EMC_CMD_BRLSHFT_3_0 0x5A8 -#define EMC_QUSE_BRLSHFT_0_0 0x5AC -#define EMC_AUTO_CAL_CONFIG4_0 0x5B0 -#define EMC_AUTO_CAL_CONFIG5_0 0x5B4 -#define EMC_QUSE_BRLSHFT_1_0 0x5B8 -#define EMC_QUSE_BRLSHFT_2_0 0x5BC -#define EMC_CCDMW_0 0x5C0 -#define EMC_QUSE_BRLSHFT_3_0 0x5C4 -#define EMC_FBIO_CFG8_0 0x5C8 -#define EMC_AUTO_CAL_CONFIG6_0 0x5CC -#define EMC_PROTOBIST_CONFIG_ADR_1_0 0x5D0 -#define EMC_PROTOBIST_CONFIG_ADR_2_0 0x5D4 -#define EMC_PROTOBIST_MISC_0 0x5D8 -#define EMC_PROTOBIST_WDATA_LOWER_0 0x5DC -#define EMC_PROTOBIST_WDATA_UPPER_0 0x5E0 -#define EMC_PROTOBIST_RDATA_0 0x5EC -#define EMC_DLL_CFG_0_0 0x5E4 -#define EMC_DLL_CFG_1_0 0x5E8 -#define EMC_CONFIG_SAMPLE_DELAY_0 0x5F0 -#define EMC_CFG_UPDATE_0 0x5F4 -#define EMC_PMACRO_QUSE_DDLL_RANK0_0_0 0x600 -#define EMC_PMACRO_QUSE_DDLL_RANK0_1_0 0x604 -#define EMC_PMACRO_QUSE_DDLL_RANK0_2_0 0x608 -#define EMC_PMACRO_QUSE_DDLL_RANK0_3_0 0x60C -#define EMC_PMACRO_QUSE_DDLL_RANK0_4_0 0x610 -#define EMC_PMACRO_QUSE_DDLL_RANK0_5_0 0x614 -#define EMC_PMACRO_QUSE_DDLL_RANK1_0_0 0x620 -#define EMC_PMACRO_QUSE_DDLL_RANK1_1_0 0x624 -#define EMC_PMACRO_QUSE_DDLL_RANK1_2_0 0x628 -#define EMC_PMACRO_QUSE_DDLL_RANK1_3_0 0x62C -#define EMC_PMACRO_QUSE_DDLL_RANK1_4_0 0x630 -#define EMC_PMACRO_QUSE_DDLL_RANK1_5_0 0x634 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_0_0 0x640 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_1_0 0x644 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_2_0 0x648 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_3_0 0x64C -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_4_0 0x650 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK0_5_0 0x654 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_0_0 0x660 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_1_0 0x664 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_2_0 0x668 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_3_0 0x66C -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_4_0 0x670 -#define EMC_PMACRO_OB_DDLL_LONG_DQ_RANK1_5_0 0x674 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_0_0 0x680 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_1_0 0x684 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_2_0 0x688 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_3_0 0x68C -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_4_0 0x690 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK0_5_0 0x694 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_0_0 0x6A0 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_1_0 0x6A4 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_2_0 0x6A8 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_3_0 0x6AC -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_4_0 0x6B0 -#define EMC_PMACRO_OB_DDLL_LONG_DQS_RANK1_5_0 0x6B4 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_0_0 0x6C0 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_1_0 0x6C4 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_2_0 0x6C8 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_3_0 0x6CC -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_4_0 0x6D0 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK0_5_0 0x6D4 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_0_0 0x6E0 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_1_0 0x6E4 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_2_0 0x6E8 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_3_0 0x6EC -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_4_0 0x6F0 -#define EMC_PMACRO_IB_DDLL_LONG_DQS_RANK1_5_0 0x6F4 -#define EMC_PMACRO_AUTOCAL_CFG_0_0 0x700 -#define EMC_PMACRO_AUTOCAL_CFG_1_0 0x704 -#define EMC_PMACRO_AUTOCAL_CFG_2_0 0x708 -#define EMC_PMACRO_TX_PWRD_0_0 0x720 -#define EMC_PMACRO_TX_PWRD_1_0 0x724 -#define EMC_PMACRO_TX_PWRD_2_0 0x728 -#define EMC_PMACRO_TX_PWRD_3_0 0x72C -#define EMC_PMACRO_TX_PWRD_4_0 0x730 -#define EMC_PMACRO_TX_PWRD_5_0 0x734 -#define EMC_PMACRO_TX_SEL_CLK_SRC_0_0 0x740 -#define EMC_PMACRO_TX_SEL_CLK_SRC_1_0 0x744 -#define EMC_PMACRO_TX_SEL_CLK_SRC_2_0 0x748 -#define EMC_PMACRO_TX_SEL_CLK_SRC_3_0 0x74C -#define EMC_PMACRO_TX_SEL_CLK_SRC_4_0 0x750 -#define EMC_PMACRO_TX_SEL_CLK_SRC_5_0 0x754 -#define EMC_PMACRO_DDLL_BYPASS_0 0x760 -#define EMC_PMACRO_DDLL_PWRD_0_0 0x770 -#define EMC_PMACRO_DDLL_PWRD_1_0 0x774 -#define EMC_PMACRO_DDLL_PWRD_2_0 0x778 -#define EMC_PMACRO_CMD_CTRL_0_0 0x780 -#define EMC_PMACRO_CMD_CTRL_1_0 0x784 -#define EMC_PMACRO_CMD_CTRL_2_0 0x788 - -#define MC_REGISTER_BASE 0x70019000 -#define MC_REGISTER_REGION_SIZE 0x1000 - -#define MC_INTSTATUS_0 0x000 -#define MC_INTMASK_0 0x004 -#define MC_ERR_STATUS_0 0x008 -#define MC_ERR_ADR_0 0x00C -#define MC_SMMU_CONFIG_0 0x010 -#define MC_SMMU_PTB_ASID_0 0x01C -#define MC_SMMU_PTB_DATA_0 0x020 -#define MC_SMMU_TLB_FLUSH_0 0x030 -#define MC_SMMU_PTC_FLUSH_0_0 0x034 -#define MC_EMEM_CFG_0 0x050 -#define MC_EMEM_ADR_CFG_0 0x054 -#define MC_EMEM_ARB_CFG_0 0x090 -#define MC_EMEM_ARB_OUTSTANDING_REQ_0 0x094 -#define MC_EMEM_ARB_TIMING_RCD_0 0x098 -#define MC_EMEM_ARB_TIMING_RP_0 0x09C -#define MC_EMEM_ARB_TIMING_RC_0 0x0A0 -#define MC_EMEM_ARB_TIMING_RAS_0 0x0A4 -#define MC_EMEM_ARB_TIMING_FAW_0 0x0A8 -#define MC_EMEM_ARB_TIMING_RRD_0 0x0AC -#define MC_EMEM_ARB_TIMING_RAP2PRE_0 0x0B0 -#define MC_EMEM_ARB_TIMING_WAP2PRE_0 0x0B4 -#define MC_EMEM_ARB_TIMING_R2R_0 0x0B8 -#define MC_EMEM_ARB_TIMING_W2W_0 0x0BC -#define MC_EMEM_ARB_TIMING_R2W_0 0x0C0 -#define MC_EMEM_ARB_TIMING_W2R_0 0x0C4 -#define MC_EMEM_ARB_MISC2_0 0x0C8 -#define MC_EMEM_ARB_DA_TURNS_0 0x0D0 -#define MC_EMEM_ARB_DA_COVERS_0 0x0D4 -#define MC_EMEM_ARB_MISC0_0 0x0D8 -#define MC_EMEM_ARB_MISC1_0 0x0DC -#define MC_TIMING_CONTROL_0 0xFC -#define MC_EMEM_ARB_RING1_THROTTLE_0 0x0E0 -#define MC_CLIENT_HOTRESET_CTRL_0 0x200 -#define MC_CLIENT_HOTRESET_STATUS_0 0x204 -#define MC_SMMU_AFI_ASID_0 0x238 -#define MC_SMMU_DC_ASID_0 0x240 -#define MC_SMMU_DCB_ASID_0 0x244 -#define MC_SMMU_HC_ASID_0 0x250 -#define MC_SMMU_HDA_ASID_0 0x254 -#define MC_SMMU_ISP2_ASID_0 0x258 -#define MC_SMMU_MSENC_NVENC_ASID_0 0x264 -#define MC_SMMU_NV_ASID_0 0x268 -#define MC_SMMU_NV2_ASID_0 0x26C -#define MC_SMMU_PPCS_ASID_0 0x270 -#define MC_SMMU_SATA_ASID_0 0x274 -#define MC_SMMU_VI_ASID_0 0x280 -#define MC_SMMU_VIC_ASID_0 0x284 -#define MC_SMMU_XUSB_HOST_ASID_0 0x288 -#define MC_SMMU_XUSB_DEV_ASID_0 0x28C -#define MC_SMMU_TSEC_ASID_0 0x294 -#define MC_LATENCY_ALLOWANCE_AVPC_0 0x2E4 -#define MC_LATENCY_ALLOWANCE_DC_0 0x2E8 -#define MC_LATENCY_ALLOWANCE_DC_1 0x2EC -#define MC_LATENCY_ALLOWANCE_DCB_0 0x2F4 -#define MC_LATENCY_ALLOWANCE_DCB_1 0x2F8 -#define MC_LATENCY_ALLOWANCE_HC_0 0x310 -#define MC_LATENCY_ALLOWANCE_HC_1 0x314 -#define MC_LATENCY_ALLOWANCE_MPCORE_0 0x320 -#define MC_LATENCY_ALLOWANCE_NVENC_0 0x328 -#define MC_LATENCY_ALLOWANCE_PPCS_0 0x344 -#define MC_LATENCY_ALLOWANCE_PPCS_1 0x348 -#define MC_LATENCY_ALLOWANCE_ISP2_0 0x370 -#define MC_LATENCY_ALLOWANCE_ISP2_1 0x374 -#define MC_LATENCY_ALLOWANCE_XUSB_0 0x37C -#define MC_LATENCY_ALLOWANCE_XUSB_1 0x380 -#define MC_LATENCY_ALLOWANCE_TSEC_0 0x390 -#define MC_LATENCY_ALLOWANCE_VIC_0 0x394 -#define MC_LATENCY_ALLOWANCE_VI2_0 0x398 -#define MC_LATENCY_ALLOWANCE_GPU_0 0x3AC -#define MC_LATENCY_ALLOWANCE_SDMMCA_0 0x3B8 -#define MC_LATENCY_ALLOWANCE_SDMMCAA_0 0x3BC -#define MC_LATENCY_ALLOWANCE_SDMMC_0 0x3C0 -#define MC_LATENCY_ALLOWANCE_SDMMCAB_0 0x3C4 -#define MC_LATENCY_ALLOWANCE_NVDEC_0 0x3D8 -#define MC_LATENCY_ALLOWANCE_GPU2_0 0x3E8 -#define MC_DIS_PTSA_RATE_0 0x41C -#define MC_DIS_PTSA_MIN_0 0x420 -#define MC_DIS_PTSA_MAX_0 0x424 -#define MC_DISB_PTSA_RATE_0 0x428 -#define MC_DISB_PTSA_MIN_0 0x42C -#define MC_DISB_PTSA_MAX_0 0x430 -#define MC_VE_PTSA_RATE_0 0x434 -#define MC_VE_PTSA_MIN_0 0x438 -#define MC_VE_PTSA_MAX_0 0x43C -#define MC_MLL_MPCORER_PTSA_RATE_0 0x44C -#define MC_RING1_PTSA_RATE_0 0x47C -#define MC_RING1_PTSA_MIN_0 0x480 -#define MC_RING1_PTSA_MAX_0 0x484 -#define MC_PCX_PTSA_RATE_0 0x4AC -#define MC_PCX_PTSA_MIN_0 0x4B0 -#define MC_PCX_PTSA_MAX_0 0x4B4 -#define MC_MSE_PTSA_RATE_0 0x4C4 -#define MC_MSE_PTSA_MIN_0 0x4C8 -#define MC_MSE_PTSA_MAX_0 0x4CC -#define MC_AHB_PTSA_RATE_0 0x4DC -#define MC_AHB_PTSA_MIN_0 0x4E0 -#define MC_AHB_PTSA_MAX_0 0x4E4 -#define MC_APB_PTSA_RATE_0 0x4E8 -#define MC_APB_PTSA_MIN_0 0x4EC -#define MC_APB_PTSA_MAX_0 0x4F0 -#define MC_FTOP_PTSA_RATE_0 0x50C -#define MC_HOST_PTSA_RATE_0 0x518 -#define MC_HOST_PTSA_MIN_0 0x51C -#define MC_HOST_PTSA_MAX_0 0x520 -#define MC_USBX_PTSA_RATE_0 0x524 -#define MC_USBX_PTSA_MIN_0 0x528 -#define MC_USBX_PTSA_MAX_0 0x52C -#define MC_USBD_PTSA_RATE_0 0x530 -#define MC_USBD_PTSA_MIN_0 0x534 -#define MC_USBD_PTSA_MAX_0 0x538 -#define MC_GK_PTSA_RATE_0 0x53C -#define MC_GK_PTSA_MIN_0 0x540 -#define MC_GK_PTSA_MAX_0 0x544 -#define MC_AUD_PTSA_RATE_0 0x548 -#define MC_AUD_PTSA_MIN_0 0x54C -#define MC_AUD_PTSA_MAX_0 0x550 -#define MC_VICPC_PTSA_RATE_0 0x554 -#define MC_VICPC_PTSA_MIN_0 0x558 -#define MC_VICPC_PTSA_MAX_0 0x55C -#define MC_JPG_PTSA_RATE_0 0x584 -#define MC_JPG_PTSA_MIN_0 0x588 -#define MC_JPG_PTSA_MAX_0 0x58C -#define MC_GK2_PTSA_RATE_0 0x610 -#define MC_GK2_PTSA_MIN_0 0x614 -#define MC_GK2_PTSA_MAX_0 0x618 -#define MC_SDM_PTSA_RATE_0 0x61C -#define MC_SDM_PTSA_MIN_0 0x620 -#define MC_SDM_PTSA_MAX_0 0x624 -#define MC_HDAPC_PTSA_RATE_0 0x628 -#define MC_HDAPC_PTSA_MIN_0 0x62C -#define MC_HDAPC_PTSA_MAX_0 0x630 -#define MC_SEC_CARVEOUT_BOM_0 0x670 -#define MC_SEC_CARVEOUT_SIZE_MB_0 0x674 -#define MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0A_0 0x690 -#define MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0AB_0 0x694 -#define MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0B_0 0x698 -#define MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0BB_0 0x69C -#define MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0C_0 0x6A0 -#define MC_SCALED_LATENCY_ALLOWANCE_DISPLAY0CB_0 0x6A4 -#define MC_EMEM_ARB_TIMING_RFCPB_0 0x6C0 -#define MC_EMEM_ARB_TIMING_CCDMW_0 0x6C4 -#define MC_EMEM_ARB_REFPB_HP_CTRL_0 0x6F0 -#define MC_EMEM_ARB_REFPB_BANK_CTRL_0 0x6F4 -#define MC_PTSA_GRANT_DECREMENT_0 0x960 -#define MC_CLIENT_HOTRESET_CTRL_1 0x970 -#define MC_CLIENT_HOTRESET_STATUS_1 0x974 -#define MC_SMMU_PTC_FLUSH_1 0x9B8 -#define MC_SMMU_DC1_ASID_0 0xA88 -#define MC_SMMU_SDMMC1A_ASID_0 0xA94 -#define MC_SMMU_SDMMC2A_ASID_0 0xA98 -#define MC_SMMU_SDMMC3A_ASID_0 0xA9C -#define MC_SMMU_SDMMC4A_ASID_0 0xAA0 -#define MC_SMMU_ISP2B_ASID_0 0xAA4 -#define MC_SMMU_GPU_ASID_0 0xAA8 -#define MC_SMMU_GPUB_ASID_0 0xAAC -#define MC_SMMU_PPCS2_ASID_0 0xAB0 -#define MC_SMMU_NVDEC_ASID_0 0xAB4 -#define MC_SMMU_APE_ASID_0 0xAB8 -#define MC_SMMU_SE_ASID_0 0xABC -#define MC_SMMU_NVJPG_ASID_0 0xAC0 -#define MC_SMMU_HC1_ASID_0 0xAC4 -#define MC_SMMU_SE1_ASID_0 0xAC8 -#define MC_SMMU_AXIAP_ASID_0 0xACC -#define MC_SMMU_ETR_ASID_0 0xAD0 -#define MC_SMMU_TSECB_ASID_0 0xAD4 -#define MC_SMMU_TSEC1_ASID_0 0xAD8 -#define MC_SMMU_TSECB1_ASID_0 0xADC -#define MC_SMMU_NVDEC1_ASID_0 0xAE0 -#define MC_EMEM_ARB_DHYST_CTRL_0 0xBCC -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_0 0xBD0 -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_1 0xBD4 -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_2 0xBD8 -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_3 0xBDC -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_4 0xBE0 -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_5 0xBE4 -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_6 0xBE8 -#define MC_EMEM_ARB_DHYST_TIMEOUT_UTIL_7 0xBEC -#define MC_ERR_GENERALIZED_CARVEOUT_STATUS_0 0xC00 -#define MC_SECURITY_CARVEOUT2_BOM_0 0xC5C -#define MC_SECURITY_CARVEOUT3_BOM_0 0xCAC - -#define CLDVFS_REGION_BASE 0x70110000 -#define CLDVFS_REGION_SIZE 0x1000 -#define CL_DVFS_CTRL_0 0x0 -#define CL_DVFS_CONFIG_0 0x4 -#define CL_DVFS_PARAMS_0 0x8 -#define CL_DVFS_TUNE0_0 0xC -#define CL_DVFS_TUNE1_0 0x10 -#define CL_DVFS_FREQ_REQ_0 0x14 -#define CL_DVFS_SCALE_RAMP_0 0x18 -#define CL_DVFS_DROOP_CTRL_0 0x1C -#define CL_DVFS_OUTPUT_CFG_0 0x20 -#define CL_DVFS_OUTPUT_FORCE_0 0x24 -#define CL_DVFS_MONITOR_CTRL_0 0x28 -#define CL_DVFS_MONITOR_DATA_0 0x2C -#define CL_DVFS_I2C_CFG_0 0x40 -#define CL_DVFS_I2C_VDD_REG_ADDR_0 0x44 -#define CL_DVFS_I2C_STS_0 0x48 -#define CL_DVFS_INTR_STS_0 0x5C -#define CL_DVFS_INTR_EN_0 0x60 -#define DVFS_DFLL_THROTTLE_CTRL_0 0x64 -#define DVFS_DFLL_THROTTLE_LIGHT_0 0x68 -#define DVFS_DFLL_THROTTLE_MEDIUM_0 0x6C -#define DVFS_DFLL_THROTTLE_HEAVY_0 0x70 -#define DVFS_CC4_HVC_0 0x74 -#define CL_DVFS_MONITOR_DATA_0 0x2C -#define CL_DVFS_I2C_CFG_0 0x40 -#define CL_DVFS_I2C_VDD_REG_ADDR_0 0x44 -#define CL_DVFS_I2C_STS_0 0x48 -#define CL_DVFS_INTR_STS_0 0x5C -#define CL_DVFS_I2C_CLK_DIVISOR_REGISTER_0 0x16C diff --git a/Source/sys-clk/common/include/rgltr.h b/Source/sys-clk/common/include/rgltr.h deleted file mode 100644 index 33268b8a..00000000 --- a/Source/sys-clk/common/include/rgltr.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) ppkantorski (bord2death) - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once -#include -#include "pcv_types.h" - -typedef struct { - Service s; -} RgltrSession; - -Result rgltrInitialize(void); - -void rgltrExit(void); - -Service* rgltrGetServiceSession(void); - -Result rgltrOpenSession(RgltrSession* session_out, PowerDomainId module_id); -void rgltrCloseSession(RgltrSession* session); -Result rgltrGetVoltage(RgltrSession* session, u32 *out_volt); -Result rgltrGetPowerModuleNumLimit(u32 *out); -Result rgltrGetVoltageEnabled(RgltrSession* session, u32 *out); -Result rgltrRequestVoltage(RgltrSession* session, u32 microvolt); -Result rgltrCancelVoltageRequest(RgltrSession* session); \ No newline at end of file diff --git a/Source/sys-clk/common/include/rgltr_services.h b/Source/sys-clk/common/include/rgltr_services.h deleted file mode 100644 index 2010cc33..00000000 --- a/Source/sys-clk/common/include/rgltr_services.h +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (c) ppkantorski (bord2death) - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#include // for Service, Result, hosversionBefore(), smGetService(), serviceClose(), etc. -#include "rgltr.h" // for RgltrSession, PowerDomainId, etc. - -extern Service g_rgltrSrv; - -Result rgltrInitialize(void); -void rgltrExit(void); - -Result rgltrOpenSession(RgltrSession* session_out, PowerDomainId module_id); - -Result rgltrGetVoltage(RgltrSession* session, u32* out_volt); - -void rgltrCloseSession(RgltrSession* session); diff --git a/Source/sys-clk/common/include/service_guard.h b/Source/sys-clk/common/include/service_guard.h deleted file mode 100644 index 96a348a5..00000000 --- a/Source/sys-clk/common/include/service_guard.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) MasaGratoR - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include -#include -#include -#include - -typedef struct ServiceGuard { - Mutex mutex; - u32 refCount; -} ServiceGuard; - -NX_INLINE bool serviceGuardBeginInit(ServiceGuard* g) -{ - mutexLock(&g->mutex); - return (g->refCount++) == 0; -} - -NX_INLINE Result serviceGuardEndInit(ServiceGuard* g, Result rc, void (*cleanupFunc)(void)) -{ - if (R_FAILED(rc)) { - cleanupFunc(); - --g->refCount; - } - mutexUnlock(&g->mutex); - return rc; -} - -NX_INLINE void serviceGuardExit(ServiceGuard* g, void (*cleanupFunc)(void)) -{ - mutexLock(&g->mutex); - if (g->refCount && (--g->refCount) == 0) - cleanupFunc(); - mutexUnlock(&g->mutex); -} - -#define NX_GENERATE_SERVICE_GUARD_PARAMS(name, _paramdecl, _parampass) \ -\ -static ServiceGuard g_##name##Guard; \ -NX_INLINE Result _##name##Initialize _paramdecl; \ -static void _##name##Cleanup(void); \ -\ -Result name##Initialize _paramdecl \ -{ \ - Result rc = 0; \ - if (serviceGuardBeginInit(&g_##name##Guard)) \ - rc = _##name##Initialize _parampass; \ - return serviceGuardEndInit(&g_##name##Guard, rc, _##name##Cleanup); \ -} \ -\ -void name##Exit(void) \ -{ \ - serviceGuardExit(&g_##name##Guard, _##name##Cleanup); \ -} - -#define NX_GENERATE_SERVICE_GUARD(name) NX_GENERATE_SERVICE_GUARD_PARAMS(name, (void), ()) - -#ifdef __cplusplus -} -#endif diff --git a/Source/sys-clk/common/include/sysclk.h b/Source/sys-clk/common/include/sysclk.h deleted file mode 100644 index c44f506b..00000000 --- a/Source/sys-clk/common/include/sysclk.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once -#include -#include // include libnx -#ifdef __cplusplus -#include "cpp_util.hpp" -extern "C" { -#endif - -// typedef std::uint32_t Result; -// typedef std::uint32_t u32; -// typedef std::int32_t s32; -// typedef std::uint64_t u64; -// typedef std::int64_t s64; -// typedef std::uint8_t u8; -// typedef std::int16_t s16; -// typedef std::uint16_t u16; - -#include "sysclk/ipc.h" -#include "sysclk/board.h" -#include "sysclk/clock_manager.h" -#include "sysclk/apm.h" -#include "sysclk/config.h" -#include "sysclk/errors.h" -#include "sysclk/psm_ext.h" - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/Source/sys-clk/common/include/sysclk/apm.h b/Source/sys-clk/common/include/sysclk/apm.h deleted file mode 100644 index 9815a9b0..00000000 --- a/Source/sys-clk/common/include/sysclk/apm.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include "board.h" - -typedef struct { - uint32_t id; - uint32_t cpu_hz; - uint32_t gpu_hz; - uint32_t mem_hz; -} SysClkApmConfiguration; - -extern SysClkApmConfiguration sysclk_g_apm_configurations[]; diff --git a/Source/sys-clk/common/include/sysclk/board.h b/Source/sys-clk/common/include/sysclk/board.h deleted file mode 100644 index 44bb8a7d..00000000 --- a/Source/sys-clk/common/include/sysclk/board.h +++ /dev/null @@ -1,270 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include -#include -#include -typedef enum -{ - SysClkSocType_Erista = 0, - SysClkSocType_Mariko, - SysClkSocType_EnumMax -} SysClkSocType; - -typedef enum -{ - HorizonOCConsoleType_Icosa = 0, - HorizonOCConsoleType_Copper, - HorizonOCConsoleType_Hoag, - HorizonOCConsoleType_Iowa, - HorizonOCConsoleType_Calcio, - HorizonOCConsoleType_Aula, - HorizonOCConsoleType_EnumMax, -} HorizonOCConsoleType; - -typedef enum { - HocClkVoltage_SOC = 0, - HocClkVoltage_EMCVDD2, - HocClkVoltage_CPU, - HocClkVoltage_GPU, - HocClkVoltage_EMCVDDQ_MarikoOnly, - HocClkVoltage_Display, - HocClkVoltage_Battery, - HocClkVoltage_EnumMax, -} HocClkVoltage; - -typedef enum -{ - SysClkProfile_Handheld = 0, - SysClkProfile_HandheldCharging, - SysClkProfile_HandheldChargingUSB, - SysClkProfile_HandheldChargingOfficial, - SysClkProfile_Docked, - SysClkProfile_EnumMax -} SysClkProfile; - -typedef enum -{ - SysClkModule_CPU = 0, - SysClkModule_GPU, - SysClkModule_MEM, - HorizonOCModule_Governor, - HorizonOCModule_Display, - SysClkModule_EnumMax, -} SysClkModule; - -typedef enum -{ - SysClkThermalSensor_SOC = 0, - SysClkThermalSensor_PCB, - SysClkThermalSensor_Skin, - HorizonOCThermalSensor_Battery, - HorizonOCThermalSensor_PMIC, - SysClkThermalSensor_EnumMax -} SysClkThermalSensor; - -typedef enum -{ - SysClkPowerSensor_Now = 0, - SysClkPowerSensor_Avg, - SysClkPowerSensor_EnumMax -} SysClkPowerSensor; - -typedef enum -{ - SysClkPartLoad_EMC = 0, - SysClkPartLoad_EMCCpu, - HocClkPartLoad_GPU, - HocClkPartLoad_CPUMax, - HocClkPartLoad_BAT, - HocClkPartLoad_FAN, - SysClkPartLoad_EnumMax -} SysClkPartLoad; - -typedef enum { - HorizonOCSpeedo_CPU = 0, - HorizonOCSpeedo_GPU, - HorizonOCSpeedo_SOC, - HorizonOCSpeedo_EnumMax, -} HorizonOCSpeedo; - -typedef enum { - GPUUVLevel_NoUV = 0, - GPUUVLevel_SLT, - GPUUVLevel_HiOPT, - GPUUVLevel_EnumMax, -} GPUUndervoltLevel; - -enum { - DVFSMode_Disabled = 0, - DVFSMode_Hijack, - // DVFSMode_OfficialService, - // DVFSMode_Hack, - DVFSMode_EnumMax, -}; - -typedef enum { - GpuSchedulingMode_DoNotOverride = 0, - GpuSchedulingMode_Enabled, - GpuSchedulingMode_Disabled, - GpuSchedulingMode_EnumMax, -} GpuSchedulingMode; - -typedef enum { - GpuSchedulingOverrideMethod_Ini = 0, - GpuSchedulingOverrideMethod_NvService, - GpuSchedulingOverrideMethod_EnumMax, -} GpuSchedulingOverrideMethod; -typedef enum { - ComponentGovernor_DoNotOverride = 0, - ComponentGovernor_Disabled = 1, - ComponentGovernor_Enabled = 2, - ComponentGovernor_EnumMax, -} ComponentGovernorState; -typedef enum { - RamDisplayMode_VDD2VDDQ = 0, - RamDisplayMode_VDD2Usage, - RamDisplayMode_VDDQUsage, - RamDisplayMode_EnumMax, -} RamDisplayMode; - -#define SYSCLK_ENUM_VALID(n, v) ((v) < n##_EnumMax) - -// Packed u32 -// Bits 0-7 - CPU -// Bits 8-15 - GPU -// Bits 16-23 - VRR -// Bits 24-32 - unused - -inline u32 GovernorStatePack(u8 cpu, u8 gpu, u8 vrr) { - return (u32)cpu | ((u32)gpu << 8) | ((u32)vrr << 16); -} -inline u8 GovernorStateCpu(u32 p) { - return (u8)(p & 0xFF); -} -inline u8 GovernorStateGpu(u32 p) { - return (u8)((p >> 8) & 0xFF); -} -inline u8 GovernorStateVrr(u32 p) { - return (u8)((p >> 16) & 0xFF); -} - -static inline const char* sysclkFormatModule(SysClkModule module, bool pretty) -{ - switch(module) - { - case SysClkModule_CPU: - return pretty ? "CPU" : "cpu"; - case SysClkModule_GPU: - return pretty ? "GPU" : "gpu"; - case SysClkModule_MEM: - return pretty ? "Memory" : "mem"; - case HorizonOCModule_Display: - return pretty ? "Display" : "display"; - case HorizonOCModule_Governor: - return pretty ? "Governor" : "governor"; - default: - return "null"; - } -} - -static inline const char* sysclkFormatThermalSensor(SysClkThermalSensor thermSensor, bool pretty) -{ - switch(thermSensor) - { - case SysClkThermalSensor_SOC: - return pretty ? "SOC" : "soc"; - case SysClkThermalSensor_PCB: - return pretty ? "PCB" : "pcb"; - case SysClkThermalSensor_Skin: - return pretty ? "Skin" : "skin"; - case HorizonOCThermalSensor_Battery: - return pretty ? "BAT" : "battery"; - case HorizonOCThermalSensor_PMIC: - return pretty ? "PMIC" : "pmic"; - - default: - return NULL; - } -} - -static inline const char* sysclkFormatPowerSensor(SysClkPowerSensor powSensor, bool pretty) -{ - switch(powSensor) - { - case SysClkPowerSensor_Now: - return pretty ? "Now" : "now"; - case SysClkPowerSensor_Avg: - return pretty ? "Avg" : "avg"; - default: - return NULL; - } -} - -static inline const char* sysclkFormatProfile(SysClkProfile profile, bool pretty) -{ - switch(profile) - { - case SysClkProfile_Docked: - return pretty ? "Docked" : "docked"; - case SysClkProfile_Handheld: - return pretty ? "Handheld" : "handheld"; - case SysClkProfile_HandheldCharging: - return pretty ? "Charging" : "handheld_charging"; - case SysClkProfile_HandheldChargingUSB: - return pretty ? "USB Charger" : "handheld_charging_usb"; - case SysClkProfile_HandheldChargingOfficial: - return pretty ? "PD Charger" : "handheld_charging_official"; - default: - return NULL; - } -} - - -static inline const char* hocClkFormatVoltage(HocClkVoltage voltage, bool pretty) -{ - switch(voltage) - { - case HocClkVoltage_CPU: - return pretty ? "CPU" : "cpu"; - case HocClkVoltage_GPU: - return pretty ? "GPU" : "gpu"; - case HocClkVoltage_EMCVDD2: - return pretty ? "VDD2" : "emcvdd2"; - case HocClkVoltage_EMCVDDQ_MarikoOnly: - return pretty ? "VDDQ" : "vddq"; - case HocClkVoltage_SOC: - return pretty ? "SOC" : "soc"; - case HocClkVoltage_Display: - return pretty ? "Display" : "display"; - default: - return NULL; - } -} \ No newline at end of file diff --git a/Source/sys-clk/common/include/sysclk/client/ipc.h b/Source/sys-clk/common/include/sysclk/client/ipc.h deleted file mode 100644 index 242e3d1a..00000000 --- a/Source/sys-clk/common/include/sysclk/client/ipc.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include "types.h" -#include "../config.h" -#include "../board.h" -#include "../ipc.h" - -bool sysclkIpcRunning(); -Result sysclkIpcInitialize(void); -void sysclkIpcExit(void); - -Result sysclkIpcGetAPIVersion(u32* out_ver); -Result sysclkIpcGetVersionString(char* out, size_t len); -Result sysclkIpcGetCurrentContext(SysClkContext* out_context); -Result sysclkIpcGetProfileCount(u64 tid, u8* out_count); -Result sysclkIpcSetEnabled(bool enabled); -Result sysclkIpcExitCmd(); -Result sysclkIpcSetOverride(SysClkModule module, u32 hz); -Result sysclkIpcGetProfiles(u64 tid, SysClkTitleProfileList* out_profiles); -Result sysclkIpcSetProfiles(u64 tid, SysClkTitleProfileList* profiles); -Result sysclkIpcGetConfigValues(SysClkConfigValueList* out_configValues); -Result sysclkIpcSetConfigValues(SysClkConfigValueList* configValues); -Result sysclkIpcGetFreqList(SysClkModule module, u32* list, u32 maxCount, u32* outCount); -Result hocClkIpcSetKipData(); -Result hocClkIpcGetKipData(); - -static inline Result sysclkIpcRemoveOverride(SysClkModule module) -{ - return sysclkIpcSetOverride(module, 0); -} diff --git a/Source/sys-clk/common/include/sysclk/client/types.h b/Source/sys-clk/common/include/sysclk/client/types.h deleted file mode 100644 index b9feb9ba..00000000 --- a/Source/sys-clk/common/include/sysclk/client/types.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __SWITCH__ - -#include -#include - -#else - -#define R_FAILED(res) ((res) != 0) -#define R_SUCCEEDED(res) ((res) == 0) - -typedef std::uint32_t Result; -typedef std::uint32_t u32; -typedef std::int32_t s32; -typedef std::uint64_t u64; -typedef std::uint8_t u8; - -#endif diff --git a/Source/sys-clk/common/include/sysclk/clock_manager.h b/Source/sys-clk/common/include/sysclk/clock_manager.h deleted file mode 100644 index a24a0e48..00000000 --- a/Source/sys-clk/common/include/sysclk/clock_manager.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include "board.h" - -typedef struct -{ - uint64_t applicationId; - SysClkProfile profile; - uint32_t freqs[SysClkModule_EnumMax]; - uint32_t realFreqs[SysClkModule_EnumMax]; - uint32_t overrideFreqs[SysClkModule_EnumMax]; - uint32_t temps[SysClkThermalSensor_EnumMax]; - int32_t power[SysClkPowerSensor_EnumMax]; - uint32_t partLoad[SysClkPartLoad_EnumMax]; - uint32_t voltages[HocClkVoltage_EnumMax]; - u16 speedos[HorizonOCSpeedo_EnumMax]; - u16 iddq[HorizonOCSpeedo_EnumMax]; - u16 waferX; - u16 waferY; - - // Misc stuff - GpuSchedulingMode gpuSchedulingMode; - bool isSysDockInstalled; - bool isSaltyNXInstalled; - bool isUsingRetroSuper; - u8 maxDisplayFreq; - u8 dramID; - bool isDram8GB; - - // FPS / Resolution - u8 fps; - u16 resolutionHeight; -} SysClkContext; - -typedef struct -{ - union { - uint32_t mhz[+SysClkProfile_EnumMax * +SysClkModule_EnumMax]; - uint32_t mhzMap[+SysClkProfile_EnumMax][+SysClkModule_EnumMax]; - }; -} SysClkTitleProfileList; - -#define SYSCLK_FREQ_LIST_MAX 32 - -#define GLOBAL_PROFILE_ID 0xA111111111111111 \ No newline at end of file diff --git a/Source/sys-clk/common/include/sysclk/config.h b/Source/sys-clk/common/include/sysclk/config.h deleted file mode 100644 index 9f5da1e9..00000000 --- a/Source/sys-clk/common/include/sysclk/config.h +++ /dev/null @@ -1,594 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include - -typedef enum { - SysClkConfigValue_PollingIntervalMs = 0, - SysClkConfigValue_TempLogIntervalMs, - SysClkConfigValue_FreqLogIntervalMs, - SysClkConfigValue_PowerLogIntervalMs, - SysClkConfigValue_CsvWriteIntervalMs, - - HocClkConfigValue_UncappedClocks, - HocClkConfigValue_OverwriteBoostMode, - - HocClkConfigValue_EristaMaxCpuClock, - HocClkConfigValue_MarikoMaxCpuClock, - - HocClkConfigValue_ThermalThrottle, - HocClkConfigValue_ThermalThrottleThreshold, - - HocClkConfigValue_HandheldTDP, - HocClkConfigValue_HandheldTDPLimit, - - HocClkConfigValue_LiteTDPLimit, - - HorizonOCConfigValue_BatteryChargeCurrent, - - HorizonOCConfigValue_OverwriteRefreshRate, - HorizonOCConfigValue_MaxDisplayClockH, - - HorizonOCConfigValue_DVFSMode, - HorizonOCConfigValue_DVFSOffset, - HorizonOCConfigValue_LiveCpuUv, - HorizonOCConfigValue_EnableExperimentalSettings, - - HorizonOCConfigValue_GPUScheduling, - HorizonOCConfigValue_GPUSchedulingMethod, - - HorizonOCConfigValue_RAMVoltUsageDisplayMode, - HorizonOCConfigValue_CpuGovernorMinimumFreq, - - KipConfigValue_custRev, - // KipConfigValue_mtcConf, - KipConfigValue_hpMode, - - KipConfigValue_commonEmcMemVolt, - KipConfigValue_eristaEmcMaxClock, - KipConfigValue_eristaEmcMaxClock1, - KipConfigValue_eristaEmcMaxClock2, - KipConfigValue_marikoEmcMaxClock, - KipConfigValue_marikoEmcVddqVolt, - KipConfigValue_emcDvbShift, - - KipConfigValue_t1_tRCD, - KipConfigValue_t2_tRP, - KipConfigValue_t3_tRAS, - KipConfigValue_t4_tRRD, - KipConfigValue_t5_tRFC, - KipConfigValue_t6_tRTW, - KipConfigValue_t7_tWTR, - KipConfigValue_t8_tREFI, - KipConfigValue_mem_burst_read_latency, - KipConfigValue_mem_burst_write_latency, - - KipConfigValue_eristaCpuUV, - KipConfigValue_eristaCpuVmin, - KipConfigValue_eristaCpuMaxVolt, - KipConfigValue_eristaCpuUnlock, - - KipConfigValue_marikoCpuUVLow, - KipConfigValue_marikoCpuUVHigh, - KipConfigValue_tableConf, - KipConfigValue_marikoCpuLowVmin, - KipConfigValue_marikoCpuHighVmin, - KipConfigValue_marikoCpuMaxVolt, - KipConfigValue_marikoCpuMaxClock, - KipConfigValue_eristaCpuBoostClock, - KipConfigValue_marikoCpuBoostClock, - - KipConfigValue_eristaGpuUV, - KipConfigValue_eristaGpuVmin, - - KipConfigValue_marikoGpuUV, - KipConfigValue_marikoGpuVmin, - KipConfigValue_marikoGpuVmax, - - KipConfigValue_commonGpuVoltOffset, - KipConfigValue_gpuSpeedo, - - KipConfigValue_g_volt_76800, - KipConfigValue_g_volt_153600, - KipConfigValue_g_volt_230400, - KipConfigValue_g_volt_307200, - KipConfigValue_g_volt_384000, - KipConfigValue_g_volt_460800, - KipConfigValue_g_volt_537600, - KipConfigValue_g_volt_614400, - KipConfigValue_g_volt_691200, - KipConfigValue_g_volt_768000, - KipConfigValue_g_volt_844800, - KipConfigValue_g_volt_921600, - KipConfigValue_g_volt_998400, - KipConfigValue_g_volt_1075200, - KipConfigValue_g_volt_1152000, - KipConfigValue_g_volt_1228800, - KipConfigValue_g_volt_1267200, - KipConfigValue_g_volt_1305600, - KipConfigValue_g_volt_1344000, - KipConfigValue_g_volt_1382400, - KipConfigValue_g_volt_1420800, - KipConfigValue_g_volt_1459200, - KipConfigValue_g_volt_1497600, - KipConfigValue_g_volt_1536000, - - KipConfigValue_g_volt_e_76800, - KipConfigValue_g_volt_e_115200, - KipConfigValue_g_volt_e_153600, - KipConfigValue_g_volt_e_192000, - KipConfigValue_g_volt_e_230400, - KipConfigValue_g_volt_e_268800, - KipConfigValue_g_volt_e_307200, - KipConfigValue_g_volt_e_345600, - KipConfigValue_g_volt_e_384000, - KipConfigValue_g_volt_e_422400, - KipConfigValue_g_volt_e_460800, - KipConfigValue_g_volt_e_499200, - KipConfigValue_g_volt_e_537600, - KipConfigValue_g_volt_e_576000, - KipConfigValue_g_volt_e_614400, - KipConfigValue_g_volt_e_652800, - KipConfigValue_g_volt_e_691200, - KipConfigValue_g_volt_e_729600, - KipConfigValue_g_volt_e_768000, - KipConfigValue_g_volt_e_806400, - KipConfigValue_g_volt_e_844800, - KipConfigValue_g_volt_e_883200, - KipConfigValue_g_volt_e_921600, - KipConfigValue_g_volt_e_960000, - KipConfigValue_g_volt_e_998400, - KipConfigValue_g_volt_e_1036800, - KipConfigValue_g_volt_e_1075200, - - KipConfigValue_t6_tRTW_fine_tune, - KipConfigValue_t7_tWTR_fine_tune, - - KipCrc32, - HocClkConfigValue_IsFirstLoad, - SysClkConfigValue_EnumMax, -} SysClkConfigValue; - -typedef struct { - uint64_t values[SysClkConfigValue_EnumMax]; -} SysClkConfigValueList; - -static inline const char* sysclkFormatConfigValue(SysClkConfigValue val, bool pretty) -{ - switch(val) - { - case SysClkConfigValue_PollingIntervalMs: - return pretty ? "Polling Interval (ms)" : "poll_interval_ms"; - case SysClkConfigValue_TempLogIntervalMs: - return pretty ? "Temperature logging interval (ms)" : "temp_log_interval_ms"; - case SysClkConfigValue_FreqLogIntervalMs: - return pretty ? "Frequency logging interval (ms)" : "freq_log_interval_ms"; - case SysClkConfigValue_PowerLogIntervalMs: - return pretty ? "Power logging interval (ms)" : "power_log_interval_ms"; - case SysClkConfigValue_CsvWriteIntervalMs: - return pretty ? "CSV write interval (ms)" : "csv_write_interval_ms"; - - case HocClkConfigValue_UncappedClocks: - return pretty ? "Uncapped Clocks" : "uncapped_clocks"; - case HocClkConfigValue_OverwriteBoostMode: - return pretty ? "Overwrite Boost Mode" : "ow_boost"; - - case HocClkConfigValue_EristaMaxCpuClock: - return pretty ? "CPU Max Clock" : "cpu_max_e"; - - case HocClkConfigValue_MarikoMaxCpuClock: - return pretty ? "CPU Max Display Clock" : "cpu_max_m"; - - case HocClkConfigValue_ThermalThrottle: - return pretty ? "Thermal Throttle" : "thermal_throttle"; - - case HocClkConfigValue_ThermalThrottleThreshold: - return pretty ? "Thermal Throttle Threshold" : "thermal_throttle_threshold"; - - case HocClkConfigValue_HandheldTDP: - return pretty ? "Handheld TDP" : "handheld_tdp"; - - case HocClkConfigValue_HandheldTDPLimit: - return pretty ? "Handheld TDP Limit" : "tdp_limit"; - - case HocClkConfigValue_LiteTDPLimit: - return pretty ? "Handheld TDP Limit" : "tdp_limit_l"; - - case HorizonOCConfigValue_BatteryChargeCurrent: - return pretty ? "Battery Charge Current" : "bat_charge_current"; - - case HorizonOCConfigValue_OverwriteRefreshRate: - return pretty ? "Display Refresh Rate Changing" : "drr_changing"; - - case HorizonOCConfigValue_MaxDisplayClockH: - return pretty ? "Max Display Clock (Handheld)" : "drr_max_clock"; - - case HorizonOCConfigValue_DVFSMode: - return pretty ? "DVFS Mode" : "dvfs_mode"; - - case HorizonOCConfigValue_DVFSOffset: - return pretty ? "DVFS Offset" : "dvfs_offset"; - - case HorizonOCConfigValue_GPUScheduling: - return pretty ? "GPU Scheduling" : "gpu_scheduling"; - - case HorizonOCConfigValue_GPUSchedulingMethod: - return pretty ? "GPU Scheduling Method" : "gpu_sched_method"; - - case HorizonOCConfigValue_LiveCpuUv: - return pretty ? "Live CPU Undervolt" : "live_cpu_uv"; - - case HorizonOCConfigValue_EnableExperimentalSettings: - return pretty ? "Enable Experimental Settings" : "enable_experimental_settings"; - - case HorizonOCConfigValue_RAMVoltUsageDisplayMode: - return pretty ? "RAM Voltage / Usage Display Mode" : "ram_volt_usage_display_mode"; - case HorizonOCConfigValue_CpuGovernorMinimumFreq: - return pretty ? "CPU Governor Minimum Frequency" : "cpu_gov_min_freq"; - // KIP config values - case KipConfigValue_custRev: - return pretty ? "Custom Revision" : "kip_cust_rev"; - // case KipConfigValue_mtcConf: - // return pretty ? "MTC Config" : "kip_mtc_conf"; - case KipConfigValue_hpMode: - return pretty ? "HP Mode" : "kip_hp_mode"; - - // EMC - case KipConfigValue_commonEmcMemVolt: - return pretty ? "Common EMC/MEM Voltage" : "common_emc_mem_volt"; - case KipConfigValue_eristaEmcMaxClock: - return pretty ? "Erista EMC Max Clock 1" : "erista_emc_max_clock"; - case KipConfigValue_eristaEmcMaxClock1: - return pretty ? "Erista EMC Max Clock 2" : "erista_emc_max_clock1"; - case KipConfigValue_eristaEmcMaxClock2: - return pretty ? "Erista EMC Max Clock 3" : "erista_emc_max_clock2"; - case KipConfigValue_marikoEmcMaxClock: - return pretty ? "Mariko EMC Max Clock" : "mariko_emc_max_clock"; - case KipConfigValue_marikoEmcVddqVolt: - return pretty ? "Mariko EMC VDDQ Voltage" : "mariko_emc_vddq_volt"; - case KipConfigValue_emcDvbShift: - return pretty ? "EMC DVB Shift" : "emc_dvb_shift"; - - // Memory timings - case KipConfigValue_t1_tRCD: - return pretty ? "t1 - tRCD" : "t1_trcd"; - case KipConfigValue_t2_tRP: - return pretty ? "t2 - tRP" : "t2_trp"; - case KipConfigValue_t3_tRAS: - return pretty ? "t3 - tRAS" : "t3_tras"; - case KipConfigValue_t4_tRRD: - return pretty ? "t4 - tRRD" : "t4_trrd"; - case KipConfigValue_t5_tRFC: - return pretty ? "t5 - tRFC" : "t5_trfc"; - case KipConfigValue_t6_tRTW: - return pretty ? "t6 - tRTW" : "t6_trtw"; - case KipConfigValue_t7_tWTR: - return pretty ? "t7 - tWTR" : "t7_twtr"; - case KipConfigValue_t8_tREFI: - return pretty ? "t8 - tREFI" : "t8_trefi"; - case KipConfigValue_mem_burst_read_latency: - return pretty ? "Memory Burst Read Latency" : "mem_burst_read_latency"; - case KipConfigValue_mem_burst_write_latency: - return pretty ? "Memory Burst Write Latency" : "mem_burst_write_latency"; - - // CPU – Erista - case KipConfigValue_eristaCpuUV: - return pretty ? "Erista CPU Undervolt" : "erista_cpu_uv"; - case KipConfigValue_eristaCpuVmin: - return pretty ? "Erista CPU vMin" : "erista_cpu_vmin"; - case KipConfigValue_eristaCpuMaxVolt: - return pretty ? "Erista CPU Max Voltage" : "erista_cpu_max_volt"; - case KipConfigValue_eristaCpuUnlock: - return pretty ? "Erista CPU Unlock" : "erista_cpu_unlock"; - - // CPU – Mariko - case KipConfigValue_marikoCpuUVLow: - return pretty ? "Mariko CPU Undervolt (Low)" : "mariko_cpu_uv_low"; - case KipConfigValue_marikoCpuUVHigh: - return pretty ? "Mariko CPU Undervolt (High)" : "mariko_cpu_uv_high"; - case KipConfigValue_tableConf: - return pretty ? "Table Config" : "kip_table_conf"; - case KipConfigValue_marikoCpuLowVmin: - return pretty ? "Mariko CPU Low Vmin" : "mariko_cpu_low_vmin"; - case KipConfigValue_marikoCpuHighVmin: - return pretty ? "Mariko CPU High Vmin" : "mariko_cpu_high_vmin"; - case KipConfigValue_marikoCpuMaxVolt: - return pretty ? "Mariko CPU Max Voltage" : "mariko_cpu_max_volt"; - - case KipConfigValue_eristaCpuBoostClock: - return pretty ? "Erista CPU Boost Clock" : "erista_cpu_boost_clock"; - case KipConfigValue_marikoCpuBoostClock: - return pretty ? "Mariko CPU Boost Clock" : "mariko_cpu_boost_clock"; - - case KipConfigValue_marikoCpuMaxClock: - return pretty ? "Mariko CPU Max Clock" : "mariko_cpu_max_clock"; - - // GPU – Erista - case KipConfigValue_eristaGpuUV: - return pretty ? "Erista GPU Undervolt" : "erista_gpu_uv"; - case KipConfigValue_eristaGpuVmin: - return pretty ? "Erista GPU Vmin" : "erista_gpu_vmin"; - - // GPU – Mariko - case KipConfigValue_marikoGpuUV: - return pretty ? "Mariko GPU Undervolt" : "mariko_gpu_uv"; - case KipConfigValue_marikoGpuVmin: - return pretty ? "Mariko GPU Vmin" : "mariko_gpu_vmin"; - case KipConfigValue_marikoGpuVmax: - return pretty ? "Mariko GPU Vmax" : "mariko_gpu_vmax"; - - case KipConfigValue_commonGpuVoltOffset: - return pretty ? "Common GPU Voltage Offset" : "common_gpu_volt_offset"; - case KipConfigValue_gpuSpeedo: - return pretty ? "GPU Speedo" : "gpu_speedo"; - - // Mariko GPU voltages (24) - case KipConfigValue_g_volt_76800: return pretty ? "Mariko GPU Volt 76 MHz" : "g_volt_76800"; - case KipConfigValue_g_volt_153600: return pretty ? "Mariko GPU Volt 153 MHz" : "g_volt_153600"; - case KipConfigValue_g_volt_230400: return pretty ? "Mariko GPU Volt 230 MHz" : "g_volt_230400"; - case KipConfigValue_g_volt_307200: return pretty ? "Mariko GPU Volt 307 MHz" : "g_volt_307200"; - case KipConfigValue_g_volt_384000: return pretty ? "Mariko GPU Volt 384 MHz" : "g_volt_384000"; - case KipConfigValue_g_volt_460800: return pretty ? "Mariko GPU Volt 460 MHz" : "g_volt_460800"; - case KipConfigValue_g_volt_537600: return pretty ? "Mariko GPU Volt 537 MHz" : "g_volt_537600"; - case KipConfigValue_g_volt_614400: return pretty ? "Mariko GPU Volt 614 MHz" : "g_volt_614400"; - case KipConfigValue_g_volt_691200: return pretty ? "Mariko GPU Volt 691 MHz" : "g_volt_691200"; - case KipConfigValue_g_volt_768000: return pretty ? "Mariko GPU Volt 768 MHz" : "g_volt_768000"; - case KipConfigValue_g_volt_844800: return pretty ? "Mariko GPU Volt 844 MHz" : "g_volt_844800"; - case KipConfigValue_g_volt_921600: return pretty ? "Mariko GPU Volt 921 MHz" : "g_volt_921600"; - case KipConfigValue_g_volt_998400: return pretty ? "Mariko GPU Volt 998 MHz" : "g_volt_998400"; - case KipConfigValue_g_volt_1075200: return pretty ? "Mariko GPU Volt 1075 MHz" : "g_volt_1075200"; - case KipConfigValue_g_volt_1152000: return pretty ? "Mariko GPU Volt 1152 MHz" : "g_volt_1152000"; - case KipConfigValue_g_volt_1228800: return pretty ? "Mariko GPU Volt 1228 MHz" : "g_volt_1228800"; - case KipConfigValue_g_volt_1267200: return pretty ? "Mariko GPU Volt 1267 MHz" : "g_volt_1267200"; - case KipConfigValue_g_volt_1305600: return pretty ? "Mariko GPU Volt 1305 MHz" : "g_volt_1305600"; - case KipConfigValue_g_volt_1344000: return pretty ? "Mariko GPU Volt 1344 MHz" : "g_volt_1344000"; - case KipConfigValue_g_volt_1382400: return pretty ? "Mariko GPU Volt 1382 MHz" : "g_volt_1382400"; - case KipConfigValue_g_volt_1420800: return pretty ? "Mariko GPU Volt 1420 MHz" : "g_volt_1420800"; - case KipConfigValue_g_volt_1459200: return pretty ? "Mariko GPU Volt 1459 MHz" : "g_volt_1459200"; - case KipConfigValue_g_volt_1497600: return pretty ? "Mariko GPU Volt 1497 MHz" : "g_volt_1497600"; - case KipConfigValue_g_volt_1536000: return pretty ? "Mariko GPU Volt 1536 MHz" : "g_volt_1536000"; - - // Erista GPU voltages (27) - case KipConfigValue_g_volt_e_76800: return pretty ? "Erista GPU Volt 76 MHz" : "g_volt_e_76800"; - case KipConfigValue_g_volt_e_115200: return pretty ? "Erista GPU Volt 115 MHz" : "g_volt_e_115200"; - case KipConfigValue_g_volt_e_153600: return pretty ? "Erista GPU Volt 153 MHz" : "g_volt_e_153600"; - case KipConfigValue_g_volt_e_192000: return pretty ? "Erista GPU Volt 192 MHz" : "g_volt_e_192000"; - case KipConfigValue_g_volt_e_230400: return pretty ? "Erista GPU Volt 230 MHz" : "g_volt_e_230400"; - case KipConfigValue_g_volt_e_268800: return pretty ? "Erista GPU Volt 268 MHz" : "g_volt_e_268800"; - case KipConfigValue_g_volt_e_307200: return pretty ? "Erista GPU Volt 307 MHz" : "g_volt_e_307200"; - case KipConfigValue_g_volt_e_345600: return pretty ? "Erista GPU Volt 345 MHz" : "g_volt_e_345600"; - case KipConfigValue_g_volt_e_384000: return pretty ? "Erista GPU Volt 384 MHz" : "g_volt_e_384000"; - case KipConfigValue_g_volt_e_422400: return pretty ? "Erista GPU Volt 422 MHz" : "g_volt_e_422400"; - case KipConfigValue_g_volt_e_460800: return pretty ? "Erista GPU Volt 460 MHz" : "g_volt_e_460800"; - case KipConfigValue_g_volt_e_499200: return pretty ? "Erista GPU Volt 499 MHz" : "g_volt_e_499200"; - case KipConfigValue_g_volt_e_537600: return pretty ? "Erista GPU Volt 537 MHz" : "g_volt_e_537600"; - case KipConfigValue_g_volt_e_576000: return pretty ? "Erista GPU Volt 576 MHz" : "g_volt_e_576000"; - case KipConfigValue_g_volt_e_614400: return pretty ? "Erista GPU Volt 614 MHz" : "g_volt_e_614400"; - case KipConfigValue_g_volt_e_652800: return pretty ? "Erista GPU Volt 652 MHz" : "g_volt_e_652800"; - case KipConfigValue_g_volt_e_691200: return pretty ? "Erista GPU Volt 691 MHz" : "g_volt_e_691200"; - case KipConfigValue_g_volt_e_729600: return pretty ? "Erista GPU Volt 729 MHz" : "g_volt_e_729600"; - case KipConfigValue_g_volt_e_768000: return pretty ? "Erista GPU Volt 768 MHz" : "g_volt_e_768000"; - case KipConfigValue_g_volt_e_806400: return pretty ? "Erista GPU Volt 806 MHz" : "g_volt_e_806400"; - case KipConfigValue_g_volt_e_844800: return pretty ? "Erista GPU Volt 844 MHz" : "g_volt_e_844800"; - case KipConfigValue_g_volt_e_883200: return pretty ? "Erista GPU Volt 883 MHz" : "g_volt_e_883200"; - case KipConfigValue_g_volt_e_921600: return pretty ? "Erista GPU Volt 921 MHz" : "g_volt_e_921600"; - case KipConfigValue_g_volt_e_960000: return pretty ? "Erista GPU Volt 960 MHz" : "g_volt_e_960000"; - case KipConfigValue_g_volt_e_998400: return pretty ? "Erista GPU Volt 998 MHz" : "g_volt_e_998400"; - case KipConfigValue_g_volt_e_1036800: return pretty ? "Erista GPU Volt 1036 MHz" : "g_volt_e_1036800"; - case KipConfigValue_g_volt_e_1075200: return pretty ? "Erista GPU Volt 1075 MHz" : "g_volt_e_1075200"; - case KipConfigValue_t6_tRTW_fine_tune: return pretty ? "t6 - tRTW Fine Tune" : "t6_tRTW_fine_fune"; - case KipConfigValue_t7_tWTR_fine_tune: return pretty ? "t7 - tWTR Fine Tune" : "t7_tWTR_fine_tune"; - case KipCrc32: - return pretty ? "CRC32" : "crc32"; - case HocClkConfigValue_IsFirstLoad: - return pretty ? "Is First Load" : "is_first_load"; - default: - return pretty ? "[cfg] no enum format string" : "err_no_format_string"; - } -} - -static inline uint64_t sysclkDefaultConfigValue(SysClkConfigValue val) -{ - switch(val) - { - case SysClkConfigValue_PollingIntervalMs: - return 300ULL; - case SysClkConfigValue_TempLogIntervalMs: - case SysClkConfigValue_FreqLogIntervalMs: - case SysClkConfigValue_PowerLogIntervalMs: - case SysClkConfigValue_CsvWriteIntervalMs: - case HocClkConfigValue_UncappedClocks: - case HocClkConfigValue_OverwriteBoostMode: - case HorizonOCConfigValue_BatteryChargeCurrent: - case HorizonOCConfigValue_OverwriteRefreshRate: - case HorizonOCConfigValue_GPUScheduling: - case HorizonOCConfigValue_LiveCpuUv: - case HorizonOCConfigValue_GPUSchedulingMethod: - return 0ULL; - case HocClkConfigValue_EristaMaxCpuClock: - return 1785ULL; - - case HocClkConfigValue_MarikoMaxCpuClock: - return 1963ULL; - - case HocClkConfigValue_ThermalThrottle: - case HocClkConfigValue_HandheldTDP: - case HocClkConfigValue_IsFirstLoad: - case HorizonOCConfigValue_DVFSMode: - return 1ULL; - case HocClkConfigValue_ThermalThrottleThreshold: - return 70ULL; - case HocClkConfigValue_HandheldTDPLimit: - return 9600ULL; // 8600mW will trigger on erista stock, so raise it a bit - case HocClkConfigValue_LiteTDPLimit: - return 6400ULL; // 0.5C - case HorizonOCConfigValue_CpuGovernorMinimumFreq: - return 612000000ULL; // 612MHz - case HorizonOCConfigValue_MaxDisplayClockH: - return 60ULL; - default: - return 0ULL; - } -} - -static inline uint64_t sysclkValidConfigValue(SysClkConfigValue val, uint64_t input) -{ - switch(val) - { - case HocClkConfigValue_EristaMaxCpuClock: - case HocClkConfigValue_MarikoMaxCpuClock: - case HocClkConfigValue_ThermalThrottleThreshold: - case HocClkConfigValue_HandheldTDPLimit: - case HocClkConfigValue_LiteTDPLimit: - case SysClkConfigValue_PollingIntervalMs: - case HorizonOCConfigValue_MaxDisplayClockH: - return input > 0; - - case SysClkConfigValue_TempLogIntervalMs: - case SysClkConfigValue_FreqLogIntervalMs: - case SysClkConfigValue_PowerLogIntervalMs: - case SysClkConfigValue_CsvWriteIntervalMs: - case HocClkConfigValue_UncappedClocks: - case HocClkConfigValue_OverwriteBoostMode: - case HocClkConfigValue_ThermalThrottle: - case HocClkConfigValue_HandheldTDP: - case HorizonOCConfigValue_OverwriteRefreshRate: - case HocClkConfigValue_IsFirstLoad: - case HorizonOCConfigValue_EnableExperimentalSettings: - case HorizonOCConfigValue_LiveCpuUv: - case HorizonOCConfigValue_GPUSchedulingMethod: - return (input & 0x1) == input; - - case KipConfigValue_custRev: - // case KipConfigValue_mtcConf: - case KipConfigValue_hpMode: - case KipConfigValue_commonEmcMemVolt: - case KipConfigValue_eristaEmcMaxClock: - case KipConfigValue_eristaEmcMaxClock1: - case KipConfigValue_eristaEmcMaxClock2: - case KipConfigValue_marikoEmcMaxClock: - case KipConfigValue_marikoEmcVddqVolt: - case KipConfigValue_emcDvbShift: - case KipConfigValue_t1_tRCD: - case KipConfigValue_t2_tRP: - case KipConfigValue_t3_tRAS: - case KipConfigValue_t4_tRRD: - case KipConfigValue_t5_tRFC: - case KipConfigValue_t6_tRTW: - case KipConfigValue_t7_tWTR: - case KipConfigValue_t8_tREFI: - case KipConfigValue_mem_burst_read_latency: - case KipConfigValue_mem_burst_write_latency: - case KipConfigValue_eristaCpuUV: - case KipConfigValue_eristaCpuMaxVolt: - case KipConfigValue_marikoCpuUVLow: - case KipConfigValue_marikoCpuUVHigh: - case KipConfigValue_tableConf: - case KipConfigValue_marikoCpuLowVmin: - case KipConfigValue_marikoCpuHighVmin: - case KipConfigValue_marikoCpuMaxVolt: - case KipConfigValue_eristaCpuBoostClock: - case KipConfigValue_marikoCpuBoostClock: - case KipConfigValue_marikoCpuMaxClock: - case KipConfigValue_eristaGpuUV: - case KipConfigValue_eristaGpuVmin: - case KipConfigValue_marikoGpuUV: - case KipConfigValue_marikoGpuVmin: - case KipConfigValue_marikoGpuVmax: - case KipConfigValue_commonGpuVoltOffset: - case KipConfigValue_gpuSpeedo: - case KipConfigValue_g_volt_76800: - case KipConfigValue_g_volt_153600: - case KipConfigValue_g_volt_230400: - case KipConfigValue_g_volt_307200: - case KipConfigValue_g_volt_384000: - case KipConfigValue_g_volt_460800: - case KipConfigValue_g_volt_537600: - case KipConfigValue_g_volt_614400: - case KipConfigValue_g_volt_691200: - case KipConfigValue_g_volt_768000: - case KipConfigValue_g_volt_844800: - case KipConfigValue_g_volt_921600: - case KipConfigValue_g_volt_998400: - case KipConfigValue_g_volt_1075200: - case KipConfigValue_g_volt_1152000: - case KipConfigValue_g_volt_1228800: - case KipConfigValue_g_volt_1267200: - case KipConfigValue_g_volt_1305600: - case KipConfigValue_g_volt_1344000: - case KipConfigValue_g_volt_1382400: - case KipConfigValue_g_volt_1420800: - case KipConfigValue_g_volt_1459200: - case KipConfigValue_g_volt_1497600: - case KipConfigValue_g_volt_1536000: - case KipConfigValue_g_volt_e_76800: - case KipConfigValue_g_volt_e_115200: - case KipConfigValue_g_volt_e_153600: - case KipConfigValue_g_volt_e_192000: - case KipConfigValue_g_volt_e_230400: - case KipConfigValue_g_volt_e_268800: - case KipConfigValue_g_volt_e_307200: - case KipConfigValue_g_volt_e_345600: - case KipConfigValue_g_volt_e_384000: - case KipConfigValue_g_volt_e_422400: - case KipConfigValue_g_volt_e_460800: - case KipConfigValue_g_volt_e_499200: - case KipConfigValue_g_volt_e_537600: - case KipConfigValue_g_volt_e_576000: - case KipConfigValue_g_volt_e_614400: - case KipConfigValue_g_volt_e_652800: - case KipConfigValue_g_volt_e_691200: - case KipConfigValue_g_volt_e_729600: - case KipConfigValue_g_volt_e_768000: - case KipConfigValue_g_volt_e_806400: - case KipConfigValue_g_volt_e_844800: - case KipConfigValue_g_volt_e_883200: - case KipConfigValue_g_volt_e_921600: - case KipConfigValue_g_volt_e_960000: - case KipConfigValue_g_volt_e_998400: - case KipConfigValue_g_volt_e_1036800: - case KipConfigValue_g_volt_e_1075200: - case KipConfigValue_eristaCpuVmin: - case KipConfigValue_eristaCpuUnlock: - case KipConfigValue_t6_tRTW_fine_tune: - case KipConfigValue_t7_tWTR_fine_tune: - case KipCrc32: - case HorizonOCConfigValue_DVFSMode: - case HorizonOCConfigValue_DVFSOffset: - case HorizonOCConfigValue_GPUScheduling: - case HorizonOCConfigValue_RAMVoltUsageDisplayMode: - case HorizonOCConfigValue_CpuGovernorMinimumFreq: - return true; - case HorizonOCConfigValue_BatteryChargeCurrent: - return ((input >= 1024) && (input <= 3072)) || !input; - default: - return false; - } -} \ No newline at end of file diff --git a/Source/sys-clk/common/include/sysclk/errors.h b/Source/sys-clk/common/include/sysclk/errors.h deleted file mode 100644 index a50f1920..00000000 --- a/Source/sys-clk/common/include/sysclk/errors.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#define SYSCLK_ERROR_MODULE 388 -#define SYSCLK_ERROR(desc) ((SYSCLK_ERROR_MODULE & 0x1FF) | (SysClkError_##desc & 0x1FFF)<<9) - -typedef enum -{ - SysClkError_Generic = 0, - SysClkError_ConfigNotLoaded = 1, - SysClkError_ConfigSaveFailed = 2, - // HocClkError_SocThermFail = 3, -} SysClkError; diff --git a/Source/sys-clk/common/include/sysclk/ipc.h b/Source/sys-clk/common/include/sysclk/ipc.h deleted file mode 100644 index 6f0f6146..00000000 --- a/Source/sys-clk/common/include/sysclk/ipc.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include "board.h" -#include "clock_manager.h" - -#define SYSCLK_IPC_API_VERSION 1 -#define SYSCLK_IPC_SERVICE_NAME "hoc:clk" - -enum SysClkIpcCmd -{ - SysClkIpcCmd_GetApiVersion = 0, - SysClkIpcCmd_GetVersionString = 1, - SysClkIpcCmd_GetCurrentContext = 2, - SysClkIpcCmd_Exit = 3, - SysClkIpcCmd_GetProfileCount = 4, - SysClkIpcCmd_GetProfiles = 5, - SysClkIpcCmd_SetProfiles = 6, - SysClkIpcCmd_SetEnabled = 7, - SysClkIpcCmd_SetOverride = 8, - SysClkIpcCmd_GetConfigValues = 9, - SysClkIpcCmd_SetConfigValues = 10, - SysClkIpcCmd_GetFreqList = 11, - HocClkIpcCmd_SetKipData = 12, - HocClkIpcCmd_GetKipData = 13, -}; - - -typedef struct -{ - uint64_t tid; - SysClkTitleProfileList profiles; -} SysClkIpc_SetProfiles_Args; - -typedef struct -{ - SysClkModule module; - uint32_t hz; -} SysClkIpc_SetOverride_Args; - -typedef struct -{ - SysClkModule module; - uint32_t maxCount; -} SysClkIpc_GetFreqList_Args; \ No newline at end of file diff --git a/Source/sys-clk/common/include/sysclk/psm_ext.h b/Source/sys-clk/common/include/sysclk/psm_ext.h deleted file mode 100644 index 8ba88c8a..00000000 --- a/Source/sys-clk/common/include/sysclk/psm_ext.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) KazushiMe - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once - -#include - -typedef enum { - PsmPDC_NewPDO = 1, //Received new Power Data Object - PsmPDC_NoPD = 2, //No Power Delivery source is detected - PsmPDC_AcceptedRDO = 3 //Received and accepted Request Data Object -} PsmChargeInfoPDC; //BM92T series - -typedef enum { - PsmPowerRole_Sink = 1, - PsmPowerRole_Source = 2 -} PsmPowerRole; - -const char* PsmPowerRoleToStr(PsmPowerRole role); - -typedef enum { - PsmInfoChargerType_None = 0, - PsmInfoChargerType_PD = 1, - PsmInfoChargerType_TypeC_1500mA = 2, - PsmInfoChargerType_TypeC_3000mA = 3, - PsmInfoChargerType_DCP = 4, - PsmInfoChargerType_CDP = 5, - PsmInfoChargerType_SDP = 6, - PsmInfoChargerType_Apple_500mA = 7, - PsmInfoChargerType_Apple_1000mA = 8, - PsmInfoChargerType_Apple_2000mA = 9 -} PsmInfoChargerType; - -const char* PsmInfoChargerTypeToStr(PsmInfoChargerType type); - -typedef enum { - PsmFlags_NoHub = BIT(0), //If hub is disconnected - PsmFlags_Rail = BIT(8), //At least one Joy-con is charging from rail - PsmFlags_SPDSRC = BIT(12), //OTG - PsmFlags_ACC = BIT(16) //Accessory -} PsmChargeInfoFlags; - -typedef struct { - int32_t InputCurrentLimit; //Input (Sink) current limit in mA - int32_t VBUSCurrentLimit; //Output (Source/VBUS/OTG) current limit in mA - int32_t ChargeCurrentLimit; //Battery charging current limit in mA (512mA when Docked, 768mA when BatteryTemperature < 17.0 C) - int32_t ChargeVoltageLimit; //Battery charging voltage limit in mV (3952mV when BatteryTemperature >= 51.0 C) - int32_t unk_x10; //Possibly an emum, getting the same value as PowerRole in all tested cases - int32_t unk_x14; //Possibly flags - PsmChargeInfoPDC PDCState; //Power Delivery Controller State - int32_t BatteryTemperature; //Battery temperature in milli C - int32_t RawBatteryCharge; //Raw battery charged capacity per cent-mille (i.e. 100% = 100000 pcm) - int32_t VoltageAvg; //Voltage avg in mV (more in Notes) - int32_t BatteryAge; //Battery age (capacity full / capacity design) per cent-mille (i.e. 100% = 100000 pcm) - PsmPowerRole PowerRole; - PsmInfoChargerType ChargerType; - int32_t ChargerVoltageLimit; //Charger and external device voltage limit in mV - int32_t ChargerCurrentLimit; //Charger and external device current limit in mA - PsmChargeInfoFlags Flags; //Unknown flags -} PsmChargeInfo; - -typedef enum { - Psm_EnableBatteryCharging = 2, - Psm_DisableBatteryCharging = 3, - Psm_EnableFastBatteryCharging = 10, - Psm_DisableFastBatteryCharging = 11, - Psm_GetBatteryChargeInfoFields = 17, -} IPsmServerCmd; - -bool PsmIsChargerConnected(const PsmChargeInfo* info); -bool PsmIsCharging(const PsmChargeInfo* info); - -typedef enum { - PsmBatteryState_Discharging, - PsmBatteryState_ChargingPaused, - PsmBatteryState_FastCharging -} PsmBatteryState; - -PsmBatteryState PsmGetBatteryState(const PsmChargeInfo* info); -const char* PsmGetBatteryStateIcon(const PsmChargeInfo* info); \ No newline at end of file diff --git a/Source/sys-clk/common/src/apm_profile_table.c b/Source/sys-clk/common/src/apm_profile_table.c deleted file mode 100644 index 41e4e520..00000000 --- a/Source/sys-clk/common/src/apm_profile_table.c +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include - -SysClkApmConfiguration sysclk_g_apm_configurations[] = { - {0x00010000, 1020000000, 384000000, 1600000000}, - {0x00010001, 1020000000, 768000000, 1600000000}, - {0x00010002, 1224000000, 691200000, 1600000000}, - {0x00020000, 1020000000, 230400000, 1600000000}, - {0x00020001, 1020000000, 307200000, 1600000000}, - {0x00020002, 1224000000, 230400000, 1600000000}, - {0x00020003, 1020000000, 307200000, 1331200000}, - {0x00020004, 1020000000, 384000000, 1331200000}, - {0x00020005, 1020000000, 307200000, 1065600000}, - {0x00020006, 1020000000, 384000000, 1065600000}, - {0x92220007, 1020000000, 460800000, 1600000000}, - {0x92220008, 1020000000, 460800000, 1331200000}, - {0x92220009, 1785000000, 76800000, 1600000000}, - {0x9222000A, 1785000000, 76800000, 1331200000}, - {0x9222000B, 1020000000, 76800000, 1600000000}, - {0x9222000C, 1020000000, 76800000, 1331200000}, - {0, 0, 0, 0}, -}; - diff --git a/Source/sys-clk/common/src/client/ipc.c b/Source/sys-clk/common/src/client/ipc.c deleted file mode 100644 index f81004f0..00000000 --- a/Source/sys-clk/common/src/client/ipc.c +++ /dev/null @@ -1,169 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#define NX_SERVICE_ASSUME_NON_DOMAIN -#include -#include -#include -#include - -static Service g_sysclkSrv; -static atomic_size_t g_refCnt; - -bool sysclkIpcRunning() -{ - Handle handle; - bool running = R_FAILED(smRegisterService(&handle, smEncodeName(SYSCLK_IPC_SERVICE_NAME), false, 1)); - - if (!running) - { - smUnregisterService(smEncodeName(SYSCLK_IPC_SERVICE_NAME)); - } - - return running; -} - -Result sysclkIpcInitialize(void) -{ - Result rc = 0; - - g_refCnt++; - - if (serviceIsActive(&g_sysclkSrv)) - return 0; - - rc = smGetService(&g_sysclkSrv, SYSCLK_IPC_SERVICE_NAME); - - if (R_FAILED(rc)) sysclkIpcExit(); - - return rc; -} - -void sysclkIpcExit(void) -{ - if (--g_refCnt == 0) - { - serviceClose(&g_sysclkSrv); - } -} - -Result sysclkIpcGetAPIVersion(u32* out_ver) -{ - return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetApiVersion, *out_ver); -} - -Result sysclkIpcGetVersionString(char* out, size_t len) -{ - return serviceDispatch(&g_sysclkSrv, SysClkIpcCmd_GetVersionString, - .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, - .buffers = {{out, len}}, - ); -} - -Result sysclkIpcGetCurrentContext(SysClkContext* out_context) -{ - return serviceDispatch(&g_sysclkSrv, SysClkIpcCmd_GetCurrentContext, - .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, - .buffers = {{out_context, sizeof(SysClkContext)}}, - ); -} - -Result sysclkIpcGetProfileCount(u64 tid, u8* out_count) -{ - return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetProfileCount, tid, *out_count); -} - -Result sysclkIpcSetEnabled(bool enabled) -{ - u8 enabledRaw = (u8)enabled; - return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetEnabled, enabledRaw); -} - -Result sysclkIpcSetOverride(SysClkModule module, u32 hz) -{ - SysClkIpc_SetOverride_Args args = { - .module = module, - .hz = hz - }; - return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetOverride, args); -} - -Result sysclkIpcGetProfiles(u64 tid, SysClkTitleProfileList* out_profiles) -{ - return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_GetProfiles, tid, - .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, - .buffers = {{out_profiles, sizeof(SysClkTitleProfileList)}}, - ); -} - -Result sysclkIpcSetProfiles(u64 tid, SysClkTitleProfileList* profiles) -{ - SysClkIpc_SetProfiles_Args args; - args.tid = tid; - memcpy(&args.profiles, profiles, sizeof(SysClkTitleProfileList)); - return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetProfiles, args); -} - -Result sysclkIpcGetConfigValues(SysClkConfigValueList* out_configValues) -{ - return serviceDispatch(&g_sysclkSrv, SysClkIpcCmd_GetConfigValues, - .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, - .buffers = {{out_configValues, sizeof(SysClkConfigValueList)}}, - ); -} - -Result sysclkIpcSetConfigValues(SysClkConfigValueList* configValues) -{ - return serviceDispatch(&g_sysclkSrv, SysClkIpcCmd_SetConfigValues, - .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_In }, - .buffers = {{configValues, sizeof(SysClkConfigValueList)}}, - ); -} - -Result sysclkIpcGetFreqList(SysClkModule module, u32* list, u32 maxCount, u32* outCount) -{ - SysClkIpc_GetFreqList_Args args = { - .module = module, - .maxCount = maxCount - }; - return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetFreqList, args, *outCount, - .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, - .buffers = {{list, maxCount * sizeof(u32)}}, - ); -} - -Result hocClkIpcSetKipData() -{ - u32 temp = 0; - return serviceDispatchIn(&g_sysclkSrv, HocClkIpcCmd_SetKipData, temp); -} - -Result hocClkIpcGetKipData() -{ - u32 temp = 0; - return serviceDispatchIn(&g_sysclkSrv, HocClkIpcCmd_GetKipData, temp); -} \ No newline at end of file diff --git a/Source/sys-clk/common/src/display_refresh_rate.cpp b/Source/sys-clk/common/src/display_refresh_rate.cpp deleted file mode 100644 index 65936751..00000000 --- a/Source/sys-clk/common/src/display_refresh_rate.cpp +++ /dev/null @@ -1,733 +0,0 @@ -/* - * Copyright (c) Souldbminer, based on reasearch by MasaGratoR and Cooler3D - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#include "display_refresh_rate.h" -#include -#include -#include -#include -#define DSI_CLOCK_HZ 234000000llu -#define NVDISP_GET_MODE2 0x803C021B -#define NVDISP_SET_MODE2 0x403C021C -#define NVDISP_VALIDATE_MODE2 0xC03C021D -#define NVDISP_GET_MODE_DB2 0xEF20021E -#define NVDISP_GET_PANEL_DATA 0xC01C0226 - -#define MAX_REFRESH_RATE 72 - -static DisplayRefreshConfig g_config = {0}; -static bool g_initialized = false; - -static uint8_t g_dockedHighestRefreshRate = 60; -static uint8_t g_dockedLinkRate = 10; -static bool g_wasRetroSuperTurnedOff = false; -static uint32_t g_lastVActive = 1080; -static bool g_canChangeRefreshRateDocked = false; -static uint8_t g_lastVActiveSet = 0; - -static const uint8_t g_dockedRefreshRates[] = {40, 45, 50, 55, 60, 70, 72, 75, 80, 90, 95, 100, 110, 120, 130, 140, 144, 150, 160, 165, 170, 180, 190, 200, 210, 220, 230, 240}; -// Calculate with this tool: - -// https://tomverbeure.github.io/video_timings_calculator?horiz_pixels=1920&vert_pixels=1080&refresh_rate=240&margins=false&interlaced=false&bpc=8&color_fmt=rgb444&video_opt=false&custom_hblank=80&custom_vblank=6 - -/* -typedef struct { - uint16_t hFrontPorch; - uint8_t hSyncWidth; - uint8_t hBackPorch; - uint8_t vFrontPorch; - uint8_t vSyncWidth; - uint8_t vBackPorch; - uint8_t VIC; - uint32_t pixelClock_kHz; -} DockedTimings; -*/ -static const DockedTimings g_dockedTimings1080p[] = { - {8, 32, 40, 7, 8, 6, 0, 88080}, // 40Hz - {8, 32, 40, 9, 8, 6, 0, 99270}, // 45Hz - {528, 44, 148, 4, 5, 36, 31, 148500}, // 50Hz - {8, 32, 40, 15, 8, 6, 0, 121990}, // 55Hz - {88, 44, 148, 4, 5, 36, 16, 148500}, // 60Hz - {8, 32, 40, 22, 8, 6, 0, 156240}, // 70Hz - {8, 32, 40, 23, 8, 6, 0, 160848}, // 72Hz - {8, 32, 40, 25, 8, 6, 0, 167850}, // 75Hz - {8, 32, 40, 28, 8, 6, 0, 179520}, // 80Hz - {8, 32, 40, 33, 8, 6, 0, 202860}, // 90Hz - {8, 32, 40, 36, 8, 6, 0, 214700}, // 95Hz - {528, 44, 148, 4, 5, 36, 64, 297000}, // 100Hz - {8, 32, 40, 44, 8, 6, 0, 250360}, // 110Hz - {88, 44, 148, 4, 5, 36, 63, 297000}, // 120Hz - {8, 32, 40, 55, 8, 6, 0, 298750}, //130Hz CVT-RBv2 - {8, 32, 40, 61, 8, 6, 0, 323400}, //140Hz CVT-RBv2 - {8, 32, 40, 63, 8, 6, 0, 333216}, //144Hz CVT-RBv2 - {8, 32, 40, 67, 8, 6, 0, 348300}, //150Hz CVT-RBv2 - {8, 32, 40, 72, 8, 6, 0, 373120}, //160Hz CVT-RBv2 - {8, 32, 40, 75, 8, 6, 0, 385770}, //165Hz CVT-RBv2 - {8, 32, 40, 78, 8, 6, 0, 398480}, //170Hz CVT-RBv2 - {8, 32, 40, 84, 8, 6, 0, 424080}, //180Hz CVT-RBv2 - {8, 32, 40, 90, 8, 6, 0, 449920}, //190Hz CVT-RBv2 - {8, 32, 40, 96, 8, 6, 0, 476000}, //200Hz CVT-RBv2 - {8, 32, 40, 102, 8, 6, 0, 502320}, //210Hz CVT-RBv2 - {8, 32, 40, 108, 8, 6, 0, 528880}, //220Hz CVT-RBv2 - {8, 32, 40, 114, 8, 6, 0, 555680}, //230Hz CVT-RBv2 - {8, 32, 40, 121, 8, 6, 0, 583200}, //240Hz CVT-RBv2 - // technically you can go to 476hz, but in practice, why would you? -}; - -// These timings *should* work but are untested -static const HandheldTimings g_handheldTimingsRETRO[] = { - {72, 136, 72, 1, 660, 9, 78000}, // 40Hz - {72, 136, 72, 1, 612, 9, 77982}, // 41Hz - {72, 136, 72, 1, 567, 9, 77994}, // 42Hz - {72, 136, 72, 1, 524, 9, 78002}, // 43Hz - {72, 136, 72, 1, 483, 9, 78012}, // 44Hz - {72, 136, 72, 1, 443, 9, 77985}, // 45Hz - {72, 136, 72, 1, 406, 9, 78016}, // 46Hz - {72, 136, 72, 1, 370, 9, 78020}, // 47Hz - {72, 136, 72, 1, 335, 9, 78000}, // 48Hz - {72, 136, 72, 1, 302, 9, 78008}, // 49Hz - {72, 136, 72, 1, 270, 9, 78000}, // 50Hz - {72, 136, 72, 1, 239, 9, 77979}, // 51Hz - {72, 136, 72, 1, 210, 9, 78000}, // 52Hz - {72, 136, 72, 1, 182, 9, 78016}, // 53Hz - {72, 136, 72, 1, 154, 9, 77976}, // 54Hz - {72, 136, 72, 1, 128, 9, 77990}, // 55Hz - {72, 136, 72, 1, 103, 9, 78008}, // 56Hz - {72, 136, 72, 1, 78, 9, 77976}, // 57Hz - {72, 136, 72, 1, 55, 9, 78010}, // 58Hz - {72, 136, 72, 1, 32, 9, 77998}, // 59Hz - {72, 136, 72, 1, 10, 9, 78000}, // 60Hz -}; - -static const MinMaxRefreshRate g_handheldModeRefreshRate = {40, 80}; - -static uint8_t _getDockedRefreshRateIterator(uint32_t refreshRate) { - for (size_t i = 0; i < sizeof(g_dockedRefreshRates) / sizeof(g_dockedRefreshRates[0]); i++) { - if (g_dockedRefreshRates[i] == refreshRate) return i; - } - return 0xFF; -} - -static void _changeOledElvssSettings(const uint32_t* offsets, const uint32_t* value, uint32_t size, uint32_t start) { - if (!g_config.dsiVirtAddr || !value || !size) return; - - volatile uint32_t* dsi = (uint32_t*)g_config.dsiVirtAddr; - - #define DSI_VIDEO_MODE_CONTROL 0x4E - #define DSI_WR_DATA 0xA - #define DSI_TRIGGER 0x13 - #define MIPI_DSI_DCS_SHORT_WRITE_PARAM 0x15 - #define MIPI_DSI_DCS_LONG_WRITE 0x39 - #define MIPI_DCS_PRIV_SM_SET_REG_OFFSET 0xB0 - #define MIPI_DCS_PRIV_SM_SET_ELVSS 0xB1 - - dsi[DSI_VIDEO_MODE_CONTROL] = true; - svcSleepThread(20000000); - - dsi[DSI_WR_DATA] = MIPI_DSI_DCS_LONG_WRITE | (5 << 8); - dsi[DSI_WR_DATA] = 0x5A5A5AE2; - dsi[DSI_WR_DATA] = 0x5A; - dsi[DSI_TRIGGER] = 0; - - for (size_t i = start; i < size; i++) { - dsi[DSI_WR_DATA] = ((MIPI_DCS_PRIV_SM_SET_REG_OFFSET | ((offsets[i] % 0x100) << 8)) << 8) | MIPI_DSI_DCS_SHORT_WRITE_PARAM; - dsi[DSI_TRIGGER] = 0; - dsi[DSI_WR_DATA] = ((MIPI_DCS_PRIV_SM_SET_ELVSS | (value[i] << 8)) << 8) | MIPI_DSI_DCS_SHORT_WRITE_PARAM; - dsi[DSI_TRIGGER] = 0; - } - - dsi[DSI_WR_DATA] = MIPI_DSI_DCS_LONG_WRITE | (5 << 8); - dsi[DSI_WR_DATA] = 0xA55A5AE2; - dsi[DSI_WR_DATA] = 0xA5; - dsi[DSI_TRIGGER] = 0; - - dsi[DSI_VIDEO_MODE_CONTROL] = false; - svcSleepThread(20000000); -} -void DisplayRefresh_SetDockedState(bool isDocked) { - g_config.isDocked = isDocked; -} - -bool DisplayRefresh_Initialize(const DisplayRefreshConfig* config) { - if (!config) return false; - - g_config = *config; - g_initialized = true; - return true; -} - -void DisplayRefresh_CorrectOledGamma(uint32_t refresh_rate) { - static uint32_t last_refresh_rate = 60; - static int counter = 0; - - if (g_config.isDocked || refresh_rate < 45 || refresh_rate > 60) { - last_refresh_rate = 60; - return; - } - - if (counter != 9) { - counter++; - return; - } - counter = 0; - - uint32_t offsets[] = {0x1A, 0x24, 0x25}; - uint32_t values[] = {2, 0, 0x83}; - - if (refresh_rate == 60) { - if (last_refresh_rate == 60) return; - } else if (refresh_rate == 45) { - if (last_refresh_rate == 45) return; - uint32_t vals[] = {4, 1, 0}; - memcpy(values, vals, sizeof(vals)); - } else if (refresh_rate == 50) { - if (last_refresh_rate == 50) return; - uint32_t vals[] = {3, 1, 0}; - memcpy(values, vals, sizeof(vals)); - } else if (refresh_rate == 55) { - if (last_refresh_rate == 55) return; - uint32_t vals[] = {3, 1, 0}; - memcpy(values, vals, sizeof(vals)); - } else { - return; - } - - for (int i = 0; i < 5; i++) { - _changeOledElvssSettings(offsets, values, 3, 0); - } - last_refresh_rate = refresh_rate; -} - -void DisplayRefresh_SetAllowedDockedRatesIPC(uint32_t refreshRates, bool is720p) { - // Function kept for API compatibility but does nothing - (void)refreshRates; - (void)is720p; -} - -uint8_t DisplayRefresh_GetDockedHighestAllowed(void) { - return (g_dockedHighestRefreshRate > 60) ? g_dockedHighestRefreshRate : 60; -} - -static void _getDockedHighestRefreshRate(uint32_t fd_in) { - uint8_t highestRefreshRate = 60; - uint32_t fd = fd_in; - - if(!fd) nvOpen(&fd, "/dev/nvdisp-disp1"); - NvdcModeDB2 db2 = {0}; - int rc = nvIoctl(fd, NVDISP_GET_MODE_DB2, &db2); - - if (rc == 0) { - for (size_t i = 0; i < db2.num_modes; i++) { - if (db2.modes[i].hActive < 1920 || db2.modes[i].vActive < 1080) - continue; - - uint32_t v_total = db2.modes[i].vActive + db2.modes[i].vSyncWidth + db2.modes[i].vFrontPorch + db2.modes[i].vBackPorch; - uint32_t h_total = db2.modes[i].hActive + db2.modes[i].hSyncWidth + db2.modes[i].hFrontPorch + db2.modes[i].hBackPorch; - double refreshRate = round((double)(db2.modes[i].pclkKHz * 1000) / (double)(v_total * h_total)); - - if (highestRefreshRate < (uint8_t)refreshRate) - highestRefreshRate = (uint8_t)refreshRate; - } - } else { - g_dockedHighestRefreshRate = 60; - } - - const size_t numRates = sizeof(g_dockedRefreshRates) / sizeof(g_dockedRefreshRates[0]); - if (highestRefreshRate > g_dockedRefreshRates[numRates - 1]) - highestRefreshRate = g_dockedRefreshRates[numRates - 1]; - - NvdcMode2 display_b = {0}; - rc = nvIoctl(fd, NVDISP_GET_MODE2, &display_b); - - struct dpaux_read_0x100 { - uint32_t cmd; - uint32_t addr; - uint32_t size; - struct { - unsigned char link_rate; - unsigned int lane_count: 5; - unsigned int unk1: 2; - unsigned int isFramingEnhanced: 1; - unsigned char downspread; - unsigned char training_pattern; - unsigned char lane_pattern[4]; - unsigned char unk2[8]; - } set; - } dpaux = {6, 0x100, 0x10}; - - rc = nvIoctl(fd, NVDISP_GET_PANEL_DATA, &dpaux); - if (rc == 0) { - g_dockedLinkRate = dpaux.set.link_rate; - // if (display_b.hActive == 1920 && display_b.vActive == 1080 && highestRefreshRate > 75 && dpaux.set.link_rate < 20 && ) - // highestRefreshRate = 75; - } - - if (!fd_in) nvClose(fd); - g_dockedHighestRefreshRate = highestRefreshRate; -} - -static bool _setPLLDHandheldRefreshRate(uint32_t new_refreshRate) { - if (!g_config.clkVirtAddr) return false; - - uint32_t fd = 0; - if (nvOpen(&fd, "/dev/nvdisp-disp0")) { - return false; - } - - struct dpaux_read { - uint32_t cmd; - uint32_t addr; - uint32_t size; - struct { - unsigned int rev_minor : 4; - unsigned int rev_major : 4; - unsigned char link_rate; - unsigned int lane_count: 5; - unsigned int unk1: 2; - unsigned int isFramingEnhanced: 1; - unsigned char unk2[13]; - } DPCD; - } dpaux = {6, 0, 0x10}; - - int rc = nvIoctl(fd, NVDISP_GET_PANEL_DATA, &dpaux); - nvClose(fd); - if (rc != 0x75c) return false; - - PLLD_BASE base = {0}; - PLLD_MISC misc = {0}; - memcpy(&base, (void*)(g_config.clkVirtAddr + 0xD0), 4); - memcpy(&misc, (void*)(g_config.clkVirtAddr + 0xDC), 4); - - uint32_t value = ((base.PLLD_DIVN / base.PLLD_DIVM) * 10) / 4; - if (value == 0 || value == 80) return false; - - if (new_refreshRate > g_handheldModeRefreshRate.max) { - new_refreshRate = g_handheldModeRefreshRate.max; - } else if (new_refreshRate < g_handheldModeRefreshRate.min) { - bool skip = false; - for (size_t i = 2; i <= 4; i++) { - if (new_refreshRate * i == 60) { - skip = true; - new_refreshRate = 60; - break; - } - } - if (!skip) { - for (size_t i = 2; i <= 4; i++) { - if (((new_refreshRate * i) >= g_handheldModeRefreshRate.min) && ((new_refreshRate * i) <= g_handheldModeRefreshRate.max)) { - skip = true; - new_refreshRate *= i; - break; - } - } - } - if (!skip) new_refreshRate = 60; - } - - uint32_t pixelClock = (9375 * ((4096 * ((2 * base.PLLD_DIVN) + 1)) + misc.PLLD_SDM_DIN)) / (8 * base.PLLD_DIVM); - uint16_t refreshRateNow = pixelClock / (DSI_CLOCK_HZ / 60); - - if (refreshRateNow == new_refreshRate) { - return true; - } - - uint8_t base_refreshRate = new_refreshRate - (new_refreshRate % 5); - base.PLLD_DIVN = (4 * base_refreshRate) / 10; - base.PLLD_DIVM = 1; - - uint64_t expected_pixel_clock = (DSI_CLOCK_HZ * new_refreshRate) / 60; - misc.PLLD_SDM_DIN = ((8 * base.PLLD_DIVM * expected_pixel_clock) / 9375) - (4096 * ((2 * base.PLLD_DIVN) + 1)); - - memcpy((void*)(g_config.clkVirtAddr + 0xD0), &base, 4); - memcpy((void*)(g_config.clkVirtAddr + 0xDC), &misc, 4); - return true; -} - -static bool _setNvDispDockedRefreshRate(uint32_t new_refreshRate) { - if (g_config.isLite || !g_canChangeRefreshRateDocked) - return false; - - uint32_t fd = 0; - if (nvOpen(&fd, "/dev/nvdisp-disp1")) { - return false; - } - - NvdcMode2 display_b = {0}; - int rc = nvIoctl(fd, NVDISP_GET_MODE2, &display_b); - if (rc != 0) { - nvClose(fd); - return false; - } - - if (!display_b.pclkKHz) { - nvClose(fd); - return false; - } - - if (!((display_b.vActive == 480 && display_b.hActive == 720) || - (display_b.vActive == 720 && display_b.hActive == 1280) || - (display_b.vActive == 1080 && display_b.hActive == 1920))) { - nvClose(fd); - return false; - } - - if (display_b.vActive != g_lastVActiveSet) { - g_lastVActiveSet = display_b.vActive; - } - - uint32_t h_total = display_b.hActive + display_b.hFrontPorch + display_b.hSyncWidth + display_b.hBackPorch; - uint32_t v_total = display_b.vActive + display_b.vFrontPorch + display_b.vSyncWidth + display_b.vBackPorch; - uint32_t refreshRateNow = ((display_b.pclkKHz) * 1000 + 999) / (h_total * v_total); - - int8_t itr = -1; - const size_t numRates = sizeof(g_dockedRefreshRates) / sizeof(g_dockedRefreshRates[0]); - - // Find closest matching refresh rate - if ((new_refreshRate <= 60) && ((60 % new_refreshRate) == 0)) { - itr = _getDockedRefreshRateIterator(60); - } - - if (itr == -1) { - for (size_t i = 0; i < numRates; i++) { - uint8_t val = g_dockedRefreshRates[i]; - if ((val % new_refreshRate) == 0) { - itr = i; - break; - } - } - } - - if (itr == -1) { - if (!g_config.matchLowestDocked) { - itr = _getDockedRefreshRateIterator(60); - } else { - for (size_t i = 0; i < numRates; i++) { - if (new_refreshRate < g_dockedRefreshRates[i]) { - itr = i; - break; - } - } - } - } - - if (itr == -1) itr = _getDockedRefreshRateIterator(60); - - // Clamp to highest allowed refresh rate - if (g_dockedRefreshRates[itr] > g_dockedHighestRefreshRate) { - for (int8_t i = itr; i >= 0; i--) { - if (g_dockedRefreshRates[i] <= g_dockedHighestRefreshRate) { - itr = i; - break; - } - } - } - - if (refreshRateNow == g_dockedRefreshRates[itr]) { - nvClose(fd); - return true; - } - - if (itr >= 0 && itr < (int8_t)numRates) { - if (display_b.vActive == 720) { - uint32_t clock = ((h_total * v_total) * g_dockedRefreshRates[itr]) / 1000; - display_b.pclkKHz = clock; - } else { - display_b.hFrontPorch = g_dockedTimings1080p[itr].hFrontPorch; - display_b.hSyncWidth = g_dockedTimings1080p[itr].hSyncWidth; - display_b.hBackPorch = g_dockedTimings1080p[itr].hBackPorch; - display_b.vFrontPorch = g_dockedTimings1080p[itr].vFrontPorch; - display_b.vSyncWidth = g_dockedTimings1080p[itr].vSyncWidth; - display_b.vBackPorch = g_dockedTimings1080p[itr].vBackPorch; - display_b.pclkKHz = g_dockedTimings1080p[itr].pixelClock_kHz; - display_b.vmode = (g_dockedRefreshRates[itr] >= 100 ? 0x400000 : 0x200000); - display_b.unk1 = (g_dockedRefreshRates[itr] >= 100 ? 0x80 : 0); - display_b.sync = 3; - display_b.bitsPerPixel = 24; - } - - rc = nvIoctl(fd, NVDISP_VALIDATE_MODE2, &display_b); - if (rc == 0) { - rc = nvIoctl(fd, NVDISP_SET_MODE2, &display_b); - } - } - - nvClose(fd); - return true; -} - -static bool _setNvDispHandheldRefreshRate(uint32_t new_refreshRate) { - if (!g_config.isRetroSUPER) return false; - - if (!g_config.displaySync) { - g_wasRetroSuperTurnedOff = false; - } else if (g_wasRetroSuperTurnedOff) { - svcSleepThread(2000000000); - g_wasRetroSuperTurnedOff = false; - } - - svcSleepThread(1000000000); - - uint32_t fd = 0; - if (nvOpen(&fd, "/dev/nvdisp-disp0")) { - return false; - } - - NvdcMode2 display_b = {0}; - int rc = nvIoctl(fd, NVDISP_GET_MODE2, &display_b); - if (rc != 0) { - nvClose(fd); - return false; - } - - if (!display_b.pclkKHz) { - nvClose(fd); - return false; - } - - if ((display_b.vActive == 1280 && display_b.hActive == 720) == false) { - nvClose(fd); - return false; - } - - uint32_t h_total = display_b.hActive + display_b.hFrontPorch + display_b.hSyncWidth + display_b.hBackPorch; - uint32_t v_total = display_b.vActive + display_b.vFrontPorch + display_b.vSyncWidth + display_b.vBackPorch; - uint32_t refreshRateNow = ((display_b.pclkKHz) * 1000 + 999) / (h_total * v_total); - - if (new_refreshRate > g_handheldModeRefreshRate.max) { - new_refreshRate = g_handheldModeRefreshRate.max; - } else if (new_refreshRate < g_handheldModeRefreshRate.min) { - bool skip = false; - for (size_t i = 2; i <= 4; i++) { - if (new_refreshRate * i == 60) { - skip = true; - new_refreshRate = 60; - break; - } - } - if (!skip) { - for (size_t i = 2; i <= (sizeof(g_handheldTimingsRETRO) / sizeof(g_handheldTimingsRETRO[0])); i++) { - if (((new_refreshRate * i) >= g_handheldModeRefreshRate.min) && ((new_refreshRate * i) <= g_handheldModeRefreshRate.max)) { - skip = true; - new_refreshRate *= i; - break; - } - } - } - if (!skip) new_refreshRate = 60; - } - - if (new_refreshRate == refreshRateNow) { - nvClose(fd); - return true; - } - - uint32_t itr = (new_refreshRate - 40) / 5; - display_b.hFrontPorch = g_handheldTimingsRETRO[itr].hFrontPorch; - display_b.hSyncWidth = g_handheldTimingsRETRO[itr].hSyncWidth; - display_b.hBackPorch = g_handheldTimingsRETRO[itr].hBackPorch; - display_b.vFrontPorch = g_handheldTimingsRETRO[itr].vFrontPorch; - display_b.vSyncWidth = g_handheldTimingsRETRO[itr].vSyncWidth; - display_b.vBackPorch = g_handheldTimingsRETRO[itr].vBackPorch; - display_b.pclkKHz = g_handheldTimingsRETRO[itr].pixelClock_kHz; - - rc = nvIoctl(fd, NVDISP_VALIDATE_MODE2, &display_b); - if (rc == 0) { - for (size_t i = 0; i < 5; i++) { - nvIoctl(fd, NVDISP_SET_MODE2, &display_b); - } - } - - nvClose(fd); - return true; -} - -bool DisplayRefresh_SetRate(uint32_t new_refreshRate) { - if (!new_refreshRate || !g_initialized) return false; - - uint32_t fd = 0; - - if (g_config.isRetroSUPER && !g_config.isDocked) { - return _setNvDispHandheldRefreshRate(new_refreshRate); - } - - else if ((!g_config.isRetroSUPER && g_config.isLite) || R_FAILED(nvOpen(&fd, "/dev/nvdisp-disp1"))) { - if (_setPLLDHandheldRefreshRate(new_refreshRate) == false) - return false; - } - else { - struct dpaux_read { - uint32_t cmd; - uint32_t addr; - uint32_t size; - struct { - unsigned int rev_minor : 4; - unsigned int rev_major : 4; - unsigned char link_rate; - unsigned int lane_count: 5; - unsigned int unk1: 2; - unsigned int isFramingEnhanced: 1; - unsigned char unk2[13]; - } DPCD; - } dpaux = {6, 0, 0x10}; - - int rc = nvIoctl(fd, NVDISP_GET_PANEL_DATA, &dpaux); - nvClose(fd); - - if (rc != 0) { - if (!g_config.isRetroSUPER) { - return _setPLLDHandheldRefreshRate(new_refreshRate); - } else { - return _setNvDispHandheldRefreshRate(new_refreshRate); - } - } else { - if(g_config.isDocked) - return _setNvDispDockedRefreshRate(new_refreshRate); - else - return true; - } - } - return false; -} - -bool DisplayRefresh_GetRate(uint32_t* out_refreshRate, bool internal) { - if (!out_refreshRate || !g_initialized || !g_config.clkVirtAddr) return false; - static uint32_t value = 60; - - if (g_config.isRetroSUPER && !g_config.isDocked) { - uint32_t fd = 0; - PLLD_BASE temp = {0}; - PLLD_MISC misc = {0}; - memcpy(&temp, (void*)(g_config.clkVirtAddr + 0xD0), 4); - memcpy(&misc, (void*)(g_config.clkVirtAddr + 0xDC), 4); - - value = ((temp.PLLD_DIVN / temp.PLLD_DIVM) * 10) / 4; - - if (value != 0 && value != 80) { - if (!nvOpen(&fd, "/dev/nvdisp-disp0")) { - NvdcMode2 display_b = {0}; - if (nvIoctl(fd, NVDISP_GET_MODE2, &display_b) == 0) { - uint32_t h_total = display_b.hActive + display_b.hFrontPorch + display_b.hSyncWidth + display_b.hBackPorch; - uint32_t v_total = display_b.vActive + display_b.vFrontPorch + display_b.vSyncWidth + display_b.vBackPorch; - uint32_t pixelClock = display_b.pclkKHz * 1000 + 999; - value = pixelClock / (h_total * v_total); - } - nvClose(fd); - } else { - return false; - } - } else { - g_wasRetroSuperTurnedOff = true; - } - } - else if ((!g_config.isPossiblySpoofedRetro) || (g_config.isPossiblySpoofedRetro && !g_config.isRetroSUPER)) { - PLLD_BASE temp = {0}; - PLLD_MISC misc = {0}; - memcpy(&temp, (void*)(g_config.clkVirtAddr + 0xD0), 4); - memcpy(&misc, (void*)(g_config.clkVirtAddr + 0xDC), 4); - - value = ((temp.PLLD_DIVN / temp.PLLD_DIVM) * 10) / 4; - - if (value == 0 || value == 80) { - // Docked mode - if (g_config.isLite) return false; - - g_config.isDocked = true; - - if (!g_canChangeRefreshRateDocked) { - uint32_t fd = 0; - if (!nvOpen(&fd, "/dev/nvdisp-disp1")) { - struct dpaux_read_0x100 { - uint32_t cmd; - uint32_t addr; - uint32_t size; - struct { - unsigned char link_rate; - unsigned int lane_count: 5; - unsigned int unk1: 2; - unsigned int isFramingEnhanced: 1; - unsigned char downspread; - unsigned char training_pattern; - unsigned char lane_pattern[4]; - unsigned char unk2[8]; - } set; - } dpaux = {6, 0x100, 0x10}; - - int rc = nvIoctl(fd, NVDISP_GET_PANEL_DATA, &dpaux); - nvClose(fd); - - if (rc == 0) { - _getDockedHighestRefreshRate(0); - g_canChangeRefreshRateDocked = true; - } else { - svcSleepThread(1000000000); - return false; - } - } else { - return false; - } - } - if(internal) { - *out_refreshRate = value; - return true; - } - uint32_t fd = 0; - if (!nvOpen(&fd, "/dev/nvdisp-disp1")) { - NvdcMode2 display_b = {0}; - if (nvIoctl(fd, NVDISP_GET_MODE2, &display_b) == 0) { - if (!display_b.pclkKHz) { - nvClose(fd); - return false; - } - - if (g_lastVActive != display_b.vActive) { - g_lastVActive = display_b.vActive; - _getDockedHighestRefreshRate(fd); - } - - uint32_t h_total = display_b.hActive + display_b.hFrontPorch + display_b.hSyncWidth + display_b.hBackPorch; - uint32_t v_total = display_b.vActive + display_b.vFrontPorch + display_b.vSyncWidth + display_b.vBackPorch; - uint32_t pixelClock = display_b.pclkKHz * 1000 + 999; - value = pixelClock / (h_total * v_total); - } else { - value = 60; - } - nvClose(fd); - } else { - value = 60; - } - } - else if (!g_config.isRetroSUPER) { - // Handheld mode - g_config.isDocked = false; - g_canChangeRefreshRateDocked = false; - - uint32_t pixelClock = (9375 * ((4096 * ((2 * temp.PLLD_DIVN) + 1)) + misc.PLLD_SDM_DIN)) / (8 * temp.PLLD_DIVM); - value = pixelClock / (DSI_CLOCK_HZ / 60); - } - else { - return false; - } - } - - *out_refreshRate = value; - return true; -} - -void DisplayRefresh_Shutdown(void) { - g_initialized = false; - memset(&g_config, 0, sizeof(g_config)); -} \ No newline at end of file diff --git a/Source/sys-clk/common/src/i2c.cpp b/Source/sys-clk/common/src/i2c.cpp deleted file mode 100644 index 3760efeb..00000000 --- a/Source/sys-clk/common/src/i2c.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/* - * Copyright (c) KazushiMe - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ -#include "i2c.h" - -Result I2cSet_U8(I2cDevice dev, u8 reg, u8 val) { - // ams::fatal::srv::StopSoundTask::StopSound() - // I2C Bus Communication Reference: https://www.ti.com/lit/an/slva704/slva704.pdf - struct { - u8 reg; - u8 val; - } __attribute__((packed)) cmd; - - I2cSession _session; - Result res = i2cOpenSession(&_session, dev); - if (res) - return res; - - cmd.reg = reg; - cmd.val = val; - res = i2csessionSendAuto(&_session, &cmd, sizeof(cmd), I2cTransactionOption_All); - i2csessionClose(&_session); - return res; -} - -Result I2cRead_OutU8(I2cDevice dev, u8 reg, u8 *out) { - struct { u8 reg; } __attribute__((packed)) cmd; - struct { u8 val; } __attribute__((packed)) rec; - - I2cSession _session; - Result res = i2cOpenSession(&_session, dev); - if (res) - return res; - - cmd.reg = reg; - res = i2csessionSendAuto(&_session, &cmd, sizeof(cmd), I2cTransactionOption_All); - if (res) { - i2csessionClose(&_session); - return res; - } - - res = i2csessionReceiveAuto(&_session, &rec, sizeof(rec), I2cTransactionOption_All); - i2csessionClose(&_session); - if (res) { - return res; - } - - *out = rec.val; - return 0; -} - -Result I2cRead_OutU16(I2cDevice dev, u8 reg, u16 *out) { - struct { u8 reg; } __attribute__((packed)) cmd; - struct { u16 val; } __attribute__((packed)) rec; - - I2cSession _session; - Result res = i2cOpenSession(&_session, dev); - if (res) - return res; - - cmd.reg = reg; - res = i2csessionSendAuto(&_session, &cmd, sizeof(cmd), I2cTransactionOption_All); - if (res) { - i2csessionClose(&_session); - return res; - } - - res = i2csessionReceiveAuto(&_session, &rec, sizeof(rec), I2cTransactionOption_All); - i2csessionClose(&_session); - if (res) { - return res; - } - - *out = rec.val; - return 0; -} - -float I2c_Max17050_GetBatteryCurrent() { - u16 val; - Result res = I2cRead_OutU16(I2cDevice_Max17050, MAX17050_CURRENT_REG, &val); - if (res) - return 0.f; - - const float SenseResistor = 5.; // in uOhm - const float CGain = 1.99993; - return (s16)val * (1.5625 / (SenseResistor * CGain)); -} - -u32 I2c_BuckConverter_MultiplierToMvOut(const I2c_BuckConverter_Domain* domain, u8 multiplier) { - return (domain->uv_min + domain->uv_step * multiplier) / 1000; -} - -u8 I2c_BuckConverter_MvOutToMultiplier(const I2c_BuckConverter_Domain* domain, u32 mvolt) { - u32 uvolt = mvolt * 1000; - if (uvolt < domain->uv_min) - uvolt = domain->uv_min; - if (uvolt > domain->uv_max) - uvolt = domain->uv_max; - - return (uvolt - domain->uv_min) / domain->uv_step; -} - -u32 I2c_BuckConverter_GetMvOut(const I2c_BuckConverter_Domain* domain) { - u8 val; - // Retry 5 times if received POR value - for (int i = 0; i < 5; i++) { - if (R_FAILED(I2cRead_OutU8(domain->device, domain->reg, &val))) - return 0u; - - // Wait 1us - svcSleepThread(1E3); - - if (!domain->por_val || val != domain->por_val) - break; - } - return I2c_BuckConverter_MultiplierToMvOut(domain, val & domain->volt_mask); -} - -Result I2c_BuckConverter_SetMvOut(const I2c_BuckConverter_Domain* domain, u32 mvolt) { - u8 val; - Result res = I2cRead_OutU8(domain->device, domain->reg, &val); - if (R_FAILED(res)) - return res; - - u8 multiplier = I2c_BuckConverter_MvOutToMultiplier(domain, mvolt); - val &= ~domain->volt_mask; - val |= multiplier & domain->volt_mask; - - res = I2cSet_U8(domain->device, domain->reg, val); - if (R_FAILED(res)) - return res; - - // 5ms Ramp delay - svcSleepThread(5E6); - u8 new_val; - res = I2cRead_OutU8(domain->device, domain->reg, &new_val); - if (R_FAILED(res)) - return res; - if (new_val != val) - return -1; - - return 0; -} - -u8 I2c_Bq24193_Convert_mA_Raw(u32 ma) { - // Adjustment is required - u8 raw = 0; - - if (ma > MA_RANGE_MAX) // capping - ma = MA_RANGE_MAX; - - bool pct20 = ma <= (MA_RANGE_MIN - 64); - if (pct20) { - ma = ma * 5; - raw |= 0x1; - } - - ma -= ma % 100; // round to 100 - ma -= (MA_RANGE_MIN - 64); // ceiling - raw |= (ma >> 6) << 2; - - return raw; -}; - -u32 I2c_Bq24193_Convert_Raw_mA(u8 raw) { - // No adjustment is allowed - u32 ma = (((raw >> 2)) << 6) + MA_RANGE_MIN; - - bool pct20 = raw & 1; - if (pct20) - ma = ma * 20 / 100; - - return ma; -}; - -Result I2c_Bq24193_GetFastChargeCurrentLimit(u32 *ma) { - u8 raw; - Result res = I2cRead_OutU8(I2cDevice_Bq24193, BQ24193_CHARGE_CURRENT_CONTROL_REG, &raw); - if (res) - return res; - - *ma = I2c_Bq24193_Convert_Raw_mA(raw); - return 0; -} - -Result I2c_Bq24193_SetFastChargeCurrentLimit(u32 ma) { - u8 raw = I2c_Bq24193_Convert_mA_Raw(ma); - return I2cSet_U8(I2cDevice_Bq24193, BQ24193_CHARGE_CURRENT_CONTROL_REG, raw); -} \ No newline at end of file diff --git a/Source/sys-clk/common/src/memmem.c b/Source/sys-clk/common/src/memmem.c deleted file mode 100644 index 33ff7e06..00000000 --- a/Source/sys-clk/common/src/memmem.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - MIT License - - Copyright (c) 2024 Roy Merkel - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in all - copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE - SOFTWARE. -*/ - -#include "memmem.h" - -void *memmem_impl(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen) -{ - const unsigned char *cmpp; - const unsigned char *p; - const unsigned char *endp; - const unsigned char *q; - const unsigned char *endq; - unsigned char found; - - if(haystack == NULL) - { - return NULL; - } - if(needle == NULL) - { - return (void*)haystack; - } - if(haystacklen == 0) - { - return NULL; - } - if(needlelen == 0) - { - return (void*)haystack; - } - - if(needlelen > haystacklen) - { - return NULL; - } - - endp = haystack + haystacklen - needlelen; - endq = needle + needlelen; - for(p = haystack; p <= endp; p++) - { - found = 1; - cmpp = p; - for(q = needle; q < endq; q++) - { - if(*cmpp != *q) - { - found = 0; - break; - } - else - { - cmpp++; - } - } - if(found) - { - return (void*)p; - } - } - - return NULL; -} diff --git a/Source/sys-clk/common/src/psm_ext.c b/Source/sys-clk/common/src/psm_ext.c deleted file mode 100644 index 9bb1ae0c..00000000 --- a/Source/sys-clk/common/src/psm_ext.c +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright (c) KazushiMe - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#include - -const char* PsmPowerRoleToStr(PsmPowerRole role) { - switch (role) { - case PsmPowerRole_Sink: return "Sink"; - case PsmPowerRole_Source: return "Source"; - default: return "Unknown"; - } -} - -const char* PsmInfoChargerTypeToStr(PsmInfoChargerType type) { - switch (type) { - case PsmInfoChargerType_None: return "None"; - case PsmInfoChargerType_PD: return "USB-C PD"; - case PsmInfoChargerType_TypeC_1500mA: - case PsmInfoChargerType_TypeC_3000mA: return "USB-C"; - case PsmInfoChargerType_DCP: return "USB DCP"; - case PsmInfoChargerType_CDP: return "USB CDP"; - case PsmInfoChargerType_SDP: return "USB SDP"; - case PsmInfoChargerType_Apple_500mA: - case PsmInfoChargerType_Apple_1000mA: - case PsmInfoChargerType_Apple_2000mA: return "Apple"; - default: return "Unknown"; - } -} - -bool PsmIsChargerConnected(const PsmChargeInfo* info) { - return info->ChargerType != PsmInfoChargerType_None; -} - -bool PsmIsCharging(const PsmChargeInfo* info) { - return PsmIsChargerConnected(info) && ((info->unk_x14 >> 8) & 1); -} - -PsmBatteryState PsmGetBatteryState(const PsmChargeInfo* info) { - if (!PsmIsChargerConnected(info)) - return PsmBatteryState_Discharging; - if (!PsmIsCharging(info)) - return PsmBatteryState_ChargingPaused; - return PsmBatteryState_FastCharging; -} - -const char* PsmGetBatteryStateIcon(const PsmChargeInfo* info) { - switch (PsmGetBatteryState(info)) { - case PsmBatteryState_Discharging: return "\u25c0"; // ◀ - case PsmBatteryState_ChargingPaused:return "| |"; - case PsmBatteryState_FastCharging: return "\u25b6"; // ▶ - default: return "?"; - } -} diff --git a/Source/sys-clk/common/src/pwm.c b/Source/sys-clk/common/src/pwm.c deleted file mode 100644 index 96475997..00000000 --- a/Source/sys-clk/common/src/pwm.c +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) MasaGratoR - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#define NX_SERVICE_ASSUME_NON_DOMAIN -#include -#include "service_guard.h" -#include "pwm.h" - -static Service g_pwmSrv; - -NX_GENERATE_SERVICE_GUARD(pwm); - -Result _pwmInitialize(void) { - return smGetService(&g_pwmSrv, "pwm"); -} - -void _pwmCleanup(void) { - serviceClose(&g_pwmSrv); -} - -Service* pwmGetServiceSession(void) { - return &g_pwmSrv; -} - -Result pwmOpenSession2(PwmChannelSession *out, u32 device_code) { - return serviceDispatchIn(&g_pwmSrv, 2, device_code, - .out_num_objects = 1, - .out_objects = &out->s, - ); -} - -Result pwmChannelSessionGetDutyCycle(PwmChannelSession *c, double* out) { - return serviceDispatchOut(&c->s, 7, *out); -} - -void pwmChannelSessionClose(PwmChannelSession *controller) { - serviceClose(&controller->s); -} \ No newline at end of file diff --git a/Source/sys-clk/common/src/rgltr_services.cpp b/Source/sys-clk/common/src/rgltr_services.cpp deleted file mode 100644 index 6365e2ed..00000000 --- a/Source/sys-clk/common/src/rgltr_services.cpp +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) ppkantorski (bord2death) - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#include -#include "rgltr.h" -#include "rgltr_services.h" // for extern Service g_rgltrSrv, etc. - -// Global service handle -Service g_rgltrSrv; - -Result rgltrInitialize(void) { - if (hosversionBefore(8, 0, 0)) { - return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer); - } - return smGetService(&g_rgltrSrv, "rgltr"); -} - -void rgltrExit(void) { - serviceClose(&g_rgltrSrv); -} - -Result rgltrOpenSession(RgltrSession* session_out, PowerDomainId module_id) { - const u32 in = (u32)module_id; - return serviceDispatchIn( - &g_rgltrSrv, - 0, - in, - .out_num_objects = 1, - .out_objects = &session_out->s - ); -} - -Result rgltrGetVoltage(RgltrSession* session, u32* out_volt) { - u32 temp = 0; - Result rc = serviceDispatchOut(&session->s, 4, temp); - if (R_SUCCEEDED(rc)) { - *out_volt = temp; - } - return rc; -} - -Result rgltrRequestVoltage(RgltrSession* session, u32 microvolt) { - return serviceDispatchIn(&session->s, 5, microvolt); -} - -Result rgltrCancelVoltageRequest(RgltrSession* session) { - return serviceDispatch(&session->s, 6); -} - -void rgltrCloseSession(RgltrSession* session) { - serviceClose(&session->s); -} diff --git a/Source/sys-clk/config.ini.template b/Source/sys-clk/config.ini.template deleted file mode 100644 index 4305c725..00000000 --- a/Source/sys-clk/config.ini.template +++ /dev/null @@ -1,19 +0,0 @@ -[values] -; Defines how often sys-clk log temperatures, in milliseconds (set 0 to disable) -temp_log_interval_ms=0 -; Defines how often sys-clk writes to the CSV, in milliseconds (set 0 to disable) -csv_write_interval_ms=0 - -; Example #1: BOTW -; Overclock CPU when docked -; Overclock MEM to docked clocks when handheld -;[01007EF00011E000] -;docked_cpu=1224 -;handheld_mem=1600 - -; Example #2: Picross -; Underclock to save battery -;[0100BA0003EEA000] -;handheld_cpu=816 -;handheld_gpu=153 -;handheld_mem=800 \ No newline at end of file diff --git a/Source/sys-clk/merge_translate.py b/Source/sys-clk/merge_translate.py deleted file mode 100644 index 1a741598..00000000 --- a/Source/sys-clk/merge_translate.py +++ /dev/null @@ -1,83 +0,0 @@ -#!/usr/bin/env python3 -""" -Merge manual and machine translation files. -Uses manual translation if available, otherwise falls back to machine. - -Usage: - python merge_translations.py - -Examples: - python merge_translations.py lang/fr_manual.json lang/fr_machine.json lang/fr.json - python merge_translations.py manual/de.json auto/de.json lang/de.json -""" - -import json -import os -import re -import sys - - -def load_json(path: str) -> dict: - with open(path, "r", encoding="utf-8") as f: - content = f.read() - content = re.sub(r",\s*}", "}", content) - return json.loads(content) - - -def save_json(data: dict, path: str): - os.makedirs(os.path.dirname(path) or ".", exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write("{\n") - items = list(data.items()) - for i, (key, val) in enumerate(items): - k = json.dumps(key, ensure_ascii=False) - v = json.dumps(val, ensure_ascii=False) - comma = "," if i < len(items) - 1 else "" - f.write(f" {k}: {v}{comma}\n") - f.write("}\n") - - -def main(): - if len(sys.argv) < 4: - print("Usage: python merge_translations.py ") - sys.exit(1) - - manual_path = sys.argv[1] - machine_path = sys.argv[2] - output_path = sys.argv[3] - - if not os.path.isfile(machine_path): - print(f"Error: machine file '{machine_path}' not found.") - sys.exit(1) - - machine = load_json(machine_path) - manual = load_json(manual_path) if os.path.isfile(manual_path) else {} - - merged = {} - manual_count = 0 - machine_count = 0 - - for key in machine: - if key in manual and manual[key] and manual[key] != key: - merged[key] = manual[key] - manual_count += 1 - else: - merged[key] = machine[key] - machine_count += 1 - - # Include any manual-only keys not in machine - for key in manual: - if key not in merged and manual[key]: - merged[key] = manual[key] - manual_count += 1 - - save_json(merged, output_path) - - total = len(merged) - print(f"Merged {total} strings -> {output_path}") - print(f" Manual: {manual_count}") - print(f" Machine: {machine_count}") - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/Source/sys-clk/overlay/.gitignore b/Source/sys-clk/overlay/.gitignore deleted file mode 100644 index 36a52c92..00000000 --- a/Source/sys-clk/overlay/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/out -/build diff --git a/Source/sys-clk/overlay/data/logo_rgba.bin b/Source/sys-clk/overlay/data/logo_rgba.bin deleted file mode 100644 index d5b9ced7..00000000 Binary files a/Source/sys-clk/overlay/data/logo_rgba.bin and /dev/null differ diff --git a/Source/sys-clk/overlay/lang/de.json b/Source/sys-clk/overlay/lang/de.json deleted file mode 100644 index d2eedf0b..00000000 --- a/Source/sys-clk/overlay/lang/de.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Informationen", - "IDDQ:": "IDDQ:", - "Module: ": "Modul:", - "sys-dock status:": "Sys-Dock-Status:", - "SaltyNX status:": "SaltyNX-Status:", - "RR Display status:": "RR Anzeigestatus:", - "Wafer Position:": "Waferposition:", - "Credits": "Credits", - "Developers": "Entwickler", - "Contributors": "Mitwirkende", - "Testers": "Tester", - "Special Thanks": "Besonderer Dank", - "Unknown": "Unbekannt", - "Installed": "Installiert", - "Not Installed": "Nicht installiert", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "DIE BIERWAREN-LIZENZ", - "Default": "Standard", - "Do Not Override": "Nicht überschreiben", - "Disabled": "Deaktiviert", - "Enabled": "Aktiviert", - " \\ue0e3 Reset": "\\ue0e3 Zurücksetzen", - "Display": "Anzeige", - "Application changed\\n\\n": "Anwendung geändert\\n\\n", - "The running application changed\\n\\n": "Die laufende Anwendung hat sich geändert\\n\\n", - "while editing was going on.": "während die Bearbeitung im Gange war.", - "Board": "Vorstand", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Es konnte keine Verbindung zum hoc-clk-Systemmodul hergestellt werden.\\n\\n", - "Please make sure everything is\\n\\n": "Bitte stellen Sie sicher, dass alles in Ordnung ist\\n\\n", - "correctly installed and enabled.": "korrekt installiert und aktiviert.", - "Fatal error": "Fataler Fehler", - "Temporary Overrides ": "Temporäre Überschreibungen", - "Sleep Mode": "Schlafmodus", - "Stock": "Lager", - "Dev OC": "Entwickler OC", - "Boost Mode": "Boost-Modus", - "Safe Max": "Sicher max", - "Unsafe Max": "Unsicher max", - "Absolute Max": "Absolutes Maximum", - "Handheld Safe Max": "Handsafe max", - "Enable": "Aktivieren", - "Edit App Profile": "App-Profil bearbeiten", - "Edit Global Profile": "Globales Profil bearbeiten", - "Temporary Overrides": "Temporäre Überschreibungen", - "Settings": "Einstellungen", - "About": "Über", - "Compiling with minimal features": "Kompilieren mit minimalen Funktionen", - "General Settings": "Allgemeine Einstellungen", - "Governor Settings": "Gouverneurseinstellungen", - "Safety Settings": "Sicherheitseinstellungen", - "Save KIP Settings": "Speichern Sie die KIP-Einstellungen", - "RAM Settings": "RAM-Einstellungen", - "CPU Settings": "CPU-Einstellungen", - "GPU Settings": "GPU-Einstellungen", - "Display Settings": "Anzeigeeinstellungen", - "Experimental": "Experimentell", - "GPU Scheduling Override Method": "GPU-Planungsüberschreibungsmethode", - "can be dangerous and may cause": "kann gefährlich sein und verursachen", - "damage to your battery or charger!": "Schäden an Ihrem Akku oder Ladegerät!", - "Charge Current Override": "Ladestrom-Überbrückung", - "RAM Voltage Display Mode": "RAM-Spannungsanzeigemodus", - "Polling Interval": "Abfrageintervall", - "CPU Governor Minimum Frequency": "Mindestfrequenz des CPU-Reglers", - "refresh rates may cause stress": "Bildwiederholraten können Stress verursachen", - "or damage to your display! ": "oder Schäden an Ihrem Display!", - "Proceed at your own risk!": "Das Vorgehen erfolgt auf eigene Gefahr!", - "Max Handheld Display": "Max Handheld-Display", - "Display Clock": "Uhr anzeigen", - "Official Rating": "Offizielle Bewertung", - "TDP Threshold": "TDP-Schwellenwert", - "Power": "Macht", - "Thermal Throttle Limit": "Thermische Drosselgrenze", - "HP Mode": "HP-Modus", - "Default (Mariko)": "Standard (Mariko)", - "Default (Erista)": "Standard (Erista)", - "Rating": "Bewertung", - "Safe Max (Mariko)": "Safe Max (Mariko)", - "Safe Max (Erista)": "Safe Max (Erista)", - "RAM VDD2 Voltage": "RAM VDD2 Spannung", - "Voltage": "Spannung", - "RAM VDDQ Voltage": "RAM-VDDQ-Spannung", - "RAM Frequency Editor": "RAM-Frequenzeditor", - "JEDEC.": "JEDEC.", - "High speedo needed!": "Hoher Tacho erforderlich!", - "3333MHz (Needs extreme Speedo/PLL)": "3333 MHz (Benötigt extremen Tacho/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 MHz (Benötigt extremen Tacho/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 MHz (Benötigt extremen Tacho/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433 MHz (Benötigt lächerlichen Tacho/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466 MHz (Benötigt lächerlichen Tacho/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 MHz (Benötigt lächerlichen Tacho/PLL)", - "Ram Max Clock": "Ram Max Uhr", - "RAM Latency Editor": "RAM-Latenz-Editor", - "RAM Timing Reductions": "Reduzierung des RAM-Timings", - "Memory Timings": "Speicherzeiten", - "Advanced": "Fortgeschritten", - "t6 tRTW Fine Tune": "t6 tRTW Feinabstimmung", - "tRTW Fine Tune": "tRTW-Feinabstimmung", - "t7 tWTR Fine Tune": "t7 tWTR Feinabstimmung", - "tWTR Fine Tune": "tWTR-Feinabstimmung", - "Memory Latencies": "Speicherlatenzen", - "Read Latency": "Leselatenz", - "Write Latency": "Schreiblatenz", - "CPU Boost Clock": "CPU-Boost-Takt", - "CPU UV": "CPU-UV", - "CPU Unlock": "CPU-Entsperrung", - "CPU VMIN": "CPU-VMIN", - "CPU Max Voltage": "Maximale CPU-Spannung", - "CPU Max Clock": "Maximaler CPU-Takt", - "Extreme UV Table": "Extremer UV-Tisch", - "CPU UV Table": "CPU-UV-Tisch", - "CPU Low UV": "CPU-niedrige UV-Strahlung", - "CPU High UV": "CPU Hohe UV-Strahlung", - "CPU Low VMIN": "CPU niedrig VMIN", - "CPU High VMIN": "CPU hoch VMIN", - "No Undervolt": "Kein Undervolt", - "SLT Table": "SLT-Tisch", - "HiOPT Table": "HiOPT-Tabelle", - "GPU Undervolt Table": "GPU-Unterspannungstabelle", - "GPU Minimum Voltage": "GPU-Mindestspannung", - "Calculate GPU Vmin": "Berechnen Sie die GPU-Vmin", - "GPU VMIN": "GPU-VMIN", - "GPU Maximum Voltage": "Maximale GPU-Spannung", - "GPU Voltage Offset": "GPU-Spannungsoffset", - "Do not override": "Nicht überschreiben", - "Enabled (Default)": "Aktiviert (Standard)", - "96.6% limit": "96,6 %-Grenze", - "99.7% limit": "99,7 %-Grenze", - "GPU Scheduling Override": "GPU-Planungsüberschreibung", - "Official Service": "Offizieller Dienst", - "GPU DVFS Mode": "GPU-DVFS-Modus", - "GPU DVFS Offset": "GPU-DVFS-Offset", - "GPU Voltage Table": "GPU-Spannungstabelle", - "GPU Custom Table (mV)": "Benutzerdefinierte GPU-Tabelle (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075 MHz ohne UV, 1152 MHz auf SLT", - "or 1228MHz on HiOPT can cause ": "oder 1228 MHz auf HiOPT kann dazu führen", - "permanent damage to your Switch!": "Dauerhafter Schaden an Ihrem Switch!", - "921MHz without UV and 960MHz on": "921 MHz ohne UV und 960 MHz eingeschaltet", - "SLT or HiOPT can cause ": "SLT oder HiOPT können dazu führen" -} diff --git a/Source/sys-clk/overlay/lang/en.json b/Source/sys-clk/overlay/lang/en.json deleted file mode 100644 index 727fab93..00000000 --- a/Source/sys-clk/overlay/lang/en.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Information", - "IDDQ:": "IDDQ:", - "Module: ": "Module: ", - "sys-dock status:": "sys-dock status:", - "SaltyNX status:": "SaltyNX status:", - "RR Display status:": "RR Display status:", - "Wafer Position:": "Wafer Position:", - "Credits": "Credits", - "Developers": "Developers", - "Contributors": "Contributors", - "Testers": "Testers", - "Special Thanks": "Special Thanks", - "Unknown": "Unknown", - "Installed": "Installed", - "Not Installed": "Not Installed", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "THE BEER-WARE LICENSE", - "Default": "Default", - "Do Not Override": "Do Not Override", - "Disabled": "Disabled", - "Enabled": "Enabled", - " \\ue0e3 Reset": " \\ue0e3 Reset", - "Display": "Display", - "Application changed\\n\\n": "Application changed\\n\\n", - "The running application changed\\n\\n": "The running application changed\\n\\n", - "while editing was going on.": "while editing was going on.", - "Board": "Board", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Could not connect to hoc-clk sysmodule.\\n\\n", - "Please make sure everything is\\n\\n": "Please make sure everything is\\n\\n", - "correctly installed and enabled.": "correctly installed and enabled.", - "Fatal error": "Fatal error", - "Temporary Overrides ": "Temporary Overrides ", - "Sleep Mode": "Sleep Mode", - "Stock": "Stock", - "Dev OC": "Dev OC", - "Boost Mode": "Boost Mode", - "Safe Max": "Safe Max", - "Unsafe Max": "Unsafe Max", - "Absolute Max": "Absolute Max", - "Handheld Safe Max": "Handheld Safe Max", - "Enable": "Enable", - "Edit App Profile": "Edit App Profile", - "Edit Global Profile": "Edit Global Profile", - "Temporary Overrides": "Temporary Overrides", - "Settings": "Settings", - "About": "About", - "Compiling with minimal features": "Compiling with minimal features", - "General Settings": "General Settings", - "Governor Settings": "Governor Settings", - "Safety Settings": "Safety Settings", - "Save KIP Settings": "Save KIP Settings", - "RAM Settings": "RAM Settings", - "CPU Settings": "CPU Settings", - "GPU Settings": "GPU Settings", - "Display Settings": "Display Settings", - "Experimental": "Experimental", - "GPU Scheduling Override Method": "GPU Scheduling Override Method", - "can be dangerous and may cause": "can be dangerous and may cause", - "damage to your battery or charger!": "damage to your battery or charger!", - "Charge Current Override": "Charge Current Override", - "RAM Voltage Display Mode": "RAM Voltage Display Mode", - "Polling Interval": "Polling Interval", - "CPU Governor Minimum Frequency": "CPU Governor Minimum Frequency", - "refresh rates may cause stress": "refresh rates may cause stress", - "or damage to your display! ": "or damage to your display! ", - "Proceed at your own risk!": "Proceed at your own risk!", - "Max Handheld Display": "Max Handheld Display", - "Display Clock": "Display Clock", - "Official Rating": "Official Rating", - "TDP Threshold": "TDP Threshold", - "Power": "Power", - "Thermal Throttle Limit": "Thermal Throttle Limit", - "HP Mode": "HP Mode", - "Default (Mariko)": "Default (Mariko)", - "Default (Erista)": "Default (Erista)", - "Rating": "Rating", - "Safe Max (Mariko)": "Safe Max (Mariko)", - "Safe Max (Erista)": "Safe Max (Erista)", - "RAM VDD2 Voltage": "RAM VDD2 Voltage", - "Voltage": "Voltage", - "RAM VDDQ Voltage": "RAM VDDQ Voltage", - "RAM Frequency Editor": "RAM Frequency Editor", - "JEDEC.": "JEDEC.", - "High speedo needed!": "High speedo needed!", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz (Needs extreme Speedo/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366MHz (Needs extreme Speedo/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400MHz (Needs extreme Speedo/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (Needs ridiculous Speedo/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz (Needs ridiculous Speedo/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz (Needs ridiculous Speedo/PLL)", - "Ram Max Clock": "Ram Max Clock", - "RAM Latency Editor": "RAM Latency Editor", - "RAM Timing Reductions": "RAM Timing Reductions", - "Memory Timings": "Memory Timings", - "Advanced": "Advanced", - "t6 tRTW Fine Tune": "t6 tRTW Fine Tune", - "tRTW Fine Tune": "tRTW Fine Tune", - "t7 tWTR Fine Tune": "t7 tWTR Fine Tune", - "tWTR Fine Tune": "tWTR Fine Tune", - "Memory Latencies": "Memory Latencies", - "Read Latency": "Read Latency", - "Write Latency": "Write Latency", - "CPU Boost Clock": "CPU Boost Clock", - "CPU UV": "CPU UV", - "CPU Unlock": "CPU Unlock", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "CPU Max Voltage", - "CPU Max Clock": "CPU Max Clock", - "Extreme UV Table": "Extreme UV Table", - "CPU UV Table": "CPU UV Table", - "CPU Low UV": "CPU Low UV", - "CPU High UV": "CPU High UV", - "CPU Low VMIN": "CPU Low VMIN", - "CPU High VMIN": "CPU High VMIN", - "No Undervolt": "No Undervolt", - "SLT Table": "SLT Table", - "HiOPT Table": "HiOPT Table", - "GPU Undervolt Table": "GPU Undervolt Table", - "GPU Minimum Voltage": "GPU Minimum Voltage", - "Calculate GPU Vmin": "Calculate GPU Vmin", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "GPU Maximum Voltage", - "GPU Voltage Offset": "GPU Voltage Offset", - "Do not override": "Do not override", - "Enabled (Default)": "Enabled (Default)", - "96.6% limit": "96.6% limit", - "99.7% limit": "99.7% limit", - "GPU Scheduling Override": "GPU Scheduling Override", - "Official Service": "Official Service", - "GPU DVFS Mode": "GPU DVFS Mode", - "GPU DVFS Offset": "GPU DVFS Offset", - "GPU Voltage Table": "GPU Voltage Table", - "GPU Custom Table (mV)": "GPU Custom Table (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075MHz without UV, 1152MHz on SLT", - "or 1228MHz on HiOPT can cause ": "or 1228MHz on HiOPT can cause ", - "permanent damage to your Switch!": "permanent damage to your Switch!", - "921MHz without UV and 960MHz on": "921MHz without UV and 960MHz on", - "SLT or HiOPT can cause ": "SLT or HiOPT can cause " -} diff --git a/Source/sys-clk/overlay/lang/es.json b/Source/sys-clk/overlay/lang/es.json deleted file mode 100644 index 546b4429..00000000 --- a/Source/sys-clk/overlay/lang/es.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Información", - "IDDQ:": "IDDQ:", - "Module: ": "Módulo:", - "sys-dock status:": "estado del sys-dock:", - "SaltyNX status:": "Estado de SaltyNX:", - "RR Display status:": "Estado de visualización RR:", - "Wafer Position:": "Posición de la oblea:", - "Credits": "Créditos", - "Developers": "Desarrolladores", - "Contributors": "Colaboradores", - "Testers": "Probadores", - "Special Thanks": "agradecimiento especial", - "Unknown": "Desconocido", - "Installed": "Instalado", - "Not Installed": "No instalado", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "LA LICENCIA DE CERVEZA", - "Default": "Predeterminado", - "Do Not Override": "No anular", - "Disabled": "Discapacitado", - "Enabled": "Habilitado", - " \\ue0e3 Reset": "\\ue0e3 Restablecer", - "Display": "Pantalla", - "Application changed\\n\\n": "Aplicación modificada\\n\\n", - "The running application changed\\n\\n": "La aplicación en ejecución cambió\\n\\n", - "while editing was going on.": "mientras se realizaba la edición.", - "Board": "tablero", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "No se pudo conectar al módulo del sistema hoc-clk.\\n\\n", - "Please make sure everything is\\n\\n": "Por favor asegúrese de que todo esté\\n\\n", - "correctly installed and enabled.": "correctamente instalado y habilitado.", - "Fatal error": "error fatal", - "Temporary Overrides ": "Anulaciones temporales", - "Sleep Mode": "Modo de suspensión", - "Stock": "Valores", - "Dev OC": "Desarrollador OC", - "Boost Mode": "Modo de impulso", - "Safe Max": "Máximo seguro", - "Unsafe Max": "Máximo inseguro", - "Absolute Max": "Máximo absoluto", - "Handheld Safe Max": "Caja fuerte de mano máx.", - "Enable": "Habilitar", - "Edit App Profile": "Editar perfil de aplicación", - "Edit Global Profile": "Editar perfil global", - "Temporary Overrides": "Anulaciones temporales", - "Settings": "Configuración", - "About": "Acerca de", - "Compiling with minimal features": "Compilando con características mínimas", - "General Settings": "Configuraciones generales", - "Governor Settings": "Configuración del gobernador", - "Safety Settings": "Configuraciones de seguridad", - "Save KIP Settings": "Guardar configuración de KIP", - "RAM Settings": "Configuración de RAM", - "CPU Settings": "Configuración de la CPU", - "GPU Settings": "Configuración de GPU", - "Display Settings": "Configuración de pantalla", - "Experimental": "Experimental", - "GPU Scheduling Override Method": "Método de anulación de programación de GPU", - "can be dangerous and may cause": "puede ser peligroso y puede causar", - "damage to your battery or charger!": "¡Daños a su batería o cargador!", - "Charge Current Override": "Anulación de corriente de carga", - "RAM Voltage Display Mode": "Modo de visualización de voltaje de RAM", - "Polling Interval": "Intervalo de sondeo", - "CPU Governor Minimum Frequency": "Frecuencia mínima del gobernador de CPU", - "refresh rates may cause stress": "Las frecuencias de actualización pueden causar estrés.", - "or damage to your display! ": "o daños a su pantalla!", - "Proceed at your own risk!": "¡Continúe bajo su propio riesgo!", - "Max Handheld Display": "Pantalla portátil máxima", - "Display Clock": "Reloj de pantalla", - "Official Rating": "Calificación oficial", - "TDP Threshold": "Umbral de TDP", - "Power": "poder", - "Thermal Throttle Limit": "Límite del acelerador térmico", - "HP Mode": "Modo HP", - "Default (Mariko)": "Predeterminado (Mariko)", - "Default (Erista)": "Predeterminado (Erista)", - "Rating": "Calificación", - "Safe Max (Mariko)": "Max seguro (Mariko)", - "Safe Max (Erista)": "Safe Max (Erista)", - "RAM VDD2 Voltage": "Voltaje RAM VDD2", - "Voltage": "voltaje", - "RAM VDDQ Voltage": "Voltaje RAM VDDQ", - "RAM Frequency Editor": "Editor de frecuencia RAM", - "JEDEC.": "JEDEC.", - "High speedo needed!": "¡Se necesita alta velocidad!", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz (Necesita Speedo/PLL extremo)", - "3366MHz (Needs extreme Speedo/PLL)": "3366MHz (Necesita Speedo/PLL extremo)", - "3400MHz (Needs extreme Speedo/PLL)": "3400MHz (Necesita Speedo/PLL extremo)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (Necesita Speedo/PLL ridículo)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz (Necesita Speedo/PLL ridículo)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz (Necesita Speedo/PLL ridículo)", - "Ram Max Clock": "Ram Max Reloj", - "RAM Latency Editor": "Editor de latencia de RAM", - "RAM Timing Reductions": "Reducciones de tiempo de RAM", - "Memory Timings": "Tiempos de memoria", - "Advanced": "Avanzado", - "t6 tRTW Fine Tune": "t6 tRTW Ajuste fino", - "tRTW Fine Tune": "Ajuste fino tRTW", - "t7 tWTR Fine Tune": "t7 tWTR Ajuste fino", - "tWTR Fine Tune": "Ajuste fino de tWTR", - "Memory Latencies": "Latencias de la memoria", - "Read Latency": "Leer latencia", - "Write Latency": "Latencia de escritura", - "CPU Boost Clock": "Reloj de aumento de CPU", - "CPU UV": "procesador ultravioleta", - "CPU Unlock": "Desbloqueo de CPU", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "Voltaje máximo de la CPU", - "CPU Max Clock": "Reloj máximo de CPU", - "Extreme UV Table": "Mesa UV extrema", - "CPU UV Table": "Tabla UV de CPU", - "CPU Low UV": "CPU baja radiación ultravioleta", - "CPU High UV": "CPU alta UV", - "CPU Low VMIN": "VMIN bajo de CPU", - "CPU High VMIN": "VMIN alto de CPU", - "No Undervolt": "Sin subvoltaje", - "SLT Table": "Mesa TR", - "HiOPT Table": "Tabla HiOPT", - "GPU Undervolt Table": "Tabla de subvoltaje de GPU", - "GPU Minimum Voltage": "Voltaje mínimo de GPU", - "Calculate GPU Vmin": "Calcular GPU Vmin", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "Voltaje máximo de GPU", - "GPU Voltage Offset": "Compensación de voltaje de GPU", - "Do not override": "no anular", - "Enabled (Default)": "Habilitado (predeterminado)", - "96.6% limit": "límite del 96,6%", - "99.7% limit": "límite del 99,7%", - "GPU Scheduling Override": "Anulación de programación de GPU", - "Official Service": "Servicio Oficial", - "GPU DVFS Mode": "Modo GPU DVFS", - "GPU DVFS Offset": "Compensación DVFS de GPU", - "GPU Voltage Table": "Tabla de voltaje de GPU", - "GPU Custom Table (mV)": "Tabla personalizada de GPU (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075MHz sin UV, 1152MHz en SLT", - "or 1228MHz on HiOPT can cause ": "o 1228MHz en HiOPT pueden causar", - "permanent damage to your Switch!": "¡Daño permanente a tu Switch!", - "921MHz without UV and 960MHz on": "921MHz sin UV y 960MHz encendido", - "SLT or HiOPT can cause ": "SLT o HiOPT pueden causar" -} diff --git a/Source/sys-clk/overlay/lang/fr.json b/Source/sys-clk/overlay/lang/fr.json deleted file mode 100644 index 2494473a..00000000 --- a/Source/sys-clk/overlay/lang/fr.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Informations", - "IDDQ:": "IDDQ :", - "Module: ": "Module :", - "sys-dock status:": "état du dock système :", - "SaltyNX status:": "Statut SaltyNX :", - "RR Display status:": "Etat d'affichage RR :", - "Wafer Position:": "Position de la plaquette :", - "Credits": "Crédits", - "Developers": "Développeurs", - "Contributors": "Contributeurs", - "Testers": "Testeurs", - "Special Thanks": "Remerciements spéciaux", - "Unknown": "Inconnu", - "Installed": "Installé", - "Not Installed": "Non installé", - "X: %u Y: %u": "X : %u Y : %u", - "THE BEER-WARE LICENSE": "LA LICENCE DE LA BIÈRE", - "Default": "Par défaut", - "Do Not Override": "Ne pas remplacer", - "Disabled": "Désactivé", - "Enabled": "Activé", - " \\ue0e3 Reset": "\\ue0e3 Réinitialiser", - "Display": "Affichage", - "Application changed\\n\\n": "Application modifiée\\n\\n", - "The running application changed\\n\\n": "L'application en cours d'exécution a changé\\n\\n", - "while editing was going on.": "pendant le montage.", - "Board": "Conseil", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Impossible de se connecter au module système hoc-clk.\\n\\n", - "Please make sure everything is\\n\\n": "Veuillez vous assurer que tout est\\n\\n", - "correctly installed and enabled.": "correctement installé et activé.", - "Fatal error": "Erreur fatale", - "Temporary Overrides ": "Remplacements temporaires", - "Sleep Mode": "Mode veille", - "Stock": "Actions", - "Dev OC": "Développeur OC", - "Boost Mode": "Mode Boost", - "Safe Max": "Coffre-fort maximum", - "Unsafe Max": "Dangereux Max", - "Absolute Max": "Max absolu", - "Handheld Safe Max": "Coffre-fort portatif Max", - "Enable": "Activer", - "Edit App Profile": "Modifier le profil de l'application", - "Edit Global Profile": "Modifier le profil global", - "Temporary Overrides": "Remplacements temporaires", - "Settings": "Paramètres", - "About": "À propos", - "Compiling with minimal features": "Compilation avec des fonctionnalités minimales", - "General Settings": "Paramètres généraux", - "Governor Settings": "Paramètres du gouverneur", - "Safety Settings": "Paramètres de sécurité", - "Save KIP Settings": "Enregistrer les paramètres KIP", - "RAM Settings": "Paramètres de la RAM", - "CPU Settings": "Paramètres du processeur", - "GPU Settings": "Paramètres du processeur graphique", - "Display Settings": "Paramètres d'affichage", - "Experimental": "Expérimental", - "GPU Scheduling Override Method": "Méthode de remplacement de la planification GPU", - "can be dangerous and may cause": "peut être dangereux et provoquer", - "damage to your battery or charger!": "dommages à votre batterie ou à votre chargeur !", - "Charge Current Override": "Remplacement du courant de charge", - "RAM Voltage Display Mode": "Mode d'affichage de la tension de la RAM", - "Polling Interval": "Intervalle d'interrogation", - "CPU Governor Minimum Frequency": "Fréquence minimale du gouverneur du processeur", - "refresh rates may cause stress": "les taux de rafraîchissement peuvent causer du stress", - "or damage to your display! ": "ou endommager votre écran !", - "Proceed at your own risk!": "Procédez à vos propres risques !", - "Max Handheld Display": "Affichage portable maximum", - "Display Clock": "Affichage de l'horloge", - "Official Rating": "Classement officiel", - "TDP Threshold": "Seuil TDP", - "Power": "Puissance", - "Thermal Throttle Limit": "Limite d'accélérateur thermique", - "HP Mode": "Mode HP", - "Default (Mariko)": "Par défaut (Mariko)", - "Default (Erista)": "Par défaut (Erista)", - "Rating": "Note", - "Safe Max (Mariko)": "Coffre-fort Max (Mariko)", - "Safe Max (Erista)": "Coffre-fort Max (Erista)", - "RAM VDD2 Voltage": "Tension de la RAM VDD2", - "Voltage": "Tension", - "RAM VDDQ Voltage": "Tension VDDQ de la RAM", - "RAM Frequency Editor": "Éditeur de fréquence RAM", - "JEDEC.": "JEDEC.", - "High speedo needed!": "Besoin d'un speedo haut !", - "3333MHz (Needs extreme Speedo/PLL)": "3333 MHz (nécessite un Speedo/PLL extrême)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 MHz (nécessite un Speedo/PLL extrême)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 MHz (nécessite un Speedo/PLL extrême)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433 MHz (nécessite un Speedo/PLL ridicule)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466 MHz (nécessite un Speedo/PLL ridicule)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 MHz (nécessite un Speedo/PLL ridicule)", - "Ram Max Clock": "Ram Max Horloge", - "RAM Latency Editor": "Éditeur de latence RAM", - "RAM Timing Reductions": "Réductions de synchronisation de la RAM", - "Memory Timings": "Horaires de mémoire", - "Advanced": "Avancé", - "t6 tRTW Fine Tune": "t6 tRTW réglage fin", - "tRTW Fine Tune": "tRTW Réglage fin", - "t7 tWTR Fine Tune": "t7 tWTR réglage fin", - "tWTR Fine Tune": "Réglage fin du tWTR", - "Memory Latencies": "Latences de mémoire", - "Read Latency": "Latence de lecture", - "Write Latency": "Latence d'écriture", - "CPU Boost Clock": "Horloge d'augmentation du processeur", - "CPU UV": "UV du processeur", - "CPU Unlock": "Déverrouillage du processeur", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "Tension maximale du processeur", - "CPU Max Clock": "Horloge maximale du processeur", - "Extreme UV Table": "Table UV Extrême", - "CPU UV Table": "Tableau UV du processeur", - "CPU Low UV": "CPU faible UV", - "CPU High UV": "CPU UV élevé", - "CPU Low VMIN": "CPU faible VMIN", - "CPU High VMIN": "Processeur VMIN élevé", - "No Undervolt": "Pas de sous-tension", - "SLT Table": "Tableau SLT", - "HiOPT Table": "Tableau HiOPT", - "GPU Undervolt Table": "Tableau de sous-tension GPU", - "GPU Minimum Voltage": "Tension minimale du GPU", - "Calculate GPU Vmin": "Calculer la Vmin du GPU", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "Tension maximale du GPU", - "GPU Voltage Offset": "Décalage de tension du GPU", - "Do not override": "Ne remplacez pas", - "Enabled (Default)": "Activé (par défaut)", - "96.6% limit": "Limite de 96,6 %", - "99.7% limit": "Limite de 99,7 %", - "GPU Scheduling Override": "Remplacement de la planification GPU", - "Official Service": "Service officiel", - "GPU DVFS Mode": "Mode GPU DVFS", - "GPU DVFS Offset": "Décalage GPU DVFS", - "GPU Voltage Table": "Tableau de tension du GPU", - "GPU Custom Table (mV)": "Tableau personnalisé GPU (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075 MHz sans UV, 1152 MHz sur SLT", - "or 1228MHz on HiOPT can cause ": "ou 1228 MHz sur HiOPT peut provoquer", - "permanent damage to your Switch!": "dommages permanents à votre Switch !", - "921MHz without UV and 960MHz on": "921 MHz sans UV et 960 MHz activé", - "SLT or HiOPT can cause ": "SLT ou HiOPT peuvent provoquer" -} diff --git a/Source/sys-clk/overlay/lang/it.json b/Source/sys-clk/overlay/lang/it.json deleted file mode 100644 index d7056f36..00000000 --- a/Source/sys-clk/overlay/lang/it.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Informazioni", - "IDDQ:": "IDDQ:", - "Module: ": "Modulo:", - "sys-dock status:": "stato del dock di sistema:", - "SaltyNX status:": "Stato di SaltyNX:", - "RR Display status:": "Stato di visualizzazione RR:", - "Wafer Position:": "Posizione del wafer:", - "Credits": "Crediti", - "Developers": "Sviluppatori", - "Contributors": "Collaboratori", - "Testers": "Tester", - "Special Thanks": "Un ringraziamento speciale", - "Unknown": "Sconosciuto", - "Installed": "Installato", - "Not Installed": "Non installato", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "LA LICENZA PER GLI ARTICOLI DI BIRRA", - "Default": "Predefinito", - "Do Not Override": "Non sovrascrivere", - "Disabled": "Disabilitato", - "Enabled": "Abilitato", - " \\ue0e3 Reset": "\\ue0e3 Ripristina", - "Display": "Visualizzazione", - "Application changed\\n\\n": "Applicazione modificata\\n\\n", - "The running application changed\\n\\n": "L'applicazione in esecuzione è cambiata\\n\\n", - "while editing was going on.": "mentre era in corso la modifica.", - "Board": "Consiglio", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Impossibile connettersi al modulo di sistema hoc-clk.\\n\\n", - "Please make sure everything is\\n\\n": "Assicurati che tutto sia\\n\\n", - "correctly installed and enabled.": "correttamente installato e abilitato.", - "Fatal error": "Errore fatale", - "Temporary Overrides ": "Sostituzioni temporanee", - "Sleep Mode": "Modalità di sospensione", - "Stock": "Magazzino", - "Dev OC": "OC di sviluppo", - "Boost Mode": "Modalità potenziamento", - "Safe Max": "Sicuro massimo", - "Unsafe Max": "Non sicuro Max", - "Absolute Max": "Massimo assoluto", - "Handheld Safe Max": "Cassaforte portatile max", - "Enable": "Abilita", - "Edit App Profile": "Modifica profilo dell'app", - "Edit Global Profile": "Modifica profilo globale", - "Temporary Overrides": "Sostituzioni temporanee", - "Settings": "Impostazioni", - "About": "Circa", - "Compiling with minimal features": "Compilazione con funzionalità minime", - "General Settings": "Impostazioni generali", - "Governor Settings": "Impostazioni del governatore", - "Safety Settings": "Impostazioni di sicurezza", - "Save KIP Settings": "Salva le impostazioni KIP", - "RAM Settings": "Impostazioni della RAM", - "CPU Settings": "Impostazioni della CPU", - "GPU Settings": "Impostazioni della GPU", - "Display Settings": "Impostazioni di visualizzazione", - "Experimental": "Sperimentale", - "GPU Scheduling Override Method": "Metodo di override della pianificazione GPU", - "can be dangerous and may cause": "può essere pericoloso e può causare", - "damage to your battery or charger!": "danni alla batteria o al caricabatterie!", - "Charge Current Override": "Override della corrente di carica", - "RAM Voltage Display Mode": "Modalità di visualizzazione della tensione RAM", - "Polling Interval": "Intervallo di polling", - "CPU Governor Minimum Frequency": "Frequenza minima del governatore della CPU", - "refresh rates may cause stress": "le frequenze di aggiornamento possono causare stress", - "or damage to your display! ": "o danni al display!", - "Proceed at your own risk!": "Procedi a tuo rischio e pericolo!", - "Max Handheld Display": "Display portatile massimo", - "Display Clock": "Visualizza orologio", - "Official Rating": "Valutazione ufficiale", - "TDP Threshold": "Soglia TDP", - "Power": "Potenza", - "Thermal Throttle Limit": "Limite della valvola termica", - "HP Mode": "Modalità HP", - "Default (Mariko)": "Predefinito (Mariko)", - "Default (Erista)": "Predefinito (Erista)", - "Rating": "Valutazione", - "Safe Max (Mariko)": "Safe Max (Mariko)", - "Safe Max (Erista)": "Safe Max (Erista)", - "RAM VDD2 Voltage": "Tensione RAM VDD2", - "Voltage": "Voltaggio", - "RAM VDDQ Voltage": "Voltaggio VDDQ della RAM", - "RAM Frequency Editor": "Editor della frequenza RAM", - "JEDEC.": "JEDEC.", - "High speedo needed!": "È necessaria l'alta velocità!", - "3333MHz (Needs extreme Speedo/PLL)": "3333 MHz (richiede Speedo/PLL estremo)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 MHz (richiede Speedo/PLL estremo)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 MHz (richiede Speedo/PLL estremo)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433 MHz (è necessario un ridicolo Speedo/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466 MHz (è necessario un ridicolo Speedo/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 MHz (è necessario un ridicolo Speedo/PLL)", - "Ram Max Clock": "Orologio Ram Max", - "RAM Latency Editor": "Editor della latenza RAM", - "RAM Timing Reductions": "Riduzioni della temporizzazione della RAM", - "Memory Timings": "Tempi di memoria", - "Advanced": "Avanzato", - "t6 tRTW Fine Tune": "t6 tRTW Sintonia fine", - "tRTW Fine Tune": "tRTW Sintonia fine", - "t7 tWTR Fine Tune": "t7 tWTR Sintonia fine", - "tWTR Fine Tune": "tWTR Sintonia fine", - "Memory Latencies": "Latenza della memoria", - "Read Latency": "Leggi latenza", - "Write Latency": "Scrivi latenza", - "CPU Boost Clock": "Orologio di potenziamento della CPU", - "CPU UV": "UV della CPU", - "CPU Unlock": "Sblocco della CPU", - "CPU VMIN": "CPUVMIN", - "CPU Max Voltage": "Voltaggio massimo della CPU", - "CPU Max Clock": "Orologio massimo della CPU", - "Extreme UV Table": "Tavolo UV estremo", - "CPU UV Table": "Tabella UV della CPU", - "CPU Low UV": "CPU con raggi UV bassi", - "CPU High UV": "UV elevato della CPU", - "CPU Low VMIN": "VMIN CPU basso", - "CPU High VMIN": "CPU alta VMIN", - "No Undervolt": "Nessuna sottotensione", - "SLT Table": "Tabella SLT", - "HiOPT Table": "Tabella HiOPT", - "GPU Undervolt Table": "Tabella di sottotensione GPU", - "GPU Minimum Voltage": "Voltaggio minimo della GPU", - "Calculate GPU Vmin": "Calcola GPU Vmin", - "GPU VMIN": "GPUVMIN", - "GPU Maximum Voltage": "Voltaggio massimo della GPU", - "GPU Voltage Offset": "Offset di tensione della GPU", - "Do not override": "Non sovrascrivere", - "Enabled (Default)": "Abilitato (impostazione predefinita)", - "96.6% limit": "Limite del 96,6%.", - "99.7% limit": "Limite del 99,7%.", - "GPU Scheduling Override": "Override della pianificazione GPU", - "Official Service": "Servizio ufficiale", - "GPU DVFS Mode": "Modalità DVFS GPU", - "GPU DVFS Offset": "Offset DVFS della GPU", - "GPU Voltage Table": "Tabella delle tensioni della GPU", - "GPU Custom Table (mV)": "Tabella personalizzata GPU (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075 MHz senza UV, 1152 MHz su SLT", - "or 1228MHz on HiOPT can cause ": "o 1228 MHz su HiOPT possono causare", - "permanent damage to your Switch!": "danni permanenti al tuo Switch!", - "921MHz without UV and 960MHz on": "921 MHz senza UV e 960 MHz attivi", - "SLT or HiOPT can cause ": "SLT o HiOPT possono causare" -} diff --git a/Source/sys-clk/overlay/lang/ja.json b/Source/sys-clk/overlay/lang/ja.json deleted file mode 100644 index fe415367..00000000 --- a/Source/sys-clk/overlay/lang/ja.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "情報", - "IDDQ:": "IDQ:", - "Module: ": "モジュール:", - "sys-dock status:": "システムドックのステータス:", - "SaltyNX status:": "SaltyNX ステータス:", - "RR Display status:": "RR 表示ステータス:", - "Wafer Position:": "ウェーハの位置:", - "Credits": "クレジット", - "Developers": "開発者", - "Contributors": "貢献者", - "Testers": "テスター", - "Special Thanks": "特別な感謝の気持ち", - "Unknown": "不明", - "Installed": "インストール済み", - "Not Installed": "インストールされていません", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "ビール製品ライセンス", - "Default": "デフォルト", - "Do Not Override": "上書きしないでください", - "Disabled": "障害者", - "Enabled": "有効", - " \\ue0e3 Reset": "\\ue0e3 リセット", - "Display": "ディスプレイ", - "Application changed\\n\\n": "アプリケーションが変更されました\\n\\n", - "The running application changed\\n\\n": "実行中のアプリケーションが変更されました\\n\\n", - "while editing was going on.": "編集を進めている最中でした。", - "Board": "理事会", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "hoc-clk sysmodule に接続できませんでした。\\n\\n", - "Please make sure everything is\\n\\n": "すべてが正しいことを確認してください\\n\\n", - "correctly installed and enabled.": "正しくインストールされ、有効になっています。", - "Fatal error": "致命的なエラー", - "Temporary Overrides ": "一時的なオーバーライド", - "Sleep Mode": "スリープモード", - "Stock": "在庫", - "Dev OC": "開発OC", - "Boost Mode": "ブーストモード", - "Safe Max": "セーフマックス", - "Unsafe Max": "危険なマックス", - "Absolute Max": "絶対最大値", - "Handheld Safe Max": "手持ち金庫マックス", - "Enable": "有効にする", - "Edit App Profile": "アプリプロファイルの編集", - "Edit Global Profile": "グローバルプロファイルの編集", - "Temporary Overrides": "一時的なオーバーライド", - "Settings": "設定", - "About": "について", - "Compiling with minimal features": "最小限の機能でコンパイルする", - "General Settings": "一般設定", - "Governor Settings": "ガバナーの設定", - "Safety Settings": "安全設定", - "Save KIP Settings": "KIP 設定の保存", - "RAM Settings": "RAM設定", - "CPU Settings": "CPUの設定", - "GPU Settings": "GPU設定", - "Display Settings": "表示設定", - "Experimental": "実験的", - "GPU Scheduling Override Method": "GPU スケジューリング オーバーライド メソッド", - "can be dangerous and may cause": "危険であり、原因となる可能性があります", - "damage to your battery or charger!": "バッテリーまたは充電器が損傷します。", - "Charge Current Override": "充電電流オーバーライド", - "RAM Voltage Display Mode": "RAM電圧表示モード", - "Polling Interval": "ポーリング間隔", - "CPU Governor Minimum Frequency": "CPU ガバナの最小周波数", - "refresh rates may cause stress": "リフレッシュレートがストレスを引き起こす可能性がある", - "or damage to your display! ": "ディスプレイに損傷を与えてしまいます。", - "Proceed at your own risk!": "自己責任で進めてください!", - "Max Handheld Display": "最大ハンドヘルドディスプレイ", - "Display Clock": "時計の表示", - "Official Rating": "公式評価", - "TDP Threshold": "TDP しきい値", - "Power": "パワー", - "Thermal Throttle Limit": "サーマルスロットル制限", - "HP Mode": "HPモード", - "Default (Mariko)": "デフォルト(マリコ)", - "Default (Erista)": "デフォルト(エリスタ)", - "Rating": "評価", - "Safe Max (Mariko)": "セーフマックス(マリコ)", - "Safe Max (Erista)": "セーフマックス(エリスタ)", - "RAM VDD2 Voltage": "RAM VDD2 電圧", - "Voltage": "電圧", - "RAM VDDQ Voltage": "RAM VDDQ 電圧", - "RAM Frequency Editor": "RAM周波数エディター", - "JEDEC.": "JEDEC。", - "High speedo needed!": "ハイスピードが必要です!", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz (エクストリーム Speedo/PLL が必要)", - "3366MHz (Needs extreme Speedo/PLL)": "3366MHz (エクストリーム Speedo/PLL が必要)", - "3400MHz (Needs extreme Speedo/PLL)": "3400MHz (エクストリーム Speedo/PLL が必要)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (とんでもない Speedo/PLL が必要)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz (とんでもない Speedo/PLL が必要)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz (とんでもない Speedo/PLL が必要)", - "Ram Max Clock": "ラムマックスクロック", - "RAM Latency Editor": "RAM レイテンシ エディター", - "RAM Timing Reductions": "RAM タイミングの削減", - "Memory Timings": "メモリタイミング", - "Advanced": "上級者向け", - "t6 tRTW Fine Tune": "t6 tRTW 微調整", - "tRTW Fine Tune": "tRTW 微調整", - "t7 tWTR Fine Tune": "t7 tWTR ファインチューン", - "tWTR Fine Tune": "tWTR ファインチューン", - "Memory Latencies": "メモリレイテンシ", - "Read Latency": "読み取りレイテンシー", - "Write Latency": "書き込みレイテンシ", - "CPU Boost Clock": "CPUブーストクロック", - "CPU UV": "CPU UV", - "CPU Unlock": "CPUロック解除", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "CPU最大電圧", - "CPU Max Clock": "CPU最大クロック", - "Extreme UV Table": "エクストリーム UV テーブル", - "CPU UV Table": "CPU UV テーブル", - "CPU Low UV": "CPU 低 UV", - "CPU High UV": "CPU 高紫外線", - "CPU Low VMIN": "CPU 低 VMIN", - "CPU High VMIN": "CPU の高い VMIN", - "No Undervolt": "不足電圧なし", - "SLT Table": "SLTテーブル", - "HiOPT Table": "HiOPT テーブル", - "GPU Undervolt Table": "GPUアンダーボルトテーブル", - "GPU Minimum Voltage": "GPUの最小電圧", - "Calculate GPU Vmin": "GPU Vmin を計算する", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "GPU最大電圧", - "GPU Voltage Offset": "GPU電圧オフセット", - "Do not override": "上書きしないでください", - "Enabled (Default)": "有効 (デフォルト)", - "96.6% limit": "96.6%制限", - "99.7% limit": "99.7%制限", - "GPU Scheduling Override": "GPU スケジュールのオーバーライド", - "Official Service": "正式サービス", - "GPU DVFS Mode": "GPU DVFS モード", - "GPU DVFS Offset": "GPU DVFS オフセット", - "GPU Voltage Table": "GPU電圧テーブル", - "GPU Custom Table (mV)": "GPUカスタムテーブル(mV)", - "1075MHz without UV, 1152MHz on SLT": "UVなしで1075MHz、SLTで1152MHz", - "or 1228MHz on HiOPT can cause ": "HiOPT で 1228MHz を使用すると、次のような問題が発生する可能性があります。", - "permanent damage to your Switch!": "Switch に永久的なダメージを与えます!", - "921MHz without UV and 960MHz on": "921MHz(UVなし)、960MHz(UVあり)", - "SLT or HiOPT can cause ": "SLT または HiOPT が原因となる可能性があります" -} diff --git a/Source/sys-clk/overlay/lang/jp.json b/Source/sys-clk/overlay/lang/jp.json deleted file mode 100644 index af92cbf7..00000000 --- a/Source/sys-clk/overlay/lang/jp.json +++ /dev/null @@ -1,146 +0,0 @@ -{ - "Information": "Information", - "IDDQ:": "IDDQ:", - "Module: ": "Module:", - "sys-dock status:": "sys-dock status:", - "SaltyNX status:": "SaltyNX status:", - "RR Display status:": "RR Display status:", - "Wafer Position:": "Wafer Position:", - "Credits": "Credits", - "Developers": "Developers", - "Contributors": "Contributors", - "Testers": "Testers", - "Special Thanks": "Special Thanks", - "Unknown": "Unknown", - "Installed": "Installed", - "Not Installed": "Not Installed", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "THE BEER-WARE LICENSE", - "Default": "Default", - "Do Not Override": "Do Not Override", - "Disabled": "Disabled", - "Enabled": "Enabled", - " \\ue0e3 Reset": "\\ue0e3 Reset", - "Display": "Display", - "Application changed\\n\\n": "Application changed\\n\\n", - "The running application changed\\n\\n": "The running application changed\\n\\n", - "while editing was going on.": "while editing was going on.", - "App ID": "App ID", - "Profile": "Profile", - "Board": "Board", - "USB Charger": "USB Charger", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Could not connect to hoc-clk sysmodule.\\n\\n", - "Please make sure everything is\\n\\n": "Please make sure everything is\\n\\n", - "correctly installed and enabled.": "correctly installed and enabled.", - "Fatal error": "Fatal error", - "Temporary Overrides ": "Temporary Overrides", - "Sleep Mode": "Sleep Mode", - "Stock": "Stock", - "Dev OC": "Dev OC", - "Boost Mode": "Boost Mode", - "Safe Max": "Safe Max", - "Unsafe Max": "Unsafe Max", - "Absolute Max": "Absolute Max", - "Handheld": "Handheld", - "Handheld Safe Max": "Handheld Safe Max", - "Docked": "Docked", - "Enable": "Enable", - "Edit App Profile": "Edit App Profile", - "Edit Global Profile": "Edit Global Profile", - "Temporary Overrides": "Temporary Overrides", - "Settings": "Settings", - "About": "About", - "Compiling with minimal features": "Compiling with minimal features", - "General Settings": "General Settings", - "Governor Settings": "Governor Settings", - "Safety Settings": "Safety Settings", - "Save KIP Settings": "Save KIP Settings", - "RAM Settings": "RAM Settings", - "CPU Settings": "CPU Settings", - "GPU Settings": "GPU Settings", - "Display Settings": "Display Settings", - "Experimental": "Experimental", - "GPU Scheduling Override Method": "GPU Scheduling Override Method", - "can be dangerous and may cause": "can be dangerous and may cause", - "damage to your battery or charger!": "damage to your battery or charger!", - "Charge Current Override": "Charge Current Override", - "RAM Voltage Display Mode": "RAM Voltage Display Mode", - "Polling Interval": "Polling Interval", - "CPU Governor Minimum Frequency": "CPU Governor Minimum Frequency", - "refresh rates may cause stress": "refresh rates may cause stress", - "or damage to your display! ": "or damage to your display!", - "Proceed at your own risk!": "Proceed at your own risk!", - "Max Handheld Display": "Max Handheld Display", - "Display Clock": "Display Clock", - "Official Rating": "Official Rating", - "TDP Threshold": "TDP Threshold", - "Power": "Power", - "Thermal Throttle Limit": "Thermal Throttle Limit", - "HP Mode": "HP Mode", - "Default (Mariko)": "Default (Mariko)", - "Default (Erista)": "Default (Erista)", - "Rating": "Rating", - "Safe Max (Mariko)": "Safe Max (Mariko)", - "Safe Max (Erista)": "Safe Max (Erista)", - "RAM VDD2 Voltage": "RAM VDD2 Voltage", - "Voltage": "Voltage", - "RAM VDDQ Voltage": "RAM VDDQ Voltage", - "RAM Frequency Editor": "RAM Frequency Editor", - "JEDEC.": "JEDEC.", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz (Needs extreme Speedo/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366MHz (Needs extreme Speedo/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400MHz (Needs extreme Speedo/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (Needs ridiculous Speedo/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz (Needs ridiculous Speedo/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz (Needs ridiculous Speedo/PLL)", - "Ram Max Clock": "Ram Max Clock", - "RAM Latency Editor": "RAM Latency Editor", - "RAM Timing Reductions": "RAM Timing Reductions", - "Memory Timings": "Memory Timings", - "tREFI": "tREFI", - "Advanced": "Advanced", - "t6 tRTW Fine Tune": "t6 tRTW Fine Tune", - "tRTW Fine Tune": "tRTW Fine Tune", - "t7 tWTR Fine Tune": "t7 tWTR Fine Tune", - "tWTR Fine Tune": "tWTR Fine Tune", - "Memory Latencies": "Memory Latencies", - "Read Latency": "Read Latency", - "Write Latency": "Write Latency", - "CPU Boost Clock": "CPU Boost Clock", - "CPU UV": "CPU UV", - "CPU Unlock": "CPU Unlock", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "CPU Max Voltage", - "CPU Max Clock": "CPU Max Clock", - "Extreme UV Table": "Extreme UV Table", - "CPU UV Table": "CPU UV Table", - "CPU Low UV": "CPU Low UV", - "CPU High UV": "CPU High UV", - "CPU Low VMIN": "CPU Low VMIN", - "CPU High VMIN": "CPU High VMIN", - "No Undervolt": "No Undervolt", - "SLT Table": "SLT Table", - "HiOPT Table": "HiOPT Table", - "GPU Undervolt Table": "GPU Undervolt Table", - "GPU Minimum Voltage": "GPU Minimum Voltage", - "Calculate GPU Vmin": "Calculate GPU Vmin", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "GPU Maximum Voltage", - "GPU Voltage Offset": "GPU Voltage Offset", - "Do not override": "Do not override", - "Enabled (Default)": "Enabled (Default)", - "96.6% limit": "96.6% limit", - "99.7% limit": "99.7% limit", - "GPU Scheduling Override": "GPU Scheduling Override", - "Official Service": "Official Service", - "GPU DVFS Mode": "GPU DVFS Mode", - "GPU DVFS Offset": "GPU DVFS Offset", - "GPU Voltage Table": "GPU Voltage Table", - "GPU Custom Table (mV)": "GPU Custom Table (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075MHz without UV, 1152MHz on SLT", - "or 1228MHz on HiOPT can cause ": "or 1228MHz on HiOPT can cause", - "permanent damage to your Switch!": "permanent damage to your Switch!", - "921MHz without UV and 960MHz on": "921MHz without UV and 960MHz on", - "SLT or HiOPT can cause ": "SLT or HiOPT can cause" -} diff --git a/Source/sys-clk/overlay/lang/ko.json b/Source/sys-clk/overlay/lang/ko.json deleted file mode 100644 index 09e73e66..00000000 --- a/Source/sys-clk/overlay/lang/ko.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "정보", - "IDDQ:": "IDDQ:", - "Module: ": "모듈:", - "sys-dock status:": "sys-dock 상태:", - "SaltyNX status:": "SaltyNX 상태:", - "RR Display status:": "RR 표시 상태:", - "Wafer Position:": "웨이퍼 위치:", - "Credits": "크레딧", - "Developers": "개발자", - "Contributors": "기여자", - "Testers": "테스터", - "Special Thanks": "특별한 분", - "Unknown": "알 수 없음", - "Installed": "설치됨", - "Not Installed": "설치되지 않음", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "맥주 제품 라이센스", - "Default": "기본값", - "Do Not Override": "재정의하지 마십시오", - "Disabled": "비활성화", - "Enabled": "활성화됨", - " \\ue0e3 Reset": "\\ue0e3 재설정", - "Display": "디스플레이", - "Application changed\\n\\n": "애플리케이션이 변경되었습니다.\\n\\n", - "The running application changed\\n\\n": "실행 중인 애플리케이션이 변경되었습니다.\\n\\n", - "while editing was going on.": "편집이 진행되는 동안.", - "Board": "보드", - "%u.%u%u mV": "%u.%u%umV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "hoc-clk 시스템 모듈에 연결할 수 없습니다.\\n\\n", - "Please make sure everything is\\n\\n": "모든 것이 올바른지 확인하십시오.\\n\\n", - "correctly installed and enabled.": "올바르게 설치되고 활성화되었습니다.", - "Fatal error": "치명적인 오류", - "Temporary Overrides ": "임시 재정의", - "Sleep Mode": "절전 모드", - "Stock": "주식", - "Dev OC": "개발 OC", - "Overwrite Boost Mode": "부스트 모드 덮어쓰기", - "Safe Max": "안전함 최대값", - "Unsafe Max": "불안정 최대값", - "Absolute Max": "절대 최대값", - "Handheld Safe Max": "휴대모드 안전함 최대값", - "Enable": "활성화", - "Edit App Profile": "앱 프로필 편집", - "Edit Global Profile": "글로벌 프로필 편집", - "Temporary Overrides": "임시 재정의", - "Settings": "설정", - "About": "소개", - "Compiling with minimal features": "최소한의 기능으로 컴파일하기", - "General Settings": "일반 설정", - "Governor Settings": "거버너 설정", - "Safety Settings": "안전 설정", - "Save KIP Settings": "KIP 설정 저장", - "RAM Settings": "RAM 설정", - "CPU Settings": "CPU 설정", - "GPU Settings": "GPU 설정", - "Display Settings": "디스플레이 설정", - "Experimental": "실험적", - "GPU Scheduling Override Method": "GPU 스케줄링 재정의 방법", - "can be dangerous and may cause": "위험할 수 있고 원인이 될 수 있습니다.", - "damage to your battery or charger!": "배터리나 충전기가 손상되었습니다!", - "Charge Current Override": "충전 전류 오버라이드", - "RAM Voltage Display Mode": "RAM 전압 표시 모드", - "Polling Interval": "폴링 간격", - "CPU Governor Minimum Frequency": "CPU 거버너 최소 주파수", - "refresh rates may cause stress": "디스플레이 주사율 빈도 변경은", - "or damage to your display! ": "기기에 손상이 발생될 수 있습니다!", - "Proceed at your own risk!": "책임하에 주의해서 사용하십시오!", - "Max Handheld Display": "최대 휴대용 디스플레이", - "Display Clock": "디스플레이 클럭", - "Official Rating": "공식 등급", - "TDP Threshold": "TDP 임계값", - "Power": "힘", - "Thermal Throttle Limit": "열 스로틀 한계", - "HP Mode": "HP 모드", - "Default (Mariko)": "기본값(마리코)", - "Default (Erista)": "기본값(에리스타)", - "Rating": "표준값", - "Safe Max (Mariko)": "안전함 최대치(마리코)", - "Safe Max (Erista)": "안전함 최대치(에리스타)", - "RAM VDD2 Voltage": "RAM VDD2 전압", - "Voltage": "전압", - "RAM VDDQ Voltage": "RAM VDDQ 전압", - "RAM Frequency Editor": "RAM 주파수 편집기", - "JEDEC.": "JEDEC.", - "High speedo needed!": "높은 스피도값이 필요합니다!", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz(극단적인 Speedo/PLL 필요)", - "3366MHz (Needs extreme Speedo/PLL)": "3366MHz(극단적인 Speedo/PLL 필요)", - "3400MHz (Needs extreme Speedo/PLL)": "3400MHz(극단적인 Speedo/PLL 필요)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (말도 안 되는 Speedo/PLL 필요)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz(터무니없는 Speedo/PLL 필요)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz(터무니없는 Speedo/PLL 필요)", - "Ram Max Clock": "RAM 최대 클럭", - "RAM Latency Editor": "RAM 지연 시간 편집기", - "RAM Timing Reductions": "RAM 타이밍 편집기", - "Memory Timings": "메모리 타이밍", - "Advanced": "고급", - "t6 tRTW Fine Tune": "t6 tRTW 미세 조정", - "tRTW Fine Tune": "tRTW 미세 조정", - "t7 tWTR Fine Tune": "t7 tWTR 미세 조정", - "tWTR Fine Tune": "tWTR 미세 조정", - "Memory Latencies": "메모리 지연 시간", - "Read Latency": "읽기 지연 시간", - "Write Latency": "쓰기 지연 시간", - "CPU Boost Clock": "CPU 부스트 클럭", - "CPU UV": "CPU 언더볼트", - "CPU Unlock": "CPU 잠금 해제", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "CPU 최대 전압", - "CPU Max Clock": "CPU 최대 클럭", - "Extreme UV Table": "익스트림 테이블", - "CPU UV Table": "CPU 언더볼트 테이블", - "CPU Low UV": "CPU 저주파 언더볼트", - "CPU High UV": "CPU 고주파 언더볼트", - "CPU Low VMIN": "CPU 저주파 최소 전압", - "CPU High VMIN": "CPU 고주파 최소 전압", - "No Undervolt": "언더볼트 없음", - "SLT Table": "SLT 테이블", - "HiOPT Table": "HiOPT 테이블", - "GPU Undervolt Table": "GPU 언더볼트 테이블", - "GPU Minimum Voltage": "GPU 최소 전압", - "Calculate GPU Vmin": "GPU Vmin 계산", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "GPU 최대 전압", - "GPU Voltage Offset": "GPU 전압 오프셋", - "Do not override": "재정의하지 않음", - "Enabled (Default)": "활성화됨(기본값)", - "96.6% limit": "96.6% 한도", - "99.7% limit": "99.7% 한도", - "GPU Scheduling Override": "GPU 스케줄링 재정의", - "Official Service": "공식 서비스", - "GPU DVFS Mode": "GPU DVFS 모드", - "GPU DVFS Offset": "GPU DVFS 오프셋", - "GPU Voltage Table": "GPU 전압 테이블", - "GPU Custom Table (mV)": "GPU 사용자 정의 테이블(mV)", - "1075MHz without UV, 1152MHz on SLT": "UV 없이 1075MHz, SLT에서 1152MHz", - "or 1228MHz on HiOPT can cause ": "또는 HiOPT에서 1228MHz를 사용하면", - "permanent damage to your Switch!": "스위치가 영구적으로 손상될 수 있습니다!", - "921MHz without UV and 960MHz on": "UV가 없는 경우 921MHz, 켜진 경우에는 960MHz", - "SLT or HiOPT can cause ": "SLT 또는 HiOPT는 다음을 유발할 수 있습니다." -} diff --git a/Source/sys-clk/overlay/lang/nl.json b/Source/sys-clk/overlay/lang/nl.json deleted file mode 100644 index 1005d3c2..00000000 --- a/Source/sys-clk/overlay/lang/nl.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Informatie", - "IDDQ:": "IDDQ:", - "Module: ": "module:", - "sys-dock status:": "sys-dock-status:", - "SaltyNX status:": "SaltyNX-status:", - "RR Display status:": "RR Weergavestatus:", - "Wafer Position:": "Waferpositie:", - "Credits": "Kredieten", - "Developers": "Ontwikkelaars", - "Contributors": "Bijdragers", - "Testers": "Testers", - "Special Thanks": "Speciale dank", - "Unknown": "Onbekend", - "Installed": "Geïnstalleerd", - "Not Installed": "Niet geïnstalleerd", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "DE LICENTIE VOOR BIERWAREN", - "Default": "Standaard", - "Do Not Override": "Niet overschrijven", - "Disabled": "Uitgeschakeld", - "Enabled": "Ingeschakeld", - " \\ue0e3 Reset": "\\ue0e3 Opnieuw instellen", - "Display": "Weergave", - "Application changed\\n\\n": "Applicatie gewijzigd\\n\\n", - "The running application changed\\n\\n": "De actieve applicatie is gewijzigd\\n\\n", - "while editing was going on.": "terwijl er werd bewerkt.", - "Board": "Bord", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Kan geen verbinding maken met hoc-clk sysmodule.\\n\\n", - "Please make sure everything is\\n\\n": "Zorg ervoor dat alles in orde is\\n\\n", - "correctly installed and enabled.": "correct geïnstalleerd en ingeschakeld.", - "Fatal error": "Fatale fout", - "Temporary Overrides ": "Tijdelijke overschrijvingen", - "Sleep Mode": "Slaapmodus", - "Stock": "Voorraad", - "Dev OC": "Ontwikkelaar OC", - "Boost Mode": "Boost-modus", - "Safe Max": "Veilig Max", - "Unsafe Max": "OnveiligMax", - "Absolute Max": "Absoluut Max", - "Handheld Safe Max": "Handkluis Max", - "Enable": "Inschakelen", - "Edit App Profile": "App-profiel bewerken", - "Edit Global Profile": "Globaal profiel bewerken", - "Temporary Overrides": "Tijdelijke overschrijvingen", - "Settings": "Instellingen", - "About": "Over", - "Compiling with minimal features": "Compileren met minimale functies", - "General Settings": "Algemene instellingen", - "Governor Settings": "Gouverneur instellingen", - "Safety Settings": "Veiligheidsinstellingen", - "Save KIP Settings": "Sla KIP-instellingen op", - "RAM Settings": "RAM-instellingen", - "CPU Settings": "CPU-instellingen", - "GPU Settings": "GPU-instellingen", - "Display Settings": "Weergave-instellingen", - "Experimental": "Experimenteel", - "GPU Scheduling Override Method": "Methode voor het overschrijven van GPU-planning", - "can be dangerous and may cause": "kan gevaarlijk zijn en kan veroorzaken", - "damage to your battery or charger!": "schade aan uw accu of lader!", - "Charge Current Override": "Laadstroom overschrijven", - "RAM Voltage Display Mode": "Weergavemodus RAM-spanning", - "Polling Interval": "Polling-interval", - "CPU Governor Minimum Frequency": "Minimale frequentie CPU-regelaar", - "refresh rates may cause stress": "vernieuwingsfrequenties kunnen stress veroorzaken", - "or damage to your display! ": "of schade aan uw display!", - "Proceed at your own risk!": "Ga verder op eigen risico!", - "Max Handheld Display": "Maximaal handheld-display", - "Display Clock": "Klok weergeven", - "Official Rating": "Officiële beoordeling", - "TDP Threshold": "TDP-drempel", - "Power": "Macht", - "Thermal Throttle Limit": "Thermische gaslimiet", - "HP Mode": "HP-modus", - "Default (Mariko)": "Standaard (Mariko)", - "Default (Erista)": "Standaard (Erista)", - "Rating": "Beoordeling", - "Safe Max (Mariko)": "Veilig Max (Mariko)", - "Safe Max (Erista)": "Veilige Max (Erista)", - "RAM VDD2 Voltage": "RAM VDD2-spanning", - "Voltage": "Spanning", - "RAM VDDQ Voltage": "RAM VDDQ-spanning", - "RAM Frequency Editor": "RAM-frequentie-editor", - "JEDEC.": "JEDEC.", - "High speedo needed!": "Hoge snelheid nodig!", - "3333MHz (Needs extreme Speedo/PLL)": "3333 MHz (vereist extreme snelheidsmeter/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 MHz (vereist extreme snelheidsmeter/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 MHz (vereist extreme snelheidsmeter/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (heeft een belachelijke snelheidsmeter/PLL nodig)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz (heeft een belachelijke snelheidsmeter/PLL nodig)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 MHz (heeft een belachelijke snelheidsmeter/PLL nodig)", - "Ram Max Clock": "Ram Max-klok", - "RAM Latency Editor": "RAM-latentie-editor", - "RAM Timing Reductions": "RAM-timingreducties", - "Memory Timings": "Geheugentijden", - "Advanced": "Geavanceerd", - "t6 tRTW Fine Tune": "t6 tRTW Fijnafstemming", - "tRTW Fine Tune": "tRTW Fijnafstemming", - "t7 tWTR Fine Tune": "t7 tWTR Fijnafstemming", - "tWTR Fine Tune": "tWTR Fijnafstemming", - "Memory Latencies": "Geheugenlatenties", - "Read Latency": "Lees Latentie", - "Write Latency": "Schrijf latentie", - "CPU Boost Clock": "CPU-boostklok", - "CPU UV": "CPU-UV", - "CPU Unlock": "CPU-ontgrendeling", - "CPU VMIN": "CPU-VMIN", - "CPU Max Voltage": "Maximale CPU-spanning", - "CPU Max Clock": "CPU maximale klok", - "Extreme UV Table": "Extreme UV-tafel", - "CPU UV Table": "CPU UV-tabel", - "CPU Low UV": "CPU Lage UV", - "CPU High UV": "CPU Hoge UV", - "CPU Low VMIN": "CPU Lage VMIN", - "CPU High VMIN": "CPU Hoge VMIN", - "No Undervolt": "Geen ondervolt", - "SLT Table": "SLT-tabel", - "HiOPT Table": "HiOPT-tabel", - "GPU Undervolt Table": "GPU-undervolttabel", - "GPU Minimum Voltage": "GPU-minimale spanning", - "Calculate GPU Vmin": "Bereken GPU Vmin", - "GPU VMIN": "GPU-VMIN", - "GPU Maximum Voltage": "GPU maximale spanning", - "GPU Voltage Offset": "GPU-spanningsoffset", - "Do not override": "Niet overschrijven", - "Enabled (Default)": "Ingeschakeld (standaard)", - "96.6% limit": "96,6% limiet", - "99.7% limit": "99,7% limiet", - "GPU Scheduling Override": "GPU-planning negeren", - "Official Service": "Officiële dienst", - "GPU DVFS Mode": "GPU DVFS-modus", - "GPU DVFS Offset": "GPU DVFS-offset", - "GPU Voltage Table": "GPU-spanningstabel", - "GPU Custom Table (mV)": "Aangepaste GPU-tabel (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075MHz zonder UV, 1152MHz op SLT", - "or 1228MHz on HiOPT can cause ": "of 1228MHz op HiOPT kan dit veroorzaken", - "permanent damage to your Switch!": "blijvende schade aan uw Switch!", - "921MHz without UV and 960MHz on": "921MHz zonder UV en 960MHz aan", - "SLT or HiOPT can cause ": "SLT of HiOPT kunnen dit veroorzaken" -} diff --git a/Source/sys-clk/overlay/lang/pl.json b/Source/sys-clk/overlay/lang/pl.json deleted file mode 100644 index 1233aa93..00000000 --- a/Source/sys-clk/overlay/lang/pl.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Informacje", - "IDDQ:": "IDDQ:", - "Module: ": "Moduł:", - "sys-dock status:": "stan sys-dock:", - "SaltyNX status:": "Stan SaltyNX:", - "RR Display status:": "Stan wyświetlacza:", - "Wafer Position:": "Pozycja wafla:", - "Credits": "Kredyty", - "Developers": "Deweloperzy", - "Contributors": "Współautorzy", - "Testers": "Testery", - "Special Thanks": "Specjalne podziękowania", - "Unknown": "Nieznany", - "Installed": "Zainstalowany", - "Not Installed": "Nie zainstalowano", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "LICENCJA NA WYROBY PIWNE", - "Default": "Domyślne", - "Do Not Override": "Nie zastępuj", - "Disabled": "Niepełnosprawny", - "Enabled": "Włączone", - " \\ue0e3 Reset": "\\ue0e3 Zresetuj", - "Display": "Wyświetlacz", - "Application changed\\n\\n": "Aplikacja została zmieniona\\n\\n", - "The running application changed\\n\\n": "Działająca aplikacja została zmieniona\\n\\n", - "while editing was going on.": "podczas gdy edycja była w toku.", - "Board": "Deska", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Nie można połączyć się z modułem sysmodule hoc-clk.\\n\\n", - "Please make sure everything is\\n\\n": "Upewnij się, że wszystko jest\\n\\n", - "correctly installed and enabled.": "poprawnie zainstalowany i włączony.", - "Fatal error": "Fatalny błąd", - "Temporary Overrides ": "Tymczasowe nadpisania", - "Sleep Mode": "Tryb uśpienia", - "Stock": "Zapas", - "Dev OC": "Dev OC", - "Boost Mode": "Tryb wzmocnienia", - "Safe Max": "Bezpieczny maks", - "Unsafe Max": "Niebezpieczny maks", - "Absolute Max": "Absolutny maks", - "Handheld Safe Max": "Sejf ręczny Max", - "Enable": "Włącz", - "Edit App Profile": "Edytuj profil aplikacji", - "Edit Global Profile": "Edytuj profil globalny", - "Temporary Overrides": "Tymczasowe nadpisania", - "Settings": "Ustawienia", - "About": "O", - "Compiling with minimal features": "Kompilacja z minimalnymi funkcjami", - "General Settings": "Ustawienia ogólne", - "Governor Settings": "Ustawienia gubernatora", - "Safety Settings": "Ustawienia bezpieczeństwa", - "Save KIP Settings": "Zapisz ustawienia KIP", - "RAM Settings": "Ustawienia pamięci RAM", - "CPU Settings": "Ustawienia procesora", - "GPU Settings": "Ustawienia GPU", - "Display Settings": "Ustawienia wyświetlania", - "Experimental": "Eksperymentalny", - "GPU Scheduling Override Method": "Metoda obejścia harmonogramu GPU", - "can be dangerous and may cause": "może być niebezpieczne i powodować", - "damage to your battery or charger!": "uszkodzenie akumulatora lub ładowarki!", - "Charge Current Override": "Obejście prądu ładowania", - "RAM Voltage Display Mode": "Tryb wyświetlania napięcia RAM", - "Polling Interval": "Interwał odpytywania", - "CPU Governor Minimum Frequency": "Minimalna częstotliwość regulatora procesora", - "refresh rates may cause stress": "częstotliwości odświeżania mogą powodować stres", - "or damage to your display! ": "lub uszkodzenie wyświetlacza!", - "Proceed at your own risk!": "Postępuj na własne ryzyko!", - "Max Handheld Display": "Maksymalny wyświetlacz ręczny", - "Display Clock": "Wyświetl zegar", - "Official Rating": "Oficjalna ocena", - "TDP Threshold": "Próg TDP", - "Power": "Moc", - "Thermal Throttle Limit": "Limit przepustnicy termicznej", - "HP Mode": "Tryb HP", - "Default (Mariko)": "Domyślny (Mariko)", - "Default (Erista)": "Domyślny (Erista)", - "Rating": "Ocena", - "Safe Max (Mariko)": "Bezpieczny Max (Mariko)", - "Safe Max (Erista)": "Bezpieczny Max (Erista)", - "RAM VDD2 Voltage": "Napięcie pamięci RAM VDD2", - "Voltage": "Napięcie", - "RAM VDDQ Voltage": "Napięcie RAM VDDQ", - "RAM Frequency Editor": "Edytor częstotliwości RAM", - "JEDEC.": "JEDEC.", - "High speedo needed!": "Potrzebna duża prędkość!", - "3333MHz (Needs extreme Speedo/PLL)": "3333 MHz (wymaga ekstremalnego Speedo/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 MHz (wymaga ekstremalnego Speedo/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 MHz (wymaga ekstremalnego Speedo/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433 MHz (potrzebuje śmiesznego Speedo/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466 MHz (potrzebuje śmiesznego Speedo/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 MHz (potrzebuje śmiesznego Speedo/PLL)", - "Ram Max Clock": "Zegar Ram Max", - "RAM Latency Editor": "Edytor opóźnień pamięci RAM", - "RAM Timing Reductions": "Zmniejszenie taktowania pamięci RAM", - "Memory Timings": "Taktowanie pamięci", - "Advanced": "Zaawansowane", - "t6 tRTW Fine Tune": "t6 tRTW Dostrój", - "tRTW Fine Tune": "tRTW Dostosuj", - "t7 tWTR Fine Tune": "t7 tWTR Dostosuj", - "tWTR Fine Tune": "tWTR Dostosuj", - "Memory Latencies": "Opóźnienia pamięci", - "Read Latency": "Przeczytaj Opóźnienie", - "Write Latency": "Opóźnienie zapisu", - "CPU Boost Clock": "Zegar wzmocnienia procesora", - "CPU UV": "Procesor UV", - "CPU Unlock": "Odblokowanie procesora", - "CPU VMIN": "Procesor VMIN", - "CPU Max Voltage": "Maksymalne napięcie procesora", - "CPU Max Clock": "Maks. zegar procesora", - "Extreme UV Table": "Ekstremalny stół UV", - "CPU UV Table": "Tabela UV procesora", - "CPU Low UV": "Niskie promieniowanie UV procesora", - "CPU High UV": "Wysokie promieniowanie UV procesora", - "CPU Low VMIN": "Niski poziom VMIN procesora", - "CPU High VMIN": "Wysoki poziom VMIN procesora", - "No Undervolt": "Brak Undervolta", - "SLT Table": "Stół SLT", - "HiOPT Table": "Stół HiOPT", - "GPU Undervolt Table": "Tabela niedoboru napięcia GPU", - "GPU Minimum Voltage": "Minimalne napięcie procesora graficznego", - "Calculate GPU Vmin": "Oblicz Vmin GPU", - "GPU VMIN": "VMIN GPU", - "GPU Maximum Voltage": "Maksymalne napięcie procesora graficznego", - "GPU Voltage Offset": "Przesunięcie napięcia GPU", - "Do not override": "Nie zastępuj", - "Enabled (Default)": "Włączone (domyślnie)", - "96.6% limit": "Limit 96,6%.", - "99.7% limit": "Limit 99,7%.", - "GPU Scheduling Override": "Zastąpienie harmonogramu GPU", - "Official Service": "Oficjalny serwis", - "GPU DVFS Mode": "Tryb DVFS procesora graficznego", - "GPU DVFS Offset": "Przesunięcie DVFS GPU", - "GPU Voltage Table": "Tabela napięć GPU", - "GPU Custom Table (mV)": "Tabela niestandardowa GPU (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075 MHz bez UV, 1152 MHz na SLT", - "or 1228MHz on HiOPT can cause ": "lub 1228 MHz na HiOPT może powodować", - "permanent damage to your Switch!": "trwałe uszkodzenie Switcha!", - "921MHz without UV and 960MHz on": "921 MHz bez UV i 960 MHz włączone", - "SLT or HiOPT can cause ": "Przyczyną mogą być SLT lub HiOPT" -} diff --git a/Source/sys-clk/overlay/lang/pt.json b/Source/sys-clk/overlay/lang/pt.json deleted file mode 100644 index fbddab17..00000000 --- a/Source/sys-clk/overlay/lang/pt.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Informação", - "IDDQ:": "IDDQ:", - "Module: ": "Módulo:", - "sys-dock status:": "status do dock do sistema:", - "SaltyNX status:": "Status do SaltyNX:", - "RR Display status:": "Status de exibição do RR:", - "Wafer Position:": "Posição da bolacha:", - "Credits": "Créditos", - "Developers": "Desenvolvedores", - "Contributors": "Colaboradores", - "Testers": "Testadores", - "Special Thanks": "Agradecimentos especiais", - "Unknown": "Desconhecido", - "Installed": "Instalado", - "Not Installed": "Não instalado", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "A LICENÇA DE CERVEJA", - "Default": "Padrão", - "Do Not Override": "Não substituir", - "Disabled": "Desativado", - "Enabled": "Habilitado", - " \\ue0e3 Reset": "\\ue0e3 Redefinir", - "Display": "Exibição", - "Application changed\\n\\n": "Aplicativo alterado\\n\\n", - "The running application changed\\n\\n": "O aplicativo em execução foi alterado\\n\\n", - "while editing was going on.": "enquanto a edição estava acontecendo.", - "Board": "Conselho", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Não foi possível conectar-se ao sysmodule hoc-clk.\\n\\n", - "Please make sure everything is\\n\\n": "Verifique se tudo está\\n\\n", - "correctly installed and enabled.": "corretamente instalado e ativado.", - "Fatal error": "Erro fatal", - "Temporary Overrides ": "Substituições temporárias", - "Sleep Mode": "Modo de suspensão", - "Stock": "Estoque", - "Dev OC": "Desenvolvedor OC", - "Boost Mode": "Modo de reforço", - "Safe Max": "Máx. Seguro", - "Unsafe Max": "Máximo inseguro", - "Absolute Max": "Máximo absoluto", - "Handheld Safe Max": "Portátil Seguro Máx.", - "Enable": "Habilitar", - "Edit App Profile": "Editar perfil do aplicativo", - "Edit Global Profile": "Editar perfil global", - "Temporary Overrides": "Substituições temporárias", - "Settings": "Configurações", - "About": "Sobre", - "Compiling with minimal features": "Compilando com recursos mínimos", - "General Settings": "Configurações Gerais", - "Governor Settings": "Configurações do Governador", - "Safety Settings": "Configurações de segurança", - "Save KIP Settings": "Salvar configurações KIP", - "RAM Settings": "Configurações de RAM", - "CPU Settings": "Configurações de CPU", - "GPU Settings": "Configurações de GPU", - "Display Settings": "Configurações de exibição", - "Experimental": "Experimental", - "GPU Scheduling Override Method": "Método de substituição de agendamento de GPU", - "can be dangerous and may cause": "pode ser perigoso e causar", - "damage to your battery or charger!": "danos à sua bateria ou carregador!", - "Charge Current Override": "Substituição de corrente de carga", - "RAM Voltage Display Mode": "Modo de exibição de tensão RAM", - "Polling Interval": "Intervalo de votação", - "CPU Governor Minimum Frequency": "Frequência Mínima do Governador da CPU", - "refresh rates may cause stress": "taxas de atualização podem causar estresse", - "or damage to your display! ": "ou danos ao seu monitor!", - "Proceed at your own risk!": "Prossiga por sua conta e risco!", - "Max Handheld Display": "Visor portátil máximo", - "Display Clock": "Exibir relógio", - "Official Rating": "Classificação Oficial", - "TDP Threshold": "Limite de TDP", - "Power": "Poder", - "Thermal Throttle Limit": "Limite de aceleração térmica", - "HP Mode": "Modo HP", - "Default (Mariko)": "Padrão (Mariko)", - "Default (Erista)": "Padrão (Erista)", - "Rating": "Avaliação", - "Safe Max (Mariko)": "Máximo Seguro (Mariko)", - "Safe Max (Erista)": "Seguro Max (Erista)", - "RAM VDD2 Voltage": "Tensão RAM VDD2", - "Voltage": "Tensão", - "RAM VDDQ Voltage": "Tensão RAM VDDQ", - "RAM Frequency Editor": "Editor de frequência RAM", - "JEDEC.": "JEDEC.", - "High speedo needed!": "Alta velocidade necessária!", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz (precisa de Speedo/PLL extremo)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 MHz (precisa de Speedo/PLL extremo)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 MHz (precisa de Speedo/PLL extremo)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (precisa de Speedo/PLL ridículo)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466 MHz (precisa de Speedo/PLL ridículo)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 MHz (precisa de Speedo/PLL ridículo)", - "Ram Max Clock": "Relógio máximo de Ram", - "RAM Latency Editor": "Editor de latência de RAM", - "RAM Timing Reductions": "Reduções de tempo de RAM", - "Memory Timings": "Tempos de memória", - "Advanced": "Avançado", - "t6 tRTW Fine Tune": "t6 tRTW Ajuste fino", - "tRTW Fine Tune": "Ajuste fino tRTW", - "t7 tWTR Fine Tune": "t7 tWTR Ajuste fino", - "tWTR Fine Tune": "Ajuste fino tWTR", - "Memory Latencies": "Latências de memória", - "Read Latency": "Latência de leitura", - "Write Latency": "Latência de gravação", - "CPU Boost Clock": "Relógio de aumento da CPU", - "CPU UV": "UV da CPU", - "CPU Unlock": "Desbloqueio da CPU", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "Tensão máxima da CPU", - "CPU Max Clock": "Relógio máximo da CPU", - "Extreme UV Table": "Mesa UV Extrema", - "CPU UV Table": "Tabela UV da CPU", - "CPU Low UV": "UV baixo da CPU", - "CPU High UV": "CPU alta UV", - "CPU Low VMIN": "CPU baixa VMIN", - "CPU High VMIN": "VMIN alto da CPU", - "No Undervolt": "Sem subtensão", - "SLT Table": "Tabela SLT", - "HiOPT Table": "Tabela HiOPT", - "GPU Undervolt Table": "Tabela de subtensão da GPU", - "GPU Minimum Voltage": "Tensão mínima da GPU", - "Calculate GPU Vmin": "Calcular Vmin da GPU", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "Tensão máxima da GPU", - "GPU Voltage Offset": "Compensação de tensão da GPU", - "Do not override": "Não substitua", - "Enabled (Default)": "Habilitado (padrão)", - "96.6% limit": "Limite de 96,6%", - "99.7% limit": "Limite de 99,7%", - "GPU Scheduling Override": "Substituição de agendamento de GPU", - "Official Service": "Serviço Oficial", - "GPU DVFS Mode": "Modo GPU DVFS", - "GPU DVFS Offset": "Deslocamento DVFS da GPU", - "GPU Voltage Table": "Tabela de tensão da GPU", - "GPU Custom Table (mV)": "Tabela personalizada de GPU (mV)", - "1075MHz without UV, 1152MHz on SLT": "1075 MHz sem UV, 1152 MHz em SLT", - "or 1228MHz on HiOPT can cause ": "ou 1228 MHz em HiOPT pode causar", - "permanent damage to your Switch!": "danos permanentes ao seu Switch!", - "921MHz without UV and 960MHz on": "921 MHz sem UV e 960 MHz ativado", - "SLT or HiOPT can cause ": "SLT ou HiOPT podem causar" -} diff --git a/Source/sys-clk/overlay/lang/ru.json b/Source/sys-clk/overlay/lang/ru.json deleted file mode 100644 index 4cfdb1bd..00000000 --- a/Source/sys-clk/overlay/lang/ru.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Информация", - "IDDQ:": "ИДДК:", - "Module: ": "Модуль:", - "sys-dock status:": "Статус системной док-станции:", - "SaltyNX status:": "Статус SaltyNX:", - "RR Display status:": "Статус отображения RR:", - "Wafer Position:": "Позиция вафли:", - "Credits": "Кредиты", - "Developers": "Разработчики", - "Contributors": "Авторы", - "Testers": "Тестеры", - "Special Thanks": "Особая благодарность", - "Unknown": "Неизвестно", - "Installed": "Установлено", - "Not Installed": "Не установлено", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "ЛИЦЕНЗИЯ НА ПРОДАЖУ ПИВА", - "Default": "По умолчанию", - "Do Not Override": "Не переопределять", - "Disabled": "Отключено", - "Enabled": "Включено", - " \\ue0e3 Reset": "\\ue0e3 Сброс", - "Display": "Дисплей", - "Application changed\\n\\n": "Приложение изменено\\n\\n", - "The running application changed\\n\\n": "Запущенное приложение изменилось\\n\\n", - "while editing was going on.": "пока шло редактирование.", - "Board": "Совет", - "%u.%u%u mV": "%u.%u%u мВ", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Не удалось подключиться к системному модулю hoc-clk.\\n\\n", - "Please make sure everything is\\n\\n": "Пожалуйста, убедитесь, что все в порядке\\n\\n", - "correctly installed and enabled.": "правильно установлен и включен.", - "Fatal error": "Неустранимая ошибка", - "Temporary Overrides ": "Временные переопределения", - "Sleep Mode": "Спящий режим", - "Stock": "Акции", - "Dev OC": "Разработчик OC", - "Boost Mode": "Режим повышения", - "Safe Max": "Сейф Макс", - "Unsafe Max": "Небезопасный Макс", - "Absolute Max": "Абсолютный Макс", - "Handheld Safe Max": "Ручной сейф Макс", - "Enable": "Включить", - "Edit App Profile": "Редактировать профиль приложения", - "Edit Global Profile": "Редактировать глобальный профиль", - "Temporary Overrides": "Временные переопределения", - "Settings": "Настройки", - "About": "О", - "Compiling with minimal features": "Компиляция с минимальными возможностями", - "General Settings": "Общие настройки", - "Governor Settings": "Настройки губернатора", - "Safety Settings": "Настройки безопасности", - "Save KIP Settings": "Сохранить настройки КИП", - "RAM Settings": "Настройки ОЗУ", - "CPU Settings": "Настройки процессора", - "GPU Settings": "Настройки графического процессора", - "Display Settings": "Настройки дисплея", - "Experimental": "Экспериментальный", - "GPU Scheduling Override Method": "Метод переопределения планирования графического процессора", - "can be dangerous and may cause": "может быть опасным и может вызвать", - "damage to your battery or charger!": "повреждение аккумулятора или зарядного устройства!", - "Charge Current Override": "Блокировка зарядного тока", - "RAM Voltage Display Mode": "Режим отображения напряжения ОЗУ", - "Polling Interval": "Интервал опроса", - "CPU Governor Minimum Frequency": "Минимальная частота регулятора ЦП", - "refresh rates may cause stress": "частота обновления может вызвать стресс", - "or damage to your display! ": "или повреждение дисплея!", - "Proceed at your own risk!": "Действуйте на свой страх и риск!", - "Max Handheld Display": "Макс. портативный дисплей", - "Display Clock": "Дисплей Часы", - "Official Rating": "Официальный рейтинг", - "TDP Threshold": "Порог TDP", - "Power": "Мощность", - "Thermal Throttle Limit": "Температурный предел дроссельной заслонки", - "HP Mode": "Режим HP", - "Default (Mariko)": "По умолчанию (Марико)", - "Default (Erista)": "По умолчанию (Эриста)", - "Rating": "Рейтинг", - "Safe Max (Mariko)": "Сейф Макс (Марико)", - "Safe Max (Erista)": "Сейф Макс (Эриста)", - "RAM VDD2 Voltage": "Напряжение ОЗУ VDD2", - "Voltage": "Напряжение", - "RAM VDDQ Voltage": "Напряжение ОЗУ VDDQ", - "RAM Frequency Editor": "Редактор частоты оперативной памяти", - "JEDEC.": "ДЖЕДЕК.", - "High speedo needed!": "Нужен высокий спидометр!", - "3333MHz (Needs extreme Speedo/PLL)": "3333 МГц (требуется экстремальный спидометр/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 МГц (требуется экстремальный спидометр/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 МГц (требуется экстремальный спидометр/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433 МГц (нужен нелепый спидометр/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466 МГц (нужен нелепый спидометр/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 МГц (нужен нелепый спидометр/PLL)", - "Ram Max Clock": "Рам Макс Часы", - "RAM Latency Editor": "Редактор задержки оперативной памяти", - "RAM Timing Reductions": "Сокращение таймингов ОЗУ", - "Memory Timings": "Тайминги памяти", - "Advanced": "Расширенный", - "t6 tRTW Fine Tune": "t6 tRTW Точная настройка", - "tRTW Fine Tune": "tRTW Точная настройка", - "t7 tWTR Fine Tune": "t7 tWTR Тонкая настройка", - "tWTR Fine Tune": "tWTR Тонкая настройка", - "Memory Latencies": "Задержки памяти", - "Read Latency": "Задержка чтения", - "Write Latency": "Задержка записи", - "CPU Boost Clock": "Тактовая частота процессора", - "CPU UV": "УФ процессора", - "CPU Unlock": "Разблокировка процессора", - "CPU VMIN": "ЦП VMIN", - "CPU Max Voltage": "Максимальное напряжение процессора", - "CPU Max Clock": "Максимальная частота процессора", - "Extreme UV Table": "Стол для экстремального УФ-излучения", - "CPU UV Table": "UV-таблица процессора", - "CPU Low UV": "ЦП с низким УФ-излучением", - "CPU High UV": "Процессор с высоким УФ", - "CPU Low VMIN": "Низкий VMIN процессора", - "CPU High VMIN": "Высокий VMIN процессора", - "No Undervolt": "Нет Андервольта", - "SLT Table": "Таблица ТА", - "HiOPT Table": "Таблица HiOPT", - "GPU Undervolt Table": "Таблица пониженного напряжения графического процессора", - "GPU Minimum Voltage": "Минимальное напряжение графического процессора", - "Calculate GPU Vmin": "Рассчитать Vmin графического процессора", - "GPU VMIN": "Вмин графического процессора", - "GPU Maximum Voltage": "Максимальное напряжение графического процессора", - "GPU Voltage Offset": "Смещение напряжения графического процессора", - "Do not override": "Не переопределять", - "Enabled (Default)": "Включено (по умолчанию)", - "96.6% limit": "Предел 96,6%", - "99.7% limit": "лимит 99,7%", - "GPU Scheduling Override": "Переопределение планирования графического процессора", - "Official Service": "Официальная служба", - "GPU DVFS Mode": "Режим графического процессора DVFS", - "GPU DVFS Offset": "Смещение DVFS графического процессора", - "GPU Voltage Table": "Таблица напряжений графического процессора", - "GPU Custom Table (mV)": "Пользовательская таблица графического процессора (мВ)", - "1075MHz without UV, 1152MHz on SLT": "1075 МГц без УФ, 1152 МГц на SLT", - "or 1228MHz on HiOPT can cause ": "или 1228 МГц на HiOPT может привести к", - "permanent damage to your Switch!": "необратимое повреждение вашего коммутатора!", - "921MHz without UV and 960MHz on": "921 МГц без УФ и 960 МГц с включенным", - "SLT or HiOPT can cause ": "SLT или HiOPT могут вызвать" -} diff --git a/Source/sys-clk/overlay/lang/uk.json b/Source/sys-clk/overlay/lang/uk.json deleted file mode 100644 index c0239f8a..00000000 --- a/Source/sys-clk/overlay/lang/uk.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "Інформація", - "IDDQ:": "IDDQ:", - "Module: ": "Модуль:", - "sys-dock status:": "стан sys-dock:", - "SaltyNX status:": "Статус SaltyNX:", - "RR Display status:": "Статус дисплея RR:", - "Wafer Position:": "Позиція пластини:", - "Credits": "Кредити", - "Developers": "Розробники", - "Contributors": "Дописувачі", - "Testers": "Тестери", - "Special Thanks": "Особлива подяка", - "Unknown": "Невідомий", - "Installed": "встановлено", - "Not Installed": "Не встановлено", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "ЛІЦЕНЗІЯ НА ПИВНИЙ ПОСУД", - "Default": "За замовчуванням", - "Do Not Override": "Не перевизначати", - "Disabled": "Вимкнено", - "Enabled": "Увімкнено", - " \\ue0e3 Reset": "\\ue0e3 Скидання", - "Display": "Дисплей", - "Application changed\\n\\n": "Додаток змінено\\n\\n", - "The running application changed\\n\\n": "Запущена програма змінена\\n\\n", - "while editing was going on.": "поки йшло редагування.", - "Board": "дошка", - "%u.%u%u mV": "%u.%u%u мВ", - "Could not connect to hoc-clk sysmodule.\\n\\n": "Не вдалося підключитися до системного модуля hoc-clk.\\n\\n", - "Please make sure everything is\\n\\n": "Переконайтеся, що все\\n\\n", - "correctly installed and enabled.": "правильно встановлено та включено.", - "Fatal error": "Фатальна помилка", - "Temporary Overrides ": "Тимчасові перевизначення", - "Sleep Mode": "Режим сну", - "Stock": "Запас", - "Dev OC": "Розробник OC", - "Boost Mode": "Режим посилення", - "Safe Max": "Безпечний макс", - "Unsafe Max": "Небезпечний макс", - "Absolute Max": "Абсолютний макс", - "Handheld Safe Max": "Портативний сейф Макс", - "Enable": "Увімкнути", - "Edit App Profile": "Редагувати профіль програми", - "Edit Global Profile": "Редагувати глобальний профіль", - "Temporary Overrides": "Тимчасові перевизначення", - "Settings": "Налаштування", - "About": "про", - "Compiling with minimal features": "Компіляція з мінімальними можливостями", - "General Settings": "Загальні налаштування", - "Governor Settings": "Налаштування губернатора", - "Safety Settings": "Налаштування безпеки", - "Save KIP Settings": "Зберегти налаштування KIP", - "RAM Settings": "Налаштування оперативної пам'яті", - "CPU Settings": "Налаштування ЦП", - "GPU Settings": "Налаштування GPU", - "Display Settings": "Налаштування дисплея", - "Experimental": "Експериментальний", - "GPU Scheduling Override Method": "Метод перевизначення планування GPU", - "can be dangerous and may cause": "може бути небезпечним і може спричинити", - "damage to your battery or charger!": "пошкодження акумулятора або зарядного пристрою!", - "Charge Current Override": "Перевизначення струму заряду", - "RAM Voltage Display Mode": "Режим відображення напруги RAM", - "Polling Interval": "Інтервал опитування", - "CPU Governor Minimum Frequency": "Мінімальна частота регулятора ЦП", - "refresh rates may cause stress": "частоти оновлення можуть викликати стрес", - "or damage to your display! ": "або пошкодження дисплея!", - "Proceed at your own risk!": "Продовжуйте на свій страх і ризик!", - "Max Handheld Display": "Максимальний портативний дисплей", - "Display Clock": "Відображення годинника", - "Official Rating": "Офіційний рейтинг", - "TDP Threshold": "Поріг TDP", - "Power": "потужність", - "Thermal Throttle Limit": "Термічний дросельний ліміт", - "HP Mode": "Режим HP", - "Default (Mariko)": "За замовчуванням (Маріко)", - "Default (Erista)": "За замовчуванням (Erista)", - "Rating": "Рейтинг", - "Safe Max (Mariko)": "Сейф Макс (Маріко)", - "Safe Max (Erista)": "Сейф Макс (Еріста)", - "RAM VDD2 Voltage": "Напруга RAM VDD2", - "Voltage": "Напруга", - "RAM VDDQ Voltage": "Напруга RAM VDDQ", - "RAM Frequency Editor": "Редактор частоти оперативної пам'яті", - "JEDEC.": "JEDEC.", - "High speedo needed!": "Потрібна висока швидкість!", - "3333MHz (Needs extreme Speedo/PLL)": "3333 МГц (потрібна екстремальна швидкість/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366 МГц (потрібна екстремальна швидкість/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400 МГц (потрібна екстремальна швидкість/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433 МГц (потрібен смішний Speedo/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466 МГц (потрібен смішний Speedo/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500 МГц (потрібен смішний Speedo/PLL)", - "Ram Max Clock": "Годинник Ram Max", - "RAM Latency Editor": "Редактор затримки оперативної пам'яті", - "RAM Timing Reductions": "Скорочення оперативної пам'яті", - "Memory Timings": "Таймінг пам'яті", - "Advanced": "Просунутий", - "t6 tRTW Fine Tune": "t6 tRTW Точне налаштування", - "tRTW Fine Tune": "Точне налаштування tRTW", - "t7 tWTR Fine Tune": "t7 tWTR Точне налаштування", - "tWTR Fine Tune": "Точна настройка tWTR", - "Memory Latencies": "Затримки пам'яті", - "Read Latency": "Прочитати затримку", - "Write Latency": "Затримка запису", - "CPU Boost Clock": "CPU Boost Clock", - "CPU UV": "CPU UV", - "CPU Unlock": "Розблокування ЦП", - "CPU VMIN": "CPU VMIN", - "CPU Max Voltage": "Максимальна напруга ЦП", - "CPU Max Clock": "Максимальна частота ЦП", - "Extreme UV Table": "Екстремальний ультрафіолетовий стіл", - "CPU UV Table": "CPU UV Таблиця", - "CPU Low UV": "CPU Low UV", - "CPU High UV": "CPU High UV", - "CPU Low VMIN": "CPU Low VMIN", - "CPU High VMIN": "CPU High VMIN", - "No Undervolt": "Без андервольта", - "SLT Table": "Таблиця SLT", - "HiOPT Table": "Таблиця HiOPT", - "GPU Undervolt Table": "Таблиця зниження напруги GPU", - "GPU Minimum Voltage": "Мінімальна напруга GPU", - "Calculate GPU Vmin": "Розрахувати GPU Vmin", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "Максимальна напруга GPU", - "GPU Voltage Offset": "Зсув напруги GPU", - "Do not override": "Не перевизначати", - "Enabled (Default)": "Увімкнено (за замовчуванням)", - "96.6% limit": "96,6% обмеження", - "99.7% limit": "Обмеження 99,7%.", - "GPU Scheduling Override": "Перевизначення планування GPU", - "Official Service": "Офіційний сервіс", - "GPU DVFS Mode": "Режим GPU DVFS", - "GPU DVFS Offset": "GPU DVFS Offset", - "GPU Voltage Table": "Таблиця напруги GPU", - "GPU Custom Table (mV)": "Спеціальна таблиця GPU (мВ)", - "1075MHz without UV, 1152MHz on SLT": "1075 МГц без УФ, 1152 МГц на SLT", - "or 1228MHz on HiOPT can cause ": "або 1228 МГц на HiOPT може спричинити", - "permanent damage to your Switch!": "незворотне пошкодження вашого комутатора!", - "921MHz without UV and 960MHz on": "921 МГц без УФ і 960 МГц увімкнено", - "SLT or HiOPT can cause ": "SLT або HiOPT можуть спричинити" -} diff --git a/Source/sys-clk/overlay/lang/zh-cn.json b/Source/sys-clk/overlay/lang/zh-cn.json deleted file mode 100644 index 53989929..00000000 --- a/Source/sys-clk/overlay/lang/zh-cn.json +++ /dev/null @@ -1,157 +0,0 @@ -{ - "Information": "信息", - "IDDQ:": "IDDQ:", - "Module: ": "模块: ", - "sys-dock status:": "sys-dock 状态:", - "SaltyNX status:": "SaltyNX 状态:", - "RR Display status:": "RR 显示状态:", - "Wafer Position:": "晶圆位置:", - "Credits": "致谢", - "Developers": "开发者", - "Contributors": "贡献者", - "Testers": "测试者", - "Special Thanks": "特别感谢", - "Unknown": "未知", - "Installed": "已安装", - "Not Installed": "未安装", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "啤酒软件许可协议", - "Default": "默认", - "Do Not Override": "不修改", - "Disabled": "已禁用", - "Enabled": "已启用", - " \\ue0e3 Reset": " \\ue0e3 重置", - "Display": "显示", - "Application changed\\n\\n": "应用已变更\\n\\n", - "The running application changed\\n\\n": "正在运行的应用已变更\\n\\n", - "while editing was going on.": "编辑过程中发生变更。", - "Board": "主板", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "无法连接到 hoc-clk 系统模块。\\n\\n", - "Please make sure everything is\\n\\n": "请确保所有内容均已\\n\\n", - "correctly installed and enabled.": "正确安装并启用。", - "Fatal error": "致命错误", - "Temporary Overrides ": "临时配置 ", - "Sleep Mode": "睡眠模式", - "Stock": "原厂默认", - "Dev OC": "开发者超频", - "Boost Mode": "加速模式", - "Safe Max": "安全最大值", - "Unsafe Max": "危险最大值", - "Absolute Max": "绝对最大值", - "Handheld Safe Max": "掌机模式安全最大值", - "Enable": "启用", - "Edit App Profile": "编辑应用配置", - "Edit Global Profile": "编辑全局配置", - "Temporary Overrides": "临时配置", - "Settings": "设置", - "About": "关于", - "Compiling with minimal features": "以最小功能编译", - "General Settings": "通用设置", - "Governor Settings": "调频器设置", - "Safety Settings": "安全设置", - "Save KIP Settings": "保存 KIP 设置", - "RAM Settings": "内存设置", - "CPU Settings": "CPU 设置", - "GPU Settings": "GPU 设置", - "Display Settings": "显示设置", - "Experimental": "实验性功能", - "GPU Scheduling Override Method": "GPU 调度覆盖方式", - "can be dangerous and may cause": "存在风险,可能导致", - "damage to your battery or charger!": "电池或充电器损坏!", - "Charge Current Override": "充电电流修改", - "RAM Voltage Display Mode": "内存电压显示模式", - "Polling Interval": "刷新间隔", - "CPU Governor Minimum Frequency": "CPU 调频器最低频率", - "\uE150 Usage of unsafe display": "\uE150 不安全的显示屏", - "refresh rates may cause stress": "刷新率可能会对", - "or damage to your display! ": "显示屏造成压力或损坏! ", - "Proceed at your own risk!": "操作风险自负!", - "Max Handheld Display": "掌机模式最大显示率", - "Display Clock": "显示时钟", - "Official Rating": "官方额定值", - "TDP Threshold": "TDP 阈值", - "Power": "电源", - "Thermal Throttle Limit": "温控设置", - "HP Mode": "高性能模式", - "Default (Mariko)": "默认 (Mariko)", - "Default (Erista)": "默认 (Erista)", - "Rating": "额定值", - "Safe Max (Mariko)": "安全最大值 (Mariko)", - "Safe Max (Erista)": "安全最大值 (Erista)", - "RAM VDD2 Voltage": "内存 VDD2 电压", - "Voltage": "电压", - "RAM VDDQ Voltage": "内存 VDDQ 电压", - "RAM Frequency Editor": "内存频率编辑器", - "JEDEC.": "JEDEC 标准。", - "High speedo needed!": "需要高 Speedo 配置!", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz (需要极限 Speedo/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366MHz (需要极限 Speedo/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400MHz (需要极限 Speedo/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz (需要极端 Speedo/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz (需要极端 Speedo/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz (需要极端 Speedo/PLL)", - "Ram Max Clock": "内存最大频率", - "RAM Latency Editor": "内存延迟编辑器", - "RAM Timing Reductions": "内存时序优化", - "Memory Timings": "内存时序", - "Memory": "内存", - "mem": "内存", - "Governor": "调频器", - "Advanced": "高级", - "Docked": "底座模式", - "Handheld": "掌机模式", - "Charging": "充电中", - "USB Charger": "USB 充电器", - "PD Charger": "PD 充电器", - "Handheld TDP": "掌机模式功耗限制", - "Thermal Throttle": "温度控制", - "Uncapped Clocks": "解除频率上限", - "Soc DVB Shift": "SoC DVB偏移", - "Overwrite Boost Mode": "接管官方CPU调度", - "Display Refresh Rate Changing": "显示刷新率变更", - "t6 tRTW Fine Tune": "t6 tRTW 微调", - "tRTW Fine Tune": "tRTW 微调", - "t7 tWTR Fine Tune": "t7 tWTR 微调", - "tWTR Fine Tune": "tWTR 微调", - "Memory Latencies": "内存延迟", - "Read Latency": "读取延迟", - "Write Latency": "写入延迟", - "CPU Boost Clock": "CPU 超频频率", - "CPU UV": "CPU 降压", - "CPU Unlock": "CPU 解锁", - "CPU VMIN": "CPU 最低电压", - "CPU Max Voltage": "CPU 最大电压", - "CPU Max Clock": "CPU 最大频率", - "Extreme UV Table": "极限降压表", - "CPU UV Table": "CPU 降压表", - "CPU Low UV": "CPU 低压降压", - "CPU High UV": "CPU 高压降压", - "CPU Low VMIN": "CPU 低压最低电压", - "CPU High VMIN": "CPU 高压最低电压", - "No Undervolt": "不降压", - "SLT Table": "SLT 表", - "HiOPT Table": "HiOPT 表", - "GPU Undervolt Table": "GPU 降压表", - "GPU Minimum Voltage": "GPU 最低电压", - "Calculate GPU Vmin": "计算 GPU 最低电压", - "GPU VMIN": "GPU 最低电压", - "GPU Maximum Voltage": "GPU 最大电压", - "GPU Voltage Offset": "GPU 电压偏移", - "Do not override": "不修改", - "Enabled (Default)": "已启用 (默认)", - "96.6% limit": "96.6% 限制", - "99.7% limit": "99.7% 限制", - "GPU Scheduling Override": "GPU 调度修改", - "Official Service": "官方服务", - "GPU DVFS Mode": "GPU DVFS 模式", - "GPU DVFS Offset": "GPU DVFS 偏移", - "GPU Voltage Table": "GPU 电压表", - "GPU Custom Table (mV)": "GPU 自定义表 (mV)", - "\uE150 Setting GPU Clocks past": "\uE150 将 GPU 频率设置超过", - "1075MHz without UV, 1152MHz on SLT": "1075MHz 无降压,SLT 表下 1152MHz", - "or 1228MHz on HiOPT can cause ": "或 HiOPT 表下 1228MHz 可能导致 ", - "permanent damage to your Switch!": "Switch 永久损坏!", - "921MHz without UV and 960MHz on": "921MHz 无降压,SLT/HiOPT 表下 960MHz", - "SLT or HiOPT can cause ": "可能导致 " -} diff --git a/Source/sys-clk/overlay/lang/zh-tw.json b/Source/sys-clk/overlay/lang/zh-tw.json deleted file mode 100644 index 5a8a5dfa..00000000 --- a/Source/sys-clk/overlay/lang/zh-tw.json +++ /dev/null @@ -1,141 +0,0 @@ -{ - "Information": "資訊", - "IDDQ:": "國際電話號碼:", - "Module: ": "模組:", - "sys-dock status:": "系統塢站狀態:", - "SaltyNX status:": "SaltyNX 狀態:", - "RR Display status:": "RR 顯示狀態:", - "Wafer Position:": "晶圓位置:", - "Credits": "製作人員", - "Developers": "開發商", - "Contributors": "貢獻者", - "Testers": "測試人員", - "Special Thanks": "特別感謝", - "Unknown": "未知", - "Installed": "已安裝", - "Not Installed": "未安裝", - "X: %u Y: %u": "X: %u Y: %u", - "THE BEER-WARE LICENSE": "啤酒製品許可證", - "Default": "預設", - "Do Not Override": "不要覆蓋", - "Disabled": "殘障人士", - "Enabled": "啟用", - " \\ue0e3 Reset": "\\ue0e3 重設", - "Display": "顯示", - "Application changed\\n\\n": "應用程式已更改\\n\\n", - "The running application changed\\n\\n": "正在運行的應用程式已更改\\n\\n", - "while editing was going on.": "當編輯正在進行時。", - "Board": "董事會", - "%u.%u%u mV": "%u.%u%u mV", - "Could not connect to hoc-clk sysmodule.\\n\\n": "無法連接到 hoc-clk 系統模組。 \\n\\n", - "Please make sure everything is\\n\\n": "請確保一切正常\\n\\n", - "correctly installed and enabled.": "正確安裝並啟用。", - "Fatal error": "致命錯誤", - "Temporary Overrides ": "臨時覆蓋", - "Sleep Mode": "睡眠模式", - "Stock": "庫存", - "Dev OC": "開發OC", - "Boost Mode": "升壓模式", - "Safe Max": "安全最大值", - "Unsafe Max": "不安全最大值", - "Absolute Max": "絕對最大值", - "Handheld Safe Max": "手持式安全最大", - "Enable": "啟用", - "Edit App Profile": "編輯應用程式設定檔", - "Edit Global Profile": "編輯全域設定檔", - "Temporary Overrides": "臨時覆蓋", - "Settings": "設定", - "About": "關於", - "Compiling with minimal features": "使用最少的功能進行編譯", - "General Settings": "常規設定", - "Governor Settings": "調速器設定", - "Safety Settings": "安全設定", - "Save KIP Settings": "儲存 KIP 設定", - "RAM Settings": "記憶體設定", - "CPU Settings": "中央處理器設定", - "GPU Settings": "GPU設定", - "Display Settings": "顯示設定", - "Experimental": "實驗性的", - "GPU Scheduling Override Method": "GPU調度覆蓋方法", - "can be dangerous and may cause": "可能很危險並可能導致", - "damage to your battery or charger!": "損壞電池或充電器!", - "Charge Current Override": "充電電流覆蓋", - "RAM Voltage Display Mode": "RAM電壓顯示模式", - "Polling Interval": "輪詢間隔", - "CPU Governor Minimum Frequency": "CPU調速器最低頻率", - "refresh rates may cause stress": "刷新率可能會造成壓力", - "or damage to your display! ": "或損壞您的顯示器!", - "Proceed at your own risk!": "請自行承擔風險!", - "Max Handheld Display": "最大手持顯示器", - "Display Clock": "顯示時鐘", - "Official Rating": "官方評級", - "TDP Threshold": "TDP閾值", - "Power": "電源", - "Thermal Throttle Limit": "熱油門限制", - "HP Mode": "惠普模式", - "Default (Mariko)": "預設(真理子)", - "Default (Erista)": "預設(埃里斯塔)", - "Rating": "評級", - "Safe Max (Mariko)": "安全最大(真理子)", - "Safe Max (Erista)": "安全最大(埃里斯塔)", - "RAM VDD2 Voltage": "RAM VDD2 電壓", - "Voltage": "電壓", - "RAM VDDQ Voltage": "RAM VDDQ 電壓", - "RAM Frequency Editor": "RAM頻率編輯器", - "JEDEC.": "JEDEC。", - "High speedo needed!": "需要高速!", - "3333MHz (Needs extreme Speedo/PLL)": "3333MHz(需要極高的 Speedo/PLL)", - "3366MHz (Needs extreme Speedo/PLL)": "3366MHz(需要極高的 Speedo/PLL)", - "3400MHz (Needs extreme Speedo/PLL)": "3400MHz(需要極高的 Speedo/PLL)", - "3433MHz (Needs ridiculous Speedo/PLL)": "3433MHz(需要荒謬的 Speedo/PLL)", - "3466MHz (Needs ridiculous Speedo/PLL)": "3466MHz(需要荒謬的 Speedo/PLL)", - "3500MHz (Needs ridiculous Speedo/PLL)": "3500MHz(需要荒謬的 Speedo/PLL)", - "Ram Max Clock": "記憶體最大時鐘", - "RAM Latency Editor": "RAM 延遲編輯器", - "RAM Timing Reductions": "RAM 時序減少", - "Memory Timings": "記憶體時序", - "Advanced": "進階", - "t6 tRTW Fine Tune": "t6 tRTW 微調", - "tRTW Fine Tune": "tRTW 微調", - "t7 tWTR Fine Tune": "t7 tWTR 微調", - "tWTR Fine Tune": "tWTR 微調", - "Memory Latencies": "記憶體延遲", - "Read Latency": "讀取延遲", - "Write Latency": "寫入延遲", - "CPU Boost Clock": "CPU 升壓時鐘", - "CPU UV": "中央處理器紫外線", - "CPU Unlock": "CPU解鎖", - "CPU VMIN": "CPU最低電壓", - "CPU Max Voltage": "CPU最大電壓", - "CPU Max Clock": "CPU 最大時脈", - "Extreme UV Table": "極端紫外線表", - "CPU UV Table": "CPU UV表", - "CPU Low UV": "CPU低紫外線", - "CPU High UV": "CPU高紫外線", - "CPU Low VMIN": "CPU 低 VMIN", - "CPU High VMIN": "CPU 高 VMIN", - "No Undervolt": "無欠壓", - "SLT Table": "SLT表", - "HiOPT Table": "HiOPT表", - "GPU Undervolt Table": "GPU 欠壓表", - "GPU Minimum Voltage": "GPU最低電壓", - "Calculate GPU Vmin": "計算 GPU Vmin", - "GPU VMIN": "GPU VMIN", - "GPU Maximum Voltage": "GPU最大電壓", - "GPU Voltage Offset": "GPU電壓偏移", - "Do not override": "不要覆蓋", - "Enabled (Default)": "啟用(預設)", - "96.6% limit": "96.6%限制", - "99.7% limit": "99.7%限制", - "GPU Scheduling Override": "GPU 調度覆蓋", - "Official Service": "官方服務", - "GPU DVFS Mode": "GPU DVFS 模式", - "GPU DVFS Offset": "GPU DVFS 偏移", - "GPU Voltage Table": "GPU電壓表", - "GPU Custom Table (mV)": "GPU 自訂表 (mV)", - "1075MHz without UV, 1152MHz on SLT": "無 UV 時為 1075MHz,SLT 時為 1152MHz", - "or 1228MHz on HiOPT can cause ": "或 HiOPT 上的 1228MHz 可能會導致", - "permanent damage to your Switch!": "對您的 Switch 造成永久性損壞!", - "921MHz without UV and 960MHz on": "無 UV 時為 921MHz,開啟時為 960MHz", - "SLT or HiOPT can cause ": "SLT 或 HiOPT 可能會導致" -} diff --git a/Source/sys-clk/overlay/lib/libultrahand b/Source/sys-clk/overlay/lib/libultrahand deleted file mode 160000 index 57fc30ac..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 57fc30ac377379cde1e1293b1538a0436534b740 diff --git a/Source/sys-clk/overlay/scripts/make_logo.sh b/Source/sys-clk/overlay/scripts/make_logo.sh deleted file mode 100644 index bbd01a7f..00000000 --- a/Source/sys-clk/overlay/scripts/make_logo.sh +++ /dev/null @@ -1,16 +0,0 @@ -#!/bin/bash -set -e - -CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" - -DEST="$CURRENT_DIR/../data/logo_rgba.bin" -FONT="$CURRENT_DIR/../../manager/resources/fira/FiraSans-Medium-rnx.ttf" -FONT_SIZE="30.5" -TEXT="sys-clk" - -function render() { - convert -background transparent -colorspace RGB -depth 8 -fill white -font "$1" -pointsize "$2" "label:$3" "$4" -} - -render "$FONT" "$FONT_SIZE" "$TEXT" info: -render "$FONT" "$FONT_SIZE" "$TEXT" "RGBA:$DEST" \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ipc.h b/Source/sys-clk/overlay/src/ipc.h deleted file mode 100644 index 8186849d..00000000 --- a/Source/sys-clk/overlay/src/ipc.h +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#if defined(__cplusplus) -#include "cpp_util.hpp" - -extern "C" -{ -#endif - -#include -#include - -#if defined(__cplusplus) -} -#endif diff --git a/Source/sys-clk/overlay/src/main.cpp b/Source/sys-clk/overlay/src/main.cpp deleted file mode 100644 index ec2fd36a..00000000 --- a/Source/sys-clk/overlay/src/main.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#define TESLA_INIT_IMPL -#include -#include "ui/gui/fatal_gui.h" -#include "ui/gui/main_gui.h" -#include "rgltr_services.h" // for extern Service g_rgltrSrv, etc. - -class AppOverlay : public tsl::Overlay -{ - public: - AppOverlay() {} - ~AppOverlay() {} - - //virtual void initServices() override { - // rgltrInitialize(); - //} - - virtual void exitServices() override { - rgltrExit(); - sysclkIpcExit(); - } - - virtual std::unique_ptr loadInitialGui() override - { - uint32_t apiVersion; - smInitialize(); - - tsl::hlp::ScopeGuard smGuard([] { smExit(); }); - - if(!sysclkIpcRunning()) - { - return initially( - "hoc-clk is not running.\n\n" - "\n" - "Please make sure it is correctly\n\n" - "installed and enabled.", - "" - ); - } - - if(R_FAILED(sysclkIpcInitialize()) || R_FAILED(sysclkIpcGetAPIVersion(&apiVersion))) - { - return initially( - "Could not connect to hoc-clk.\n\n" - "\n" - "Please make sure it is correctly\n\n" - "installed and enabled.", - "" - ); - } - - if(SYSCLK_IPC_API_VERSION != apiVersion) - { - return initially( - "Overlay not compatible with\n\n" - "the running hoc-clk version.\n\n" - "\n" - "Please make sure everything is\n\n" - "installed and up to date.", - "" - ); - } - - return initially(); - } -}; - -int main(int argc, char **argv) -{ - return tsl::loop(argc, argv); -} diff --git a/Source/sys-clk/overlay/src/ui/elements/base_frame.h b/Source/sys-clk/overlay/src/ui/elements/base_frame.h deleted file mode 100644 index 58f6025f..00000000 --- a/Source/sys-clk/overlay/src/ui/elements/base_frame.h +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include "../gui/base_gui.h" - -class BaseFrame : public tsl::elm::HeaderOverlayFrame -{ - public: - BaseFrame(BaseGui* gui) : tsl::elm::HeaderOverlayFrame(234) { - this->gui = gui; - } - - void draw(tsl::gfx::Renderer* renderer) override - { - tsl::elm::HeaderOverlayFrame::draw(renderer); - this->gui->preDraw(renderer); - } - - protected: - BaseGui* gui; -}; diff --git a/Source/sys-clk/overlay/src/ui/format.h b/Source/sys-clk/overlay/src/ui/format.h deleted file mode 100644 index 008c6a40..00000000 --- a/Source/sys-clk/overlay/src/ui/format.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include -#include - -#define FREQ_DEFAULT_TEXT "Do not override" - -static inline std::string formatListFreqMHz(std::uint32_t mhz) -{ - if(mhz == 0) - { - return FREQ_DEFAULT_TEXT; - } - - char buf[10]; - return std::string(buf, snprintf(buf, sizeof(buf), "%u MHz", mhz)); -} - -static inline std::string formatListFreqHz(std::uint32_t hz) { return formatListFreqMHz(hz / 1000000); } diff --git a/Source/sys-clk/overlay/src/ui/gui/about_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/about_gui.cpp deleted file mode 100644 index f4632ba6..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/about_gui.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - */ - - -#include "about_gui.h" -#include "../format.h" -#include -#include -#include "cat.h" -#include "ult_ext.h" - -tsl::elm::ListItem* SpeedoItem = NULL; -tsl::elm::ListItem* IddqItem = NULL; -tsl::elm::ListItem* DramModule = NULL; -tsl::elm::ListItem* sysdockStatusItem = NULL; -tsl::elm::ListItem* saltyNXStatusItem = NULL; -tsl::elm::ListItem* RETROStatusItem = NULL; -tsl::elm::ListItem* waferCordsItem = NULL; - -ImageElement* CatImage = NULL; -HideableCategoryHeader* CatHeader = NULL; -HideableCustomDrawer* CatSpacer = NULL; -int lightosClickCount = 0; - -AboutGui::AboutGui() -{ - memset(strings, 0, sizeof(strings)); -} - -AboutGui::~AboutGui() -{ -} - -void AboutGui::listUI() -{ - this->listElement->addItem( - new tsl::elm::CategoryHeader("Information") - ); - - SpeedoItem = - new tsl::elm::ListItem("Speedo:"); - this->listElement->addItem(SpeedoItem); - - IddqItem = - new tsl::elm::ListItem("IDDQ:"); - this->listElement->addItem(IddqItem); - - DramModule = - new tsl::elm::ListItem("Module: "); - this->listElement->addItem(DramModule); - - if(!IsHoag()) { - sysdockStatusItem = - new tsl::elm::ListItem("sys-dock status:"); - this->listElement->addItem(sysdockStatusItem); - } - - saltyNXStatusItem = - new tsl::elm::ListItem("SaltyNX status:"); - this->listElement->addItem(saltyNXStatusItem); - - if(IsHoag()) { - RETROStatusItem = - new tsl::elm::ListItem("RR Display status:"); - this->listElement->addItem(RETROStatusItem); - } - - waferCordsItem = - new tsl::elm::ListItem("Wafer Position:"); - this->listElement->addItem(waferCordsItem); - - this->listElement->addItem( - new tsl::elm::CategoryHeader("Credits") - ); - - this->listElement->addItem( - new tsl::elm::CategoryHeader("Developers") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Souldbminer") - ); - - // Create special clickable item for Lightos - auto lightosItem = new tsl::elm::ListItem("Lightos_"); - lightosItem->setClickListener([this](u64 keys) -> bool { - if (keys & HidNpadButton_A) { - lightosClickCount++; - if (lightosClickCount >= 10) { - if (CatImage != NULL) CatImage->setVisible(true); - if (CatHeader != NULL) CatHeader->setVisible(true); - if (CatSpacer != NULL) CatSpacer->setVisible(true); - } - return true; - } - return false; - }); - this->listElement->addItem(lightosItem); - - // ---- Contributors ---- - this->listElement->addItem( - new tsl::elm::CategoryHeader("Contributors") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Dom") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Blaise25") - ); - - // ---- Testers ---- - this->listElement->addItem( - new tsl::elm::CategoryHeader("Testers") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Dom") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Samybigio2011") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Delta") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Miki1305") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Happy") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Flopsider") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Winnerboi77") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Blaise25") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("WE1ZARD") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Alvise") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("TDRR") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("agjeococh") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Xenshen") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("Frost") - ); - - // ---- Special Thanks ---- - this->listElement->addItem( - new tsl::elm::CategoryHeader("Special Thanks") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("ScriesM - Atmosphere CFW") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("KazushiMe - Switch OC Suite") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("hanai3bi - Switch OC Suite & EOS") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("NaGaa95 - L4T-OC-Kernel") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("B3711 - EOS") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("RetroNX - sys-clk") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("b0rd2death - Ultrahand") - ); - - this->listElement->addItem( - new tsl::elm::ListItem("MasaGratoR - Status Monitor") - ); - - // Create cat elements but hide them initially - CatHeader = new HideableCategoryHeader("Cat"); - CatHeader->setVisible(false); - this->listElement->addItem(CatHeader); - - CatImage = new ImageElement(CAT_DATA, CAT_WIDTH, CAT_HEIGHT); - CatImage->setVisible(false); - this->listElement->addItem(CatImage); - - CatSpacer = new HideableCustomDrawer(75); - CatSpacer->setVisible(false); - this->listElement->addItem(CatSpacer); -} - -std::string AboutGui::formatRamModule() { - switch (this->context->dramID) { - case 0: return "HB-MGCH 4GB"; - case 4: return "HM-MGCH 6GB"; - case 7: return "HM-MGXX 8GB"; - - case 1: return "NLE 4GB"; - case 2: return "WT:C 4GB"; - - case 3: - case 5 ... 6: return "NEE 4GB"; - - case 8: - case 12: return "AM-MGCJ 4GB"; - case 9: - case 13: return "AM-MGCJ 8GB"; - - case 10: - case 14: return "NME 4GB"; - - case 11: - case 15: return "WT:E 4GB"; - - case 17: - case 19: - case 24: return "AA-MGCL 4GB"; - - case 18: - case 23: - case 28: return "AA-MGCL 8GB"; - - case 20 ... 22: return "AB-MGCL 4GB"; - - case 25 ... 27: return "WT:F 4GB"; - - case 29 ... 31: return "x267 4GB"; - - case 32 ... 34: return "WT:B 4GB"; - - default: return "Unknown"; - } -} - -void AboutGui::update() -{ - BaseMenuGui::update(); -} - -void AboutGui::refresh() -{ - BaseMenuGui::refresh(); - - if (!this->context) - return; - // Format strings once per refresh - sprintf(strings[0], "%u/%u/%u", this->context->speedos[HorizonOCSpeedo_CPU], this->context->speedos[HorizonOCSpeedo_GPU], this->context->speedos[HorizonOCSpeedo_SOC]); - // This is how hekate does it - sprintf(strings[1], "%u/%u/%u", this->context->iddq[HorizonOCSpeedo_CPU], this->context->iddq[HorizonOCSpeedo_GPU], this->context->iddq[HorizonOCSpeedo_SOC]); - SpeedoItem->setValue(strings[0]); - IddqItem->setValue(strings[1]); - DramModule->setValue(formatRamModule()); - if(!IsHoag()) - sysdockStatusItem->setValue(this->context->isSysDockInstalled ? "Installed" : "Not Installed"); - - saltyNXStatusItem->setValue(this->context->isSaltyNXInstalled ? "Installed" : "Not Installed"); - - if(IsHoag()) - RETROStatusItem->setValue(this->context->isUsingRetroSuper ? "Installed" : "Not Installed"); - - sprintf(strings[2], "X: %u Y: %u", this->context->waferX, this->context->waferY); - waferCordsItem->setValue(strings[2]); -} diff --git a/Source/sys-clk/overlay/src/ui/gui/about_gui.h b/Source/sys-clk/overlay/src/ui/gui/about_gui.h deleted file mode 100644 index f2fef93a..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/about_gui.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - */ - -#pragma once -#include "../../ipc.h" -#include "base_menu_gui.h" -#include "freq_choice_gui.h" -#include "value_choice_gui.h" -#include "fatal_gui.h" -#include -#include - -class AboutGui : public BaseMenuGui -{ -protected: - char strings[32][32]; - -public: - AboutGui(); - ~AboutGui(); - - void listUI() override; - void update() override; - void refresh() override; - -private: - std::string formatRamModule(); -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.cpp deleted file mode 100644 index 44a903e7..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.cpp +++ /dev/null @@ -1,468 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "app_profile_gui.h" - -#include "../format.h" -#include "fatal_gui.h" -#include "labels.h" -AppProfileGui::AppProfileGui(std::uint64_t applicationId, SysClkTitleProfileList* profileList) -{ - this->applicationId = applicationId; - this->profileList = profileList; -} - -AppProfileGui::~AppProfileGui() -{ - delete this->profileList; -} - -void AppProfileGui::openFreqChoiceGui(tsl::elm::ListItem* listItem, SysClkProfile profile, SysClkModule module) -{ - std::uint32_t hzList[SYSCLK_FREQ_LIST_MAX]; - std::uint32_t hzCount; - Result rc = sysclkIpcGetFreqList(module, &hzList[0], SYSCLK_FREQ_LIST_MAX, &hzCount); - if(R_FAILED(rc)) - { - FatalGui::openWithResultCode("sysclkIpcGetFreqList", rc); - return; - } - std::map labels = {}; - - if (module == SysClkModule_CPU) { - bool isUsingUv = IsMariko() ? configList.values[KipConfigValue_marikoCpuUVHigh] : configList.values[KipConfigValue_eristaCpuUV]; - labels = IsMariko() ? (isUsingUv ? cpu_freq_label_m_uv : cpu_freq_label_m) : (isUsingUv ? cpu_freq_label_e_uv : cpu_freq_label_e); - } else if (module == SysClkModule_GPU) { - labels = IsMariko() ? *(marikoUV[configList.values[KipConfigValue_marikoGpuUV]]) : *(eristaUV[configList.values[KipConfigValue_eristaGpuUV]]); - } - tsl::changeTo(this->profileList->mhzMap[profile][module] * 1000000, hzList, hzCount, module, [this, listItem, profile, module](std::uint32_t hz) { - this->profileList->mhzMap[profile][module] = hz / 1000000; - listItem->setValue(formatListFreqMHz(this->profileList->mhzMap[profile][module])); - Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList); - if(R_FAILED(rc)) - { - FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); - return false; - } - - return true; - }, true, labels - ); -} - -void AppProfileGui::openValueChoiceGui( - tsl::elm::ListItem* listItem, - std::uint32_t currentValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds, - bool enableThresholds, - const std::map& labels, - const std::vector& namedValues, - bool showDefaultValue -) -{ - tsl::changeTo( - currentValue, - range, - categoryName, - listener, - thresholds, - enableThresholds, - labels, - namedValues, - showDefaultValue, - true - ); -} - -void AppProfileGui::addModuleListItem(SysClkProfile profile, SysClkModule module) -{ - tsl::elm::ListItem* listItem = new tsl::elm::ListItem(sysclkFormatModule(module, true)); - listItem->setValue(formatListFreqMHz(this->profileList->mhzMap[profile][module])); - listItem->setClickListener([this, listItem, profile, module](u64 keys) { - if((keys & HidNpadButton_A) == HidNpadButton_A) - { - this->openFreqChoiceGui(listItem, profile, module); - return true; - } - else if((keys & HidNpadButton_Y) == HidNpadButton_Y) - { - // Reset to "Default" (0 MHz) - this->profileList->mhzMap[profile][module] = 0; - listItem->setValue(formatListFreqMHz(0)); - - Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList); - if(R_FAILED(rc)) - { - FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); - return false; - } - return true; - } - return false; - }); - this->listElement->addItem(listItem); -} - -void AppProfileGui::addModuleListItemToggle(SysClkProfile profile, SysClkModule module) -{ - const char* moduleName = sysclkFormatModule(module, true); - std::uint32_t currentValue = this->profileList->mhzMap[profile][module]; - - tsl::elm::ToggleListItem* toggle = new tsl::elm::ToggleListItem(moduleName, currentValue != 0); - - toggle->setStateChangedListener([this, profile, module](bool state) { - this->profileList->mhzMap[profile][module] = state ? 1 : 0; - - Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList); - if(R_FAILED(rc)) - { - FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); - } - }); - - this->listElement->addItem(toggle); -} - -std::string AppProfileGui::formatValueDisplay( - std::uint32_t value, - const std::vector& namedValues, - const std::string& suffix, - std::uint32_t divisor, - int decimalPlaces -) -{ - if (value == 0) { - return FREQ_DEFAULT_TEXT; - } - - if (!namedValues.empty()) { - for (const auto& namedValue : namedValues) { - if (namedValue.value == value) { - return namedValue.name; - } - } - } - - char buf[32]; - if (decimalPlaces > 0) { - double displayValue = (double)value / divisor; - snprintf(buf, sizeof(buf), "%.*f%s", decimalPlaces, displayValue, suffix.c_str()); - } else { - snprintf(buf, sizeof(buf), "%u%s", value / divisor, suffix.c_str()); - } - return std::string(buf); -} - -void AppProfileGui::addModuleListItemValue( - SysClkProfile profile, - SysClkModule module, - const std::string& categoryName, - std::uint32_t min, - std::uint32_t max, - std::uint32_t step, - const std::string& suffix, - std::uint32_t divisor, - int decimalPlaces, - ValueThresholds thresholds, - std::vector namedValues, - bool showDefaultValue -) -{ - tsl::elm::ListItem* listItem = - new tsl::elm::ListItem(sysclkFormatModule(module, true)); - std::uint32_t storedValue = this->profileList->mhzMap[profile][module]; - - listItem->setValue(this->formatValueDisplay(storedValue, namedValues, suffix, divisor, decimalPlaces)); - - listItem->setClickListener( - [this, - listItem, - profile, - module, - categoryName, - min, - max, - step, - suffix, - divisor, - decimalPlaces, - thresholds, - namedValues, - showDefaultValue](u64 keys) - { - if ((keys & HidNpadButton_A) == HidNpadButton_A) - { - std::uint32_t currentValue = - this->profileList->mhzMap[profile][module] * divisor; - ValueRange range( - min, - max, - step, - suffix, - divisor, - decimalPlaces - ); - this->openValueChoiceGui( - listItem, - currentValue, - range, - categoryName, - [this, listItem, profile, module, divisor, suffix, decimalPlaces, thresholds, namedValues](std::uint32_t value) -> bool - { - this->profileList->mhzMap[profile][module] = value / divisor; - listItem->setValue(this->formatValueDisplay(value / divisor, namedValues, suffix, divisor, decimalPlaces)); - - Result rc = - sysclkIpcSetProfiles(this->applicationId, - this->profileList); - if (R_FAILED(rc)) - { - FatalGui::openWithResultCode( - "sysclkIpcSetProfiles", rc); - return false; - } - return true; - }, - thresholds, - false, - {}, - namedValues, - showDefaultValue - ); - return true; - } - else if ((keys & HidNpadButton_Y) == HidNpadButton_Y) - { - this->profileList->mhzMap[profile][module] = 0; - listItem->setValue(FREQ_DEFAULT_TEXT); - Result rc = - sysclkIpcSetProfiles(this->applicationId, - this->profileList); - if (R_FAILED(rc)) - { - FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); - return false; - } - return true; - } - return false; - }); - this->listElement->addItem(listItem); -} - -class GovernorProfileSubMenuGui : public BaseMenuGui { - uint64_t applicationId; - SysClkTitleProfileList* profileList; - SysClkProfile profile; -public: - GovernorProfileSubMenuGui(uint64_t appId, SysClkTitleProfileList* pList, SysClkProfile prof) - : applicationId(appId), profileList(pList), profile(prof) {} - - void listUI() override { - Result rc = sysclkIpcGetConfigValues(&configList); - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - this->listElement->addItem(new tsl::elm::CategoryHeader("Governor")); - - static constexpr struct { const char* label; int shift; } kAll[] = { - {"CPU", 0}, {"GPU", 8}, {"VRR", 16} - }; - int count = configList.values[HorizonOCConfigValue_OverwriteRefreshRate] ? 3 : 2; - - for (int i = 0; i < count; i++) { - u8 cur = (this->profileList->mhzMap[this->profile][HorizonOCModule_Governor] >> kAll[i].shift) & 0xFF; - auto* bar = new tsl::elm::NamedStepTrackBar( - "", {"Do Not Override", "Disabled", "Enabled"}, - true, kAll[i].label - ); - bar->setProgress(cur); - int shift = kAll[i].shift; - bar->setValueChangedListener([this, shift](u8 value) { - u32& packed = this->profileList->mhzMap[this->profile][HorizonOCModule_Governor]; - packed = (packed & ~(0xFFu << shift)) | ((u32)value << shift); - Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList); - if (R_FAILED(rc)) FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); - }); - this->listElement->addItem(bar); - } - } -}; - -void AppProfileGui::addGovernorSection(SysClkProfile profile) { - auto* item = new tsl::elm::ListItem("Governor"); - item->setValue("\u2192"); // Right arrow - item->setClickListener([this, profile](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo( - this->applicationId, this->profileList, profile - ); - return true; - } - return false; - }); - this->listElement->addItem(item); -} - -void AppProfileGui::addProfileUI(SysClkProfile profile) -{ - BaseMenuGui::refresh(); - if(!this->context) - return; - Result rc = sysclkIpcGetConfigValues(&configList); - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - if((profile == SysClkProfile_Docked && IsHoag()) || profile == SysClkProfile_HandheldCharging) - return; - this->listElement->addItem(new tsl::elm::CategoryHeader(sysclkFormatProfile(profile, true) + std::string(" ") + ult::DIVIDER_SYMBOL + " \ue0e3 Reset")); - this->addModuleListItem(profile, SysClkModule_CPU); - this->addModuleListItem(profile, SysClkModule_GPU); - this->addModuleListItem(profile, SysClkModule_MEM); - #if IS_MINIMAL == 0 - ValueThresholds lcdThresholds(60, 65); - ValueThresholds DThresholdsOLED(120, 500); // nothing is dangerous, past 120hz you can get applet crashes - - if(configList.values[HorizonOCConfigValue_OverwriteRefreshRate]) { - if(profile != SysClkProfile_Docked) { - this->addModuleListItemValue(profile, HorizonOCModule_Display, "Display", IsAula() ? 45 : 40, configList.values[HorizonOCConfigValue_MaxDisplayClockH], this->context->isUsingRetroSuper ? 5 : 1, " Hz", 1, 0, lcdThresholds); - } else { - if(IsAula() && this->context->isSysDockInstalled) { - std::vector dockedFreqs = { - NamedValue("40 Hz", 40), - NamedValue("45 Hz", 45), - NamedValue("50 Hz", 50), - NamedValue("55 Hz", 55), - NamedValue("60 Hz", 60), - NamedValue("70 Hz", 70), - NamedValue("72 Hz", 72), - NamedValue("75 Hz", 75), - NamedValue("80 Hz", 80), - NamedValue("90 Hz", 90), - NamedValue("95 Hz", 95), - NamedValue("100 Hz", 100), - NamedValue("110 Hz", 110), - NamedValue("120 Hz", 120), - NamedValue("130 Hz", 130), - NamedValue("140 Hz", 140), - NamedValue("144 Hz", 144), - NamedValue("150 Hz", 150), - NamedValue("160 Hz", 160), - NamedValue("165 Hz", 165), - NamedValue("170 Hz", 170), - NamedValue("180 Hz", 180), - NamedValue("190 Hz", 190), - NamedValue("200 Hz", 200), - NamedValue("210 Hz", 210), - NamedValue("220 Hz", 220), - NamedValue("230 Hz", 230), - NamedValue("240 Hz", 240) - }; - - this->addModuleListItemValue(profile, HorizonOCModule_Display, "Display", 40, 240, 1, " Hz", 1, 0, DThresholdsOLED, dockedFreqs); - } else if (IsAula() && !this->context->isSysDockInstalled) { - std::vector dockedFreqsLimited = { - NamedValue("50 Hz", 50), - NamedValue("55 Hz", 55), - NamedValue("60 Hz", 60), - NamedValue("65 Hz", 65), - NamedValue("70 Hz", 70), - NamedValue("72 Hz", 72), - NamedValue("75 Hz", 75) - }; - - this->addModuleListItemValue(profile, HorizonOCModule_Display, "Display", 50, 75, 1, " Hz", 1, 0, DThresholdsOLED, dockedFreqsLimited); - } else { - std::vector dockedFreqsStandard = { - NamedValue("50 Hz", 50), - NamedValue("55 Hz", 55), - NamedValue("60 Hz", 60), - NamedValue("65 Hz", 65), - NamedValue("70 Hz", 70), - NamedValue("72 Hz", 72), - NamedValue("75 Hz", 75), - NamedValue("80 Hz", 80), - NamedValue("85 Hz", 85), - NamedValue("90 Hz", 90), - NamedValue("95 Hz", 95), - NamedValue("100 Hz", 100), - NamedValue("105 Hz", 105), - NamedValue("110 Hz", 110), - NamedValue("115 Hz", 115), - NamedValue("120 Hz", 120) - }; - this->addModuleListItemValue(profile, HorizonOCModule_Display, "Display", 50, 120, 1, " Hz", 1, 0, ValueThresholds(), dockedFreqsStandard); - } - } - } - #endif - this->addGovernorSection(profile); -} - -void AppProfileGui::listUI() -{ - this->addProfileUI(SysClkProfile_Docked); - this->addProfileUI(SysClkProfile_Handheld); - this->addProfileUI(SysClkProfile_HandheldCharging); - this->addProfileUI(SysClkProfile_HandheldChargingOfficial); - this->addProfileUI(SysClkProfile_HandheldChargingUSB); -} - -void AppProfileGui::changeTo(std::uint64_t applicationId) -{ - SysClkTitleProfileList* profileList = new SysClkTitleProfileList; - Result rc = sysclkIpcGetProfiles(applicationId, profileList); - if(R_FAILED(rc)) - { - delete profileList; - FatalGui::openWithResultCode("sysclkIpcGetProfiles", rc); - return; - } - - tsl::changeTo(applicationId, profileList); -} - -void AppProfileGui::update() -{ - BaseMenuGui::update(); - - if((this->context && this->applicationId != this->context->applicationId) && this->applicationId != SYSCLK_GLOBAL_PROFILE_TID) - { - tsl::changeTo( - "Application changed\n\n" - "\n" - "The running application changed\n\n" - "while editing was going on.", - "" - ); - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.h b/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.h deleted file mode 100644 index e261282f..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ -#pragma once -#include "../../ipc.h" -#include "base_menu_gui.h" -#include "freq_choice_gui.h" -#include "value_choice_gui.h" -#define SYSCLK_GLOBAL_PROFILE_TID 0xA111111111111111 -class AppProfileGui : public BaseMenuGui -{ - protected: - std::uint64_t applicationId; - SysClkTitleProfileList* profileList; - void openFreqChoiceGui(tsl::elm::ListItem* listItem, SysClkProfile profile, SysClkModule module); - void addModuleListItem(SysClkProfile profile, SysClkModule module); - void addModuleListItemToggle(SysClkProfile profile, SysClkModule module); - void openValueChoiceGui( - tsl::elm::ListItem* listItem, - std::uint32_t currentValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds = ValueThresholds(), - bool enableThresholds = false, - const std::map& labels = {}, - const std::vector& namedValues = {}, - bool showDefaultValue = true - ); - std::string formatValueDisplay( - std::uint32_t value, - const std::vector& namedValues, - const std::string& suffix, - std::uint32_t divisor, - int decimalPlaces - ); - void addModuleListItemValue( - SysClkProfile profile, - SysClkModule module, - const std::string& categoryName, - std::uint32_t min, - std::uint32_t max, - std::uint32_t step, - const std::string& suffix, - std::uint32_t divisor, - int decimalPlaces, - ValueThresholds thresholds, - std::vector namedValues = {}, - bool showDefaultValue = true - ); - void addGovernorSection(SysClkProfile profile); - void addProfileUI(SysClkProfile profile); - public: - AppProfileGui(std::uint64_t applicationId, SysClkTitleProfileList* profileList); - ~AppProfileGui(); - void listUI() override; - static void changeTo(std::uint64_t applicationId); - void update() override; -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp deleted file mode 100644 index b98865f7..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - -#include "base_gui.h" - -#include "../elements/base_frame.h" - -#include -#include - -#define LOGO_X 20 -#define LOGO_Y 50 -#define LOGO_LABEL_FONT_SIZE 45 - -#define VERSION_X (LOGO_X + 250) -#define VERSION_Y (LOGO_Y - 40) -#define VERSION_FONT_SIZE 15 - -std::string getVersionString() { - char buf[0x100] = ""; - Result rc = sysclkIpcGetVersionString(buf, sizeof(buf)); - if (R_FAILED(rc) || buf[0] == '\0') { - return "Unknown"; - } - return std::string(buf); -} - -static constexpr tsl::Color dynamicLogoRGB1 = tsl::Color(0, 4, 8, 15); -static constexpr tsl::Color dynamicLogoRGB2 = tsl::Color(7, 15, 15, 15); -static constexpr tsl::Color STATIC_AQUA = tsl::Color(2, 10, 12, 15); -const std::string name = "Horizon OC Zeus"; - -static s32 drawDynamicUltraText( - tsl::gfx::Renderer* renderer, - s32 startX, - s32 y, - u32 fontSize, - const tsl::Color& staticColor, - bool useNotificationMethod = false) -{ - static constexpr double cycleDuration = 1.6; - - s32 currentX = startX; - - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const double timeNow = static_cast(currentTime_ns) / 1e9; - const double timeBase = fmod(timeNow, cycleDuration); - - const double waveScale = 2.0 * M_PI / cycleDuration; - - for (size_t i = 0; i < name.size(); i++) - { - char letter = name[i]; - if (letter == '\0') break; - - double phase = waveScale * (timeBase + i * 0.12); - - double raw = cos(phase); - double n = (raw + 1.0) * 0.5; - double s1 = n * n * (3.0 - 2.0 * n); - double blend = std::clamp(s1, 0.0, 1.0); - - double glow = (cos(phase * 1.5) + 1.0) * 0.5; - double brightness = 0.75 + glow * 0.25; - - u8 r = static_cast( - (dynamicLogoRGB1.r + (dynamicLogoRGB2.r - dynamicLogoRGB1.r) * blend) * brightness - ); - u8 g = static_cast( - (dynamicLogoRGB1.g + (dynamicLogoRGB2.g - dynamicLogoRGB1.g) * blend) * brightness - ); - u8 b = static_cast( - (dynamicLogoRGB1.b + (dynamicLogoRGB2.b - dynamicLogoRGB1.b) * blend) * brightness - ); - - r = std::clamp(r, 0, 15); - g = std::clamp(g, 0, 15); - b = std::clamp(b, 0, 15); - - bool lightning = (fmod(timeNow, 5.0) < 0.15); - if (lightning) { - r = std::min(r + 4, 15); - g = std::min(g + 4, 15); - b = std::min(b + 15, 15); - } - - tsl::Color color(r, g, b, 15); - - std::string ls(1, letter); - - if (useNotificationMethod) - currentX += renderer->drawNotificationString(ls, false, currentX, y, fontSize, color).first; - else - currentX += renderer->drawString(ls, false, currentX, y, fontSize, color).first; - } - - return currentX; -} - -void BaseGui::preDraw(tsl::gfx::Renderer* renderer) { - drawDynamicUltraText( - renderer, - LOGO_X, - LOGO_Y, - LOGO_LABEL_FONT_SIZE, - STATIC_AQUA, - false - ); -} - -tsl::elm::Element* BaseGui::createUI() -{ - BaseFrame* rootFrame = new BaseFrame(this); - rootFrame->setContent(this->baseUI()); - return rootFrame; -} - -void BaseGui::update() -{ - this->refresh(); -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/base_gui.h b/Source/sys-clk/overlay/src/ui/gui/base_gui.h deleted file mode 100644 index eca76c09..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/base_gui.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include -#include -#include -#include - -#include "../style.h" -#include "../../ipc.h" - -class BaseGui : public tsl::Gui -{ - public: - BaseGui() {} - ~BaseGui() {} - virtual void preDraw(tsl::gfx::Renderer* renderer); - void update() override; - tsl::elm::Element* createUI() override; - virtual tsl::elm::Element* baseUI() = 0; - virtual void refresh() {} - private: -}; - - -extern std::string getVersionString(); diff --git a/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.cpp deleted file mode 100644 index fdef64f9..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.cpp +++ /dev/null @@ -1,323 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "base_menu_gui.h" -#include "fatal_gui.h" - -// Cache hardware model to avoid repeated syscalls - -BaseMenuGui::BaseMenuGui() : tempColors{ tsl::Color(0), tsl::Color(0), tsl::Color(0), tsl::Color(0), tsl::Color(0), tsl::Color(0), tsl::Color(0), } -{ - tsl::initializeThemeVars(); - this->context = nullptr; - this->lastContextUpdate = 0; - this->listElement = nullptr; - - - // Pre-cache hardware model during initialization - IsAula(); - IsMariko(); - IsHoag(); - - // Initialize display strings - memset(displayStrings, 0, sizeof(displayStrings)); -} - -BaseMenuGui::~BaseMenuGui() { - delete this->context; // delete handles nullptr automatically -} - -// Fast preDraw - just renders pre-computed strings -void BaseMenuGui::preDraw(tsl::gfx::Renderer* renderer) { - BaseGui::preDraw(renderer); - if(!this->context) [[unlikely]] return; - - // All constants pre-calculated and cached - static constexpr const char* const labels[] = { - "App ID", "Profile", "CPU", "GPU", "MEM", "SoC", "Board", "Skin", "Now", "Avg", "BAT", "PMIC", "FAN", "DISP", "FPS", "RES" - }; - - static constexpr u32 dataPositions[6] = {63-3+3, 200-1, 344-1-3, 200-1, 342-1, 321-1}; - - static u32 labelWidths[10]; - static bool positionsInitialized = false; - - if (!positionsInitialized) { - for (int i = 0; i < 10; i++) { - labelWidths[i] = renderer->getTextDimensions(labels[i], false, SMALL_TEXT_SIZE).first; - } - positionsInitialized = true; - } - static u32 positions[10] = {24-1, 310-labelWidths[1], 24-1, 192-labelWidths[3], 332-labelWidths[4], 24-1, 192 - labelWidths[6], 332-labelWidths[7], 192 - labelWidths[8], 332-labelWidths[9]}; - - static u32 maxProfileValueWidth = renderer->getTextDimensions("USB Charger", false, SMALL_TEXT_SIZE).first; // longest word - - u32 y = 91; - - // === TOP SECTION === - renderer->drawRoundedRect(14, 70-1, 420, 30+2, 12.0f, renderer->aWithOpacity(tsl::tableBGColor)); - - // App ID - use pre-formatted string - renderer->drawString(labels[0], false, positions[0], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - renderer->drawString(displayStrings[0], false, positions[0] + labelWidths[0] + 9, y, SMALL_TEXT_SIZE, tsl::infoTextColor); - - // Profile - use pre-formatted string - renderer->drawString(labels[1], false, 423 - maxProfileValueWidth - labelWidths[1] - 9, y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - renderer->drawString(displayStrings[1], false, 423 - maxProfileValueWidth, y, SMALL_TEXT_SIZE, tsl::infoTextColor); - - y += 38; // Direct assignment instead of += 38 - - // === MAIN DATA SECTION === - // renderer->drawRoundedRect(14, 106, 420, 156, 10.0f, renderer->aWithOpacity(tsl::tableBGColor)); - renderer->drawRoundedRect(14, 106, 420, 136, 12.0f, renderer->aWithOpacity(tsl::tableBGColor)); - // === FREQUENCY SECTION === - // Labels first (better cache locality) - renderer->drawString(labels[2], false, positions[2], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - renderer->drawString(labels[3], false, positions[3], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - renderer->drawString(labels[4], false, positions[4], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - - renderer->drawString(displayStrings[5], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // CPU real - renderer->drawString(displayStrings[6], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // GPU real - renderer->drawString(displayStrings[7], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // MEM real - - // Current frequencies - use pre-formatted strings - // renderer->drawString(displayStrings[2], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // CPU - // renderer->drawString(displayStrings[3], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // GPU - // renderer->drawString(displayStrings[4], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // MEM - - y += 20; // Direct assignment (129 + 20) - - renderer->drawString(displayStrings[19], false, positions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // CPU Usage - renderer->drawString(displayStrings[17], false, positions[3], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // GPU Usage - if(configList.values[HorizonOCConfigValue_RAMVoltUsageDisplayMode] == RamDisplayMode_VDD2Usage || configList.values[HorizonOCConfigValue_RAMVoltUsageDisplayMode] == RamDisplayMode_VDDQUsage) - renderer->drawString(displayStrings[18], false, positions[4], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // RAM Usage - // === REAL FREQUENCIES === - - // y += 20; // Direct assignment (149 + 20) - - // === VOLTAGES === - renderer->drawString(displayStrings[8], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // CPU voltage - renderer->drawString(displayStrings[9], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // GPU voltage - - renderer->drawStringWithColoredSections(displayStrings[10], false, {""}, configList.values[HorizonOCConfigValue_RAMVoltUsageDisplayMode] == RamDisplayMode_VDD2VDDQ ? dataPositions[5]-16 : dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor, tsl::separatorColor); - - y += 22; // Direct assignment (169 + 22) - - // === TEMPERATURE SECTION === - // Labels - renderer->drawString(labels[5], false, positions[5], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - renderer->drawString(labels[6], false, positions[6]-1, y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - renderer->drawString(labels[7], false, positions[7], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - - // Temperatures with color - use pre-computed colors - renderer->drawString(displayStrings[11], false, dataPositions[0], y, SMALL_TEXT_SIZE, tempColors[SysClkThermalSensor_SOC]); // SOC - renderer->drawString(displayStrings[12], false, dataPositions[1], y, SMALL_TEXT_SIZE, tempColors[SysClkThermalSensor_PCB]); // PCB - renderer->drawString(displayStrings[13], false, dataPositions[2], y, SMALL_TEXT_SIZE, tempColors[SysClkThermalSensor_Skin]); // Skin - - y += 20; // Direct assignment (191 + 20) - - renderer->drawString(displayStrings[14], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); - - // Power labels and values - renderer->drawString(labels[8], false, positions[8]-1, y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - renderer->drawString(labels[9], false, positions[9], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - - renderer->drawString(displayStrings[15], false, dataPositions[3], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // Power now - renderer->drawString(displayStrings[16], false, dataPositions[4], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // Power avg - - y+=20; - - renderer->drawString(labels[10], false, positions[2], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); - - renderer->drawString(displayStrings[20], false, dataPositions[0], y, SMALL_TEXT_SIZE, tempColors[HorizonOCThermalSensor_Battery]); // Battery - - renderer->drawString(labels[13], false, positions[4], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); // disp label - - renderer->drawString(displayStrings[25], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // disp freq - - renderer->drawString(labels[12], false, positions[3], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); // fan label - - renderer->drawString(displayStrings[24], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // fan speed - - y+=20; - - renderer->drawString(displayStrings[21], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // Bat voltage - renderer->drawString(displayStrings[23], false, positions[2] - 2, y, SMALL_TEXT_SIZE, tsl::infoTextColor); // Bat Age - - if(this->context->isSaltyNXInstalled) { - - renderer->drawString(labels[15], false, positions[3], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); // RES label - renderer->drawString(displayStrings[27], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // RES - - renderer->drawString(labels[14], false, positions[4], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); // FPS label - renderer->drawString(displayStrings[26], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // FPS - - } - - y+=20; -} - -// Optimized refresh - now does all the string formatting once per second -void BaseMenuGui::refresh() -{ - const u64 ticks = armGetSystemTick(); - // Use cached comparison - 1 billion nanoseconds - if (armTicksToNs(ticks - this->lastContextUpdate) <= 1000000000UL) [[likely]] { - return; // Early exit for most calls - } - - this->lastContextUpdate = ticks; - - // Lazy context allocation - if (!this->context) [[unlikely]] { - this->context = new SysClkContext; - } - - // === SYSCLK CONTEXT UPDATE === - Result rc = sysclkIpcGetCurrentContext(this->context); - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetCurrentContext", rc); - return; - } - - rc = sysclkIpcGetConfigValues(&configList); - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - // dockedHighestAllowedRefreshRate = this->context->maxDisplayFreq; - - // === FORMAT ALL DISPLAY STRINGS (once per second) === - // App ID (hex conversion) - sprintf(displayStrings[0], "%016lX", context->applicationId); - - // Profile - strcpy(displayStrings[1], sysclkFormatProfile(context->profile, true)); - - // Current frequencies - u32 hz = context->freqs[SysClkModule_CPU]; // CPU - sprintf(displayStrings[2], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); - - hz = context->freqs[SysClkModule_GPU]; // GPU - sprintf(displayStrings[3], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); - - hz = context->freqs[SysClkModule_MEM]; // MEM - sprintf(displayStrings[4], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); - - // Real frequencies - hz = context->realFreqs[SysClkModule_CPU]; // CPU - sprintf(displayStrings[5], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); - - hz = context->realFreqs[SysClkModule_GPU]; // GPU - sprintf(displayStrings[6], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); - - hz = context->realFreqs[SysClkModule_MEM]; // MEM - sprintf(displayStrings[7], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); - - // Voltages - sprintf(displayStrings[8], "%.1f mV", context->voltages[HocClkVoltage_CPU] / 1000.0); - sprintf(displayStrings[9], "%.1f mV", context->voltages[HocClkVoltage_GPU] / 1000.0); - - switch(configList.values[HorizonOCConfigValue_RAMVoltUsageDisplayMode]) { - case RamDisplayMode_VDD2VDDQ: - sprintf(displayStrings[10], "%u.%u%u mV", context->voltages[HocClkVoltage_EMCVDD2] / 1000U, (context->voltages[HocClkVoltage_EMCVDD2] % 1000U) / 100U, context->voltages[HocClkVoltage_EMCVDDQ_MarikoOnly] / 1000U); - break; - case RamDisplayMode_VDD2Usage: - sprintf(displayStrings[10], "%u.%u mV", context->voltages[HocClkVoltage_EMCVDD2] / 1000U, (context->voltages[HocClkVoltage_EMCVDD2] % 1000U) / 100U); - break; - case RamDisplayMode_VDDQUsage: - sprintf(displayStrings[10], "%u.%u mV", context->voltages[HocClkVoltage_EMCVDDQ_MarikoOnly] / 1000U, (context->voltages[HocClkVoltage_EMCVDDQ_MarikoOnly] % 1000U) / 100U); - break; - default: - strcpy(displayStrings[10], "N/A"); - break; - } - - // Temperatures and pre-compute colors - u32 millis = context->temps[SysClkThermalSensor_SOC]; // SOC - sprintf(displayStrings[11], "%u.%u °C", millis / 1000U, (millis % 1000U) / 100U); - tempColors[SysClkThermalSensor_SOC] = tsl::GradientColor(millis * 0.001f); - - millis = context->temps[SysClkThermalSensor_PCB]; // PCB - sprintf(displayStrings[12], "%u.%u °C", millis / 1000U, (millis % 1000U) / 100U); - tempColors[SysClkThermalSensor_PCB] = tsl::GradientColor(millis * 0.001f); - - millis = context->temps[SysClkThermalSensor_Skin]; // Skin - sprintf(displayStrings[13], "%u.%u °C", millis / 1000U, (millis % 1000U) / 100U); - tempColors[SysClkThermalSensor_Skin] = tsl::GradientColor(millis * 0.001f); - - // SOC voltage (if available) - sprintf(displayStrings[14], "%u mV", context->voltages[HocClkVoltage_SOC] / 1000U); - - // Power - sprintf(displayStrings[15], "%d mW", context->power[0]); // Now - sprintf(displayStrings[16], "%d mW", context->power[1]); // Avg - - sprintf(displayStrings[17], "%u%%", context->partLoad[HocClkPartLoad_GPU] / 10); - sprintf(displayStrings[18], "%u%%", context->partLoad[SysClkPartLoad_EMC] / 10); - sprintf(displayStrings[19], "%u%%", context->partLoad[HocClkPartLoad_CPUMax] / 10); - - millis = context->temps[HorizonOCThermalSensor_Battery]; // Battery - sprintf(displayStrings[20], "%u.%u °C", millis / 1000U, (millis % 1000U) / 100U); - tempColors[HorizonOCThermalSensor_Battery] = tsl::GradientColor(millis * 0.001f); - - sprintf(displayStrings[21], "%d mV", context->voltages[HocClkVoltage_Battery]); // BAT AVG - - sprintf(displayStrings[23], "%u%%", context->partLoad[HocClkPartLoad_BAT] / 1000); - - sprintf(displayStrings[24], "%u%%", context->partLoad[HocClkPartLoad_FAN]); - - sprintf(displayStrings[25], "%u Hz", context->realFreqs[HorizonOCModule_Display]); - if(this->context->isSaltyNXInstalled) { - if(context->fps == 254) { - strcpy(displayStrings[26], "N/A"); - } else { - memset(displayStrings[26], 0, sizeof(displayStrings[26])); - sprintf(displayStrings[26], "%u", context->fps); - } - } - - if(this->context->isSaltyNXInstalled) { - if(context->resolutionHeight == 0) { - strcpy(displayStrings[27], "N/A"); - } else { - memset(displayStrings[27], 0, sizeof(displayStrings[27])); - sprintf(displayStrings[27], "%up", context->resolutionHeight); - } - } - -} - -tsl::elm::Element* BaseMenuGui::baseUI() -{ - auto* list = new tsl::elm::List(); - list->addItem(new tsl::elm::CustomDrawer([](tsl::gfx::Renderer*, s32, s32, s32, s32) {}), 10); // add a bit of space - this->listElement = list; - this->listUI(); - - return list; -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.h b/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.h deleted file mode 100644 index 50650986..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include "../../ipc.h" -#include "base_gui.h" - -class BaseMenuGui : public BaseGui -{ - protected: - - public: - // u8 dockedHighestAllowedRefreshRate = 60; - SysClkContext* context; - std::uint64_t lastContextUpdate; - SysClkConfigValueList configList; - bool g_hardwareModelCached = false; - bool g_isMariko = false; - bool g_isAula = false; - bool g_isHoag = false; - SetSysProductModel HWmodel = SetSysProductModel_Invalid; - - bool IsAula() { - if (!g_hardwareModelCached) { - setsysGetProductModel(&HWmodel); - g_hardwareModelCached = true; - } - g_isAula = (HWmodel == SetSysProductModel_Aula); - return g_isAula; - } - bool IsHoag() { - if (!g_hardwareModelCached) { - setsysGetProductModel(&HWmodel); - g_hardwareModelCached = true; - } - g_isHoag = (HWmodel == SetSysProductModel_Hoag); - return g_isHoag; - } - bool IsMariko() { - if (!g_hardwareModelCached) { - setsysGetProductModel(&HWmodel); - g_hardwareModelCached = true; - } - g_isMariko = (HWmodel == SetSysProductModel_Iowa || - HWmodel == SetSysProductModel_Hoag || - HWmodel == SetSysProductModel_Calcio || - HWmodel == SetSysProductModel_Aula); - - return g_isMariko; - } - - bool IsErista() { - return !IsMariko(); - } - BaseMenuGui(); - ~BaseMenuGui(); - void preDraw(tsl::gfx::Renderer* renderer) override; - tsl::elm::List* listElement; - tsl::elm::Element* baseUI() override; - void refresh() override; - virtual void listUI() = 0; - - private: - char displayStrings[32][32]; // Pre-formatted display strings - tsl::Color tempColors[7]; // Pre-computed temperature colors -}; diff --git a/Source/sys-clk/overlay/src/ui/gui/cat.h b/Source/sys-clk/overlay/src/ui/gui/cat.h deleted file mode 100644 index a4c56ff4..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/cat.h +++ /dev/null @@ -1,4118 +0,0 @@ -/* - * Copyright (c) Lightos and Souldbminer - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ -// this is a generated file, do not edit manually. -// cat.png - 96x128 -static const unsigned int CAT_WIDTH = 96; -static const unsigned int CAT_HEIGHT = 128; -static const unsigned char CAT_DATA[] = { - 0xE0, 0xE0, 0xDC, 0xFF, 0xE0, 0xE0, 0xDC, 0xFF, 0xE1, 0xE1, 0xDD, 0xFF, - 0xE1, 0xE1, 0xDD, 0xFF, 0xE1, 0xE1, 0xDD, 0xFF, 0xE1, 0xE1, 0xDD, 0xFF, - 0xE2, 0xE3, 0xDE, 0xFF, 0xE2, 0xE3, 0xDE, 0xFF, 0xE3, 0xE4, 0xDF, 0xFF, - 0xE3, 0xE4, 0xDF, 0xFF, 0xE3, 0xE4, 0xDF, 0xFF, 0xE3, 0xE4, 0xDF, 0xFF, - 0xE3, 0xE4, 0xDF, 0xFF, 0xE3, 0xE4, 0xDF, 0xFF, 0xE3, 0xE4, 0xDF, 0xFF, - 0xE3, 0xE4, 0xDF, 0xFF, 0xE3, 0xE3, 0xE1, 0xFF, 0xE3, 0x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 0x15, 0x15, 0x13, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x14, 0x14, 0x14, 0xFF, 0x16, 0x16, 0x16, 0xFF, - 0x17, 0x17, 0x17, 0xFF, 0x16, 0x16, 0x18, 0xFF, 0x14, 0x13, 0x16, 0xFF, - 0x13, 0x13, 0x13, 0xFF, 0x13, 0x13, 0x13, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x0F, 0x10, 0x0B, 0xFF, 0x0D, 0x0E, 0x09, 0xFF, 0x0A, 0x0B, 0x06, 0xFF, - 0x14, 0x15, 0x10, 0xFF, 0x1A, 0x1A, 0x16, 0xFF, 0x22, 0x23, 0x1E, 0xFF, - 0x29, 0x2A, 0x25, 0xFF, 0x23, 0x24, 0x1F, 0xFF, 0x29, 0x2A, 0x25, 0xFF, - 0x32, 0x33, 0x2C, 0xFF, 0x38, 0x39, 0x32, 0xFF, 0x28, 0x29, 0x22, 0xFF, - 0x2F, 0x30, 0x29, 0xFF, 0x31, 0x32, 0x29, 0xFF, 0x2C, 0x2E, 0x24, 0xFF, - 0x2D, 0x2F, 0x27, 0xFF, 0x28, 0x29, 0x22, 0xFF, 0x22, 0x23, 0x1C, 0xFF, - 0x1C, 0x1D, 0x16, 0xFF, 0x17, 0x18, 0x13, 0xFF, 0x17, 0x18, 0x13, 0xFF, - 0x17, 0x18, 0x13, 0xFF, 0x17, 0x18, 0x13, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x09, 0x0A, 0x07, 0xFF, 0x14, 0x14, 0x12, 0xFF, - 0x17, 0x18, 0x13, 0xFF, 0x11, 0x12, 0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0xFF, 0xE4, 0xE5, 0xE2, 0xFF, - 0xE3, 0xE3, 0xE1, 0xFF, 0xE5, 0xE6, 0xE3, 0xFF, 0x65, 0x66, 0x63, 0xFF, - 0x1B, 0x1B, 0x19, 0xFF, 0x18, 0x19, 0x16, 0xFF, 0x1A, 0x1A, 0x18, 0xFF, - 0x16, 0x17, 0x14, 0xFF, 0x14, 0x14, 0x12, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x13, 0x13, 0x13, 0xFF, 0x16, 0x16, 0x16, 0xFF, - 0x18, 0x18, 0x18, 0xFF, 0x08, 0x08, 0x0A, 0xFF, 0x0C, 0x0B, 0x0E, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x13, 0x13, 0x13, 0xFF, 0x09, 0x0A, 0x07, 0xFF, - 0x0D, 0x0E, 0x09, 0xFF, 0x10, 0x11, 0x0C, 0xFF, 0x13, 0x13, 0x0F, 0xFF, - 0x13, 0x13, 0x0F, 0xFF, 0x1B, 0x1C, 0x17, 0xFF, 0x26, 0x27, 0x22, 0xFF, - 0x30, 0x31, 0x2C, 0xFF, 0x31, 0x32, 0x2D, 0xFF, 0x2D, 0x2E, 0x29, 0xFF, - 0x29, 0x2A, 0x23, 0xFF, 0x25, 0x26, 0x1F, 0xFF, 0x36, 0x37, 0x30, 0xFF, - 0x38, 0x39, 0x32, 0xFF, 0x34, 0x36, 0x2C, 0xFF, 0x2A, 0x2B, 0x22, 0xFF, - 0x28, 0x29, 0x22, 0xFF, 0x22, 0x23, 0x1C, 0xFF, 0x1C, 0x1D, 0x16, 0xFF, - 0x16, 0x17, 0x10, 0xFF, 0x14, 0x15, 0x10, 0xFF, 0x14, 0x15, 0x10, 0xFF, - 0x14, 0x15, 0x10, 0xFF, 0x14, 0x15, 0x10, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x14, 0x14, 0x12, 0xFF, 0x18, 0x19, 0x16, 0xFF, 0x1B, 0x1B, 0x19, 0x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 0xA0, 0xFF, 0xA4, 0xA5, 0xA0, 0xFF, 0xA4, 0xA5, 0x9E, 0xFF, - 0xA2, 0xA3, 0x9C, 0xFF, 0xA1, 0xA2, 0x9B, 0xFF, 0xA1, 0xA2, 0x9B, 0xFF, - 0xA1, 0xA1, 0x9D, 0xFF, 0xA0, 0xA0, 0x9B, 0xFF, 0x9D, 0x9E, 0x99, 0xFF, - 0x9C, 0x9D, 0x98, 0xFF, 0x95, 0x96, 0x91, 0xFF, 0x95, 0x96, 0x91, 0xFF, - 0x95, 0x96, 0x91, 0xFF, 0x95, 0x96, 0x91, 0xFF, 0x92, 0x92, 0x90, 0xFF, - 0x87, 0x87, 0x85, 0xFF, 0x78, 0x78, 0x76, 0xFF, 0x6D, 0x6E, 0x6B, 0xFF, - 0x47, 0x47, 0x45, 0xFF, 0x45, 0x45, 0x43, 0xFF, 0x45, 0x45, 0x43, 0xFF, - 0x2D, 0x2E, 0x2B, 0xFF, 0x1F, 0x20, 0x1D, 0xFF, 0x14, 0x14, 0x12, 0xFF, - 0x07, 0x07, 0x05, 0xFF, 0x17, 0x18, 0x15, 0xFF, 0x14, 0x14, 0x12, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, - 0x0F, 0x0F, 0x0F, 0xFF, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x0F, 0x0F, 0x0F, 0xFF, 0x0F, 0x0F, 0x0F, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x13, 0x13, 0x13, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x13, 0x13, 0x13, 0xFF, 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x0E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21, 0x21, 0x1D, 0xFF, 0x16, 0x17, 0x12, 0xFF, - 0x13, 0x13, 0x0F, 0xFF, 0x1B, 0x1B, 0x19, 0xFF, 0x17, 0x18, 0x15, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x11, 0x12, 0x0F, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x14, 0x14, 0x12, 0xFF, 0x1B, 0x1B, 0x19, 0xFF, - 0x1C, 0x1D, 0x18, 0xFF, 0x23, 0x24, 0x1F, 0xFF, 0x44, 0x44, 0x3F, 0xFF, - 0x42, 0x43, 0x3E, 0xFF, 0x68, 0x68, 0x64, 0xFF, 0xA1, 0xA1, 0x9D, 0xFF, - 0x3B, 0x3D, 0x35, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x08, 0x09, 0x02, 0xFF, - 0x2F, 0x30, 0x29, 0xFF, 0x54, 0x55, 0x50, 0xFF, 0x78, 0x79, 0x74, 0xFF, - 0x18, 0x19, 0x14, 0xFF, 0x0E, 0x0F, 0x0A, 0xFF, 0x14, 0x15, 0x10, 0xFF, - 0x0C, 0x0C, 0x08, 0xFF, 0x09, 0x0A, 0x05, 0xFF, 0x08, 0x09, 0x04, 0xFF, - 0x0D, 0x0D, 0x0B, 0xFF, 0x0E, 0x0E, 0x0C, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x17, 0x18, 0x15, 0xFF, 0x0E, 0x0E, 0x0C, 0xFF, - 0x2D, 0x2E, 0x2B, 0xFF, 0x92, 0x92, 0x90, 0xFF, 0xA9, 0xA9, 0xA7, 0xFF, - 0x94, 0x94, 0x92, 0xFF, 0x8B, 0x8B, 0x89, 0xFF,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xFF, 0x64, 0x65, 0x5E, 0xFF, 0x5F, 0x60, 0x5B, 0xFF, - 0x5A, 0x5A, 0x56, 0xFF, 0x50, 0x51, 0x4C, 0xFF, 0x46, 0x47, 0x42, 0xFF, - 0x2C, 0x2D, 0x28, 0xFF, 0x1E, 0x1F, 0x1A, 0xFF, 0x15, 0x16, 0x11, 0xFF, - 0x11, 0x12, 0x0D, 0xFF, 0x1A, 0x1A, 0x18, 0xFF, 0x17, 0x18, 0x15, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x11, 0x12, 0x0F, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, 0x1D, 0x1D, 0x1B, 0xFF, - 0x1A, 0x1A, 0x16, 0xFF, 0x28, 0x28, 0x24, 0xFF, 0x45, 0x45, 0x41, 0xFF, - 0x4B, 0x4B, 0x46, 0xFF, 0x49, 0x4A, 0x45, 0xFF, 0x8F, 0x90, 0x8B, 0xFF, - 0x8E, 0x8F, 0x88, 0xFF, 0x55, 0x56, 0x4F, 0xFF, 0x5C, 0x5D, 0x56, 0xFF, - 0x76, 0x76, 0x72, 0xFF, 0x7D, 0x7D, 0x79, 0xFF, 0x52, 0x52, 0x4D, 0xFF, - 0x03, 0x04, 0x00, 0xFF, 0x16, 0x17, 0x12, 0xFF, 0x16, 0x17, 0x12, 0xFF, - 0x10, 0x11, 0x0C, 0xFF, 0x08, 0x09, 0x04, 0xFF, 0x05, 0x05, 0x03, 0xFF, - 0x0D, 0x0D, 0x0B, 0xFF, 0x0E, 0x0E, 0x0C, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x0F, 0x10, 0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C, 0xFF, 0x7D, 0x7D, 0x79, 0xFF, 0x79, 0x7A, 0x75, 0xFF, - 0x77, 0x78, 0x73, 0xFF, 0x70, 0x71, 0x6A, 0xFF, 0x6B, 0x6C, 0x65, 0xFF, - 0x64, 0x65, 0x5E, 0xFF, 0x5F, 0x61, 0x59, 0xFF, 0x5D, 0x5E, 0x59, 0xFF, - 0x57, 0x58, 0x53, 0xFF, 0x4E, 0x4F, 0x4A, 0xFF, 0x40, 0x41, 0x3C, 0xFF, - 0x28, 0x28, 0x24, 0xFF, 0x1D, 0x1E, 0x19, 0xFF, 0x15, 0x16, 0x11, 0xFF, - 0x14, 0x15, 0x10, 0xFF, 0x18, 0x19, 0x16, 0xFF, 0x17, 0x18, 0x15, 0xFF, - 0x14, 0x14, 0x12, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, 0x10, 0x10, 0x10, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x0F, 0x0F, 0x0F, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, - 0x0F, 0x10, 0x0D, 0xFF, 0x1A, 0x1A, 0x18, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x18, 0x19, 0x14, 0xFF, 0x2D, 0x2E, 0x29, 0xFF, 0x29, 0x2A, 0x25, 0xFF, - 0x48, 0x49, 0x44, 0xFF, 0x33, 0x34, 0x2F, 0xFF, 0x46, 0x47, 0x42, 0xFF, - 0x84, 0x84, 0x80, 0xFF, 0x7A, 0x7B, 0x76, 0xFF, 0x77, 0x78, 0x73, 0xFF, - 0x63, 0x64, 0x5F, 0xFF, 0x4F, 0x50, 0x4D, 0xFF, 0x24, 0x24, 0x22, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x23, 0x23, 0x21, 0xFF, 0x22, 0x22, 0x20, 0xFF, - 0x1B, 0x1B, 0x19, 0xFF, 0x0F, 0x12, 0x0E, 0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0xFF, - 0x9D, 0x9E, 0x99, 0xFF, 0x9A, 0x9A, 0x96, 0xFF, 0x97, 0x98, 0x93, 0xFF, - 0x95, 0x96, 0x91, 0xFF, 0x95, 0x96, 0x91, 0xFF, 0x93, 0x93, 0x8F, 0xFF, - 0x8F, 0x90, 0x8B, 0xFF, 0x8D, 0x8E, 0x89, 0xFF, 0x8B, 0x8B, 0x87, 0xFF, - 0x88, 0x89, 0x84, 0xFF, 0x85, 0x86, 0x81, 0xFF, 0x82, 0x83, 0x7E, 0xFF, - 0x7A, 0x7B, 0x76, 0xFF, 0x77, 0x78, 0x73, 0xFF, 0x74, 0x75, 0x70, 0xFF, - 0x72, 0x73, 0x6E, 0xFF, 0x70, 0x71, 0x6A, 0xFF, 0x6A, 0x6B, 0x64, 0xFF, - 0x63, 0x64, 0x5D, 0xFF, 0x5E, 0x5F, 0x58, 0xFF, 0x5C, 0x5D, 0x58, 0xFF, - 0x57, 0x58, 0x53, 0xFF, 0x4D, 0x4E, 0x49, 0xFF, 0x40, 0x41, 0x3C, 0xFF, - 0x29, 0x2A, 0x25, 0xFF, 0x1E, 0x1F, 0x1A, 0xFF, 0x16, 0x17, 0x12, 0xFF, - 0x15, 0x16, 0x11, 0xFF, 0x16, 0x17, 0x14, 0xFF, 0x16, 0x17, 0x14, 0xFF, - 0x14, 0x14, 0x12, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x0E, 0x0E, 0x0C, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x1A, 0x1A, 0x16, 0xFF, 0x22, 0x23, 0x1E, 0xFF, 0x1C, 0x1D, 0x18, 0xFF, - 0x3E, 0x3E, 0x3A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 0xCB, 0xD0, 0xCC, 0xFF, 0xC6, 0xCB, 0xC7, 0xFF, 0xBF, 0xC4, 0xC0, 0xFF, - 0xBF, 0xC4, 0xC0, 0xFF, 0xBF, 0xC4, 0xC0, 0xFF, 0xBF, 0xC4, 0xC0, 0xFF, - 0x9D, 0x9E, 0x99, 0xFF, 0x9A, 0x9A, 0x96, 0xFF, 0x97, 0x98, 0x93, 0xFF, - 0x95, 0x96, 0x91, 0xFF, 0x95, 0x96, 0x91, 0xFF, 0x93, 0x93, 0x8F, 0xFF, - 0x8F, 0x90, 0x8B, 0xFF, 0x8D, 0x8E, 0x89, 0xFF, 0x89, 0x8A, 0x85, 0xFF, - 0x87, 0x88, 0x83, 0xFF, 0x84, 0x84, 0x80, 0xFF, 0x81, 0x82, 0x7D, 0xFF, - 0x78, 0x79, 0x74, 0xFF, 0x74, 0x75, 0x70, 0xFF, 0x72, 0x73, 0x6E, 0xFF, - 0x70, 0x71, 0x6C, 0xFF, 0x70, 0x71, 0x6A, 0xFF, 0x69, 0x6A, 0x63, 0xFF, - 0x63, 0x64, 0x5D, 0xFF, 0x5E, 0x5F, 0x58, 0xFF, 0x5C, 0x5D, 0x58, 0xFF, - 0x57, 0x58, 0x53, 0xFF, 0x4C, 0x4C, 0x48, 0xFF, 0x40, 0x41, 0x3C, 0xFF, - 0x2A, 0x2B, 0x26, 0xFF, 0x1E, 0x1F, 0x1A, 0xFF, 0x16, 0x17, 0x12, 0xFF, - 0x15, 0x16, 0x11, 0xFF, 0x15, 0x15, 0x13, 0xFF, 0x15, 0x15, 0x13, 0xFF, - 0x14, 0x14, 0x12, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x10, 0x10, 0x10, 0xFF, 0x10, 0x10, 0x10, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 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17, 0x12, 0xFF, - 0x14, 0x15, 0x10, 0xFF, 0x14, 0x14, 0x12, 0xFF, 0x14, 0x14, 0x12, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x15, 0x15, 0x15, 0xFF, - 0x18, 0x18, 0x18, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1F, 0x1F, 0x1F, 0xFF, - 0x22, 0x22, 0x20, 0xFF, 0x22, 0x22, 0x20, 0xFF, 0x22, 0x22, 0x20, 0xFF, - 0x22, 0x22, 0x20, 0xFF, 0x23, 0x23, 0x23, 0xFF, 0x22, 0x22, 0x22, 0xFF, - 0x1F, 0x21, 0x21, 0xFF, 0x1E, 0x20, 0x1F, 0xFF, 0x13, 0x16, 0x15, 0xFF, - 0x10, 0x12, 0x11, 0xFF, 0x0E, 0x10, 0x0F, 0xFF, 0x0B, 0x0E, 0x0D, 0xFF, - 0x0F, 0x11, 0x10, 0xFF, 0x11, 0x13, 0x13, 0xFF, 0x12, 0x15, 0x14, 0xFF, - 0x13, 0x16, 0x15, 0xFF, 0x17, 0x17, 0x17, 0xFF, 0x0F, 0x0F, 0x0F, 0xFF, - 0x18, 0x18, 0x18, 0xFF, 0x1F, 0x1F, 0x1F, 0xFF, 0x3F, 0x3F, 0x3F, 0xFF, - 0x3F, 0x3F, 0x3F, 0xFF, 0x70, 0x70, 0x70, 0xFF, 0xB0, 0xB0, 0xB0, 0xFF, - 0xC6, 0xC6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 0x5A, 0x56, 0xFF, - 0x50, 0x51, 0x4C, 0xFF, 0x4B, 0x4B, 0x46, 0xFF, 0x41, 0x42, 0x3D, 0xFF, - 0x2B, 0x2C, 0x27, 0xFF, 0x1F, 0x20, 0x1B, 0xFF, 0x16, 0x17, 0x12, 0xFF, - 0x14, 0x15, 0x10, 0xFF, 0x14, 0x14, 0x12, 0xFF, 0x14, 0x14, 0x12, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x11, 0x12, 0x0F, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x14, 0x14, 0x14, 0xFF, - 0x16, 0x16, 0x16, 0xFF, 0x17, 0x17, 0x17, 0xFF, 0x18, 0x18, 0x18, 0xFF, - 0x18, 0x19, 0x16, 0xFF, 0x1A, 0x1A, 0x18, 0xFF, 0x1A, 0x1A, 0x18, 0xFF, - 0x1B, 0x1B, 0x19, 0xFF, 0x1F, 0x1F, 0x1F, 0xFF, 0x21, 0x21, 0x21, 0xFF, - 0x20, 0x23, 0x22, 0xFF, 0x21, 0x24, 0x23, 0xFF, 0x13, 0x16, 0x15, 0xFF, - 0x10, 0x12, 0x11, 0xFF, 0x0E, 0x10, 0x0F, 0xFF, 0x0B, 0x0E, 0x0D, 0xFF, - 0x10, 0x12, 0x11, 0xFF, 0x12, 0x15, 0x14, 0xFF, 0x13, 0x16, 0x15, 0xFF, - 0x13, 0x16, 0x15, 0xFF, 0x15, 0x15, 0x15, 0xFF, 0x14, 0x14, 0x14, 0xFF, - 0x13, 0x13, 0x13, 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72, 0x6D, 0xFF, - 0x71, 0x72, 0x6D, 0xFF, 0x6B, 0x6C, 0x65, 0xFF, 0x66, 0x68, 0x60, 0xFF, - 0x61, 0x62, 0x5B, 0xFF, 0x5C, 0x5D, 0x56, 0xFF, 0x5A, 0x5A, 0x56, 0xFF, - 0x4F, 0x50, 0x4B, 0xFF, 0x49, 0x4A, 0x45, 0xFF, 0x40, 0x41, 0x3C, 0xFF, - 0x2C, 0x2D, 0x28, 0xFF, 0x1F, 0x20, 0x1B, 0xFF, 0x16, 0x17, 0x12, 0xFF, - 0x14, 0x15, 0x10, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x11, 0x12, 0x0F, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x10, 0x11, 0x0E, 0xFF, 0x11, 0x12, 0x0F, 0xFF, 0x13, 0x13, 0x13, 0xFF, - 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x14, 0x14, 0x12, 0xFF, 0x15, 0x15, 0x13, 0xFF, 0x15, 0x15, 0x13, 0xFF, - 0x15, 0x15, 0x15, 0xFF, 0x1C, 0x1C, 0x1C, 0xFF, 0x1F, 0x1F, 0x1F, 0xFF, - 0x23, 0x25, 0x24, 0xFF, 0x25, 0x27, 0x26, 0xFF, 0x13, 0x16, 0x15, 0xFF, - 0x10, 0x12, 0x11, 0xFF, 0x0E, 0x10, 0x0F, 0xFF, 0x0B, 0x0E, 0x0D, 0xFF, - 0x10, 0x12, 0x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0x8C, 0x88, 0xFF, - 0x88, 0x89, 0x84, 0xFF, 0x82, 0x83, 0x7E, 0xFF, 0x7E, 0x7F, 0x7A, 0xFF, - 0x7B, 0x7C, 0x77, 0xFF, 0x74, 0x75, 0x70, 0xFF, 0x71, 0x72, 0x6D, 0xFF, - 0x6D, 0x6E, 0x69, 0xFF, 0x6B, 0x6C, 0x65, 0xFF, 0x65, 0x66, 0x5F, 0xFF, - 0x5D, 0x5E, 0x57, 0xFF, 0x58, 0x5A, 0x52, 0xFF, 0x54, 0x55, 0x50, 0xFF, - 0x4F, 0x50, 0x4B, 0xFF, 0x48, 0x49, 0x44, 0xFF, 0x40, 0x41, 0x3C, 0xFF, - 0x32, 0x33, 0x2E, 0xFF, 0x24, 0x25, 0x20, 0xFF, 0x18, 0x19, 0x14, 0xFF, - 0x14, 0x15, 0x10, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x10, 0x11, 0x0E, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x0F, 0x10, 0x0D, 0xFF, 0x0F, 0x10, 0x0D, 0xFF, 0x0E, 0x0E, 0x0C, 0xFF, - 0x0E, 0x0E, 0x0C, 0xFF, 0x0E, 0x0E, 0x0C, 0xFF, 0x0E, 0x0E, 0x0C, 0xFF, - 0x0E, 0x0E, 0x0C, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x13, 0x13, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x13, 0x13, 0x13, 0xFF, 0x13, 0x13, 0x13, 0xFF, 0x13, 0x13, 0x13, 0xFF, - 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, 0x11, 0x11, 0x11, 0xFF, - 0x11, 0x11, 0x11, 0xFF, 0x16, 0x16, 0x18, 0xFF, 0x1A, 0x19, 0x1C, 0xFF, - 0x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0x86, 0x81, 0xFF, 0x81, 0x82, 0x7D, 0xFF, - 0x7E, 0x7F, 0x7A, 0xFF, 0x78, 0x79, 0x74, 0xFF, 0x73, 0x74, 0x6F, 0xFF, - 0x71, 0x72, 0x6D, 0xFF, 0x6B, 0x6C, 0x65, 0xFF, 0x65, 0x66, 0x5F, 0xFF, - 0x5E, 0x5F, 0x58, 0xFF, 0x58, 0x5A, 0x52, 0xFF, 0x54, 0x55, 0x50, 0xFF, - 0x4E, 0x4F, 0x4A, 0xFF, 0x47, 0x48, 0x43, 0xFF, 0x40, 0x41, 0x3C, 0xFF, - 0x36, 0x36, 0x32, 0xFF, 0x28, 0x28, 0x24, 0xFF, 0x1E, 0x1F, 0x1A, 0xFF, - 0x1D, 0x1E, 0x19, 0xFF, 0x1A, 0x1A, 0x16, 0xFF, 0x17, 0x18, 0x13, 0xFF, - 0x15, 0x16, 0x11, 0xFF, 0x14, 0x15, 0x10, 0xFF, 0x11, 0x12, 0x0D, 0xFF, - 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, 0x10, 0x11, 0x0C, 0xFF, - 0x10, 0x11, 0x0C, 0xFF, 0x0F, 0x10, 0x0B, 0xFF, 0x0F, 0x10, 0x0B, 0xFF, - 0x0F, 0x10, 0x0B, 0xFF, 0x0F, 0x10, 0x0B, 0xFF, 0x0F, 0x10, 0x0B, 0xFF, - 0x0F, 0x10, 0x0B, 0xFF, 0x0F, 0x10, 0x0B, 0xFF, 0x14, 0x14, 0x12, 0xFF, - 0x13, 0x13, 0x11, 0xFF, 0x11, 0x12, 0x0F, 0xFF, 0x11, 0x12, 0x0F, 0xFF, - 0x18, 0x19, 0x16, 0xFF, 0x17, 0x18, 0x15, 0xFF, 0x16, 0x17, 0x14, 0xFF, - 0x15, 0x15, 0x13, 0xFF, 0x21, 0x1F, 0x1D, 0xFF, 0x28, 0x26, 0x24, 0xFF, - 0x26, 0x27, 0x24, 0xFF, 0x1F, 0x20, 0x1D, 0xFF, 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94, 0x95, 0x90, 0xFF, 0x97, 0x98, 0x93, 0xFF, 0x95, 0x96, 0x91, 0xFF, - 0x93, 0x93, 0x8F, 0xFF, 0x92, 0x92, 0x8E, 0xFF, 0x8D, 0x8E, 0x89, 0xFF, - 0x8B, 0x8B, 0x87, 0xFF, 0x85, 0x86, 0x81, 0xFF, 0x81, 0x82, 0x7D, 0xFF, - 0x7E, 0x7F, 0x7A, 0xFF, 0x78, 0x79, 0x74, 0xFF, 0x73, 0x74, 0x6F, 0xFF, - 0x71, 0x72, 0x6D, 0xFF, 0x6B, 0x6C, 0x67, 0xFF, 0x65, 0x66, 0x5F, 0xFF, - 0x5E, 0x5F, 0x58, 0xFF, 0x58, 0x5A, 0x52, 0xFF, 0x54, 0x55, 0x50, 0xFF, - 0x4E, 0x4F, 0x4A, 0xFF, 0x47, 0x48, 0x43, 0xFF, 0x40, 0x41, 0x3C, 0xFF, - 0x36, 0x36, 0x32, 0xFF, 0x28, 0x28, 0x24, 0xFF, 0x1E, 0x1F, 0x1A, 0xFF, - 0x1C, 0x1D, 0x18, 0xFF, 0x1A, 0x1A, 0x16, 0xFF, 0x17, 0x18, 0x13, 0xFF, - 0x15, 0x16, 0x11, 0xFF, 0x14, 0x15, 0x10, 0xFF, 0x11, 0x12, 0x0D, 0xFF, - 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, - 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, - 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, - 0x11, 0x12, 0x0D, 0xFF, 0x11, 0x12, 0x0D, 0xFF, 0x10, 0x11, 0x0E, 0xFF, - 0x11, 0x12, 0x0F, 0xFF, 0x14, 0x14, 0x12, 0xFF, 0x15, 0x15, 0x13, 0xFF, - 0x1C, 0x1C, 0x1A, 0xFF,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0x22, 0x21, 0x1D, 0xFF, - 0x29, 0x28, 0x24, 0xFF, 0x27, 0x25, 0x21, 0xFF, 0x28, 0x26, 0x22, 0xFF, - 0x27, 0x25, 0x21, 0xFF, 0x26, 0x24, 0x20, 0xFF, 0x26, 0x24, 0x20, 0xFF, - 0x33, 0x2F, 0x2C, 0xFF, 0x2C, 0x28, 0x25, 0xFF, 0x26, 0x22, 0x1F, 0xFF, - 0x21, 0x1D, 0x1A, 0xFF, 0x1C, 0x1B, 0x17, 0xFF, 0x14, 0x13, 0x0F, 0xFF, - 0x1A, 0x18, 0x14, 0xFF, 0x1A, 0x18, 0x14, 0xFF, 0x14, 0x12, 0x11, 0xFF, - 0x18, 0x16, 0x14, 0xFF, 0x1C, 0x1A, 0x19, 0xFF, 0x20, 0x1E, 0x1C, 0xFF, - 0x11, 0x0F, 0x0D, 0xFF, 0x14, 0x12, 0x11, 0xFF, 0x13, 0x11, 0x0F, 0xFF, - 0x0E, 0x0C, 0x0B, 0xFF, 0x14, 0x12, 0x11, 0xFF, 0x1A, 0x1A, 0x18, 0xFF, - 0x23, 0x25, 0x22, 0xFF, 0x29, 0x2C, 0x29, 0xFF, 0x2E, 0x31, 0x2E, 0xFF, - 0x44, 0x47, 0x44, 0xFF, 0x69, 0x6E, 0x6A, 0xFF, 0x7F, 0x84, 0x80, 0xFF, - 0x81, 0x84, 0x80, 0xFF, 0x85, 0x88, 0x85, 0xFF, 0x8C, 0x8F, 0x8C, 0xFF, - 0x92, 0x95, 0x92, 0xFF, 0x7A, 0x7A, 0x7A, 0xFF, 0x76, 0x76, 0x76, 0xFF, - 0x7A, 0x7A, 0x7A, 0xFF, 0x85, 0x85, 0x85, 0xFF, 0x8F, 0x8F, 0x8F, 0xFF, - 0x90, 0x90, 0x90, 0xFF, 0x93, 0x93, 0x93, 0xFF, 0x94, 0x94, 0x94, 0xFF, - 0x8F, 0x8F, 0x8F, 0xFF, 0x96, 0x96, 0x96, 0xFF, 0xAA, 0xAA, 0xAA, 0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 0xB0, 0xAC, 0xFF, 0xAC, 0xB9, 0xB4, 0xFF, 0xBC, 0xC8, 0xC4, 0xFF, - 0xB7, 0xC3, 0xBF, 0xFF, 0xA2, 0xAE, 0xAA, 0xFF, 0xB6, 0xC2, 0xBE, 0xFF -}; diff --git a/Source/sys-clk/overlay/src/ui/gui/fatal_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/fatal_gui.cpp deleted file mode 100644 index fa2c6c89..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/fatal_gui.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "fatal_gui.h" - -FatalGui::FatalGui(const std::string message, const std::string info) -{ - this->message = message; - this->info = info; -} - -void FatalGui::openWithResultCode(std::string tag, Result rc) -{ - char rcStr[32]; - std::string info = tag; - info.append(rcStr, snprintf(rcStr, sizeof(rcStr), "\n\n[0x%x] %04d-%04d", rc, R_MODULE(rc), R_DESCRIPTION(rc))); - - tsl::changeTo( - "Could not connect to hoc-clk sysmodule.\n\n" - "\n" - "Please make sure everything is\n\n" - "correctly installed and enabled.", - info - ); -} - -tsl::elm::Element* FatalGui::baseUI() -{ - tsl::elm::CustomDrawer* drawer = new tsl::elm::CustomDrawer([this](tsl::gfx::Renderer* renderer, u16 x, u16 y, u16 w, u16 h) { - renderer->drawString("\uE150", false, 40, 210, 40, TEXT_COLOR); - renderer->drawString("Fatal error", false, 100, 210, 30, TEXT_COLOR); - - std::uint32_t txtY = 255; - if(!this->message.empty()) - { - txtY += renderer->drawString(this->message.c_str(), false, 40, txtY, 23, TEXT_COLOR).second; - txtY += 55; - } - - if(!this->info.empty()) - { - renderer->drawString(this->info.c_str(), false, 40, txtY, 18, DESC_COLOR); - } - }); - - return drawer; -} - -bool FatalGui::handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) -{ - if((keysDown & HidNpadButton_A) == HidNpadButton_A || (keysDown & HidNpadButton_B) == HidNpadButton_B) - { - while(tsl::Overlay::get()->getCurrentGui() != nullptr) { - tsl::goBack(); - } - return true; - } - - return false; -} diff --git a/Source/sys-clk/overlay/src/ui/gui/fatal_gui.h b/Source/sys-clk/overlay/src/ui/gui/fatal_gui.h deleted file mode 100644 index 61616e58..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/fatal_gui.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include - -#include "base_gui.h" - -class FatalGui : public BaseGui -{ - protected: - std::string message; - std::string info; - - public: - FatalGui(const std::string message, const std::string info); - ~FatalGui() {} - tsl::elm::Element* baseUI() override; - bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight); - static void openWithResultCode(std::string tag, Result rc); -}; diff --git a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp deleted file mode 100644 index 311ce921..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp +++ /dev/null @@ -1,219 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "freq_choice_gui.h" - -#include "../format.h" -#include "fatal_gui.h" - -FreqChoiceGui::FreqChoiceGui(std::uint32_t selectedHz, - std::uint32_t* hzList, - std::uint32_t hzCount, - SysClkModule module, - FreqChoiceListener listener, - bool checkMax, - std::map labels) -{ - this->selectedHz = selectedHz; - this->hzList = hzList; - this->hzCount = hzCount; - this->module = module; - this->listener = listener; - this->checkMax = checkMax; - this->labels = labels; - this->configList = new SysClkConfigValueList {}; -} - -FreqChoiceGui::~FreqChoiceGui() -{ - delete this->configList; -} - -tsl::elm::ListItem* FreqChoiceGui::createFreqListItem(std::uint32_t hz, bool selected, int safety) -{ - std::string text = formatListFreqHz(hz); - - std::string rightText = ""; - auto it = labels.find(hz); - if (it != labels.end()) - rightText = it->second; - - if (selected) - const_cast(rightText) = "\uE14B"; - - tsl::elm::ListItem* listItem = - new tsl::elm::ListItem(text, rightText, false); - - switch (safety) - { - case 0: - listItem->setTextColor(tsl::Color(255, 255, 255, 255)); - listItem->setValueColor(tsl::Color(255, 255, 255, 255)); - break; - case 1: - listItem->setTextColor(tsl::Color(255, 165, 0, 255)); - listItem->setValueColor(tsl::Color(255, 165, 0, 255)); - break; - case 2: - listItem->setTextColor(tsl::Color(255, 0, 0, 255)); - listItem->setValueColor(tsl::Color(255, 0, 0, 255)); - break; - } - - // Make annotation grey - if (!rightText.empty() && !selected) - listItem->setValueColor(tsl::Color(180, 180, 180, 255)); - else if(selected) - listItem->setValueColor(tsl::infoTextColor); - - listItem->setClickListener([this, hz](u64 keys) - { - if ((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) { - if (this->listener(hz)) { - tsl::goBack(); - } - return true; - } - return false; - }); - - return listItem; -} - -void FreqChoiceGui::listUI() -{ - sysclkIpcGetConfigValues(this->configList); - - // Header based on CPU/GPU/MEM module - std::string moduleName = sysclkFormatModule(this->module, false); - this->listElement->addItem(new tsl::elm::CategoryHeader(moduleName)); - - // Default option - this->listElement->addItem( - this->createFreqListItem(0, this->selectedHz == 0, 0)); - - for (std::uint32_t i = 0; i < this->hzCount; i++) - { - std::uint32_t hz = this->hzList[i]; - uint32_t mhz = hz / 1000000; - - // if (checkMax && IsMariko()) { - // if (moduleName == "cpu" && - // this->configList->values[HocClkConfigValue_MarikoMaxCpuClock] < mhz) - // continue; - - // // if (moduleName == "gpu" && - // // this->configList->values[HocClkConfigValue_MarikoMaxGpuClock] < mhz) - // // continue; - - // // if (moduleName == "mem" && - // // this->configList->values[HocClkConfigValue_MarikoMaxMemClock] < mhz) - // // continue; - - if (checkMax && IsErista()) - if (moduleName == "cpu" && this->configList->values[HocClkConfigValue_EristaMaxCpuClock] < mhz) - continue; - - // // if (moduleName == "gpu" && - // // this->configList->values[HocClkConfigValue_EristaMaxGpuClock] < mhz) - // // continue; - - // // if (moduleName == "mem" && - // // this->configList->values[HocClkConfigValue_EristaMaxMemClock] < mhz) - // // continue; - // } - - if (moduleName == "mem" && mhz <= 600) - continue; - - uint32_t unsafe_cpu; - uint32_t unsafe_gpu; - uint32_t danger_cpu; - uint32_t danger_gpu; - - if (IsMariko()) - { - unsafe_cpu = this->configList->values[KipConfigValue_marikoCpuUVHigh] ? 2398 : 1964; - if(this->configList->values[KipConfigValue_marikoGpuUV] == 0) { - unsafe_gpu = 1076; - } else if (this->configList->values[KipConfigValue_marikoGpuUV] == 1) { - unsafe_gpu = 1153; - } else { - unsafe_gpu = 1229; - } - danger_cpu = this->configList->values[KipConfigValue_marikoCpuUVHigh] ? 2500 : 2398; - danger_gpu = 1306; - } - else - { - unsafe_cpu = this->configList->values[KipConfigValue_eristaCpuUV] ? 2092 : 1786; - if(this->configList->values[KipConfigValue_eristaGpuUV] == 0) { - unsafe_gpu = 922; - } else { - unsafe_gpu = 961; - } - danger_cpu = this->configList->values[KipConfigValue_eristaCpuUV] ? 2194 : 1964; - danger_gpu = 999; - } - - int safety = 0; - - if (moduleName == "cpu") { - - if (mhz >= danger_cpu) - safety = 2; - else if (mhz >= unsafe_cpu) - safety = 1; - else - safety = 0; - - } else if (moduleName == "gpu") { - - if (mhz >= danger_gpu) - safety = 2; - else if (mhz >= unsafe_gpu) - safety = 1; - else - safety = 0; - - } else if (moduleName == "mem") { - - safety = 0; - - } - - this->listElement->addItem( - this->createFreqListItem( - hz, - (mhz == this->selectedHz / 1000000), - safety - ) - ); - } - - this->listElement->jumpToItem("", ""); -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h deleted file mode 100644 index 1ccaf264..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include -#include -#include "base_menu_gui.h" - -using FreqChoiceListener = std::function; - -class FreqChoiceGui : public BaseMenuGui -{ -protected: - SysClkConfigValueList* configList; - std::uint32_t selectedHz; - std::uint32_t* hzList; - std::uint32_t hzCount; - SysClkModule module; - FreqChoiceListener listener; - bool checkMax; - - std::map labels; - - tsl::elm::ListItem* createFreqListItem(std::uint32_t hz, bool selected, int safety); - -public: - FreqChoiceGui(std::uint32_t selectedHz, - std::uint32_t* hzList, - std::uint32_t hzCount, - SysClkModule module, - FreqChoiceListener listener, - bool checkMax = true, - std::map labels = {}); - - ~FreqChoiceGui(); - - void listUI() override; -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/global_override_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/global_override_gui.cpp deleted file mode 100644 index 737ada09..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/global_override_gui.cpp +++ /dev/null @@ -1,418 +0,0 @@ -/* - * - * Copyright (c) Souldbminer and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#include "../format.h" -#include "fatal_gui.h" -#include "global_override_gui.h" -#include "value_choice_gui.h" -#include "labels.h" - -GlobalOverrideGui::GlobalOverrideGui() -{ - for (std::uint16_t m = 0; m < SysClkModule_EnumMax; m++) { - this->listItems[m] = nullptr; - this->listHz[m] = 0; - } -} - -void GlobalOverrideGui::openFreqChoiceGui(SysClkModule module) -{ - std::uint32_t hzList[SYSCLK_FREQ_LIST_MAX]; - std::uint32_t hzCount; - Result rc = - sysclkIpcGetFreqList(module, &hzList[0], SYSCLK_FREQ_LIST_MAX, &hzCount); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcGetFreqList", rc); - return; - } - - std::map labels = {}; - - if (module == SysClkModule_CPU) { - bool isUsingUv = IsMariko() ? configList.values[KipConfigValue_marikoCpuUVHigh] : configList.values[KipConfigValue_eristaCpuUV]; - labels = IsMariko() ? (isUsingUv ? cpu_freq_label_m_uv : cpu_freq_label_m) : (isUsingUv ? cpu_freq_label_e_uv : cpu_freq_label_e); - } else if (module == SysClkModule_GPU) { - labels = IsMariko() ? *(marikoUV[configList.values[KipConfigValue_marikoGpuUV]]) : *(eristaUV[configList.values[KipConfigValue_eristaGpuUV]]); - } - tsl::changeTo( - this->context->overrideFreqs[module], hzList, hzCount, module, - [this, module](std::uint32_t hz) { - Result rc = sysclkIpcSetOverride(module, hz); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetOverride", rc); - return false; - } - - this->lastContextUpdate = armGetSystemTick(); - this->context->overrideFreqs[module] = hz; - - return true; - }, - true, labels - ); -} - -void GlobalOverrideGui::openValueChoiceGui( - tsl::elm::ListItem* listItem, - std::uint32_t currentValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds, - bool enableThresholds, - const std::map& labels, - const std::vector& namedValues, - bool showDefaultValue -) -{ - tsl::changeTo( - currentValue, - range, - categoryName, - listener, - thresholds, - enableThresholds, - labels, - namedValues, - showDefaultValue, - true - ); -} - -void GlobalOverrideGui::addModuleListItemValue( - SysClkModule module, - const std::string& categoryName, - std::uint32_t min, - std::uint32_t max, - std::uint32_t step, - const std::string& suffix, - std::uint32_t divisor, - int decimalPlaces, - ValueThresholds thresholds, - const std::vector& namedValues, - bool showDefaultValue -) -{ - bool hasNamedValues = !namedValues.empty(); - - if (!hasNamedValues) { - this->customFormatModules[module] = std::make_tuple(suffix, divisor, decimalPlaces); - } - - tsl::elm::ListItem* listItem = - new tsl::elm::ListItem(sysclkFormatModule(module, true)); - - listItem->setValue(FREQ_DEFAULT_TEXT); - - listItem->setClickListener( - [this, - listItem, - module, - categoryName, - min, - max, - step, - suffix, - divisor, - decimalPlaces, - thresholds, - namedValues, - hasNamedValues, - showDefaultValue](u64 keys) - { - if ((keys & HidNpadButton_A) == HidNpadButton_A) - { - if (!this->context) { - return false; - } - - std::uint32_t currentValue = - this->context->overrideFreqs[module] * divisor; - - ValueRange range( - min, - max, - step, - suffix, - divisor, - decimalPlaces - ); - - this->openValueChoiceGui( - listItem, - currentValue, - range, - categoryName, - - [this, listItem, module, divisor, suffix, decimalPlaces, thresholds, namedValues, hasNamedValues, showDefaultValue](std::uint32_t value) -> bool - { - if (!this->context) { - return false; - } - - this->context->overrideFreqs[module] = value / divisor; - this->listHz[module] = value / divisor; - - if (value == 0) { - listItem->setValue(FREQ_DEFAULT_TEXT); - } else if (hasNamedValues) { - for (const auto& namedValue : namedValues) { - if (namedValue.value == value / divisor) { - listItem->setValue(namedValue.name); - break; - } - } - } else { - char buf[32]; - if (decimalPlaces > 0) { - double displayValue = (double)value / divisor; - snprintf(buf, sizeof(buf), "%.*f%s", - decimalPlaces, displayValue, suffix.c_str()); - } else { - snprintf(buf, sizeof(buf), "%u%s", - value / divisor, suffix.c_str()); - } - listItem->setValue(buf); - } - - Result rc = - sysclkIpcSetOverride(module, this->context->overrideFreqs[module]); - - if (R_FAILED(rc)) - { - FatalGui::openWithResultCode( - "sysclkIpcSetOverride", rc); - return false; - } - - this->lastContextUpdate = armGetSystemTick(); - return true; - }, - - thresholds, - false, - std::map(), - namedValues, - showDefaultValue - ); - - return true; - } - else if ((keys & HidNpadButton_Y) == HidNpadButton_Y) - { - if (!this->context) { - return false; - } - - this->context->overrideFreqs[module] = 0; - this->listHz[module] = 0; - listItem->setValue(FREQ_DEFAULT_TEXT); - - Result rc = sysclkIpcSetOverride(module, 0); - - if (R_FAILED(rc)) - { - FatalGui::openWithResultCode("sysclkIpcSetOverride", rc); - return false; - } - - this->lastContextUpdate = armGetSystemTick(); - return true; - } - - return false; - }); - - this->listElement->addItem(listItem); - this->listItems[module] = listItem; -} - -void GlobalOverrideGui::addModuleListItem(SysClkModule module) -{ - tsl::elm::ListItem *listItem = - new tsl::elm::ListItem(sysclkFormatModule(module, true)); - listItem->setValue(formatListFreqMHz(0)); - listItem->setClickListener([this, module](u64 keys) { - if ((keys & HidNpadButton_A) == HidNpadButton_A) { - this->openFreqChoiceGui(module); - return true; - } else if ((keys & HidNpadButton_Y) == HidNpadButton_Y) { - Result rc = sysclkIpcSetOverride(module, 0); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetOverride", rc); - return false; - } - - this->lastContextUpdate = armGetSystemTick(); - this->context->overrideFreqs[module] = 0; - this->listHz[module] = 0; - - this->listItems[module]->setValue(formatListFreqHz(0)); - - return true; - } - return false; - }); - - this->listElement->addItem(listItem); - this->listItems[module] = listItem; -} - -void GlobalOverrideGui::addModuleToggleItem(SysClkModule module) -{ - const char *moduleName = sysclkFormatModule(module, true); - bool isOn = this->listHz[module]; - - tsl::elm::ToggleListItem *toggle = - new tsl::elm::ToggleListItem(moduleName, isOn); - - toggle->setStateChangedListener([this, module, toggle](bool state) { - Result rc = sysclkIpcSetOverride(module, state ? 1 : 0); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); - } - this->lastContextUpdate = armGetSystemTick(); - this->context->overrideFreqs[module] = 0; - this->listHz[module] = 0; - }); - this->listElement->addItem(toggle); - this->listItems[module] = toggle; -} - -class GovernorOverrideSubMenuGui : public BaseMenuGui { - u32 packed; -public: - GovernorOverrideSubMenuGui(u32 initialPacked) : packed(initialPacked) {} - - void listUI() override { - Result rc = sysclkIpcGetConfigValues(&configList); // idk why this is needed, probably some refreshing issue - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - this->listElement->addItem(new tsl::elm::CategoryHeader("Governor")); - - static constexpr struct { const char* label; int shift; } kAll[] = { - {"CPU", 0}, {"GPU", 8}, {"VRR", 16} - }; - int count = configList.values[HorizonOCConfigValue_OverwriteRefreshRate] ? 3 : 2; - - for (int i = 0; i < count; i++) { - u8 cur = (this->packed >> kAll[i].shift) & 0xFF; - auto* bar = new tsl::elm::NamedStepTrackBar( - "", {"Do Not Override", "Disabled", "Enabled"}, - true, kAll[i].label - ); - bar->setProgress(cur); - int shift = kAll[i].shift; - bar->setValueChangedListener([this, shift](u8 value) { - this->packed = (this->packed & ~(0xFFu << shift)) | ((u32)value << shift); - Result rc = sysclkIpcSetOverride(HorizonOCModule_Governor, this->packed); - if (R_FAILED(rc)) FatalGui::openWithResultCode("sysclkIpcSetOverride", rc); - this->lastContextUpdate = armGetSystemTick(); - }); - this->listElement->addItem(bar); - } - } -}; - -void GlobalOverrideGui::addGovernorSection() { - auto* item = new tsl::elm::ListItem("Governor"); - item->setValue("\u2192"); // right arrow - item->setClickListener([this](u64 keys) { - if (keys & HidNpadButton_A) { - u32 packed = this->context ? this->context->overrideFreqs[HorizonOCModule_Governor] : 0; - tsl::changeTo(packed); - return true; - } - return false; - }); - this->listElement->addItem(item); -} - -void GlobalOverrideGui::listUI() -{ - BaseMenuGui::refresh(); // get latest context - if(!this->context) - return; - - Result rc = sysclkIpcGetConfigValues(&configList); // idk why this is needed, probably some refreshing issue - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - - this->listElement->addItem(new tsl::elm::CategoryHeader( - "Temporary Overrides " + ult::DIVIDER_SYMBOL + " \ue0e3 Reset")); - this->addModuleListItem(SysClkModule_CPU); - this->addModuleListItem(SysClkModule_GPU); - this->addModuleListItem(SysClkModule_MEM); - #if IS_MINIMAL == 0 - ValueThresholds lcdThresholds(60, 65); - if(configList.values[HorizonOCConfigValue_OverwriteRefreshRate]) - this->addModuleListItemValue(HorizonOCModule_Display, "Display", IsAula() ? 45 : 40, configList.values[HorizonOCConfigValue_MaxDisplayClockH], this->context->isUsingRetroSuper ? 5 : 1, " Hz", 1, 0, lcdThresholds); - #endif - - this->addGovernorSection(); -} - -void GlobalOverrideGui::refresh() -{ - BaseMenuGui::refresh(); - - if (!this->context) - return; - - for (std::uint16_t m = 0; m < SysClkModule_EnumMax; m++) { - if (m == HorizonOCModule_Governor) { - this->listHz[m] = this->context->overrideFreqs[m]; - continue; - } - - if (this->listItems[m] != nullptr && - this->listHz[m] != this->context->overrideFreqs[m]) { - - auto it = this->customFormatModules.find((SysClkModule)m); - if (it != this->customFormatModules.end()) { - std::string suffix = std::get<0>(it->second); - std::uint32_t divisor = std::get<1>(it->second); - int decimalPlaces = std::get<2>(it->second); - - if (this->context->overrideFreqs[m] == 0) { - this->listItems[m]->setValue(FREQ_DEFAULT_TEXT); - } else { - char buf[32]; - if (decimalPlaces > 0) { - double displayValue = (double)this->context->overrideFreqs[m] / divisor; - snprintf(buf, sizeof(buf), "%.*f%s", - decimalPlaces, displayValue, suffix.c_str()); - } else { - snprintf(buf, sizeof(buf), "%u%s", - this->context->overrideFreqs[m] / divisor, suffix.c_str()); - } - this->listItems[m]->setValue(buf); - } - } else { - this->listItems[m]->setValue( - formatListFreqHz(this->context->overrideFreqs[m])); - } - - this->listHz[m] = this->context->overrideFreqs[m]; - } - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/global_override_gui.h b/Source/sys-clk/overlay/src/ui/gui/global_override_gui.h deleted file mode 100644 index 9e5d6db9..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/global_override_gui.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ -#pragma once -#include "../../ipc.h" -#include "base_menu_gui.h" -#include "freq_choice_gui.h" -#include -#include "value_choice_gui.h" -class GlobalOverrideGui : public BaseMenuGui -{ - protected: - std::map> customFormatModules; - tsl::elm::ListItem* listItems[SysClkModule_EnumMax]; - std::uint32_t listHz[SysClkModule_EnumMax]; - void openFreqChoiceGui(SysClkModule module); - void addGovernorSection(); - void addModuleListItem(SysClkModule module); - void addModuleToggleItem(SysClkModule module); - void openValueChoiceGui( - tsl::elm::ListItem* listItem, - std::uint32_t currentValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds, - bool enableThresholds, - const std::map& labels, - const std::vector& namedValues, - bool showDefaultValue - ); - void addModuleListItemValue( - SysClkModule module, - const std::string& categoryName, - std::uint32_t min, - std::uint32_t max, - std::uint32_t step, - const std::string& suffix, - std::uint32_t divisor, - int decimalPlaces, - ValueThresholds thresholds = {}, - const std::vector& namedValues = {}, - bool showDefaultValue = true - ); - public: - GlobalOverrideGui(); - ~GlobalOverrideGui() {} - void listUI() override; - void refresh() override; - void setModuleCustomFormat(SysClkModule module, const std::string& suffix, std::uint32_t divisor, int decimalPlaces); -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/labels.cpp b/Source/sys-clk/overlay/src/ui/gui/labels.cpp deleted file mode 100644 index 12697cc1..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/labels.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#include -#include -#include - -std::map cpu_freq_label_m = { - {612000000, "Sleep Mode"}, - {1020000000, "Stock"}, - {1224000000, "Dev OC"}, - {1785000000, "Boost Mode"}, - {1963000000, "Safe Max"}, - {2397000000, "Unsafe Max"}, - {2703000000, "Absolute Max"}, -}; - -std::map cpu_freq_label_m_uv = { - {612000000, "Sleep Mode"}, - {1020000000, "Stock"}, - {1224000000, "Dev OC"}, - {1785000000, "Boost Mode"}, - {2397000000, "Safe Max"}, - {2499000000, "Unsafe Max"}, - {2703000000, "Absolute Max"}, -}; - -std::map cpu_freq_label_e = { - {612000000, "Sleep Mode"}, - {1020000000, "Stock"}, - {1224000000, "Dev OC"}, - {1785000000, "Safe Max"}, - {2091000000, "Unsafe Max"}, - {2397000000, "Absolute Max"}, -}; - -std::map cpu_freq_label_e_uv = { - {612000000, "Sleep Mode"}, - {1020000000, "Stock"}, - {1224000000, "Dev OC"}, - {1785000000, "Boost Mode"}, - {2091000000, "Safe Max"}, - {2193000000, "Unsafe Max"}, - {2397000000, "Absolute Max"}, -}; - - -std::map gpu_freq_label_e = { - {76800000, "Boost Mode"}, - {307200000, "Handheld"}, - {345600000, "Handheld"}, - {384000000, "Handheld"}, - {422400000, "Handheld"}, - {460800000, "Handheld Safe Max"}, - {768000000, "Docked"}, - {921600000, "Safe Max"}, - {960000000, "Unsafe Max"}, - {1075200000, "Absolute Max"}, -}; - -std::map gpu_freq_label_e_uv = { - {76800000, "Boost Mode"}, - {307200000, "Handheld"}, - {345600000, "Handheld"}, - {384000000, "Handheld"}, - {422400000, "Handheld"}, - {460800000, "Handheld Safe Max"}, - {768000000, "Docked"}, - {960000000, "Safe Max"}, - {1075200000, "Absolute Max"}, -}; - -std::map gpu_freq_label_m = { - {76800000, "Boost Mode"}, - {307200000, "Handheld"}, - {384000000, "Handheld"}, - {460800000, "Handheld"}, - {614400000, "Handheld Safe Max"}, - {768000000, "Docked"}, - {1075200000, "Safe Max"}, - {1305600000, "Unsafe Max"}, - {1536000000, "Absolute Max"}, -}; - -std::map gpu_freq_label_m_slt = { - {76800000, "Boost Mode"}, - {307200000, "Handheld"}, - {384000000, "Handheld"}, - {460800000, "Handheld"}, - {614400000, "Handheld Safe Max"}, - {768000000, "Docked"}, - {1152200000, "Safe Max"}, - {1305600000, "Unsafe Max"}, - {1536000000, "Absolute Max"}, -}; - -std::map gpu_freq_label_m_hiopt = { - {76800000, "Boost Mode"}, - {307200000, "Handheld"}, - {384000000, "Handheld"}, - {460800000, "Handheld"}, - {614400000, "Handheld Safe Max"}, - {768000000, "Docked"}, - {1228800000, "Safe Max"}, - {1305600000, "Unsafe Max"}, - {1536000000, "Absolute Max"}, -}; - -std::map* marikoUV[3] { - &gpu_freq_label_m, - &gpu_freq_label_m_slt, - &gpu_freq_label_m_hiopt, -}; - - -std::map* eristaUV[3] { - &gpu_freq_label_e, - &gpu_freq_label_e_uv, - &gpu_freq_label_e_uv, -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/labels.h b/Source/sys-clk/overlay/src/ui/gui/labels.h deleted file mode 100644 index bbebef02..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/labels.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once -#include -#include -#include - -extern std::map cpu_freq_label_m; -extern std::map cpu_freq_label_m_uv; -extern std::map cpu_freq_label_e; -extern std::map cpu_freq_label_e_uv; -extern std::map gpu_freq_label_m; -extern std::map gpu_freq_label_m_slt; -extern std::map gpu_freq_label_m_hiopt; -extern std::map gpu_freq_label_e; -extern std::map gpu_freq_label_e_uv; - -extern std::map* marikoUV[3]; -extern std::map* eristaUV[3]; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/main_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/main_gui.cpp deleted file mode 100644 index 76cffc33..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/main_gui.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "main_gui.h" - -#include "fatal_gui.h" -#include "app_profile_gui.h" -#include "global_override_gui.h" -#include "misc_gui.h" -#include "about_gui.h" - -void MainGui::listUI() -{ - // this->enabledToggle = new tsl::elm::ToggleListItem("Enable", false); - // enabledToggle->setStateChangedListener([this](bool state) { - // Result rc = sysclkIpcSetEnabled(state); - // if(R_FAILED(rc)) - // { - // FatalGui::openWithResultCode("sysclkIpcSetEnabled", rc); - // } - - // this->lastContextUpdate = armGetSystemTick(); - // this->context->enabled = state; - // }); - // this->listElement->addItem(this->enabledToggle); - - tsl::elm::ListItem* appProfileItem = new tsl::elm::ListItem("Edit App Profile"); - appProfileItem->setClickListener([this](u64 keys) { - if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) - { - AppProfileGui::changeTo(this->context->applicationId); - return true; - } - - return false; - }); - this->listElement->addItem(appProfileItem); - - - tsl::elm::ListItem* globalProfileItem = new tsl::elm::ListItem("Edit Global Profile"); - globalProfileItem->setClickListener([this](u64 keys) { - if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) - { - AppProfileGui::changeTo(SYSCLK_GLOBAL_PROFILE_TID); - return true; - } - - return false; - }); - this->listElement->addItem(globalProfileItem); - - tsl::elm::ListItem* globalOverrideItem = new tsl::elm::ListItem("Temporary Overrides"); - globalOverrideItem->setClickListener([this](u64 keys) { - if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) - { - tsl::changeTo(); - return true; - } - - return false; - }); - this->listElement->addItem(globalOverrideItem); - - //this->listElement->addItem(new tsl::elm::CategoryHeader("Misc")); - - tsl::elm::ListItem* miscItem = new tsl::elm::ListItem("Settings"); - miscItem->setClickListener([this](u64 keys) { - if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) - { - tsl::changeTo(); - return true; - } - - return false; - }); - this->listElement->addItem(miscItem); - - tsl::elm::ListItem* aboutItem = new tsl::elm::ListItem("About"); - aboutItem->setClickListener([this](u64 keys) { - if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) - { - tsl::changeTo(); - return true; - } - - return false; - }); - this->listElement->addItem(aboutItem); - -} - -void MainGui::refresh() -{ - BaseMenuGui::refresh(); - //if(this->context) - //{ - // this->enabledToggle->setState(this->context->enabled); - //} -} diff --git a/Source/sys-clk/overlay/src/ui/gui/main_gui.h b/Source/sys-clk/overlay/src/ui/gui/main_gui.h deleted file mode 100644 index 6eae080c..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/main_gui.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include "base_menu_gui.h" - -class MainGui : public BaseMenuGui -{ - public: - MainGui() {} - ~MainGui() {} - void listUI() override; - void refresh() override; -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp deleted file mode 100644 index e52c6eb1..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp +++ /dev/null @@ -1,1748 +0,0 @@ -/* - * - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#include "misc_gui.h" -#include "fatal_gui.h" -#include "../format.h" -#include -#include -#include -#include -#include "labels.h" -#if IS_MINIMAL == 1 -#pragma message("Compiling with minimal features") -#endif - -#define A_BTN "\ue0e0" -#define R_ARROW "\u2192" - -class GeneralSettingsSubMenuGui; -class GovernorSettingsSubMenuGui; -class DisplaySubMenuGui; -class SafetySubMenuGui; -class RamSubmenuGui; -class RamTimingsSubmenuGui; -class RamLatenciesSubmenuGui; -class CpuSubmenuGui; -class GpuSubmenuGui; -class GpuCustomTableSubmenuGui; -class RamTableEditor; - -MiscGui::MiscGui() -{ - this->configList = new SysClkConfigValueList {}; -} - -MiscGui::~MiscGui() -{ - delete this->configList; - this->configToggles.clear(); - this->configTrackbars.clear(); - this->configButtons.clear(); - this->configRanges.clear(); -} - -void MiscGui::addConfigToggle(SysClkConfigValue configVal, const char* altName) { - const char* configName = altName ? altName : sysclkFormatConfigValue(configVal, true); - tsl::elm::ToggleListItem* toggle = new tsl::elm::ToggleListItem(configName, this->configList->values[configVal]); - toggle->setStateChangedListener([this, configVal](bool state) { - this->configList->values[configVal] = uint64_t(state); - Result rc = sysclkIpcSetConfigValues(this->configList); - if (R_FAILED(rc)) - FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); - this->lastContextUpdate = armGetSystemTick(); - }); - this->listElement->addItem(toggle); - this->configToggles[configVal] = toggle; -} - - -void MiscGui::addConfigButton(SysClkConfigValue configVal, - const char* altName, - const ValueRange& range, - const std::string& categoryName, - const ValueThresholds* thresholds, - const std::map& labels, - const std::vector& namedValues, - bool showDefaultValue) -{ - const char* configName = altName ? altName : sysclkFormatConfigValue(configVal, true); - - tsl::elm::ListItem* listItem = new tsl::elm::ListItem(configName); - - uint64_t currentValue = this->configList->values[configVal]; - char valueText[32]; - if (currentValue == 0 && showDefaultValue) { - snprintf(valueText, sizeof(valueText), "%s", VALUE_DEFAULT_TEXT); - } else { - bool foundNamedValue = false; - for (const auto& namedValue : namedValues) { - if (currentValue == namedValue.value) { - snprintf(valueText, sizeof(valueText), "%s", namedValue.name.c_str()); - foundNamedValue = true; - break; - } - } - - if (!foundNamedValue) { - uint64_t displayValue = currentValue / range.divisor; - if (!range.suffix.empty()) { - snprintf(valueText, sizeof(valueText), "%lu %s", displayValue, range.suffix.c_str()); - } else { - snprintf(valueText, sizeof(valueText), "%lu", displayValue); - } - } - } - listItem->setValue(valueText); - - ValueThresholds thresholdsCopy = (thresholds ? *thresholds : ValueThresholds{}); - - listItem->setClickListener( - [this, configVal, range, categoryName, thresholdsCopy, labels, namedValues, showDefaultValue](u64 keys) - { - if ((keys & HidNpadButton_A) == 0) - return false; - - std::uint32_t currentValue = this->configList->values[configVal]; - - if (thresholdsCopy.warning != 0 || thresholdsCopy.danger != 0) { - - tsl::changeTo( - currentValue, - range, - categoryName, - [this, configVal](std::uint32_t value) { - this->configList->values[configVal] = value; - Result rc = sysclkIpcSetConfigValues(this->configList); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); - return false; - } - this->lastContextUpdate = armGetSystemTick(); - return true; - }, - thresholdsCopy, - true, - labels, - namedValues, - showDefaultValue - ); - } else { - - tsl::changeTo( - currentValue, - range, - categoryName, - [this, configVal](std::uint32_t value) { - this->configList->values[configVal] = value; - Result rc = sysclkIpcSetConfigValues(this->configList); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); - return false; - } - this->lastContextUpdate = armGetSystemTick(); - return true; - }, - ValueThresholds(), - false, - labels, - namedValues, - showDefaultValue - ); - } - - return true; - }); - - this->listElement->addItem(listItem); - this->configButtons[configVal] = listItem; - this->configRanges[configVal] = range; - this->configNamedValues[configVal] = namedValues; -} - -void MiscGui::addConfigButtonS(SysClkConfigValue configVal, - const char* altName, - const ValueRange& range, - const std::string& categoryName, - const ValueThresholds* thresholds, - const std::map& labels, - const std::vector& namedValues, - bool showDefaultValue, - const char* subText) -{ - tsl::elm::ListItem* listItem = new tsl::elm::ListItem(""); - - uint64_t currentValue = this->configList->values[configVal]; - char valueText[32]; - if (currentValue == 0 && showDefaultValue) { - snprintf(valueText, sizeof(valueText), "%s", VALUE_DEFAULT_TEXT); - } else { - bool foundNamedValue = false; - for (const auto& namedValue : namedValues) { - if (currentValue == namedValue.value) { - snprintf(valueText, sizeof(valueText), "%s", namedValue.name.c_str()); - foundNamedValue = true; - break; - } - } - - if (!foundNamedValue) { - uint64_t displayValue = currentValue / range.divisor; - if (!range.suffix.empty()) { - snprintf(valueText, sizeof(valueText), "%lu %s", displayValue, range.suffix.c_str()); - } else { - snprintf(valueText, sizeof(valueText), "%lu", displayValue); - } - } - } - - listItem->setText(valueText); - listItem->setValue(subText ? subText : ""); - - ValueThresholds thresholdsCopy = (thresholds ? *thresholds : ValueThresholds{}); - - listItem->setClickListener( - [this, configVal, range, categoryName, thresholdsCopy, labels, namedValues, showDefaultValue](u64 keys) - { - if ((keys & HidNpadButton_A) == 0) - return false; - - std::uint32_t currentValue = this->configList->values[configVal]; - - if (thresholdsCopy.warning != 0 || thresholdsCopy.danger != 0) { - - tsl::changeTo( - currentValue, - range, - categoryName, - [this, configVal](std::uint32_t value) { - this->configList->values[configVal] = value; - Result rc = sysclkIpcSetConfigValues(this->configList); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); - return false; - } - this->lastContextUpdate = armGetSystemTick(); - return true; - }, - thresholdsCopy, - true, - labels, - namedValues, - showDefaultValue - ); - } else { - - tsl::changeTo( - currentValue, - range, - categoryName, - [this, configVal](std::uint32_t value) { - this->configList->values[configVal] = value; - Result rc = sysclkIpcSetConfigValues(this->configList); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); - return false; - } - this->lastContextUpdate = armGetSystemTick(); - return true; - }, - ValueThresholds(), - false, - labels, - namedValues, - showDefaultValue - ); - } - - return true; - }); - - this->listElement->addItem(listItem); - this->configButtons[configVal] = listItem; - this->configRanges[configVal] = range; - this->configNamedValues[configVal] = namedValues; - this->configButtonSKeys.insert(configVal); - if (subText) - this->configButtonSSubtext[configVal] = std::string(subText); -} - -void MiscGui::updateConfigToggles() { - for (const auto& [value, toggle] : this->configToggles) { - if (toggle != nullptr) - toggle->setState(this->configList->values[value]); - } -} - -void MiscGui::addFreqButton(SysClkConfigValue configVal, - const char* altName, - SysClkModule module, - const std::map& labels) -{ - const char* configName = altName ? altName : sysclkFormatConfigValue(configVal, true); - - tsl::elm::ListItem* listItem = new tsl::elm::ListItem(configName); - - uint64_t currentMHz = this->configList->values[configVal]; - char valueText[32]; - snprintf(valueText, sizeof(valueText), "%lu MHz", currentMHz); - listItem->setValue(valueText); - - listItem->setClickListener( - [this, configVal, module, labels](u64 keys) - { - if ((keys & HidNpadButton_A) == 0) - return false; - - std::uint32_t hzList[SYSCLK_FREQ_LIST_MAX]; - std::uint32_t hzCount; - - Result rc = sysclkIpcGetFreqList(module, hzList, SYSCLK_FREQ_LIST_MAX, &hzCount); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcGetFreqList", rc); - return false; - } - - std::uint32_t currentHz = this->configList->values[configVal] * 1'000'000; - - tsl::changeTo( - currentHz, - hzList, - hzCount, - module, - [this, configVal](std::uint32_t hz) - { - uint64_t mhz = hz / 1'000'000; - this->configList->values[configVal] = mhz; - - Result rc = sysclkIpcSetConfigValues(this->configList); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("sysclkIpcSetConfigValues", rc); - return false; - } - - this->lastContextUpdate = armGetSystemTick(); - return true; - }, - false, - labels - ); - - return true; - }); - - this->listElement->addItem(listItem); - this->configButtons[configVal] = listItem; - - this->configRanges[configVal] = ValueRange(0, 0, 0, "MHz", 1); -} - -void MiscGui::listUI() -{ - Result rc = sysclkIpcGetConfigValues(configList); - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - - ValueThresholds thresholdsDisabled(0, 0); - std::vector noNamedValues = {}; - - this->listElement->addItem(new tsl::elm::CategoryHeader("Settings")); - tsl::elm::ListItem* sysmoduleSettingsSubMenu = new tsl::elm::ListItem("General Settings"); - sysmoduleSettingsSubMenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - sysmoduleSettingsSubMenu->setValue(R_ARROW); - this->listElement->addItem(sysmoduleSettingsSubMenu); - - tsl::elm::ListItem* governorSettingsSubMenu = new tsl::elm::ListItem("Governor Settings"); - governorSettingsSubMenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - governorSettingsSubMenu->setValue(R_ARROW); - this->listElement->addItem(governorSettingsSubMenu); - - tsl::elm::ListItem* safetySubmenu = new tsl::elm::ListItem("Safety Settings"); - safetySubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - safetySubmenu->setValue(R_ARROW); - this->listElement->addItem(safetySubmenu); - - // this->listElement->addItem(new tsl::elm::CategoryHeader("KIP")); - - tsl::elm::ListItem* saveBtn = new tsl::elm::ListItem("Save KIP Settings"); - saveBtn->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - Result rc = hocClkIpcSetKipData(); - if (R_FAILED(rc)) { - FatalGui::openWithResultCode("hocClkIpcSetKipData", rc); - return false; - } - return true; - } - return false; - }); - saveBtn->setValue(A_BTN); - this->listElement->addItem(saveBtn); - - tsl::elm::ListItem* ramSubmenu = new tsl::elm::ListItem("RAM Settings"); - ramSubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - ramSubmenu->setValue(R_ARROW); - this->listElement->addItem(ramSubmenu); - - tsl::elm::ListItem* cpuSubmenu = new tsl::elm::ListItem("CPU Settings"); - cpuSubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - cpuSubmenu->setValue(R_ARROW); - this->listElement->addItem(cpuSubmenu); - - tsl::elm::ListItem* gpuSubmenu = new tsl::elm::ListItem("GPU Settings"); - gpuSubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - gpuSubmenu->setValue(R_ARROW); - this->listElement->addItem(gpuSubmenu); - - tsl::elm::ListItem* displaySubMenu = new tsl::elm::ListItem("Display Settings"); - displaySubMenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - displaySubMenu->setValue(R_ARROW); - this->listElement->addItem(displaySubMenu); - - #if IS_MINIMAL == 0 - // std::vector chargerCurrents = { - // NamedValue("Disabled", 0), - // NamedValue("1024mA", 1024), - // NamedValue("1280mA", 1280), - // NamedValue("1536mA", 1536), - // NamedValue("1792mA", 1792), - // NamedValue("2048mA", 2048), - // NamedValue("2304mA", 2304), - // NamedValue("2560mA", 2560), - // NamedValue("2816mA", 2816), - // NamedValue("3072mA", 3072), - // }; - if(this->configList->values[HorizonOCConfigValue_EnableExperimentalSettings]) { - this->listElement->addItem(new tsl::elm::CategoryHeader("Experimental")); - - addConfigToggle(HorizonOCConfigValue_LiveCpuUv, nullptr); - std::vector gpuSchedMethodValues = { - NamedValue("INI", GpuSchedulingOverrideMethod_Ini), - NamedValue("NV Service", GpuSchedulingOverrideMethod_NvService), - }; - addConfigButton( - HorizonOCConfigValue_GPUSchedulingMethod, - "GPU Scheduling Override Method", - ValueRange(0, 0, 1, "", 0), - "GPU Scheduling Override Method", - &thresholdsDisabled, - {}, - gpuSchedMethodValues, - false - ); - tsl::elm::CustomDrawer* chargeWarningText = new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) { - renderer->drawString("\uE150 Overriding the charge current", false, x + 20, y + 30, 18, tsl::style::color::ColorText); - renderer->drawString("can be dangerous and may cause", false, x + 20, y + 50, 18, tsl::style::color::ColorText); - renderer->drawString("damage to your battery or charger!", false, x + 20, y + 70, 18, tsl::style::color::ColorText); - }); - chargeWarningText->setBoundaries(0, 0, tsl::cfg::FramebufferWidth, 90); - this->listElement->addItem(chargeWarningText); - - if(!IsHoag()) { - std::vector chargerCurrents = { - NamedValue("Disabled", 0), - NamedValue("1024mA", 1024), - NamedValue("1280mA", 1280), - NamedValue("1536mA", 1536), - NamedValue("1792mA", 1792), - NamedValue("2048mA", 2048), - NamedValue("2304mA", 2304), - NamedValue("2560mA", 2560), - NamedValue("2816mA", 2816), - NamedValue("3072mA", 3072), - }; - - ValueThresholds chargerThresholds(2048, 2049); - - addConfigButton( - HorizonOCConfigValue_BatteryChargeCurrent, - "Charge Current Override", - ValueRange(0, 0, 1, "", 0), - "Charge Current Override", - &chargerThresholds, - {}, - chargerCurrents, - false - ); - } - else { - std::vector chargerCurrents = { - NamedValue("Disabled", 0), - NamedValue("1024mA", 1024), - NamedValue("1280mA", 1280), - NamedValue("1536mA", 1536), - NamedValue("1792mA", 1792), - NamedValue("2048mA", 2048), - NamedValue("2304mA", 2304), - NamedValue("2560mA", 2560), - }; - - ValueThresholds chargerThresholds(1792, 1793); - - addConfigButton( - HorizonOCConfigValue_BatteryChargeCurrent, - "Charge Current Override", - ValueRange(0, 0, 1, "", 0), - "Charge Current Override", - &chargerThresholds, - {}, - chargerCurrents, - false - ); - - } - } - #endif -} - -class GeneralSettingsSubMenuGui : public MiscGui { -public: - GeneralSettingsSubMenuGui() { } - -protected: - void listUI() override { - this->listElement->addItem(new tsl::elm::CategoryHeader("General Settings")); - ValueThresholds thresholdsDisabled(0, 0); - std::vector ramVoltDispModes = { - NamedValue("VDD2 + VDDQ", RamDisplayMode_VDD2VDDQ), - NamedValue("VDD2 + Usage", RamDisplayMode_VDD2Usage), - NamedValue("VDDQ + Usage", RamDisplayMode_VDDQUsage), - }; - - addConfigButton(HorizonOCConfigValue_RAMVoltUsageDisplayMode, "RAM Voltage Display Mode", ValueRange(0, 12, 1, "", 0), "RAM Voltage Display Mode", &thresholdsDisabled, {}, ramVoltDispModes, false); - - addConfigButton( - SysClkConfigValue_PollingIntervalMs, - "Polling Interval", - ValueRange(50, 1000, 50, "ms", 1), - "Polling Interval", - &thresholdsDisabled, - {}, - {}, - false - ); - } -}; - -class GovernorSettingsSubMenuGui : public MiscGui { -public: - GovernorSettingsSubMenuGui() { } - -protected: - void listUI() override { - this->listElement->addItem(new tsl::elm::CategoryHeader("Governor Settings")); - ValueThresholds thresholdsDisabled(0, 0); - - std::vector GovernorMinHz = { - NamedValue("510 MHz", 510000000), - NamedValue("612 MHz", 612000000), - NamedValue("714 MHz", 714000000), - NamedValue("816 MHz", 816000000), - NamedValue("918 MHz", 918000000), - NamedValue("1020 MHz", 1020000000), - }; - - addConfigButton( - HorizonOCConfigValue_CpuGovernorMinimumFreq, - "CPU Governor Minimum Frequency", - ValueRange(0, 0, 1, "", 0), - "CPU Governor Minimum Frequency", - &thresholdsDisabled, - {}, - GovernorMinHz, - false - ); - - } -}; - - -class DisplaySubMenuGui : public MiscGui { -public: - DisplaySubMenuGui() { } - -protected: - void listUI() override { - BaseMenuGui::refresh(); // get latest context - if(!this->context) - return; - - this->listElement->addItem(new tsl::elm::CategoryHeader("Display Settings")); - addConfigToggle(HorizonOCConfigValue_OverwriteRefreshRate, nullptr); - if(!this->context->isUsingRetroSuper) { - tsl::elm::CustomDrawer* warningText = new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) { - renderer->drawString("\uE150 Usage of unsafe display", false, x + 20, y + 30, 18, tsl::style::color::ColorText); - renderer->drawString("refresh rates may cause stress", false, x + 20, y + 50, 18, tsl::style::color::ColorText); - renderer->drawString("or damage to your display! ", false, x + 20, y + 70, 18, tsl::style::color::ColorText); - renderer->drawString("Proceed at your own risk!", false, x + 20, y + 90, 18, tsl::style::color::ColorText); - }); - - warningText->setBoundaries(0, 0, tsl::cfg::FramebufferWidth, 110); - this->listElement->addItem(warningText); - ValueThresholds displayThresholds(60, 65); - addConfigButton( - HorizonOCConfigValue_MaxDisplayClockH, - "Max Handheld Display", - ValueRange(60, IsAula() ? 65 : 75, 1, " Hz", 1), - "Display Clock", - &displayThresholds, - {}, - {}, - false - ); - } - } -}; - -class SafetySubMenuGui : public MiscGui { -public: - SafetySubMenuGui() { } - -protected: - void listUI() override { - this->listElement->addItem(new tsl::elm::CategoryHeader("Safety Settings")); - addConfigToggle(HocClkConfigValue_UncappedClocks, nullptr); - addConfigToggle(HocClkConfigValue_ThermalThrottle, nullptr); - addConfigToggle(HocClkConfigValue_HandheldTDP, nullptr); - - #if IS_MINIMAL == 0 - std::map labels_pwr_l = { - {6400, "Official Rating"} - }; - - if(IsHoag()) { - ValueThresholds tdpThresholdsLite(6400, 7500); - addConfigButton( - HocClkConfigValue_LiteTDPLimit, - "TDP Threshold", - ValueRange(4000, 8000, 100, "mW", 1), - "Power", - &tdpThresholdsLite, - labels_pwr_l - ); - } else { - ValueThresholds tdpThresholds(9600, 11000); - addConfigButton( - HocClkConfigValue_HandheldTDPLimit, - "TDP Threshold", - ValueRange(8000, 12000, 100, "mW", 1), - "Power", - &tdpThresholds - ); - } - - ValueThresholds throttleThresholds(70, 80); - addConfigButton( - HocClkConfigValue_ThermalThrottleThreshold, - "Thermal Throttle Limit", - ValueRange(50, 85, 1, "°C", 1), - "Temp", - &throttleThresholds - ); - #endif - } -}; - -class RamSubmenuGui : public MiscGui { -public: - RamSubmenuGui() { } - -protected: - void listUI() override { - ValueThresholds thresholdsDisabled(0, 0); - std::vector noNamedValues = {}; - - this->listElement->addItem(new tsl::elm::CategoryHeader("RAM Settings")); - - addConfigToggle(KipConfigValue_hpMode, "HP Mode"); - - std::map emc_voltage_label = { - {1100000, "Default (Mariko)"}, - {1125000, "Default (Erista)"}, - {1175000, "Rating"}, - {1212500, "Safe Max (Mariko)"}, - {1237500, "Safe Max (Erista)"}, - {1250000, "Unsafe Max"}, - }; - - ValueThresholds vdd2Thresholds(1212500, 1250000); - addConfigButton( - KipConfigValue_commonEmcMemVolt, - "RAM VDD2 Voltage", - ValueRange(912500, 1350000, 12500, "mV", 1000, 1), - "Voltage", - &vdd2Thresholds, - emc_voltage_label, - noNamedValues, - false - ); - - if(IsMariko()) { - addConfigButton( - KipConfigValue_marikoEmcVddqVolt, - "RAM VDDQ Voltage", - ValueRange(400000, 700000, 5000, "mV", 1000), - "RAM VDDQ Voltage", - &thresholdsDisabled, - {}, - {}, - false - ); - } - - addConfigButton( - KipConfigValue_emcDvbShift, - "SoC DVB Shift", - ValueRange(0, 10, 1, "", 1), - "SoC DVB Shift", - &thresholdsDisabled, - {}, - {}, - false - ); - - if (IsErista()) { - tsl::elm::ListItem* freqSubmenu = new tsl::elm::ListItem("RAM Frequency Editor"); - freqSubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - freqSubmenu->setValue(R_ARROW); - this->listElement->addItem(freqSubmenu); - } else { - std::vector marikoMaxEmcClock = { - NamedValue("Disabled", 1600000), - NamedValue("1633 MHz", 1633000), - NamedValue("1666 MHz", 1666000), - NamedValue("1700 MHz", 1700000), - NamedValue("1733 MHz", 1733000), - NamedValue("1766 MHz", 1766000), - NamedValue("1800 MHz", 1800000), - NamedValue("1833 MHz", 1833000), - NamedValue("1866 MHz", 1866000, "JEDEC."), - NamedValue("1900 MHz", 1900000), - NamedValue("1933 MHz", 1933000), - NamedValue("1966 MHz", 1966000), - NamedValue("1996 MHz", 1996800, "JEDEC."), - NamedValue("2000 MHz", 2000000), - NamedValue("2033 MHz", 2033000), - NamedValue("2066 MHz", 2066000), - NamedValue("2100 MHz", 2100000), - NamedValue("2133 MHz", 2133000, "JEDEC."), - NamedValue("2166 MHz", 2166000), - NamedValue("2200 MHz", 2200000), - NamedValue("2233 MHz", 2233000), - NamedValue("2266 MHz", 2266000), - NamedValue("2300 MHz", 2300000), - NamedValue("2333 MHz", 2333000), - NamedValue("2366 MHz", 2366000), - NamedValue("2400 MHz", 2400000, "JEDEC."), - NamedValue("2433 MHz", 2433000), - NamedValue("2466 MHz", 2466000), - NamedValue("2500 MHz", 2500000), - NamedValue("2533 MHz", 2533000), - NamedValue("2566 MHz", 2566000), - NamedValue("2600 MHz", 2600000), - NamedValue("2633 MHz", 2633000), - NamedValue("2666 MHz", 2666000, "JEDEC."), - NamedValue("2700 MHz", 2700000), - NamedValue("2733 MHz", 2733000), - NamedValue("2766 MHz", 2766000), - NamedValue("2800 MHz", 2800000), - NamedValue("2833 MHz", 2833000), - NamedValue("2866 MHz", 2866000), - NamedValue("2900 MHz", 2900000), - NamedValue("2933 MHz", 2933000, "JEDEC."), - NamedValue("2966 MHz", 2966000), - NamedValue("3000 MHz", 3000000), - NamedValue("3033 MHz", 3033000), - NamedValue("3066 MHz", 3066000), - NamedValue("3100 MHz", 3100000), - NamedValue("3133 MHz", 3133000), - NamedValue("3166 MHz", 3166000), - NamedValue("3200 MHz", 3200000, "JEDEC."), - NamedValue("3233 MHz", 3233000, "High speedo needed!"), - NamedValue("3266 MHz", 3266000, "High speedo needed!"), - NamedValue("3300 MHz", 3300000, "High speedo needed!"), - // NamedValue("3333MHz (Needs extreme Speedo/PLL)", 3333000), - // NamedValue("3366MHz (Needs extreme Speedo/PLL)", 3366000), - // NamedValue("3400MHz (Needs extreme Speedo/PLL)", 3400000), - // NamedValue("3433MHz (Needs ridiculous Speedo/PLL)", 3433000), - // NamedValue("3466MHz (Needs ridiculous Speedo/PLL)", 3466000), - // NamedValue("3500MHz (Needs ridiculous Speedo/PLL)", 3500000), - }; - - addConfigButton(KipConfigValue_marikoEmcMaxClock, "Ram Max Clock", ValueRange(0, 1, 1, "", 1), "Ram Max Clock", &thresholdsDisabled, {}, marikoMaxEmcClock, false); - } - - tsl::elm::ListItem* latenciesSubmenu = new tsl::elm::ListItem("RAM Latency Editor"); - latenciesSubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - latenciesSubmenu->setValue(R_ARROW); - this->listElement->addItem(latenciesSubmenu); - - tsl::elm::ListItem* timingsSubmenu = new tsl::elm::ListItem("RAM Timing Reductions"); - timingsSubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - timingsSubmenu->setValue(R_ARROW); - this->listElement->addItem(timingsSubmenu); - - } -}; - -class RamTimingsSubmenuGui : public MiscGui { -public: - RamTimingsSubmenuGui() { } - -protected: - void listUI() override { - ValueThresholds thresholdsDisabled(0, 0); - - this->listElement->addItem(new tsl::elm::CategoryHeader("Memory Timings")); - - addConfigButton(KipConfigValue_t1_tRCD, "t1 tRCD", ValueRange(0, 8, 1, "", 1), "tRCD", &thresholdsDisabled, {}, {}, false); - addConfigButton(KipConfigValue_t2_tRP, "t2 tRP", ValueRange(0, 8, 1, "", 1), "tRP", &thresholdsDisabled, {}, {}, false); - addConfigButton(KipConfigValue_t3_tRAS, "t3 tRAS", ValueRange(0, 10, 1, "", 1), "tRAS", &thresholdsDisabled, {}, {}, false); - addConfigButton(KipConfigValue_t4_tRRD, "t4 tRRD", ValueRange(0, 7, 1, "", 1), "tRRD", &thresholdsDisabled, {}, {}, false); - addConfigButton(KipConfigValue_t5_tRFC, "t5 tRFC", ValueRange(0, 11, 1, "", 1), "tRFC", &thresholdsDisabled, {}, {}, false); - addConfigButton(KipConfigValue_t6_tRTW, "t6 tRTW", ValueRange(0, 10, 1, "", 1), "tRTW", &thresholdsDisabled, {}, {}, false); - addConfigButton(KipConfigValue_t7_tWTR, "t7 tWTR", ValueRange(0, 10, 1, "", 1), "tWTR", &thresholdsDisabled, {}, {}, false); - addConfigButton(KipConfigValue_t8_tREFI, "t8 tREFI", ValueRange(0, 6, 1, "", 1), "tREFI", &thresholdsDisabled, {}, {}, false); - - std::vector t6_tRTW_fine_tune = { - NamedValue("-2", 0xFFFFFFFE), - NamedValue("-1", 0xFFFFFFFF), - NamedValue(" 0", 0), - NamedValue("+1", 1), - NamedValue("+2", 2), - }; - - std::vector t7_tWTR_fine_tune = { - NamedValue("-3", 0xFFFFFFFD), - NamedValue("-2", 0xFFFFFFFE), - NamedValue("-1", 0xFFFFFFFF), - NamedValue(" 0", 0), - NamedValue("+1", 1), - NamedValue("+2", 2), - NamedValue("+3", 3), - }; - - this->listElement->addItem(new tsl::elm::CategoryHeader("Advanced")); - addConfigButton(KipConfigValue_t6_tRTW_fine_tune, "t6 tRTW Fine Tune", ValueRange(0, 4, 1, "", 0), "tRTW Fine Tune", &thresholdsDisabled, {}, t6_tRTW_fine_tune, false); - addConfigButton(KipConfigValue_t7_tWTR_fine_tune, "t7 tWTR Fine Tune", ValueRange(0, 6, 1, "", 0), "tWTR Fine Tune", &thresholdsDisabled, {}, t7_tWTR_fine_tune, false); - } -}; - -class RamLatenciesSubmenuGui : public MiscGui { -public: - RamLatenciesSubmenuGui() { } - -protected: - void listUI() override { - ValueThresholds thresholdsDisabled(0, 0); - - this->listElement->addItem(new tsl::elm::CategoryHeader("Memory Latencies")); - - std::vector rlLabels = { - NamedValue("1333 RL", 28), - NamedValue("1600 RL", 32), - NamedValue("1866 RL", 36), - NamedValue("2133 RL", 40) - }; - - std::vector wlLabels = { - NamedValue("1333 WL", 12), - NamedValue("1600 WL", 14), - NamedValue("1866 WL", 16), - NamedValue("2133 WL", 18) - }; - - addConfigButton( - KipConfigValue_mem_burst_read_latency, - "Read Latency", - ValueRange(0, 6, 1, "", 0), - "Read Latency", - &thresholdsDisabled, - {}, - rlLabels, - false - ); - - addConfigButton( - KipConfigValue_mem_burst_write_latency, - "Write Latency", - ValueRange(0, 6, 1, "", 0), - "Write Latency", - &thresholdsDisabled, - {}, - wlLabels, - false - ); - } -}; - -class CpuSubmenuGui : public MiscGui { -public: - CpuSubmenuGui() { } - -protected: - void listUI() override { - Result rc = sysclkIpcGetConfigValues(this->configList); // populate config list early otherwise wont work - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - - ValueThresholds thresholdsDisabled(0, 0); - ValueThresholds mCpuClockThresholds(1963000, 2397000); - ValueThresholds mCpuClockThresholdsUV(2397000, 2499000); - ValueThresholds eCpuClockThresholds(1785000, 2091000); - ValueThresholds eCpuClockThresholdsUV(2091000, 2193000); - - this->listElement->addItem(new tsl::elm::CategoryHeader("CPU Settings")); - if(IsMariko()) { - std::vector ClkOptions = { - NamedValue("1963 MHz", 1963000), - NamedValue("2091 MHz", 2091000), - NamedValue("2193 MHz", 2193000), - NamedValue("2295 MHz", 2295000), - NamedValue("2397 MHz", 2397000), - NamedValue("2499 MHz", 2499000), - NamedValue("2601 MHz", 2601000), - NamedValue("2703 MHz", 2703000), - }; - - addConfigButton( - KipConfigValue_marikoCpuBoostClock, - "CPU Boost Clock", - ValueRange(0, 0, 1, "", 1), - "CPU Boost Clock", - this->configList->values[KipConfigValue_marikoCpuUVHigh] ? &mCpuClockThresholdsUV : &mCpuClockThresholds, - {}, - ClkOptions, - false - ); - } else { - std::vector ClkOptionsE = { - NamedValue("1785 MHz", 1785000), - NamedValue("1887 MHz", 1887000), - NamedValue("1963 MHz", 1963000), - NamedValue("2091 MHz", 2091000), - NamedValue("2193 MHz", 2193000), - NamedValue("2295 MHz", 2295000), - NamedValue("2397 MHz", 2397000), - }; - addConfigButton( - KipConfigValue_eristaCpuBoostClock, - "CPU Boost Clock", - ValueRange(0, 0, 1, "", 1), - "CPU Boost Clock", - this->configList->values[KipConfigValue_eristaCpuUV] ? &eCpuClockThresholdsUV : &eCpuClockThresholds, - {}, - ClkOptionsE, - false - ); - } - if(IsErista()) { - addConfigButton( - KipConfigValue_eristaCpuUV, - "CPU UV", - ValueRange(0, 5, 1, "", 1), - "CPU UV", - &thresholdsDisabled, - {}, - {}, - false - ); - - addConfigToggle(KipConfigValue_eristaCpuUnlock, "CPU Unlock"); - addConfigButton( - KipConfigValue_eristaCpuVmin, - "CPU VMIN", - ValueRange(700, 900, 25, "mV", 1), - "CPU VMIN", - &thresholdsDisabled, - {}, - {}, - false - ); - - ValueThresholds eCpuVoltThresholds(1235, 1260); - addConfigButton( - KipConfigValue_eristaCpuMaxVolt, - "CPU Max Voltage", - ValueRange(1120, 1260, 5, "mV", 1), - "CPU Max Voltage", - &eCpuVoltThresholds, - {}, - {}, - false - ); - - std::vector maxClkOptions = { - NamedValue("1785 MHz", 1785), - NamedValue("1887 MHz", 1887), - NamedValue("1963 MHz", 1963), - NamedValue("2091 MHz", 2091), - NamedValue("2193 MHz", 2193), - NamedValue("2295 MHz", 2295), - NamedValue("2397 MHz", 2397), - }; - ValueThresholds eCpuMaxClockThresholds(1785, 2091); - addConfigButton( - HocClkConfigValue_EristaMaxCpuClock, - "CPU Max Clock", - ValueRange(0, 0, 1, "", 1), - "CPU Max Clock", - &eCpuMaxClockThresholds, - {}, - maxClkOptions, - false - ); - } else { - std::vector marikoTableConf = { - // NamedValue("Auto", 0), - NamedValue("Default", 1), - NamedValue("1581MHz Tbreak", 2), - NamedValue("1683MHz Tbreak", 3), - NamedValue("Extreme UV Table", 4) - }; - - addConfigButton( - KipConfigValue_tableConf, - "CPU UV Table", - ValueRange(0, 12, 1, "", 0), - "CPU UV Table", - &thresholdsDisabled, - {}, - marikoTableConf, - false - ); - addConfigButton( - KipConfigValue_marikoCpuUVLow, - "CPU Low UV", - ValueRange(0, 8, 1, "", 1), - "CPU Low UV", - &thresholdsDisabled, - {}, - {}, - false - ); - addConfigButton( - KipConfigValue_marikoCpuUVHigh, - "CPU High UV", - ValueRange(0, 12, 1, "", 1), - "CPU High UV", - &thresholdsDisabled, - {}, - {}, - false - ); - - std::vector maxClkOptions = { - NamedValue("1785 MHz", 1785000), - NamedValue("1887 MHz", 1887000), - NamedValue("1963 MHz", 1963000), - NamedValue("2091 MHz", 2091000), - NamedValue("2193 MHz", 2193000), - NamedValue("2295 MHz", 2295000), - NamedValue("2397 MHz", 2397000), - NamedValue("2499 MHz", 2499000), - NamedValue("2601 MHz", 2601000), - NamedValue("2703 MHz", 2703000), - }; - - addConfigButton( - KipConfigValue_marikoCpuMaxClock, - "CPU Max Clock", - ValueRange(0, 0, 1, "", 1), - "CPU Max Clock", - this->configList->values[KipConfigValue_marikoCpuUVHigh] ? &mCpuClockThresholdsUV : &mCpuClockThresholds, - {}, - maxClkOptions, - false - ); - - addConfigButton( - KipConfigValue_marikoCpuLowVmin, - "CPU Low VMIN", - ValueRange(550, 750, 5, "mV", 1), - "CPU VMIN", - &thresholdsDisabled, - {}, - {}, - false - ); - - addConfigButton( - KipConfigValue_marikoCpuHighVmin, - "CPU High VMIN", - ValueRange(650, 900, 5, "mV", 1), - "CPU VMIN", - &thresholdsDisabled, - {}, - {}, - false - ); - - ValueThresholds mCpuVoltThresholds(1160, 1180); - addConfigButton( - KipConfigValue_marikoCpuMaxVolt, - "CPU Max Voltage", - ValueRange(1000, 1200, 5, "mV", 1), - "CPU Max Voltage", - &mCpuVoltThresholds, - {}, - {}, - false - ); - - addConfigToggle(HocClkConfigValue_OverwriteBoostMode, nullptr); - - } - } -}; - -class RamTableEditor : public MiscGui { -public: - RamTableEditor() { } - -protected: - void listUI() override { - this->listElement->addItem(new tsl::elm::CategoryHeader("RAM Frequency Editor")); - - ValueThresholds thresholdsDisabled(0, 0); - // 1600000, 1331200, 1065600, 800000, 665600, 408000, 204000 - - tsl::elm::ListItem* ramItem665 = new tsl::elm::ListItem("665 MHz"); - this->listElement->addItem(ramItem665); - - tsl::elm::ListItem* ramItem800 = new tsl::elm::ListItem("800 MHz"); - this->listElement->addItem(ramItem800); - - tsl::elm::ListItem* ramItem1065 = new tsl::elm::ListItem("1065 MHz"); - this->listElement->addItem(ramItem1065); - - tsl::elm::ListItem* ramItem1331 = new tsl::elm::ListItem("1331 MHz"); - this->listElement->addItem(ramItem1331); - - tsl::elm::ListItem* ramItem1600 = new tsl::elm::ListItem("1600 MHz"); - this->listElement->addItem(ramItem1600); - - ValueThresholds eristaRamThresholds(2208000, 2304000); - - std::vector eristaMaxEmcClock = { - NamedValue("Disabled", 1600000), - NamedValue("1633 MHz", 1633000), - NamedValue("1666 MHz", 1666000), - NamedValue("1700 MHz", 1700000), - NamedValue("1733 MHz", 1733000), - NamedValue("1766 MHz", 1766000), - NamedValue("1800 MHz", 1800000), - NamedValue("1833 MHz", 1833000), - NamedValue("1862 MHz", 1862400, "JEDEC."), - NamedValue("1881 MHz", 1881600), - NamedValue("1900 MHz", 1900800), - NamedValue("1920 MHz", 1920000), - NamedValue("1939 MHz", 1939200), - NamedValue("1958 MHz", 1958400), - NamedValue("1977 MHz", 1977600), - NamedValue("1996 MHz", 1996800, "JEDEC."), - NamedValue("2016 MHz", 2016000), - NamedValue("2035 MHz", 2035200), - NamedValue("2054 MHz", 2054400), - NamedValue("2073 MHz", 2073600), - NamedValue("2092 MHz", 2092800), - NamedValue("2112 MHz", 2112000), - NamedValue("2131 MHz", 2131200, "JEDEC."), - NamedValue("2150 MHz", 2150400), - NamedValue("2169 MHz", 2169600), - NamedValue("2188 MHz", 2188800), - NamedValue("2208 MHz", 2208000), - NamedValue("2227 MHz", 2227200), - NamedValue("2246 MHz", 2246400), - NamedValue("2265 MHz", 2265600), - NamedValue("2284 MHz", 2284800), - NamedValue("2304 MHz", 2304000), - NamedValue("2323 MHz", 2323200), - NamedValue("2342 MHz", 2342400), - NamedValue("2361 MHz", 2361600), - NamedValue("2380 MHz", 2380800), - NamedValue("2400 MHz", 2400000, "JEDEC."), - }; - - addConfigButtonS(KipConfigValue_eristaEmcMaxClock, "", ValueRange(0, 1, 1, "", 1), "", &eristaRamThresholds, {}, eristaMaxEmcClock, false, A_BTN); - addConfigButtonS(KipConfigValue_eristaEmcMaxClock1, "", ValueRange(0, 1, 1, "", 1), "", &eristaRamThresholds, {}, eristaMaxEmcClock, false, A_BTN); - addConfigButtonS(KipConfigValue_eristaEmcMaxClock2, "", ValueRange(0, 1, 1, "", 1), "", &eristaRamThresholds, {}, eristaMaxEmcClock, false, A_BTN); - }; -}; - -class GpuSubmenuGui : public MiscGui { -public: - GpuSubmenuGui() { } - -protected: - void listUI() override { - ValueThresholds thresholdsDisabled(0, 0); - std::vector noNamedValues = {}; - - this->listElement->addItem(new tsl::elm::CategoryHeader("GPU Settings")); - - std::vector gpuUvConf = { - NamedValue("No Undervolt", 0), - NamedValue("SLT Table", 1), - NamedValue("HiOPT Table", 2), - }; - - std::vector mGpuVoltsVmin = { - NamedValue("Auto", 0), - NamedValue("480mV", 480), NamedValue("485mV", 485), NamedValue("490mV", 490), - NamedValue("495mV", 495), NamedValue("500mV", 500), NamedValue("505mV", 505), - NamedValue("510mV", 510), NamedValue("515mV", 515), NamedValue("520mV", 520), - NamedValue("525mV", 525), NamedValue("530mV", 530), NamedValue("535mV", 535), - NamedValue("540mV", 540), NamedValue("545mV", 545), NamedValue("550mV", 550), - NamedValue("555mV", 555), NamedValue("560mV", 560), NamedValue("565mV", 565), - NamedValue("570mV", 570), NamedValue("575mV", 575), NamedValue("580mV", 580), - NamedValue("585mV", 585), NamedValue("590mV", 590), NamedValue("595mV", 595), - NamedValue("600mV", 600), NamedValue("605mV", 605), NamedValue("610mV", 610), - NamedValue("615mV", 615), NamedValue("620mV", 620), NamedValue("625mV", 625), - NamedValue("630mV", 630), NamedValue("635mV", 635), NamedValue("640mV", 640), - NamedValue("645mV", 645), NamedValue("650mV", 650), NamedValue("655mV", 655), - NamedValue("660mV", 660), NamedValue("665mV", 665), NamedValue("670mV", 670), - NamedValue("675mV", 675), NamedValue("680mV", 680), NamedValue("685mV", 685), - NamedValue("690mV", 690), NamedValue("695mV", 695), NamedValue("700mV", 700), - NamedValue("705mV", 705), NamedValue("710mV", 710), NamedValue("715mV", 715), - NamedValue("720mV", 720), NamedValue("725mV", 725), NamedValue("730mV", 730), - NamedValue("735mV", 735), NamedValue("740mV", 740), NamedValue("745mV", 745), - NamedValue("750mV", 750), NamedValue("755mV", 755), NamedValue("760mV", 760), - NamedValue("765mV", 765), NamedValue("770mV", 770), NamedValue("775mV", 775), - NamedValue("780mV", 780), NamedValue("785mV", 785), NamedValue("790mV", 790), - NamedValue("795mV", 795), NamedValue("800mV", 800) - }; - - if(IsErista()) { - addConfigButton( - KipConfigValue_eristaGpuUV, - "GPU Undervolt Table", - ValueRange(0, 1, 1, "", 1), - "GPU Undervolt Table", - &thresholdsDisabled, - {}, - gpuUvConf, - false - ); - addConfigButton( - KipConfigValue_eristaGpuVmin, - "GPU Minimum Voltage", - ValueRange(700, 875, 5, "mV", 1), - "GPU Minimum Voltage", - &thresholdsDisabled, - {}, - {}, - false - ); - } else { - addConfigButton( - KipConfigValue_marikoGpuUV, - "GPU Undervolt Table", - ValueRange(0, 1, 1, "", 1), - "GPU Undervolt Table", - &thresholdsDisabled, - {}, - gpuUvConf, - false - ); - - // tsl::elm::ListItem* vminCalcBtn = new tsl::elm::ListItem("Calculate GPU Vmin"); - // vminCalcBtn->setClickListener([this](u64 keys) { - // if (keys & HidNpadButton_A) { - // Result rc = hocClkIpcCalculateGpuVmin(); - // if (R_FAILED(rc)) { - // FatalGui::openWithResultCode("hocClkIpcCalculateGpuVmin", rc); - // return false; - // } - // return true; - // } - // return false; - // }); - - addConfigButton(KipConfigValue_marikoGpuVmin, "GPU VMIN", ValueRange(0, 0, 0, "0", 1), "GPU VMIN", &thresholdsDisabled, {}, mGpuVoltsVmin, false); - ValueThresholds MgpuVmaxThresholds(805, 850); - addConfigButton( - KipConfigValue_marikoGpuVmax, - "GPU Maximum Voltage", - ValueRange(800, 960, 5, "mV", 1), - "GPU Maximum Voltage", - &MgpuVmaxThresholds, - {}, - {}, - false - ); - } - - addConfigButton( - KipConfigValue_commonGpuVoltOffset, - "GPU Voltage Offset", - ValueRange(0, 50, 5, "mV", 1), - "GPU Voltage Offset", - &thresholdsDisabled, - {}, - {}, - false - ); - - std::vector gpuSchedValues = { - NamedValue("Do not override", GpuSchedulingMode_DoNotOverride), - NamedValue("Enabled (Default)", GpuSchedulingMode_Enabled, "96.6% limit"), - NamedValue("Disabled", GpuSchedulingMode_Disabled, "99.7% limit"), - }; - - addConfigButton( - HorizonOCConfigValue_GPUScheduling, - "GPU Scheduling Override", - ValueRange(0, 0, 1, "", 0), - "GPU Scheduling Override", - &thresholdsDisabled, - {}, - gpuSchedValues, - false - ); - - if (IsMariko()) { - std::vector dvfsOffset = { - NamedValue("-80 mV", 0xFFFFFFB0), - NamedValue("-75 mV", 0xFFFFFFB5), - NamedValue("-70 mV", 0xFFFFFFBA), - NamedValue("-65 mV", 0xFFFFFFBF), - NamedValue("-60 mV", 0xFFFFFFC4), - NamedValue("-55 mV", 0xFFFFFFC9), - NamedValue("-50 mV", 0xFFFFFFCE), - NamedValue("-45 mV", 0xFFFFFFD3), - NamedValue("-40 mV", 0xFFFFFFD8), - NamedValue("-30 mV", 0xFFFFFFE2), - NamedValue("-25 mV", 0xFFFFFFE7), - NamedValue("-20 mV", 0xFFFFFFEC), - NamedValue("-15 mV", 0xFFFFFFF1), - NamedValue("-10 mV", 0xFFFFFFF6), - NamedValue(" -5 mV", 0xFFFFFFFB), - NamedValue("Disabled", 0), - NamedValue(" +5 mV", 5), - NamedValue("+10 mV", 10), - NamedValue("+15 mV", 15), - NamedValue("+20 mV", 20), - }; - - std::vector dvfsValues = { - NamedValue("Disabled", DVFSMode_Disabled), - NamedValue("PCV Hijack", DVFSMode_Hijack), - // NamedValue("Official Service", DVFSMode_OfficialService), - }; - - addConfigButton( - HorizonOCConfigValue_DVFSMode, - "GPU DVFS Mode", - ValueRange(0, 0, 1, "", 0), - "GPU DVFS Mode", - &thresholdsDisabled, - {}, - dvfsValues, - false - ); - - addConfigButton(HorizonOCConfigValue_DVFSOffset, "GPU DVFS Offset", ValueRange(0, 12, 1, "", 0), "GPU DVFS Offset", &thresholdsDisabled, {}, dvfsOffset, false); - } - - tsl::elm::ListItem* customTableSubmenu = new tsl::elm::ListItem("GPU Voltage Table"); - customTableSubmenu->setClickListener([](u64 keys) { - if (keys & HidNpadButton_A) { - tsl::changeTo(); - return true; - } - return false; - }); - customTableSubmenu->setValue(R_ARROW); - this->listElement->addItem(customTableSubmenu); - } -}; - -class GpuCustomTableSubmenuGui : public MiscGui { -public: - GpuCustomTableSubmenuGui() { } - -protected: - void listUI() override { - - Result rc = sysclkIpcGetConfigValues(this->configList); // populate config list early otherwise wont work - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - - this->listElement->addItem(new tsl::elm::CategoryHeader("GPU Custom Table (mV)")); - - ValueThresholds MgpuVmaxThresholds(800, 850); - ValueThresholds EgpuVmaxThresholds(950, 975); - - std::vector mGpuVolts = { - NamedValue("Disabled", 2000), - NamedValue("Auto", 0), - NamedValue("480mV", 480), NamedValue("485mV", 485), NamedValue("490mV", 490), - NamedValue("495mV", 495), NamedValue("500mV", 500), NamedValue("505mV", 505), - NamedValue("510mV", 510), NamedValue("515mV", 515), NamedValue("520mV", 520), - NamedValue("525mV", 525), NamedValue("530mV", 530), NamedValue("535mV", 535), - NamedValue("540mV", 540), NamedValue("545mV", 545), NamedValue("550mV", 550), - NamedValue("555mV", 555), NamedValue("560mV", 560), NamedValue("565mV", 565), - NamedValue("570mV", 570), NamedValue("575mV", 575), NamedValue("580mV", 580), - NamedValue("585mV", 585), NamedValue("590mV", 590), NamedValue("595mV", 595), - NamedValue("600mV", 600), NamedValue("605mV", 605), NamedValue("610mV", 610), - NamedValue("615mV", 615), NamedValue("620mV", 620), NamedValue("625mV", 625), - NamedValue("630mV", 630), NamedValue("635mV", 635), NamedValue("640mV", 640), - NamedValue("645mV", 645), NamedValue("650mV", 650), NamedValue("655mV", 655), - NamedValue("660mV", 660), NamedValue("665mV", 665), NamedValue("670mV", 670), - NamedValue("675mV", 675), NamedValue("680mV", 680), NamedValue("685mV", 685), - NamedValue("690mV", 690), NamedValue("695mV", 695), NamedValue("700mV", 700), - NamedValue("705mV", 705), NamedValue("710mV", 710), NamedValue("715mV", 715), - NamedValue("720mV", 720), NamedValue("725mV", 725), NamedValue("730mV", 730), - NamedValue("735mV", 735), NamedValue("740mV", 740), NamedValue("745mV", 745), - NamedValue("750mV", 750), NamedValue("755mV", 755), NamedValue("760mV", 760), - NamedValue("765mV", 765), NamedValue("770mV", 770), NamedValue("775mV", 775), - NamedValue("780mV", 780), NamedValue("785mV", 785), NamedValue("790mV", 790), - NamedValue("795mV", 795), NamedValue("800mV", 800), NamedValue("805mV", 805), - NamedValue("810mV", 810), NamedValue("815mV", 815), NamedValue("820mV", 820), - NamedValue("825mV", 825), NamedValue("830mV", 830), NamedValue("835mV", 835), - NamedValue("840mV", 840), NamedValue("845mV", 845), NamedValue("850mV", 850), - NamedValue("855mV", 855), NamedValue("860mV", 860), NamedValue("865mV", 865), - NamedValue("870mV", 870), NamedValue("875mV", 875), NamedValue("880mV", 880), - NamedValue("885mV", 885), NamedValue("890mV", 890), NamedValue("895mV", 895), - NamedValue("900mV", 900), NamedValue("905mV", 905), NamedValue("910mV", 910), - NamedValue("915mV", 915), NamedValue("920mV", 920), NamedValue("925mV", 925), - NamedValue("930mV", 930), NamedValue("935mV", 935), NamedValue("940mV", 940), - NamedValue("945mV", 945), NamedValue("950mV", 950), NamedValue("955mV", 955), - NamedValue("960mV", 960), - }; - - std::vector eGpuVolts = { - NamedValue("Disabled", 2000), - NamedValue("Auto", 0), - NamedValue("700mV", 700), NamedValue("705mV", 705), NamedValue("710mV", 710), - NamedValue("715mV", 715), NamedValue("720mV", 720), NamedValue("725mV", 725), - NamedValue("730mV", 730), NamedValue("735mV", 735), NamedValue("740mV", 740), - NamedValue("745mV", 745), NamedValue("750mV", 750), NamedValue("755mV", 755), - NamedValue("760mV", 760), NamedValue("765mV", 765), NamedValue("770mV", 770), - NamedValue("775mV", 775), NamedValue("780mV", 780), NamedValue("785mV", 785), - NamedValue("790mV", 790), NamedValue("795mV", 795), NamedValue("800mV", 800), - NamedValue("805mV", 805), NamedValue("810mV", 810), NamedValue("815mV", 815), - NamedValue("820mV", 820), NamedValue("825mV", 825), NamedValue("830mV", 830), - NamedValue("835mV", 835), NamedValue("840mV", 840), NamedValue("845mV", 845), - NamedValue("850mV", 850), NamedValue("855mV", 855), NamedValue("860mV", 860), - NamedValue("865mV", 865), NamedValue("870mV", 870), NamedValue("875mV", 875), - NamedValue("880mV", 880), NamedValue("885mV", 885), NamedValue("890mV", 890), - NamedValue("895mV", 895), NamedValue("900mV", 900), NamedValue("905mV", 905), - NamedValue("910mV", 910), NamedValue("915mV", 915), NamedValue("920mV", 920), - NamedValue("925mV", 925), NamedValue("930mV", 930), NamedValue("935mV", 935), - NamedValue("940mV", 940), NamedValue("945mV", 945), NamedValue("950mV", 950), - NamedValue("955mV", 955), NamedValue("960mV", 960), NamedValue("965mV", 965), - NamedValue("970mV", 970), NamedValue("975mV", 975), NamedValue("980mV", 980), - NamedValue("985mV", 985), NamedValue("990mV", 990), NamedValue("995mV", 995), - }; - - std::vector mGpuVolts_noAuto = { - NamedValue("Disabled", 2000), - NamedValue("480mV", 480), NamedValue("485mV", 485), NamedValue("490mV", 490), - NamedValue("495mV", 495), NamedValue("500mV", 500), NamedValue("505mV", 505), - NamedValue("510mV", 510), NamedValue("515mV", 515), NamedValue("520mV", 520), - NamedValue("525mV", 525), NamedValue("530mV", 530), NamedValue("535mV", 535), - NamedValue("540mV", 540), NamedValue("545mV", 545), NamedValue("550mV", 550), - NamedValue("555mV", 555), NamedValue("560mV", 560), NamedValue("565mV", 565), - NamedValue("570mV", 570), NamedValue("575mV", 575), NamedValue("580mV", 580), - NamedValue("585mV", 585), NamedValue("590mV", 590), NamedValue("595mV", 595), - NamedValue("600mV", 600), NamedValue("605mV", 605), NamedValue("610mV", 610), - NamedValue("615mV", 615), NamedValue("620mV", 620), NamedValue("625mV", 625), - NamedValue("630mV", 630), NamedValue("635mV", 635), NamedValue("640mV", 640), - NamedValue("645mV", 645), NamedValue("650mV", 650), NamedValue("655mV", 655), - NamedValue("660mV", 660), NamedValue("665mV", 665), NamedValue("670mV", 670), - NamedValue("675mV", 675), NamedValue("680mV", 680), NamedValue("685mV", 685), - NamedValue("690mV", 690), NamedValue("695mV", 695), NamedValue("700mV", 700), - NamedValue("705mV", 705), NamedValue("710mV", 710), NamedValue("715mV", 715), - NamedValue("720mV", 720), NamedValue("725mV", 725), NamedValue("730mV", 730), - NamedValue("735mV", 735), NamedValue("740mV", 740), NamedValue("745mV", 745), - NamedValue("750mV", 750), NamedValue("755mV", 755), NamedValue("760mV", 760), - NamedValue("765mV", 765), NamedValue("770mV", 770), NamedValue("775mV", 775), - NamedValue("780mV", 780), NamedValue("785mV", 785), NamedValue("790mV", 790), - NamedValue("795mV", 795), NamedValue("800mV", 800), NamedValue("805mV", 805), - NamedValue("810mV", 810), NamedValue("815mV", 815), NamedValue("820mV", 820), - NamedValue("825mV", 825), NamedValue("830mV", 830), NamedValue("835mV", 835), - NamedValue("840mV", 840), NamedValue("845mV", 845), NamedValue("850mV", 850), - NamedValue("855mV", 855), NamedValue("860mV", 860), NamedValue("865mV", 865), - NamedValue("870mV", 870), NamedValue("875mV", 875), NamedValue("880mV", 880), - NamedValue("885mV", 885), NamedValue("890mV", 890), NamedValue("895mV", 895), - NamedValue("900mV", 900), NamedValue("905mV", 905), NamedValue("910mV", 910), - NamedValue("915mV", 915), NamedValue("920mV", 920), NamedValue("925mV", 925), - NamedValue("930mV", 930), NamedValue("935mV", 935), NamedValue("940mV", 940), - NamedValue("945mV", 945), NamedValue("950mV", 950), NamedValue("955mV", 955), - NamedValue("960mV", 960), - }; - - std::vector eGpuVolts_noAuto = { - NamedValue("Disabled", 2000), - NamedValue("700mV", 700), NamedValue("705mV", 705), NamedValue("710mV", 710), - NamedValue("715mV", 715), NamedValue("720mV", 720), NamedValue("725mV", 725), - NamedValue("730mV", 730), NamedValue("735mV", 735), NamedValue("740mV", 740), - NamedValue("745mV", 745), NamedValue("750mV", 750), NamedValue("755mV", 755), - NamedValue("760mV", 760), NamedValue("765mV", 765), NamedValue("770mV", 770), - NamedValue("775mV", 775), NamedValue("780mV", 780), NamedValue("785mV", 785), - NamedValue("790mV", 790), NamedValue("795mV", 795), NamedValue("800mV", 800), - NamedValue("805mV", 805), NamedValue("810mV", 810), NamedValue("815mV", 815), - NamedValue("820mV", 820), NamedValue("825mV", 825), NamedValue("830mV", 830), - NamedValue("835mV", 835), NamedValue("840mV", 840), NamedValue("845mV", 845), - NamedValue("850mV", 850), NamedValue("855mV", 855), NamedValue("860mV", 860), - NamedValue("865mV", 865), NamedValue("870mV", 870), NamedValue("875mV", 875), - NamedValue("880mV", 880), NamedValue("885mV", 885), NamedValue("890mV", 890), - NamedValue("895mV", 895), NamedValue("900mV", 900), NamedValue("905mV", 905), - NamedValue("910mV", 910), NamedValue("915mV", 915), NamedValue("920mV", 920), - NamedValue("925mV", 925), NamedValue("930mV", 930), NamedValue("935mV", 935), - NamedValue("940mV", 940), NamedValue("945mV", 945), NamedValue("950mV", 950), - NamedValue("955mV", 955), NamedValue("960mV", 960), NamedValue("965mV", 965), - NamedValue("970mV", 970), NamedValue("975mV", 975), NamedValue("980mV", 980), - NamedValue("985mV", 985), NamedValue("990mV", 990), NamedValue("995mV", 995), - }; - - if (IsMariko()) { - - tsl::elm::CustomDrawer* warningText = new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) { - renderer->drawString("\uE150 Setting GPU Clocks past", false, x + 20, y + 30, 18, tsl::style::color::ColorText); - renderer->drawString("1075MHz without UV, 1152MHz on SLT", false, x + 20, y + 50, 18, tsl::style::color::ColorText); - renderer->drawString("or 1228MHz on HiOPT can cause ", false, x + 20, y + 70, 18, tsl::style::color::ColorText); - renderer->drawString("permanent damage to your Switch!", false, x + 20, y + 90, 18, tsl::style::color::ColorText); - renderer->drawString("Proceed at your own risk!", false, x + 20, y + 110, 18, tsl::style::color::ColorText); - }); - warningText->setBoundaries(0, 0, tsl::cfg::FramebufferWidth, 130); - this->listElement->addItem(warningText); - - addConfigButton(KipConfigValue_g_volt_76800, "76.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_153600, "153.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_230400, "230.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_307200, "307.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_384000, "384.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_460800, "460.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_537600, "537.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_614400, "614.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_691200, "691.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_768000, "768.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_844800, "844.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_921600, "921.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_998400, "998.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_1075200, "1075.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - if(this->configList->values[KipConfigValue_marikoGpuUV] >= GPUUVLevel_SLT) - addConfigButton(KipConfigValue_g_volt_1152000, "1152.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - if(this->configList->values[KipConfigValue_marikoGpuUV] >= GPUUVLevel_HiOPT) { - addConfigButton(KipConfigValue_g_volt_1228800, "1228.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_1267200, "1267.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_1305600, "1305.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_1344000, "1344.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts_noAuto, false); - addConfigButton(KipConfigValue_g_volt_1382400, "1382.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts_noAuto, false); - addConfigButton(KipConfigValue_g_volt_1420800, "1420.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts_noAuto, false); - addConfigButton(KipConfigValue_g_volt_1459200, "1459.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts_noAuto, false); - addConfigButton(KipConfigValue_g_volt_1497600, "1497.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts_noAuto, false); - addConfigButton(KipConfigValue_g_volt_1536000, "1536.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &MgpuVmaxThresholds, {}, mGpuVolts_noAuto, false); - } - - } else { - - tsl::elm::CustomDrawer* warningText = new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) { - renderer->drawString("\uE150 Setting GPU Clocks past", false, x + 20, y + 30, 18, tsl::style::color::ColorText); - renderer->drawString("921MHz without UV and 960MHz on", false, x + 20, y + 50, 18, tsl::style::color::ColorText); - renderer->drawString("SLT or HiOPT can cause ", false, x + 20, y + 70, 18, tsl::style::color::ColorText); - renderer->drawString("permanent damage to your Switch!", false, x + 20, y + 90, 18, tsl::style::color::ColorText); - renderer->drawString("Proceed at your own risk!", false, x + 20, y + 110, 18, tsl::style::color::ColorText); - }); - warningText->setBoundaries(0, 0, tsl::cfg::FramebufferWidth, 130); - this->listElement->addItem(warningText); - - addConfigButton(KipConfigValue_g_volt_e_76800, "76.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_115200, "115.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_153600, "153.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_192000, "192.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_230400, "230.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_268800, "268.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_307200, "307.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_345600, "345.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_384000, "384.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_422400, "422.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_460800, "460.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_499200, "499.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_537600, "537.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_576000, "576.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_614400, "614.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_652800, "652.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_691200, "691.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_729600, "729.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_768000, "768.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_806400, "806.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_844800, "844.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_883200, "883.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_921600, "921.6MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - if(this->configList->values[KipConfigValue_eristaGpuUV] >= GPUUVLevel_SLT) - addConfigButton(KipConfigValue_g_volt_e_960000, "960.0MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - if(this->configList->values[KipConfigValue_eristaGpuUV] >= GPUUVLevel_HiOPT) { - addConfigButton(KipConfigValue_g_volt_e_998400, "998.4MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts, false); - addConfigButton(KipConfigValue_g_volt_e_1036800, "1036.8MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts_noAuto, false); - addConfigButton(KipConfigValue_g_volt_e_1075200, "1075.2MHz", ValueRange(0, 0, 0, "0", 1), "Voltage", &EgpuVmaxThresholds, {}, eGpuVolts_noAuto, false); - } - } - } -}; - - -static std::string getValueDisplayText(uint64_t currentValue, - const ValueRange& range, - const std::vector& namedValues) -{ - char valueText[32]; - - for (const auto& namedValue : namedValues) { - if (currentValue == namedValue.value) { - return namedValue.name; - } - } - - if (currentValue == 0) { - snprintf(valueText, sizeof(valueText), "%s", VALUE_DEFAULT_TEXT); - } else { - uint64_t displayValue = currentValue / range.divisor; - if (!range.suffix.empty()) { - snprintf(valueText, sizeof(valueText), "%lu %s", displayValue, range.suffix.c_str()); - } else { - snprintf(valueText, sizeof(valueText), "%lu", displayValue); - } - } - return std::string(valueText); -} - -void MiscGui::refresh() { - BaseMenuGui::refresh(); - - if (this->context && ++frameCounter >= 60) { - frameCounter = 0; - - Result rc = sysclkIpcGetConfigValues(this->configList); - if (R_FAILED(rc)) [[unlikely]] { - FatalGui::openWithResultCode("sysclkIpcGetConfigValues", rc); - return; - } - updateConfigToggles(); - - for (const auto& [configVal, button] : this->configButtons) { - uint64_t currentValue = this->configList->values[configVal]; - const ValueRange& range = this->configRanges[configVal]; - - auto namedValuesIt = this->configNamedValues.find(configVal); - const std::vector& namedValues = (namedValuesIt != this->configNamedValues.end()) - ? namedValuesIt->second - : std::vector(); - - char valueText[32]; - - bool foundNamedValue = false; - for (const auto& namedValue : namedValues) { - if (currentValue == namedValue.value) { - snprintf(valueText, sizeof(valueText), "%s", namedValue.name.c_str()); - foundNamedValue = true; - break; - } - } - - if (!foundNamedValue) { - uint64_t displayValue = currentValue / range.divisor; - if (!range.suffix.empty()) { - snprintf(valueText, sizeof(valueText), "%lu %s", displayValue, range.suffix.c_str()); - } else { - snprintf(valueText, sizeof(valueText), "%lu", displayValue); - } - } - - if (this->configButtonSKeys.count(configVal)) { - button->setText(valueText); - auto subtextIt = this->configButtonSSubtext.find(configVal); - if (subtextIt != this->configButtonSSubtext.end()) - button->setValue(subtextIt->second); - else - button->setValue(""); - } else { - button->setValue(valueText); - } - } - } -} diff --git a/Source/sys-clk/overlay/src/ui/gui/misc_gui.h b/Source/sys-clk/overlay/src/ui/gui/misc_gui.h deleted file mode 100644 index 3c2bd71d..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/misc_gui.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ -#pragma once -#include "../../ipc.h" -#include "base_menu_gui.h" -#include -#include -#include -#include -#include "freq_choice_gui.h" -#include "value_choice_gui.h" -class MiscGui : public BaseMenuGui -{ -public: - MiscGui(); - ~MiscGui(); - void listUI() override; - void refresh() override; - -protected: - SysClkConfigValueList* configList; - std::map configButtons; - std::map configRanges; - std::map> configNamedValues; - std::map configToggles; - std::map>> configTrackbars; - std::set configButtonSKeys; - std::map configButtonSSubtext; - - void addConfigToggle(SysClkConfigValue configVal, const char* altName); - void addConfigButton(SysClkConfigValue configVal, - const char* altName, - const ValueRange& range, - const std::string& categoryName, - const ValueThresholds* thresholds, - const std::map& labels = {}, - const std::vector& namedValues = {}, - bool showDefaultValue = true); - - void addConfigButtonS(SysClkConfigValue configVal, - const char* altName, - const ValueRange& range, - const std::string& categoryName, - const ValueThresholds* thresholds, - const std::map& labels = {}, - const std::vector& namedValues = {}, - bool showDefaultValue = true, - const char* subText = nullptr); - void addFreqButton(SysClkConfigValue configVal, - const char* altName, - SysClkModule module, - const std::map& labels = {}); - void updateConfigToggles(); - - tsl::elm::ToggleListItem* enabledToggle; - u8 frameCounter = 60; -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/ult_ext.h b/Source/sys-clk/overlay/src/ui/gui/ult_ext.h deleted file mode 100644 index 82267fd9..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/ult_ext.h +++ /dev/null @@ -1,126 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -#pragma once -#include - -class ImageElement : public tsl::elm::ListItem { -private: - const uint8_t* imgData; - uint32_t imgWidth, imgHeight; - bool visible; - -public: - ImageElement(const uint8_t* data, uint32_t w, uint32_t h) - : tsl::elm::ListItem(""), imgData(data), imgWidth(w), imgHeight(h), visible(true) {} - - void setVisible(bool v) { - visible = v; - } - - virtual void draw(tsl::gfx::Renderer *renderer) override { - if (!visible) return; - - // Draw image centered horizontally - u16 centerX = this->getX() + (this->getWidth() - imgWidth) / 2; - renderer->drawBitmap( - centerX, - this->getY() + 10, - imgWidth, - imgHeight, - imgData - ); - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - if (!visible) { - // Take up no space when hidden - this->setBoundaries(parentX, parentY, 0, 0); - } else { - // Normal layout when visible - tsl::elm::ListItem::layout(parentX, parentY, parentWidth, parentHeight); - } - } - - virtual void drawHighlight(tsl::gfx::Renderer *renderer) override { - // Do nothing - no highlight - } - - virtual bool onClick(u64 keys) override { - return false; // Non-clickable - } - - virtual Element* requestFocus(Element *oldFocus, tsl::FocusDirection direction) override { - return nullptr; // Make it non-focusable - } -}; - -class HideableCategoryHeader : public tsl::elm::CategoryHeader { -private: - bool visible; - -public: - HideableCategoryHeader(const std::string& title) - : tsl::elm::CategoryHeader(title), visible(true) {} - - void setVisible(bool v) { - visible = v; - } - - virtual void draw(tsl::gfx::Renderer *renderer) override { - if (!visible) return; - tsl::elm::CategoryHeader::draw(renderer); - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - if (!visible) { - this->setBoundaries(parentX, parentY, 0, 0); - } else { - tsl::elm::CategoryHeader::layout(parentX, parentY, parentWidth, parentHeight); - } - } -}; - -class HideableCustomDrawer : public tsl::elm::Element { -private: - bool visible; - u32 height; - -public: - HideableCustomDrawer(u32 h) - : Element(), visible(true), height(h) {} - - void setVisible(bool v) { - visible = v; - } - - virtual void draw(tsl::gfx::Renderer *renderer) override { - // Empty drawer - just for spacing - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - if (!visible) { - this->setBoundaries(parentX, parentY, 0, 0); - } else { - this->setBoundaries(parentX, parentY, parentWidth, height); - } - } - - virtual Element* requestFocus(Element *oldFocus, tsl::FocusDirection direction) override { - return nullptr; - } -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.cpp deleted file mode 100644 index 9b8d6265..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.cpp +++ /dev/null @@ -1,200 +0,0 @@ - -/* - * - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ -#include "value_choice_gui.h" -#include "../format.h" -#include "fatal_gui.h" -#include -#include - -ValueChoiceGui::ValueChoiceGui(std::uint32_t selectedValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds, - bool enableThresholds, - std::map labels, - std::vector namedValues, - bool showDefaultValue, - bool showDNO) - : selectedValue(selectedValue), - range(range), - categoryName(categoryName), - listener(listener), - thresholds(thresholds), - enableThresholds(enableThresholds), - labels(labels), - namedValues(namedValues), - showDefaultValue(showDefaultValue), - showDNO(showDNO) -{ -} - -ValueChoiceGui::~ValueChoiceGui() -{ -} - -std::string ValueChoiceGui::formatValue(std::uint32_t value) -{ - std::ostringstream oss; - if(showDefaultValue) { - if (value == 0) { - return this->showDNO ? FREQ_DEFAULT_TEXT : VALUE_DEFAULT_TEXT; - } - } - double displayValue = static_cast(value) / static_cast(range.divisor); - oss << std::fixed << std::setprecision(range.decimalPlaces) << displayValue; - if (!range.suffix.empty()) { - oss << " " << range.suffix; - } - return oss.str(); -} - -int ValueChoiceGui::getSafetyLevel(std::uint32_t value) -{ - if(thresholds.warning == 0 && thresholds.danger == 0) { - return 0; - } - - if (value > thresholds.danger) { - return 2; - } - if (value > thresholds.warning) { - return 1; - } - return 0; -} - -tsl::elm::ListItem* ValueChoiceGui::createValueListItem(std::uint32_t value, bool selected, int safety) -{ - std::string text = formatValue(value); - std::string rightText = ""; - - auto it = labels.find(value); - if (it != labels.end()) { - rightText = it->second; - } - - if (selected) { - const_cast(rightText) = "\uE14B"; - } - - tsl::elm::ListItem* listItem = new tsl::elm::ListItem(text, rightText, false); - switch (safety) - { - case 0: - listItem->setTextColor(tsl::Color(255, 255, 255, 255)); - listItem->setValueColor(tsl::Color(255, 255, 255, 255)); - break; - case 1: - listItem->setTextColor(tsl::Color(255, 165, 0, 255)); - listItem->setValueColor(tsl::Color(255, 165, 0, 255)); - break; - case 2: - listItem->setTextColor(tsl::Color(255, 0, 0, 255)); - listItem->setValueColor(tsl::Color(255, 0, 0, 255)); - break; - } - - // Make annotation grey - if (!rightText.empty() && !selected) - listItem->setValueColor(tsl::Color(180, 180, 180, 255)); - else if(selected) - listItem->setValueColor(tsl::infoTextColor); - - listItem->setClickListener([this, value](u64 keys) - { - if ((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) { - if (this->listener(value)) { - tsl::goBack(); - } - return true; - } - return false; - }); - return listItem; -} - -tsl::elm::ListItem* ValueChoiceGui::createNamedValueListItem(const NamedValue& namedValue, bool selected, int safety) -{ - std::string text = namedValue.name; - if (selected) { - const_cast(namedValue.rightText) = "\uE14B"; - } - - tsl::elm::ListItem* listItem = new tsl::elm::ListItem(text, namedValue.rightText, false); - switch (safety) - { - case 0: - listItem->setTextColor(tsl::Color(255, 255, 255, 255)); - listItem->setValueColor(tsl::Color(255, 255, 255, 255)); - break; - case 1: - listItem->setTextColor(tsl::Color(255, 165, 0, 255)); - listItem->setValueColor(tsl::Color(255, 165, 0, 255)); - break; - case 2: - listItem->setTextColor(tsl::Color(255, 0, 0, 255)); - listItem->setValueColor(tsl::Color(255, 0, 0, 255)); - break; - } - - if (!namedValue.rightText.empty() && !selected) - listItem->setValueColor(tsl::Color(180, 180, 180, 255)); - else if(selected) - listItem->setValueColor(tsl::infoTextColor); - - listItem->setClickListener([this, value = namedValue.value](u64 keys) - { - if ((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) { - if (this->listener(value)) { - tsl::goBack(); - } - return true; - } - return false; - }); - return listItem; -} - -void ValueChoiceGui::listUI() -{ - if (!categoryName.empty()) { - this->listElement->addItem(new tsl::elm::CategoryHeader(categoryName)); - } - - if (showDefaultValue) { - this->listElement->addItem(this->createValueListItem(0, this->selectedValue == 0, 0)); - } - for (const auto& namedValue : namedValues) { - int safety = enableThresholds ? getSafetyLevel(namedValue.value) : 0; - bool selected = (namedValue.value == this->selectedValue); - this->listElement->addItem(this->createNamedValueListItem(namedValue, selected, safety)); - } - - if (namedValues.empty()) { - for (std::uint32_t value = range.min; value <= range.max; value += range.step) - { - int safety = getSafetyLevel(value); - bool selected = (value == this->selectedValue); - this->listElement->addItem(this->createValueListItem(value, selected, safety)); - } - } - - this->listElement->jumpToItem("", "\uE14B"); -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.h b/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.h deleted file mode 100644 index 49c7883d..00000000 --- a/Source/sys-clk/overlay/src/ui/gui/value_choice_gui.h +++ /dev/null @@ -1,114 +0,0 @@ - -/* - * - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ -#pragma once -#include -#include -#include -#include -#include -#include "base_menu_gui.h" - -using ValueChoiceListener = std::function; -#define VALUE_DEFAULT_TEXT "Default" - -struct ValueRange { - std::uint32_t min; - std::uint32_t max; - std::uint32_t step; - std::string suffix; - std::uint32_t divisor; - int decimalPlaces; - ValueRange() - : min(0), max(0), step(1), suffix(""), divisor(1), decimalPlaces(0) {} - ValueRange(std::uint32_t min, std::uint32_t max, std::uint32_t step, - const std::string& suffix = "", std::uint32_t divisor = 1, int decimalPlaces = 0) - : min(min), max(max), step(step), suffix(suffix), - divisor(divisor), decimalPlaces(decimalPlaces) {} -}; - -struct ValueThresholds { - std::uint32_t warning; - std::uint32_t danger; - ValueThresholds(std::uint32_t warning = 0, std::uint32_t danger = 0) - : warning(warning), danger(danger) {} -}; - -struct NamedValue { - std::string name; - std::uint32_t value; - std::string rightText; - - NamedValue(const std::string& name, std::uint32_t value, const std::string& rightText = "") - : name(name), value(value), rightText(rightText) {} -}; - -class ValueChoiceGui : public BaseMenuGui -{ -protected: - std::uint32_t selectedValue; - ValueRange range; - std::string categoryName; - ValueChoiceListener listener; - ValueThresholds thresholds; - bool enableThresholds; - std::map labels; - - std::vector namedValues; - bool showDefaultValue = true; - bool showDNO = false; - tsl::elm::ListItem* createValueListItem(std::uint32_t value, bool selected, int safety); - tsl::elm::ListItem* createNamedValueListItem(const NamedValue& namedValue, bool selected, int safety); - std::string formatValue(std::uint32_t value); - int getSafetyLevel(std::uint32_t value); - -public: - ValueChoiceGui(std::uint32_t selectedValue, - const ValueRange& range, - const std::string& categoryName, - ValueChoiceListener listener, - const ValueThresholds& thresholds = ValueThresholds(), - bool enableThresholds = false, - std::map labels = {}, - std::vector namedValues = {}, - bool showDefaultValue = true, - bool showDNO = false); - ~ValueChoiceGui(); - - void addNamedValue(const std::string& name, std::uint32_t value, const std::string& rightText = "") - { - namedValues.emplace_back(name, value, rightText); - } - - void addNamedValues(const std::vector& values) - { - namedValues.insert(namedValues.end(), values.begin(), values.end()); - } - - void clearNamedValues() - { - namedValues.clear(); - } - - void setShowDefaultValue(bool show) - { - showDefaultValue = show; - } - - void listUI() override; -}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/style.h b/Source/sys-clk/overlay/src/ui/style.h deleted file mode 100644 index 45692881..00000000 --- a/Source/sys-clk/overlay/src/ui/style.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include - -#define TEXT_COLOR tsl::gfx::Renderer::a(0xFFFF) -#define DESC_COLOR tsl::gfx::Renderer::a({ 0xC, 0xC, 0xC, 0xF }) -#define VALUE_COLOR tsl::gfx::Renderer::a({ 0x5, 0xC, 0xA, 0xF }) -#define SMALL_TEXT_SIZE 15 -#define LABEL_SPACING 7 -#define LABEL_FONT_SIZE 15 diff --git a/Source/sys-clk/sysmodule/.gitignore b/Source/sys-clk/sysmodule/.gitignore deleted file mode 100644 index 36a52c92..00000000 --- a/Source/sys-clk/sysmodule/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/out -/build diff --git a/Source/sys-clk/sysmodule/Makefile b/Source/sys-clk/sysmodule/Makefile deleted file mode 100644 index ae8bfa66..00000000 --- a/Source/sys-clk/sysmodule/Makefile +++ /dev/null @@ -1,164 +0,0 @@ -#--------------------------------------------------------------------------------- -.SUFFIXES: -#--------------------------------------------------------------------------------- - -ifeq ($(strip $(DEVKITPRO)),) -$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") -endif - -TOPDIR ?= $(CURDIR) -include $(DEVKITPRO)/libnx/switch_rules - -#--------------------------------------------------------------------------------- -# TARGET is the name of the output -# BUILD is the directory where object files & intermediate files will be placed -# SOURCES is a list of directories containing source code -# DATA is a list of directories containing data files -# INCLUDES is a list of directories containing header files -# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm". -#--------------------------------------------------------------------------------- -TARGET := horizon-oc -BUILD := build -OUTDIR := out -RESOURCES := res -SOURCES := src src/nx/ipc ../common/src -DATA := data -INCLUDES := ../common/include -EXEFS_SRC := exefs_src -LIBNAMES := minIni nxExt - -#--------------------------------------------------------------------------------- -# version control constants -#--------------------------------------------------------------------------------- -TARGET_VERSION := $(shell git describe --dirty --always --tags) - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -DEFINES := -DDISABLE_IPC -DTARGET="\"$(TARGET)\"" -DTARGET_VERSION="\"$(TARGET_VERSION)\"" - -ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE - -CFLAGS := -g -Wall -Os -ffunction-sections \ - $(ARCH) $(DEFINES) - -CFLAGS += $(INCLUDE) -D__SWITCH__ - -CXXFLAGS := $(CFLAGS) -fno-rtti -std=gnu++17 - -ASFLAGS := -g $(ARCH) -LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) - -LIBS := $(foreach lib,$(LIBNAMES),-l$(lib)) -lnx - -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(PORTLIBS) $(LIBNX) $(foreach lib,$(LIBNAMES),$(TOPDIR)/lib/$(lib)) - -#--------------------------------------------------------------------------------- -# no real need to edit anything past this point unless you need to add additional -# rules for different file extensions -#--------------------------------------------------------------------------------- -ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- - -export OUTPUT := $(CURDIR)/$(OUTDIR)/$(TARGET) -export TOPDIR := $(CURDIR) - -export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) - -export DEPSDIR := $(CURDIR)/$(BUILD) - -CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) -CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) -SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) -BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) - -#--------------------------------------------------------------------------------- -# use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- -ifeq ($(strip $(CPPFILES)),) -#--------------------------------------------------------------------------------- - export LD := $(CC) -#--------------------------------------------------------------------------------- -else -#--------------------------------------------------------------------------------- - export LD := $(CXX) -#--------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------- - -export OFILES := $(addsuffix .o,$(BINFILES)) \ - $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) - -export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ - -I$(CURDIR)/$(BUILD) - -export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) - -export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC) - -export APP_JSON := $(TOPDIR)/perms.json - -.PHONY: $(BUILD) clean clean-libs clean-build all libs - -#--------------------------------------------------------------------------------- -all: $(BUILD) - -libs: - @$(foreach lib,$(LIBNAMES),$(MAKE) --no-print-directory -C $(TOPDIR)/lib/$(lib) && ) true - -$(LIBNAMES): - @echo $@ - -$(BUILD): libs - @[ -d $@ ] || mkdir -p $@ - @[ -d $(OUTDIR) ] || mkdir -p $(OUTDIR) - @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean-libs: - @echo clean libs $(LIBNAMES) ... - @$(foreach lib,$(LIBNAMES),$(MAKE) -C $(TOPDIR)/lib/$(lib) clean && ) true - -clean-build: - @echo clean build ... - @rm -fr $(BUILD) $(TARGET).kip $(TARGET).nsp $(TARGET).npdm $(TARGET).nso $(TARGET).elf $(OUTDIR) - -clean: clean-libs clean-build - - -#--------------------------------------------------------------------------------- -else -.PHONY: all $(LIBFILES) - -LIBFILES := $(foreach lib,$(LIBNAMES),$(TOPDIR)/lib/$(lib)/lib/lib$(lib).a) -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- - -all: $(OUTPUT).nsp - -$(OUTPUT).nsp: $(OUTPUT).nso $(OUTPUT).npdm - -$(OUTPUT).elf: $(OFILES) $(LIBFILES) - -#--------------------------------------------------------------------------------- -# you need a rule like this for each extension you use as binary data -#--------------------------------------------------------------------------------- -%.bin.o : %.bin -#--------------------------------------------------------------------------------- - @echo $(notdir $<) - @$(bin2o) - --include $(DEPENDS) - -#--------------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/sysmodule/lib/minIni/.gitignore b/Source/sys-clk/sysmodule/lib/minIni/.gitignore deleted file mode 100644 index 0806f7bf..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# Editor files -*.swp -*~ - -# Objects -*.o -*.a -*.so - -# Lib -lib -release -debug \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/minIni/.gitrepo b/Source/sys-clk/sysmodule/lib/minIni/.gitrepo deleted file mode 100644 index 44cc0b36..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/.gitrepo +++ /dev/null @@ -1,12 +0,0 @@ -; DO NOT EDIT (unless you know what you are doing) -; -; This subdirectory is a git "subrepo", and this file is maintained by the -; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme -; -[subrepo] - remote = https://github.com/compuphase/minIni - branch = master - commit = 8ce144c3c287fa4e59f8ed4c405cd8b7e29f189b - parent = f32c0b1bca87a6d7e55fb341f8db9ef33b13819f - method = merge - cmdver = 0.4.0 diff --git a/Source/sys-clk/sysmodule/lib/minIni/LICENSE b/Source/sys-clk/sysmodule/lib/minIni/LICENSE deleted file mode 100644 index cbf8eb4c..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/LICENSE +++ /dev/null @@ -1,189 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - - EXCEPTION TO THE APACHE 2.0 LICENSE - - As a special exception to the Apache License 2.0 (and referring to the - definitions in Section 1 of this license), you may link, statically or - dynamically, the "Work" to other modules to produce an executable file - containing portions of the "Work", and distribute that executable file - in "Object" form under the terms of your choice, without any of the - additional requirements listed in Section 4 of the Apache License 2.0. - This exception applies only to redistributions in "Object" form (not - "Source" form) and only if no modifications have been made to the "Work". - - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - diff --git a/Source/sys-clk/sysmodule/lib/minIni/Makefile b/Source/sys-clk/sysmodule/lib/minIni/Makefile deleted file mode 100644 index b9565d07..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/Makefile +++ /dev/null @@ -1,133 +0,0 @@ -#--------------------------------------------------------------------------------- -.SUFFIXES: -#--------------------------------------------------------------------------------- - -ifeq ($(strip $(DEVKITPRO)),) -$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") -endif - -include $(DEVKITPRO)/libnx/switch_rules - -#--------------------------------------------------------------------------------- -# TARGET is the name of the output -# SOURCES is a list of directories containing source code -# DATA is a list of directories containing data files -# INCLUDES is a list of directories containing header files -#--------------------------------------------------------------------------------- -TARGET := $(notdir $(CURDIR)) -SOURCES := dev -DATA := data -INCLUDES := dev -SRC_H_FILES := - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIC -ftls-model=local-exec - -CFLAGS := -g -Wall -Werror \ - -ffunction-sections \ - -fdata-sections \ - $(ARCH) \ - $(BUILD_CFLAGS) - -CFLAGS += $(INCLUDE) - -CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions - -ASFLAGS := -g $(ARCH) - -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(PORTLIBS) $(LIBNX) - -#--------------------------------------------------------------------------------- -# no real need to edit anything past this point unless you need to add additional -# rules for different file extensions -#--------------------------------------------------------------------------------- -ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- - -export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) - -CFILES := minIni.c -CPPFILES := -SFILES := -BINFILES := - -#--------------------------------------------------------------------------------- -# use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- -ifeq ($(strip $(CPPFILES)),) -#--------------------------------------------------------------------------------- - export LD := $(CC) -#--------------------------------------------------------------------------------- -else -#--------------------------------------------------------------------------------- - export LD := $(CXX) -#--------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------- - -export OFILES_BIN := $(addsuffix .o,$(BINFILES)) -export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) -export OFILES := $(OFILES_BIN) $(OFILES_SRC) -export HFILES := $(addsuffix .h,$(subst .,_,$(BINFILES))) - -export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ - -I$(CURDIR)/$(BUILD) - -.PHONY: clean all lib/lib$(TARGET).a - -#--------------------------------------------------------------------------------- -all: lib/lib$(TARGET).a - -lib: - @[ -d $@ ] || mkdir -p $@ - -release: - @[ -d $@ ] || mkdir -p $@ - -debug: - @[ -d $@ ] || mkdir -p $@ - -lib/lib$(TARGET).a : lib release $(SOURCES) $(INCLUDES) - @$(MAKE) BUILD=release OUTPUT=$(CURDIR)/$@ \ - BUILD_CFLAGS="-DNDEBUG=1 -O2" \ - DEPSDIR=$(CURDIR)/release \ - --no-print-directory -C release \ - -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean: - @echo clean ... - @rm -fr release debug lib - -#--------------------------------------------------------------------------------- -else - -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- -$(OUTPUT) : $(OFILES) - -$(OFILES_SRC) : $(HFILES) - -#--------------------------------------------------------------------------------- -%_bin.h %.bin.o : %.bin -#--------------------------------------------------------------------------------- - @echo $(notdir $<) - @$(bin2o) - - --include $(DEPENDS) - -#--------------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/sysmodule/lib/minIni/NOTICE b/Source/sys-clk/sysmodule/lib/minIni/NOTICE deleted file mode 100644 index dbd0bba0..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/NOTICE +++ /dev/null @@ -1,12 +0,0 @@ -minIni is a programmer's library to read and write "INI" files in embedded -systems. The library takes little resources and can be configured for various -kinds of file I/O libraries. - -The method for portable INI file management in minIni is, in part based, on the -article "Multiplatform .INI Files" by Joseph J. Graf in the March 1994 issue of -Dr. Dobb's Journal. - -The C++ class in minIni.h was contributed by Steven Van Ingelgem. - -The option to compile minIni as a read-only library was contributed by Luca -Bassanello. diff --git a/Source/sys-clk/sysmodule/lib/minIni/README.md b/Source/sys-clk/sysmodule/lib/minIni/README.md deleted file mode 100644 index 9f30a019..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/README.md +++ /dev/null @@ -1,170 +0,0 @@ -# minIni -minIni is a portable and configurable library for reading and writing ".INI" files. At 830 lines of commented source -code -(version 1.2), minIni truly is a "mini" INI file parser, especially considering its features. - -The library does not require the file I/O functions from the standard C/C++ library, but instead lets you configure -the file I/O interface to use via macros. minIni uses limited stack space and does not use dynamic memory (malloc and -friends) at all. - -Some minor variations on standard INI files are supported too, notably minIni supports INI files that lack sections. - - -# Acknowledgement - -minIni is derived from an earlier INI file parser (which I wrote) for desktop systems. - -In turn, that earlier parser was a re-write of the code from the article "Multiplatform .INI Files" by Joseph J. Graf -in the March 1994 issue of Dr. Dobb's Journal. In other words, minIni has its roots in the work of Joseph Graf (even -though the code has been almost completely re-written). - - -# Features - -minIni is a programmer's library to read and write "INI" files in embedded systems. minIni takes little resources, -can be configured for various kinds of file I/O libraries and provides functionality for reading, writing and -deleting keys from an INI file. - -Although the main feature of minIni is that it is small and minimal, it has a few other features: - - * minIni supports reading keys that are outside a section, and it thereby supports configuration files that do not use sections (but that are otherwise compatible with INI files). - * You may use a colon to separate key and value; the colon is equivalent to the equal sign. That is, the strings "Name: Value" and "Name=Value" have the same meaning. - * The hash character ("#") is an alternative for the semicolon to start a comment. Trailing comments (i.e. behind a key/value pair on a line) are allowed. - * Leading and trailing white space around key names and values is ignored. - * When writing a value that contains a comment character (";" or "#"), that value will automatically be put between double quotes; when reading the value, these quotes are removed. When a double-quote itself appears in the setting, these characters are escaped. - * Section and key enumeration are supported. - * You can optionally set the line termination (for text files) that minIni will use. (This is a compile-time setting, not a run-time setting.) - * Since writing speed is much lower than reading speed in Flash memory (SD/MMC cards, USB memory sticks), minIni minimizes "file writes" at the expense of double "file reads". - * The memory footprint is deterministic. There is no dynamic memory allocation. - -## INI file reading paradigms - -There are two approaches to reading settings from an INI file. One way is to call a function, such as -GetProfileString() for every section and key that you need. This is especially convenient if there is a large -INI file, but you only need a few settings from that file at any time —especially if the INI file can also -change while your program runs. This is the approach that the Microsoft Windows API uses. - -The above procedure is quite inefficient, however, when you need to retrieve quite a few settings in a row from -the INI file —especially if the INI file is not cached in memory (which it isn't, in minIni). A different approach -to getting settings from an INI file is to call a "parsing" function and let that function call the application -back with the section and key names plus the associated data. XML parsing libraries often use this approach; see -for example the Expat library. - -minIni supports both approaches. For reading a single setting, use functions like ini_gets(). For the callback -approach, implement a callback and call ini_browse(). See the minIni manual for details. - - -# INI file syntax - -INI files are best known from Microsoft Windows, but they are also used with applications that run on other -platforms (although their file extension is sometimes ".cfg" instead of ".ini"). - -INI files have a simple syntax with name/value pairs in a plain text file. The name must be unique (per section) -and the value must fit on a single line. INI files are commonly separated into sections —in minIni, this is -optional. A section is a name between square brackets, like "[Network]" in the example below. - -``` -[Network] -hostname=My Computer -address=dhcp -dns = 192.168.1.1 -``` - -In the API and in this documentation, the "name" for a setting is denoted as the key for the setting. The key -and the value are separated by an equal sign ("="). minIni supports the colon (":") as an alternative to the -equal sign for the key/value delimiter. - -Leading a trailing spaces around values or key names are removed. If you need to include leading and/or trailing -spaces in a value, put the value between double quotes. The ini_gets() function (from the minIni library, see the -minIni manual) strips off the double quotes from the returned value. Function ini_puts() adds double quotes if -the value to write contains trailing white space (or special characters). - -minIni ignores spaces around the "=" or ":" delimiters, but it does not ignore spaces between the brackets in a -section name. In other words, it is best not to put spaces behind the opening bracket "[" or before the closing -bracket "]" of a section name. - -Comments in the INI must start with a semicolon (";") or a hash character ("#"), and run to the end of the line. -A comment can be a line of its own, or it may follow a key/value pair (the "#" character and trailing comments -are extensions of minIni). - -For more details on the format, please see http://en.wikipedia.org/wiki/INI_file. - - -# Adapting minIni to a file system - -The minIni library must be configured for a platform with the help of a so- called "glue file". This glue file -contains macros (and possibly functions) that map file reading and writing functions used by the minIni library -to those provided by the operating system. The glue file must be called "minGlue.h". - -To get you started, the minIni distribution comes with the following example glue files: - - * a glue file that maps to the standard C/C++ library (specifically the file I/O functions from the "stdio" package), - * a glue file for Microchip's "Memory Disk Drive File System Library" (see http://www.microchip.com/), - * a glue file for the FAT library provided with the CCS PIC compiler (see http://www.ccsinfo.com/) - * a glue file for the EFS Library (EFSL, http://www.efsl.be/), - * and a glue file for the FatFs and Petit-FatFs libraries (http://elm-chan.org/fsw/ff/00index_e.html). - -The minIni library does not rely on the availability of a standard C library, because embedded operating systems -may have limited support for file I/O. Even on full operating systems, separating the file I/O from the INI format -parsing carries advantages, because it allows you to cache the INI file and thereby enhance performance. - -The glue file must specify the type that identifies a file, whether it is a handle or a pointer. For the standard -C/C++ file I/O library, this would be: - -```C -#define INI_FILETYPE FILE* -``` - -If you are not using the standard C/C++ file I/O library, chances are that you need a different handle or -"structure" to identify the storage than the ubiquitous "FILE*" type. For example, the glue file for the FatFs -library uses the following declaration: - -```C -#define INI_FILETYPE FIL -``` - -The minIni functions declare variables of this INI_FILETYPE type and pass these variables to sub-functions -(including the glue interface functions) by reference. - -For "write support", another type that must be defined is for variables that hold the "current position" in a -file. For the standard C/C++ I/O library, this is "fpos_t". - -Another item that needs to be configured is the buffer size. The functions in the minIni library allocate this -buffer on the stack, so the buffer size is directly related to the stack usage. In addition, the buffer size -determines the maximum line length that is supported in the INI file and the maximum path name length for the -temporary file. For example, minGlue.h could contain the definition: - -```C -#define INI_BUFFERSIZE 512 -``` - -The above macro limits the line length of the INI files supported by minIni to 512 characters. - -The temporary file is only used when writing to INI files. The minIni routines copy/change the INI file to a -temporary file and then rename that temporary file to the original file. This approach uses the least amount of -memory. The path name of the temporary file is the same as the input file, but with the last character set to a -tilde ("~"). - -Below is an example of a glue file (this is the one that maps to the C/C++ "stdio" library). - -```C -#include - -#define INI_FILETYPE FILE* -#define ini_openread(filename,file) ((*(file) = fopen((filename),"r")) != NULL) -#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"w")) != NULL) -#define ini_close(file) (fclose(*(file)) == 0) -#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL) -#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0) -#define ini_rename(source,dest) (rename((source), (dest)) == 0) -#define ini_remove(filename) (remove(filename) == 0) - -#define INI_FILEPOS fpos_t -#define ini_tell(file,pos) (fgetpos(*(file), (pos)) == 0) -#define ini_seek(file,pos) (fsetpos(*(file), (pos)) == 0) -``` - -As you can see, a glue file is mostly a set of macros that wraps one function definition around another. - -The glue file may contain more settings, for support of rational numbers, to explicitly set the line termination -character(s), or to disable write support (for example). See the manual that comes with the archive for the details. diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-FatFs.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-FatFs.h deleted file mode 100644 index 51593a26..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-FatFs.h +++ /dev/null @@ -1,37 +0,0 @@ -/* Glue functions for the minIni library, based on the FatFs and Petit-FatFs - * libraries, see http://elm-chan.org/fsw/ff/00index_e.html - * - * By CompuPhase, 2008-2012 - * This "glue file" is in the public domain. It is distributed without - * warranties or conditions of any kind, either express or implied. - * - * (The FatFs and Petit-FatFs libraries are copyright by ChaN and licensed at - * its own terms.) - */ - -#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ - -/* You must set _USE_STRFUNC to 1 or 2 in the include file ff.h (or tff.h) - * to enable the "string functions" fgets() and fputs(). - */ -#include "ff.h" /* include tff.h for Tiny-FatFs */ - -#define INI_FILETYPE FIL -#define ini_openread(filename,file) (f_open((file), (filename), FA_READ+FA_OPEN_EXISTING) == FR_OK) -#define ini_openwrite(filename,file) (f_open((file), (filename), FA_WRITE+FA_CREATE_ALWAYS) == FR_OK) -#define ini_close(file) (f_close(file) == FR_OK) -#define ini_read(buffer,size,file) f_gets((buffer), (size),(file)) -#define ini_write(buffer,file) f_puts((buffer), (file)) -#define ini_remove(filename) (f_unlink(filename) == FR_OK) - -#define INI_FILEPOS DWORD -#define ini_tell(file,pos) (*(pos) = f_tell((file))) -#define ini_seek(file,pos) (f_lseek((file), *(pos)) == FR_OK) - -static int ini_rename(TCHAR *source, const TCHAR *dest) -{ - /* Function f_rename() does not allow drive letters in the destination file */ - char *drive = strchr(dest, ':'); - drive = (drive == NULL) ? dest : drive + 1; - return (f_rename(source, drive) == FR_OK); -} diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ccs.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ccs.h deleted file mode 100644 index 22a8c92b..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ccs.h +++ /dev/null @@ -1,64 +0,0 @@ -/* minIni glue functions for FAT library by CCS, Inc. (as provided with their - * PIC MCU compiler) - * - * By CompuPhase, 2011-2012 - * This "glue file" is in the public domain. It is distributed without - * warranties or conditions of any kind, either express or implied. - * - * (The FAT library is copyright (c) 2007 Custom Computer Services, and - * licensed at its own terms.) - */ - -#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ - -#ifndef FAT_PIC_C - #error FAT library must be included before this module -#endif -#define const /* keyword not supported by CCS */ - -#define INI_FILETYPE FILE -#define ini_openread(filename,file) (fatopen((filename), "r", (file)) == GOODEC) -#define ini_openwrite(filename,file) (fatopen((filename), "w", (file)) == GOODEC) -#define ini_close(file) (fatclose((file)) == 0) -#define ini_read(buffer,size,file) (fatgets((buffer), (size), (file)) != NULL) -#define ini_write(buffer,file) (fatputs((buffer), (file)) == GOODEC) -#define ini_remove(filename) (rm_file((filename)) == 0) - -#define INI_FILEPOS fatpos_t -#define ini_tell(file,pos) (fatgetpos((file), (pos)) == 0) -#define ini_seek(file,pos) (fatsetpos((file), (pos)) == 0) - -#ifndef INI_READONLY -/* CCS FAT library lacks a rename function, so instead we copy the file to the - * new name and delete the old file - */ -static int ini_rename(char *source, char *dest) -{ - FILE fr, fw; - int n; - - if (fatopen(source, "r", &fr) != GOODEC) - return 0; - if (rm_file(dest) != 0) - return 0; - if (fatopen(dest, "w", &fw) != GOODEC) - return 0; - - /* With some "insider knowledge", we can save some memory: the "source" - * parameter holds a filename that was built from the "dest" parameter. It - * was built in a local buffer with the size INI_BUFFERSIZE. We can reuse - * this buffer for copying the file. - */ - while (n=fatread(source, 1, INI_BUFFERSIZE, &fr)) - fatwrite(source, 1, n, &fw); - - fatclose(&fr); - fatclose(&fw); - - /* Now we need to delete the source file. However, we have garbled the buffer - * that held the filename of the source. So we need to build it again. - */ - ini_tempname(source, dest, INI_BUFFERSIZE); - return rm_file(source) == 0; -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-efsl.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-efsl.h deleted file mode 100644 index 5fe0fcf8..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-efsl.h +++ /dev/null @@ -1,63 +0,0 @@ -/* Glue functions for the minIni library, based on the EFS Library, see - * http://www.efsl.be/ - * - * By CompuPhase, 2008-2012 - * This "glue file" is in the public domain. It is distributed without - * warranties or conditions of any kind, either express or implied. - * - * (EFSL is copyright 2005-2006 Lennart Ysboodt and Michael De Nil, and - * licensed under the GPL with an exception clause for static linking.) - */ - -#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ -#define INI_LINETERM "\r\n" /* set line termination explicitly */ - -#include "efs.h" -extern EmbeddedFileSystem g_efs; - -#define INI_FILETYPE EmbeddedFile -#define ini_openread(filename,file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'r') == 0) -#define ini_openwrite(filename,file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'w') == 0) -#define ini_close(file) file_fclose(file) -#define ini_read(buffer,size,file) (file_read((file), (size), (buffer)) > 0) -#define ini_write(buffer,file) (file_write((file), strlen(buffer), (char*)(buffer)) > 0) -#define ini_remove(filename) rmfile(&g_efs.myFs, (char*)(filename)) - -#define INI_FILEPOS euint32 -#define ini_tell(file,pos) (*(pos) = (file)->FilePtr)) -#define ini_seek(file,pos) file_setpos((file), (*pos)) - -#if ! defined INI_READONLY -/* EFSL lacks a rename function, so instead we copy the file to the new name - * and delete the old file - */ -static int ini_rename(char *source, const char *dest) -{ - EmbeddedFile fr, fw; - int n; - - if (file_fopen(&fr, &g_efs.myFs, source, 'r') != 0) - return 0; - if (rmfile(&g_efs.myFs, (char*)dest) != 0) - return 0; - if (file_fopen(&fw, &g_efs.myFs, (char*)dest, 'w') != 0) - return 0; - - /* With some "insider knowledge", we can save some memory: the "source" - * parameter holds a filename that was built from the "dest" parameter. It - * was built in buffer and this buffer has the size INI_BUFFERSIZE. We can - * reuse this buffer for copying the file. - */ - while (n=file_read(&fr, INI_BUFFERSIZE, source)) - file_write(&fw, n, source); - - file_fclose(&fr); - file_fclose(&fw); - - /* Now we need to delete the source file. However, we have garbled the buffer - * that held the filename of the source. So we need to build it again. - */ - ini_tempname(source, dest, INI_BUFFERSIZE); - return rmfile(&g_efs.myFs, source) == 0; -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ffs.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ffs.h deleted file mode 100644 index bf874e41..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ffs.h +++ /dev/null @@ -1,26 +0,0 @@ -/* Glue functions for the minIni library, based on the "FAT Filing System" - * library by embedded-code.com - * - * By CompuPhase, 2008-2012 - * This "glue file" is in the public domain. It is distributed without - * warranties or conditions of any kind, either express or implied. - * - * (The "FAT Filing System" library itself is copyright embedded-code.com, and - * licensed at its own terms.) - */ - -#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ -#include - -#define INI_FILETYPE FFS_FILE* -#define ini_openread(filename,file) ((*(file) = ffs_fopen((filename),"r")) != NULL) -#define ini_openwrite(filename,file) ((*(file) = ffs_fopen((filename),"w")) != NULL) -#define ini_close(file) (ffs_fclose(*(file)) == 0) -#define ini_read(buffer,size,file) (ffs_fgets((buffer),(size),*(file)) != NULL) -#define ini_write(buffer,file) (ffs_fputs((buffer),*(file)) >= 0) -#define ini_rename(source,dest) (ffs_rename((source), (dest)) == 0) -#define ini_remove(filename) (ffs_remove(filename) == 0) - -#define INI_FILEPOS long -#define ini_tell(file,pos) (ffs_fgetpos(*(file), (pos)) == 0) -#define ini_seek(file,pos) (ffs_fsetpos(*(file), (pos)) == 0) diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-mdd.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-mdd.h deleted file mode 100644 index ec5e0be1..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-mdd.h +++ /dev/null @@ -1,58 +0,0 @@ -/* minIni glue functions for Microchip's "Memory Disk Drive" file system - * library, as presented in Microchip application note AN1045. - * - * By CompuPhase, 2011-2014 - * This "glue file" is in the public domain. It is distributed without - * warranties or conditions of any kind, either express or implied. - * - * (The "Microchip Memory Disk Drive File System" is copyright (c) Microchip - * Technology Incorporated, and licensed at its own terms.) - */ - -#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ - -#include "MDD File System\fsio.h" -#include - -#define INI_FILETYPE FSFILE* -#define ini_openread(filename,file) ((*(file) = FSfopen((filename),FS_READ)) != NULL) -#define ini_openwrite(filename,file) ((*(file) = FSfopen((filename),FS_WRITE)) != NULL) -#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),FS_READPLUS)) != NULL) -#define ini_close(file) (FSfclose(*(file)) == 0) -#define ini_write(buffer,file) (FSfwrite((buffer), 1, strlen(buffer), (*file)) > 0) -#define ini_remove(filename) (FSremove((filename)) == 0) - -#define INI_FILEPOS long int -#define ini_tell(file,pos) (*(pos) = FSftell(*(file))) -#define ini_seek(file,pos) (FSfseek(*(file), *(pos), SEEK_SET) == 0) - -/* Since the Memory Disk Drive file system library reads only blocks of files, - * the function to read a text line does so by "over-reading" a block of the - * of the maximum size and truncating it behind the end-of-line. - */ -static int ini_read(char *buffer, int size, INI_FILETYPE *file) -{ - size_t numread = size; - char *eol; - - if ((numread = FSfread(buffer, 1, size, *file)) == 0) - return 0; /* at EOF */ - if ((eol = strchr(buffer, '\n')) == NULL) - eol = strchr(buffer, '\r'); - if (eol != NULL) { - /* terminate the buffer */ - *++eol = '\0'; - /* "unread" the data that was read too much */ - FSfseek(*file, - (int)(numread - (size_t)(eol - buffer)), SEEK_CUR); - } /* if */ - return 1; -} - -#ifndef INI_READONLY -static int ini_rename(const char *source, const char *dest) -{ - FSFILE* ftmp = FSfopen((source), FS_READ); - FSrename((dest), ftmp); - return FSfclose(ftmp) == 0; -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-stdio.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-stdio.h deleted file mode 100644 index 67d24334..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-stdio.h +++ /dev/null @@ -1,31 +0,0 @@ -/* Glue functions for the minIni library, based on the C/C++ stdio library - * - * Or better said: this file contains macros that maps the function interface - * used by minIni to the standard C/C++ file I/O functions. - * - * By CompuPhase, 2008-2014 - * This "glue file" is in the public domain. It is distributed without - * warranties or conditions of any kind, either express or implied. - */ - -/* map required file I/O types and functions to the standard C library */ -#include - -#define INI_FILETYPE FILE* -#define ini_openread(filename,file) ((*(file) = fopen((filename),"rb")) != NULL) -#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"wb")) != NULL) -#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),"r+b")) != NULL) -#define ini_close(file) (fclose(*(file)) == 0) -#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL) -#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0) -#define ini_rename(source,dest) (rename((source), (dest)) == 0) -#define ini_remove(filename) (remove(filename) == 0) - -#define INI_FILEPOS long int -#define ini_tell(file,pos) (*(pos) = ftell(*(file))) -#define ini_seek(file,pos) (fseek(*(file), *(pos), SEEK_SET) == 0) - -/* for floating-point support, define additional types and functions */ -#define INI_REAL float -#define ini_ftoa(string,value) sprintf((string),"%f",(value)) -#define ini_atof(string) (INI_REAL)strtod((string),NULL) diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue.h deleted file mode 100644 index c3149627..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue.h +++ /dev/null @@ -1,35 +0,0 @@ -/* Glue functions for the minIni library, based on the C/C++ stdio library - * - * Or better said: this file contains macros that maps the function interface - * used by minIni to the standard C/C++ file I/O functions. - * - * By CompuPhase, 2008-2014 - * This "glue file" is in the public domain. It is distributed without - * warranties or conditions of any kind, either express or implied. - */ - -/* map required file I/O types and functions to the standard C library */ -#include - -#define INI_FILETYPE FILE* -#define ini_openread(filename,file) ((*(file) = fopen((filename),"rb")) != NULL) -#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"wb")) != NULL) -#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),"r+b")) != NULL) -#define ini_close(file) (fclose(*(file)) == 0) -#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL) -#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0) -#define ini_rename(source,dest) (rename((source), (dest)) == 0) -#define ini_remove(filename) (remove(filename) == 0) - -#define INI_FILEPOS long int -#define ini_tell(file,pos) (*(pos) = ftell(*(file))) -#define ini_seek(file,pos) (fseek(*(file), *(pos), SEEK_SET) == 0) - -/* for floating-point support, define additional types and functions */ -//#define INI_REAL float -//#define ini_ftoa(string,value) sprintf((string),"%f",(value)) -//#define ini_atof(string) (INI_REAL)strtod((string),NULL) - -#define INI_ANSIONLY -#define INI_LINETERM "\n" -#define PORTABLE_STRNICMP \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.c b/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.c deleted file mode 100644 index a0f75a27..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.c +++ /dev/null @@ -1,1009 +0,0 @@ -/* minIni - Multi-Platform INI file parser, suitable for embedded systems - * - * These routines are in part based on the article "Multiplatform .INI Files" - * by Joseph J. Graf in the March 1994 issue of Dr. Dobb's Journal. - * - * Copyright (c) CompuPhase, 2008-2017 - * - * 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 - * - * http://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. - * - * Version: $Id: minIni.c 53 2015-01-18 13:35:11Z thiadmer.riemersma@gmail.com $ - */ - -#if (defined _UNICODE || defined __UNICODE__ || defined UNICODE) && !defined INI_ANSIONLY -# if !defined UNICODE /* for Windows */ -# define UNICODE -# endif -# if !defined _UNICODE /* for C library */ -# define _UNICODE -# endif -#endif - -#define MININI_IMPLEMENTATION -#include "minIni.h" -#if defined NDEBUG - #define assert(e) -#else - #include -#endif - -#if !defined __T || defined INI_ANSIONLY - #include - #include - #include - #define TCHAR char - #define __T(s) s - #define _tcscat strcat - #define _tcschr strchr - #define _tcscmp strcmp - #define _tcscpy strcpy - #define _tcsicmp stricmp - #define _tcslen strlen - #define _tcsncmp strncmp - #define _tcsnicmp strnicmp - #define _tcsrchr strrchr - #define _tcstol strtol - #define _tcstod strtod - #define _totupper toupper - #define _stprintf sprintf - #define _tfgets fgets - #define _tfputs fputs - #define _tfopen fopen - #define _tremove remove - #define _trename rename -#endif - -#if defined __linux || defined __linux__ - #define __LINUX__ -#elif defined FREEBSD && !defined __FreeBSD__ - #define __FreeBSD__ -#elif defined(_MSC_VER) - #pragma warning(disable: 4996) /* for Microsoft Visual C/C++ */ -#endif -#if !defined strnicmp && !defined PORTABLE_STRNICMP - #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__ - #define strnicmp strncasecmp - #endif -#endif -#if !defined _totupper - #define _totupper toupper -#endif - -#if !defined INI_LINETERM - #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__ - #define INI_LINETERM __T("\n") - #else - #define INI_LINETERM __T("\r\n") - #endif -#endif -#if !defined INI_FILETYPE - #error Missing definition for INI_FILETYPE. -#endif - -#if !defined sizearray - #define sizearray(a) (sizeof(a) / sizeof((a)[0])) -#endif - -enum quote_option { - QUOTE_NONE, - QUOTE_ENQUOTE, - QUOTE_DEQUOTE, -}; - -#if defined PORTABLE_STRNICMP -int strnicmp(const TCHAR *s1, const TCHAR *s2, size_t n) -{ - while (n-- != 0 && (*s1 || *s2)) { - register int c1, c2; - c1 = *s1++; - if ('a' <= c1 && c1 <= 'z') - c1 += ('A' - 'a'); - c2 = *s2++; - if ('a' <= c2 && c2 <= 'z') - c2 += ('A' - 'a'); - if (c1 != c2) - return c1 - c2; - } /* while */ - return 0; -} -#endif /* PORTABLE_STRNICMP */ - -static TCHAR *skipleading(const TCHAR *str) -{ - assert(str != NULL); - while ('\0' < *str && *str <= ' ') - str++; - return (TCHAR *)str; -} - -static TCHAR *skiptrailing(const TCHAR *str, const TCHAR *base) -{ - assert(str != NULL); - assert(base != NULL); - while (str > base && '\0' < *(str-1) && *(str-1) <= ' ') - str--; - return (TCHAR *)str; -} - -static TCHAR *striptrailing(TCHAR *str) -{ - TCHAR *ptr = skiptrailing(_tcschr(str, '\0'), str); - assert(ptr != NULL); - *ptr = '\0'; - return str; -} - -static TCHAR *ini_strncpy(TCHAR *dest, const TCHAR *source, size_t maxlen, enum quote_option option) -{ - size_t d, s; - - assert(maxlen>0); - assert(source != NULL && dest != NULL); - assert((dest < source || (dest == source && option != QUOTE_ENQUOTE)) || dest > source + strlen(source)); - if (option == QUOTE_ENQUOTE && maxlen < 3) - option = QUOTE_NONE; /* cannot store two quotes and a terminating zero in less than 3 characters */ - - switch (option) { - case QUOTE_NONE: - for (d = 0; d < maxlen - 1 && source[d] != '\0'; d++) - dest[d] = source[d]; - assert(d < maxlen); - dest[d] = '\0'; - break; - case QUOTE_ENQUOTE: - d = 0; - dest[d++] = '"'; - for (s = 0; source[s] != '\0' && d < maxlen - 2; s++, d++) { - if (source[s] == '"') { - if (d >= maxlen - 3) - break; /* no space to store the escape character plus the one that follows it */ - dest[d++] = '\\'; - } /* if */ - dest[d] = source[s]; - } /* for */ - dest[d++] = '"'; - dest[d] = '\0'; - break; - case QUOTE_DEQUOTE: - for (d = s = 0; source[s] != '\0' && d < maxlen - 1; s++, d++) { - if ((source[s] == '"' || source[s] == '\\') && source[s + 1] == '"') - s++; - dest[d] = source[s]; - } /* for */ - dest[d] = '\0'; - break; - default: - assert(0); - } /* switch */ - - return dest; -} - -static TCHAR *cleanstring(TCHAR *string, enum quote_option *quotes) -{ - int isstring; - TCHAR *ep; - - assert(string != NULL); - assert(quotes != NULL); - - /* Remove a trailing comment */ - isstring = 0; - for (ep = string; *ep != '\0' && ((*ep != ';' && *ep != '#') || isstring); ep++) { - if (*ep == '"') { - if (*(ep + 1) == '"') - ep++; /* skip "" (both quotes) */ - else - isstring = !isstring; /* single quote, toggle isstring */ - } else if (*ep == '\\' && *(ep + 1) == '"') { - ep++; /* skip \" (both quotes */ - } /* if */ - } /* for */ - assert(ep != NULL && (*ep == '\0' || *ep == ';' || *ep == '#')); - *ep = '\0'; /* terminate at a comment */ - striptrailing(string); - /* Remove double quotes surrounding a value */ - *quotes = QUOTE_NONE; - if (*string == '"' && (ep = _tcschr(string, '\0')) != NULL && *(ep - 1) == '"') { - string++; - *--ep = '\0'; - *quotes = QUOTE_DEQUOTE; /* this is a string, so remove escaped characters */ - } /* if */ - return string; -} - -static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key, - int idxSection, int idxKey, TCHAR *Buffer, int BufferSize, - INI_FILEPOS *mark) -{ - TCHAR *sp, *ep; - int len, idx; - enum quote_option quotes; - TCHAR LocalBuffer[INI_BUFFERSIZE]; - - assert(fp != NULL); - /* Move through file 1 line at a time until a section is matched or EOF. If - * parameter Section is NULL, only look at keys above the first section. If - * idxSection is positive, copy the relevant section name. - */ - len = (Section != NULL) ? (int)_tcslen(Section) : 0; - if (len > 0 || idxSection >= 0) { - assert(idxSection >= 0 || Section != NULL); - idx = -1; - do { - if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp)) - return 0; - sp = skipleading(LocalBuffer); - ep = _tcsrchr(sp, ']'); - } while (*sp != '[' || ep == NULL || - (((int)(ep-sp-1) != len || Section == NULL || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection)); - if (idxSection >= 0) { - if (idx == idxSection) { - assert(ep != NULL); - assert(*ep == ']'); - *ep = '\0'; - ini_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE); - return 1; - } /* if */ - return 0; /* no more section found */ - } /* if */ - } /* if */ - - /* Now that the section has been found, find the entry. - * Stop searching upon leaving the section's area. - */ - assert(Key != NULL || idxKey >= 0); - len = (Key != NULL) ? (int)_tcslen(Key) : 0; - idx = -1; - do { - if (mark != NULL) - ini_tell(fp, mark); /* optionally keep the mark to the start of the line */ - if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[') - return 0; - sp = skipleading(LocalBuffer); - ep = _tcschr(sp, '='); /* Parse out the equal sign */ - if (ep == NULL) - ep = _tcschr(sp, ':'); - } while (*sp == ';' || *sp == '#' || ep == NULL - || ((len == 0 || (int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey)); - if (idxKey >= 0) { - if (idx == idxKey) { - assert(ep != NULL); - assert(*ep == '=' || *ep == ':'); - *ep = '\0'; - striptrailing(sp); - ini_strncpy(Buffer, sp, BufferSize, QUOTE_NONE); - return 1; - } /* if */ - return 0; /* no more key found (in this section) */ - } /* if */ - - /* Copy up to BufferSize chars to buffer */ - assert(ep != NULL); - assert(*ep == '=' || *ep == ':'); - sp = skipleading(ep + 1); - sp = cleanstring(sp, "es); /* Remove a trailing comment */ - ini_strncpy(Buffer, sp, BufferSize, quotes); - return 1; -} - -/** ini_gets() - * \param Section the name of the section to search for - * \param Key the name of the entry to find the value of - * \param DefValue default string in the event of a failed read - * \param Buffer a pointer to the buffer to copy into - * \param BufferSize the maximum number of characters to copy - * \param Filename the name and full path of the .ini file to read from - * - * \return the number of characters copied into the supplied buffer - */ -int ini_gets(const TCHAR *Section, const TCHAR *Key, const TCHAR *DefValue, - TCHAR *Buffer, int BufferSize, const TCHAR *Filename) -{ - INI_FILETYPE fp; - int ok = 0; - - if (Buffer == NULL || BufferSize <= 0 || Key == NULL) - return 0; - if (ini_openread(Filename, &fp)) { - ok = getkeystring(&fp, Section, Key, -1, -1, Buffer, BufferSize, NULL); - (void)ini_close(&fp); - } /* if */ - if (!ok) - ini_strncpy(Buffer, (DefValue != NULL) ? DefValue : __T(""), BufferSize, QUOTE_NONE); - return (int)_tcslen(Buffer); -} - -/** ini_getl() - * \param Section the name of the section to search for - * \param Key the name of the entry to find the value of - * \param DefValue the default value in the event of a failed read - * \param Filename the name of the .ini file to read from - * - * \return the value located at Key - */ -long ini_getl(const TCHAR *Section, const TCHAR *Key, long DefValue, const TCHAR *Filename) -{ - TCHAR LocalBuffer[64]; - int len = ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename); - return (len == 0) ? DefValue - : ((len >= 2 && _totupper((int)LocalBuffer[1]) == 'X') ? _tcstol(LocalBuffer, NULL, 16) - : _tcstol(LocalBuffer, NULL, 10)); -} - -#if defined INI_REAL -/** ini_getf() - * \param Section the name of the section to search for - * \param Key the name of the entry to find the value of - * \param DefValue the default value in the event of a failed read - * \param Filename the name of the .ini file to read from - * - * \return the value located at Key - */ -INI_REAL ini_getf(const TCHAR *Section, const TCHAR *Key, INI_REAL DefValue, const TCHAR *Filename) -{ - TCHAR LocalBuffer[64]; - int len = ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename); - return (len == 0) ? DefValue : ini_atof(LocalBuffer); -} -#endif - -/** ini_getbool() - * \param Section the name of the section to search for - * \param Key the name of the entry to find the value of - * \param DefValue default value in the event of a failed read; it should - * zero (0) or one (1). - * \param Filename the name and full path of the .ini file to read from - * - * A true boolean is found if one of the following is matched: - * - A string starting with 'y' or 'Y' - * - A string starting with 't' or 'T' - * - A string starting with '1' - * - * A false boolean is found if one of the following is matched: - * - A string starting with 'n' or 'N' - * - A string starting with 'f' or 'F' - * - A string starting with '0' - * - * \return the true/false flag as interpreted at Key - */ -int ini_getbool(const TCHAR *Section, const TCHAR *Key, int DefValue, const TCHAR *Filename) -{ - TCHAR LocalBuffer[2] = __T(""); - int ret; - - ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename); - LocalBuffer[0] = (TCHAR)_totupper((int)LocalBuffer[0]); - if (LocalBuffer[0] == 'Y' || LocalBuffer[0] == '1' || LocalBuffer[0] == 'T') - ret = 1; - else if (LocalBuffer[0] == 'N' || LocalBuffer[0] == '0' || LocalBuffer[0] == 'F') - ret = 0; - else - ret = DefValue; - - return(ret); -} - -/** ini_getsection() - * \param idx the zero-based sequence number of the section to return - * \param Buffer a pointer to the buffer to copy into - * \param BufferSize the maximum number of characters to copy - * \param Filename the name and full path of the .ini file to read from - * - * \return the number of characters copied into the supplied buffer - */ -int ini_getsection(int idx, TCHAR *Buffer, int BufferSize, const TCHAR *Filename) -{ - INI_FILETYPE fp; - int ok = 0; - - if (Buffer == NULL || BufferSize <= 0 || idx < 0) - return 0; - if (ini_openread(Filename, &fp)) { - ok = getkeystring(&fp, NULL, NULL, idx, -1, Buffer, BufferSize, NULL); - (void)ini_close(&fp); - } /* if */ - if (!ok) - *Buffer = '\0'; - return (int)_tcslen(Buffer); -} - -/** ini_getkey() - * \param Section the name of the section to browse through, or NULL to - * browse through the keys outside any section - * \param idx the zero-based sequence number of the key to return - * \param Buffer a pointer to the buffer to copy into - * \param BufferSize the maximum number of characters to copy - * \param Filename the name and full path of the .ini file to read from - * - * \return the number of characters copied into the supplied buffer - */ -int ini_getkey(const TCHAR *Section, int idx, TCHAR *Buffer, int BufferSize, const TCHAR *Filename) -{ - INI_FILETYPE fp; - int ok = 0; - - if (Buffer == NULL || BufferSize <= 0 || idx < 0) - return 0; - if (ini_openread(Filename, &fp)) { - ok = getkeystring(&fp, Section, NULL, -1, idx, Buffer, BufferSize, NULL); - (void)ini_close(&fp); - } /* if */ - if (!ok) - *Buffer = '\0'; - return (int)_tcslen(Buffer); -} - - -#if !defined INI_NOBROWSE -/** ini_browse() - * \param Callback a pointer to a function that will be called for every - * setting in the INI file. - * \param UserData arbitrary data, which the function passes on the - * \c Callback function - * \param Filename the name and full path of the .ini file to read from - * - * \return 1 on success, 0 on failure (INI file not found) - * - * \note The \c Callback function must return 1 to continue - * browsing through the INI file, or 0 to stop. Even when the - * callback stops the browsing, this function will return 1 - * (for success). - */ -int ini_browse(INI_CALLBACK Callback, void *UserData, const TCHAR *Filename) -{ - TCHAR LocalBuffer[INI_BUFFERSIZE]; - int lenSec, lenKey; - enum quote_option quotes; - INI_FILETYPE fp; - - if (Callback == NULL) - return 0; - if (!ini_openread(Filename, &fp)) - return 0; - - LocalBuffer[0] = '\0'; /* copy an empty section in the buffer */ - lenSec = (int)_tcslen(LocalBuffer) + 1; - for ( ;; ) { - TCHAR *sp, *ep; - if (!ini_read(LocalBuffer + lenSec, INI_BUFFERSIZE - lenSec, &fp)) - break; - sp = skipleading(LocalBuffer + lenSec); - /* ignore empty strings and comments */ - if (*sp == '\0' || *sp == ';' || *sp == '#') - continue; - /* see whether we reached a new section */ - ep = _tcsrchr(sp, ']'); - if (*sp == '[' && ep != NULL) { - *ep = '\0'; - ini_strncpy(LocalBuffer, sp + 1, INI_BUFFERSIZE, QUOTE_NONE); - lenSec = (int)_tcslen(LocalBuffer) + 1; - continue; - } /* if */ - /* not a new section, test for a key/value pair */ - ep = _tcschr(sp, '='); /* test for the equal sign or colon */ - if (ep == NULL) - ep = _tcschr(sp, ':'); - if (ep == NULL) - continue; /* invalid line, ignore */ - *ep++ = '\0'; /* split the key from the value */ - striptrailing(sp); - ini_strncpy(LocalBuffer + lenSec, sp, INI_BUFFERSIZE - lenSec, QUOTE_NONE); - lenKey = (int)_tcslen(LocalBuffer + lenSec) + 1; - /* clean up the value */ - sp = skipleading(ep); - sp = cleanstring(sp, "es); /* Remove a trailing comment */ - ini_strncpy(LocalBuffer + lenSec + lenKey, sp, INI_BUFFERSIZE - lenSec - lenKey, quotes); - /* call the callback */ - if (!Callback(LocalBuffer, LocalBuffer + lenSec, LocalBuffer + lenSec + lenKey, UserData)) - break; - } /* for */ - - (void)ini_close(&fp); - return 1; -} -#endif /* INI_NOBROWSE */ - -#if ! defined INI_READONLY -static void ini_tempname(TCHAR *dest, const TCHAR *source, int maxlength) -{ - TCHAR *p; - - ini_strncpy(dest, source, maxlength, QUOTE_NONE); - p = _tcsrchr(dest, '\0'); - assert(p != NULL); - *(p - 1) = '~'; -} - -static enum quote_option check_enquote(const TCHAR *Value) -{ - const TCHAR *p; - - /* run through the value, if it has trailing spaces, or '"', ';' or '#' - * characters, enquote it - */ - assert(Value != NULL); - for (p = Value; *p != '\0' && *p != '"' && *p != ';' && *p != '#'; p++) - /* nothing */; - return (*p != '\0' || (p > Value && *(p - 1) == ' ')) ? QUOTE_ENQUOTE : QUOTE_NONE; -} - -static void writesection(TCHAR *LocalBuffer, const TCHAR *Section, INI_FILETYPE *fp) -{ - if (Section != NULL && _tcslen(Section) > 0) { - TCHAR *p; - LocalBuffer[0] = '['; - ini_strncpy(LocalBuffer + 1, Section, INI_BUFFERSIZE - 4, QUOTE_NONE); /* -1 for '[', -1 for ']', -2 for '\r\n' */ - p = _tcsrchr(LocalBuffer, '\0'); - assert(p != NULL); - *p++ = ']'; - _tcscpy(p, INI_LINETERM); /* copy line terminator (typically "\n") */ - if (fp != NULL) - (void)ini_write(LocalBuffer, fp); - } /* if */ -} - -static void writekey(TCHAR *LocalBuffer, const TCHAR *Key, const TCHAR *Value, INI_FILETYPE *fp) -{ - TCHAR *p; - enum quote_option option = check_enquote(Value); - ini_strncpy(LocalBuffer, Key, INI_BUFFERSIZE - 3, QUOTE_NONE); /* -1 for '=', -2 for '\r\n' */ - p = _tcsrchr(LocalBuffer, '\0'); - assert(p != NULL); - *p++ = '='; - ini_strncpy(p, Value, INI_BUFFERSIZE - (p - LocalBuffer) - 2, option); /* -2 for '\r\n' */ - p = _tcsrchr(LocalBuffer, '\0'); - assert(p != NULL); - _tcscpy(p, INI_LINETERM); /* copy line terminator (typically "\n") */ - if (fp != NULL) - (void)ini_write(LocalBuffer, fp); -} - -static int cache_accum(const TCHAR *string, int *size, int max) -{ - int len = (int)_tcslen(string); - if (*size + len >= max) - return 0; - *size += len; - return 1; -} - -static int cache_flush(TCHAR *buffer, int *size, - INI_FILETYPE *rfp, INI_FILETYPE *wfp, INI_FILEPOS *mark) -{ - int terminator_len = (int)_tcslen(INI_LINETERM); - int pos = 0; - - (void)ini_seek(rfp, mark); - assert(buffer != NULL); - buffer[0] = '\0'; - assert(size != NULL); - assert(*size <= INI_BUFFERSIZE); - while (pos < *size) { - (void)ini_read(buffer + pos, INI_BUFFERSIZE - pos, rfp); - while (pos < *size && buffer[pos] != '\0') - pos++; /* cannot use _tcslen() because buffer may not be zero-terminated */ - } /* while */ - if (buffer[0] != '\0') { - assert(pos > 0 && pos <= INI_BUFFERSIZE); - if (pos == INI_BUFFERSIZE) - pos--; - buffer[pos] = '\0'; /* force zero-termination (may be left unterminated in the above while loop) */ - (void)ini_write(buffer, wfp); - } - ini_tell(rfp, mark); /* update mark */ - *size = 0; - /* return whether the buffer ended with a line termination */ - return (pos > terminator_len) && (_tcscmp(buffer + pos - terminator_len, INI_LINETERM) == 0); -} - -static int close_rename(INI_FILETYPE *rfp, INI_FILETYPE *wfp, const TCHAR *filename, TCHAR *buffer) -{ - (void)ini_close(rfp); - (void)ini_close(wfp); - (void)ini_remove(filename); - (void)ini_tempname(buffer, filename, INI_BUFFERSIZE); - (void)ini_rename(buffer, filename); - return 1; -} - -/** ini_puts() - * \param Section the name of the section to write the string in - * \param Key the name of the entry to write, or NULL to erase all keys in the section - * \param Value a pointer to the buffer the string, or NULL to erase the key - * \param Filename the name and full path of the .ini file to write to - * - * \return 1 if successful, otherwise 0 - */ -int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename) -{ - INI_FILETYPE rfp; - INI_FILETYPE wfp; - INI_FILEPOS mark; - INI_FILEPOS head, tail; - TCHAR *sp, *ep; - TCHAR LocalBuffer[INI_BUFFERSIZE]; - int len, match, flag, cachelen; - - assert(Filename != NULL); - if (!ini_openread(Filename, &rfp)) { - /* If the .ini file doesn't exist, make a new file */ - if (Key != NULL && Value != NULL) { - if (!ini_openwrite(Filename, &wfp)) - return 0; - writesection(LocalBuffer, Section, &wfp); - writekey(LocalBuffer, Key, Value, &wfp); - (void)ini_close(&wfp); - } /* if */ - return 1; - } /* if */ - - /* If parameters Key and Value are valid (so this is not an "erase" request) - * and the setting already exists, there are two short-cuts to avoid rewriting - * the INI file. - */ - if (Key != NULL && Value != NULL) { - ini_tell(&rfp, &mark); - match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer), &head); - if (match) { - /* if the current setting is identical to the one to write, there is - * nothing to do. - */ - if (_tcscmp(LocalBuffer,Value) == 0) { - (void)ini_close(&rfp); - return 1; - } /* if */ - /* if the new setting has the same length as the current setting, and the - * glue file permits file read/write access, we can modify in place. - */ - #if defined ini_openrewrite - /* we already have the start of the (raw) line, get the end too */ - ini_tell(&rfp, &tail); - /* create new buffer (without writing it to file) */ - writekey(LocalBuffer, Key, Value, NULL); - if (_tcslen(LocalBuffer) == (size_t)(tail - head)) { - /* length matches, close the file & re-open for read/write, then - * write at the correct position - */ - (void)ini_close(&rfp); - if (!ini_openrewrite(Filename, &wfp)) - return 0; - (void)ini_seek(&wfp, &head); - (void)ini_write(LocalBuffer, &wfp); - (void)ini_close(&wfp); - return 1; - } /* if */ - #endif - } /* if */ - /* key not found, or different value & length -> proceed (but rewind the - * input file first) - */ - (void)ini_seek(&rfp, &mark); - } /* if */ - - /* Get a temporary file name to copy to. Use the existing name, but with - * the last character set to a '~'. - */ - ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE); - if (!ini_openwrite(LocalBuffer, &wfp)) { - (void)ini_close(&rfp); - return 0; - } /* if */ - (void)ini_tell(&rfp, &mark); - cachelen = 0; - - /* Move through the file one line at a time until a section is - * matched or until EOF. Copy to temp file as it is read. - */ - len = (Section != NULL) ? (int)_tcslen(Section) : 0; - if (len > 0) { - do { - if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { - /* Failed to find section, so add one to the end */ - flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - if (Key!=NULL && Value!=NULL) { - if (!flag) - (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */ - writesection(LocalBuffer, Section, &wfp); - writekey(LocalBuffer, Key, Value, &wfp); - } /* if */ - return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ - } /* if */ - /* Copy the line from source to dest, but not if this is the section that - * we are looking for and this section must be removed - */ - sp = skipleading(LocalBuffer); - ep = _tcsrchr(sp, ']'); - match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0); - if (!match || Key != NULL) { - if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); - } /* if */ - } /* if */ - } while (!match); - } /* if */ - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - /* when deleting a section, the section head that was just found has not been - * copied to the output file, but because this line was not "accumulated" in - * the cache, the position in the input file was reset to the point just - * before the section; this must now be skipped (again) - */ - if (Key == NULL) { - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - (void)ini_tell(&rfp, &mark); - } /* if */ - - /* Now that the section has been found, find the entry. Stop searching - * upon leaving the section's area. Copy the file as it is read - * and create an entry if one is not found. - */ - len = (Key != NULL) ? (int)_tcslen(Key) : 0; - for( ;; ) { - if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { - /* EOF without an entry so make one */ - flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - if (Key!=NULL && Value!=NULL) { - if (!flag) - (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */ - writekey(LocalBuffer, Key, Value, &wfp); - } /* if */ - return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ - } /* if */ - sp = skipleading(LocalBuffer); - ep = _tcschr(sp, '='); /* Parse out the equal sign */ - if (ep == NULL) - ep = _tcschr(sp, ':'); - match = (ep != NULL && len > 0 && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0); - if ((Key != NULL && match) || *sp == '[') - break; /* found the key, or found a new section */ - /* copy other keys in the section */ - if (Key == NULL) { - (void)ini_tell(&rfp, &mark); /* we are deleting the entire section, so update the read position */ - } else { - if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); - } /* if */ - } /* if */ - } /* for */ - /* the key was found, or we just dropped on the next section (meaning that it - * wasn't found); in both cases we need to write the key, but in the latter - * case, we also need to write the line starting the new section after writing - * the key - */ - flag = (*sp == '['); - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - if (Key != NULL && Value != NULL) - writekey(LocalBuffer, Key, Value, &wfp); - /* cache_flush() reset the "read pointer" to the start of the line with the - * previous key or the new section; read it again (because writekey() destroyed - * the buffer) - */ - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - if (flag) { - /* the new section heading needs to be copied to the output file */ - cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); - } else { - /* forget the old key line */ - (void)ini_tell(&rfp, &mark); - } /* if */ - /* Copy the rest of the INI file */ - while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { - if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); - } /* if */ - } /* while */ - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ -} - -/* Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C" book. */ -#define ABS(v) ((v) < 0 ? -(v) : (v)) - -static void strreverse(TCHAR *str) -{ - int i, j; - for (i = 0, j = (int)_tcslen(str) - 1; i < j; i++, j--) { - TCHAR t = str[i]; - str[i] = str[j]; - str[j] = t; - } /* for */ -} - -static void long2str(long value, TCHAR *str) -{ - int i = 0; - long sign = value; - - /* generate digits in reverse order */ - do { - int n = (int)(value % 10); /* get next lowest digit */ - str[i++] = (TCHAR)(ABS(n) + '0'); /* handle case of negative digit */ - } while (value /= 10); /* delete the lowest digit */ - if (sign < 0) - str[i++] = '-'; - str[i] = '\0'; - - strreverse(str); -} - -/** ini_putl() - * \param Section the name of the section to write the value in - * \param Key the name of the entry to write - * \param Value the value to write - * \param Filename the name and full path of the .ini file to write to - * - * \return 1 if successful, otherwise 0 - */ -int ini_putl(const TCHAR *Section, const TCHAR *Key, long Value, const TCHAR *Filename) -{ - TCHAR LocalBuffer[32]; - long2str(Value, LocalBuffer); - return ini_puts(Section, Key, LocalBuffer, Filename); -} - -#if defined INI_REAL -/** ini_putf() - * \param Section the name of the section to write the value in - * \param Key the name of the entry to write - * \param Value the value to write - * \param Filename the name and full path of the .ini file to write to - * - * \return 1 if successful, otherwise 0 - */ -int ini_putf(const TCHAR *Section, const TCHAR *Key, INI_REAL Value, const TCHAR *Filename) -{ - TCHAR LocalBuffer[64]; - ini_ftoa(LocalBuffer, Value); - return ini_puts(Section, Key, LocalBuffer, Filename); -} -#endif /* INI_REAL */ - -static void putsection(TCHAR *LocalBuffer, const TCHAR *Section, const TCHAR **Keys, const TCHAR **Values, INI_FILETYPE *fp) { - if(Keys && Values && *Keys && *Values) { - writesection(LocalBuffer, Section, fp); - while(*Keys && *Values) { - writekey(LocalBuffer, *Keys, *Values, fp); - Keys++; - Values++; - } - (void)ini_write(INI_LINETERM, fp); /* force a new line behind the last line of the section */ - } -} - -int ini_putsection(const TCHAR *Section, const TCHAR **Keys, const TCHAR **Values, const TCHAR *Filename) -{ - INI_FILETYPE rfp; - INI_FILETYPE wfp; - INI_FILEPOS mark; - TCHAR *sp = NULL; - TCHAR *ep; - TCHAR LocalBuffer[INI_BUFFERSIZE]; - int len, match, flag, cachelen; - - assert(Filename != NULL); - if (!ini_openread(Filename, &rfp)) { - /* If the .ini file doesn't exist, make a new file */ - if (!ini_openwrite(Filename, &wfp)) - return 0; - putsection(LocalBuffer, Section, Keys, Values, &wfp); - (void)ini_close(&wfp); - return 1; - } /* if */ - - /* Get a temporary file name to copy to. Use the existing name, but with - * the last character set to a '~'. - */ - ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE); - if (!ini_openwrite(LocalBuffer, &wfp)) { - (void)ini_close(&rfp); - return 0; - } /* if */ - (void)ini_tell(&rfp, &mark); - cachelen = 0; - - /* Move through the file one line at a time until a section is - * matched or until EOF. Copy to temp file as it is read. - */ - len = (Section != NULL) ? (int)_tcslen(Section) : 0; - if (len > 0) { - do { - if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { - /* Failed to find section, so add one to the end */ - flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - if (!flag) - (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */ - - putsection(LocalBuffer, Section, Keys, Values, &wfp); - - return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ - } /* if */ - /* Copy the line from source to dest, but not if this is the section that - * we are looking for - */ - sp = skipleading(LocalBuffer); - ep = _tcsrchr(sp, ']'); - match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0); - if (!match) { - if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); - } /* if */ - } /* if */ - } while (!match); - } /* if */ - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - /* when deleting a section, the section head that was just found has not been - * copied to the output file, but because this line was not "accumulated" in - * the cache, the position in the input file was reset to the point just - * before the section; this must now be skipped (again) - */ - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - (void)ini_tell(&rfp, &mark); - - /* Now that the section has been found, find the entry. Stop searching - * upon leaving the section's area. Copy the file as it is read - * and create an entry if one is not found. - */ - len = 0; - for( ;; ) { - if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { - /* EOF without an entry */ - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - (void)ini_tell(&rfp, &mark); /* we are deleting the entire section, so update the read position */ - break; - } /* if */ - sp = skipleading(LocalBuffer); - if (*sp == '[') - break; /* found a new section */ - /* copy other keys in the section */ - (void)ini_tell(&rfp, &mark); /* we are deleting the entire section, so update the read position */ - } /* for */ - /* we just dropped on the next section - * we also need to write the line starting the new section after writing - */ - flag = (sp && *sp == '['); - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - putsection(LocalBuffer, Section, Keys, Values, &wfp); - - /* cache_flush() reset the "read pointer" to the start of the line with the - * previous key or the new section; read it again (because writekey() destroyed - * the buffer) - */ - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - if (flag) { - /* the new section heading needs to be copied to the output file */ - cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); - } else { - /* forget the old key line */ - (void)ini_tell(&rfp, &mark); - } /* if */ - /* Copy the rest of the INI file */ - while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { - if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); - cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); - } /* if */ - } /* while */ - cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); - return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ -} - -#endif /* !INI_READONLY */ diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.h deleted file mode 100644 index 73e33c01..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.h +++ /dev/null @@ -1,68 +0,0 @@ -/* minIni - Multi-Platform INI file parser, suitable for embedded systems - * - * Copyright (c) CompuPhase, 2008-2017 - * - * 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 - * - * http://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. - * - * Version: $Id: minIni.h 53 2015-01-18 13:35:11Z thiadmer.riemersma@gmail.com $ - */ -#ifndef MININI_H -#define MININI_H - -#include "minGlue.h" - -#if (defined _UNICODE || defined __UNICODE__ || defined UNICODE) && !defined INI_ANSIONLY - #include - #define mTCHAR TCHAR -#else - /* force TCHAR to be "char", but only for minIni */ - #define mTCHAR char -#endif - -#if !defined INI_BUFFERSIZE - #define INI_BUFFERSIZE 512 -#endif - -#if defined __cplusplus - extern "C" { -#endif - -int ini_getbool(const mTCHAR *Section, const mTCHAR *Key, int DefValue, const mTCHAR *Filename); -long ini_getl(const mTCHAR *Section, const mTCHAR *Key, long DefValue, const mTCHAR *Filename); -int ini_gets(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *DefValue, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename); -int ini_getsection(int idx, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename); -int ini_getkey(const mTCHAR *Section, int idx, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename); - -#if defined INI_REAL -INI_REAL ini_getf(const mTCHAR *Section, const mTCHAR *Key, INI_REAL DefValue, const mTCHAR *Filename); -#endif - -#if !defined INI_READONLY -int ini_putl(const mTCHAR *Section, const mTCHAR *Key, long Value, const mTCHAR *Filename); -int ini_puts(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *Value, const mTCHAR *Filename); -int ini_putsection(const mTCHAR *Section, const mTCHAR **Keys, const mTCHAR **Values, const mTCHAR *Filename); -#if defined INI_REAL -int ini_putf(const mTCHAR *Section, const mTCHAR *Key, INI_REAL Value, const mTCHAR *Filename); -#endif -#endif /* INI_READONLY */ - -#if !defined INI_NOBROWSE -typedef int (*INI_CALLBACK)(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *Value, void *UserData); -int ini_browse(INI_CALLBACK Callback, void *UserData, const mTCHAR *Filename); -#endif /* INI_NOBROWSE */ - -#if defined __cplusplus - } -#endif - -#endif /* MININI_H */ diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/test.c b/Source/sys-clk/sysmodule/lib/minIni/dev/test.c deleted file mode 100644 index 80508cd7..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/test.c +++ /dev/null @@ -1,117 +0,0 @@ -/* Simple test program - * - * gcc -o test test.c minIni.c - */ -#include -#include -#include -#include "minIni.h" - -#define sizearray(a) (sizeof(a) / sizeof((a)[0])) - -const char inifile[] = "test.ini"; -const char inifile2[] = "testplain.ini"; - -int Callback(const char *section, const char *key, const char *value, void *userdata) -{ - (void)userdata; /* this parameter is not used in this example */ - printf(" [%s]\t%s=%s\n", section, key, value); - return 1; -} - -int main(void) -{ - char str[100]; - long n; - int s, k; - char section[50]; - - /* string reading */ - n = ini_gets("first", "string", "dummy", str, sizearray(str), inifile); - assert(n==4 && strcmp(str,"noot")==0); - n = ini_gets("second", "string", "dummy", str, sizearray(str), inifile); - assert(n==4 && strcmp(str,"mies")==0); - n = ini_gets("first", "undefined", "dummy", str, sizearray(str), inifile); - assert(n==5 && strcmp(str,"dummy")==0); - /* ----- */ - n = ini_gets("", "string", "dummy", str, sizearray(str), inifile2); - assert(n==4 && strcmp(str,"noot")==0); - n = ini_gets(NULL, "string", "dummy", str, sizearray(str), inifile2); - assert(n==4 && strcmp(str,"noot")==0); - /* ----- */ - printf("1. String reading tests passed\n"); - - /* value reading */ - n = ini_getl("first", "val", -1, inifile); - assert(n==1); - n = ini_getl("second", "val", -1, inifile); - assert(n==2); - n = ini_getl("first", "undefined", -1, inifile); - assert(n==-1); - /* ----- */ - n = ini_getl(NULL, "val", -1, inifile2); - assert(n==1); - /* ----- */ - printf("2. Value reading tests passed\n"); - - /* string writing */ - n = ini_puts("first", "alt", "flagged as \"correct\"", inifile); - assert(n==1); - n = ini_gets("first", "alt", "dummy", str, sizearray(str), inifile); - assert(n==20 && strcmp(str,"flagged as \"correct\"")==0); - /* ----- */ - n = ini_puts("second", "alt", "correct", inifile); - assert(n==1); - n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile); - assert(n==7 && strcmp(str,"correct")==0); - /* ----- */ - n = ini_puts("third", "test", "correct", inifile); - assert(n==1); - n = ini_gets("third", "test", "dummy", str, sizearray(str), inifile); - assert(n==7 && strcmp(str,"correct")==0); - /* ----- */ - n = ini_puts("second", "alt", "overwrite", inifile); - assert(n==1); - n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile); - assert(n==9 && strcmp(str,"overwrite")==0); - /* ----- */ - n = ini_puts("second", "alt", "123456789", inifile); - assert(n==1); - n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile); - assert(n==9 && strcmp(str,"123456789")==0); - /* ----- */ - n = ini_puts(NULL, "alt", "correct", inifile2); - assert(n==1); - n = ini_gets(NULL, "alt", "dummy", str, sizearray(str), inifile2); - assert(n==7 && strcmp(str,"correct")==0); - /* ----- */ - printf("3. String writing tests passed\n"); - - /* section/key enumeration */ - printf("4. Section/key enumeration, file structure follows\n"); - for (s = 0; ini_getsection(s, section, sizearray(section), inifile) > 0; s++) { - printf(" [%s]\n", section); - for (k = 0; ini_getkey(section, k, str, sizearray(str), inifile) > 0; k++) { - printf("\t%s\n", str); - } /* for */ - } /* for */ - - /* browsing through the file */ - printf("5. browse through all settings, file field list follows\n"); - ini_browse(Callback, NULL, inifile); - - /* string deletion */ - n = ini_puts("first", "alt", NULL, inifile); - assert(n==1); - n = ini_puts("second", "alt", NULL, inifile); - assert(n==1); - n = ini_puts("third", NULL, NULL, inifile); - assert(n==1); - /* ----- */ - n = ini_puts(NULL, "alt", NULL, inifile2); - assert(n==1); - printf("6. String deletion tests passed\n"); - - return 0; -} - diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/test.ini b/Source/sys-clk/sysmodule/lib/minIni/dev/test.ini deleted file mode 100644 index 565aef78..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/test.ini +++ /dev/null @@ -1,8 +0,0 @@ -[First] -String=noot # trailing commment -Val=1 - -[Second] -Val = 2 -#comment=3 -String = mies diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/test2.cc b/Source/sys-clk/sysmodule/lib/minIni/dev/test2.cc deleted file mode 100644 index 4e19b319..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/test2.cc +++ /dev/null @@ -1,80 +0,0 @@ -/* - gcc -o minIni.o -c minIni.c - g++ -o test2.o -c test2.cc - g++ -o test2 test2.o minIni.o - ./test2 -*/ - - -#include -#include -#include -using namespace std ; - -#include "minIni.h" - -int main(void) -{ - minIni ini("test.ini"); - string s; - - /* string reading */ - s = ini.gets( "first", "string" , "aap" ); - assert(s == "noot"); - s = ini.gets( "second", "string" , "aap" ); - assert(s == "mies"); - s = ini.gets( "first", "dummy" , "aap" ); - assert(s == "aap"); - cout << "1. String reading tests passed" << endl ; - - - /* value reading */ - long n; - n = ini.getl("first", "val", -1 ); - assert(n==1); - n = ini.getl("second", "val", -1); - assert(n==2); - n = ini.getl("first", "dummy", -1); - assert(n==-1); - cout << "2. Value reading tests passed" << endl ; - - - /* string writing */ - bool b; - b = ini.put("first", "alt", "flagged as \"correct\""); - assert(b); - s = ini.gets("first", "alt", "aap"); - assert(s=="flagged as \"correct\""); - - b = ini.put("second", "alt", "correct"); - assert(b); - s = ini.gets("second", "alt", "aap"); - assert(s=="correct"); - - b = ini.put("third", "alt", "correct"); - assert(b); - s = ini.gets("third", "alt", "aap" ); - assert(s=="correct"); - cout << "3. String writing tests passed" << endl; - - /* section/key enumeration */ - cout << "4. section/key enumeration; file contents follows" << endl; - string section; - for (int is = 0; section = ini.getsection(is), section.length() > 0; is++) { - cout << " [" << section.c_str() << "]" << endl; - for (int ik = 0; s = ini.getkey(section, ik), s.length() > 0; ik++) { - cout << "\t" << s.c_str() << endl; - } - } - - /* string deletion */ - b = ini.del("first", "alt"); - assert(b); - b = ini.del("second", "alt"); - assert(b); - b = ini.del("third"); - assert(b); - cout << "5. string deletion passed " << endl; - - return 0; -} diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/testplain.ini b/Source/sys-clk/sysmodule/lib/minIni/dev/testplain.ini deleted file mode 100644 index 2a5ce4b6..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/testplain.ini +++ /dev/null @@ -1,3 +0,0 @@ -String=noot # trailing commment -#comment=3 -Val=1 diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/wxMinIni.h b/Source/sys-clk/sysmodule/lib/minIni/dev/wxMinIni.h deleted file mode 100644 index f932bb63..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/dev/wxMinIni.h +++ /dev/null @@ -1,101 +0,0 @@ -/* minIni - Multi-Platform INI file parser, wxWidgets interface - * - * Copyright (c) CompuPhase, 2008-2012 - * - * 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 - * - * http://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. - * - * Version: $Id: wxMinIni.h 44 2012-01-04 15:52:56Z thiadmer.riemersma@gmail.com $ - */ -#ifndef WXMININI_H -#define WXMININI_H - -#include -#include "minIni.h" - -class minIni -{ -public: - minIni(const wxString& filename) : iniFilename(filename) - { } - - bool getbool(const wxString& Section, const wxString& Key, bool DefValue=false) const - { return ini_getbool(Section.utf8_str(), Key.utf8_str(), int(DefValue), iniFilename.utf8_str()) != 0; } - - long getl(const wxString& Section, const wxString& Key, long DefValue=0) const - { return ini_getl(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str()); } - - int geti(const wxString& Section, const wxString& Key, int DefValue=0) const - { return static_cast(ini_getl(Section.utf8_str(), Key.utf8_str(), (long)DefValue, iniFilename.utf8_str())); } - - wxString gets(const wxString& Section, const wxString& Key, const wxString& DefValue=wxT("")) const - { - char buffer[INI_BUFFERSIZE]; - ini_gets(Section.utf8_str(), Key.utf8_str(), DefValue.utf8_str(), buffer, INI_BUFFERSIZE, iniFilename.utf8_str()); - wxString result = wxString::FromUTF8(buffer); - return result; - } - - wxString getsection(int idx) const - { - char buffer[INI_BUFFERSIZE]; - ini_getsection(idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str()); - wxString result = wxString::FromUTF8(buffer); - return result; - } - - wxString getkey(const wxString& Section, int idx) const - { - char buffer[INI_BUFFERSIZE]; - ini_getkey(Section.utf8_str(), idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str()); - wxString result = wxString::FromUTF8(buffer); - return result; - } - -#if defined INI_REAL - INI_REAL getf(const wxString& Section, wxString& Key, INI_REAL DefValue=0) const - { return ini_getf(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str()); } -#endif - -#if ! defined INI_READONLY - bool put(const wxString& Section, const wxString& Key, long Value) const - { return ini_putl(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; } - - bool put(const wxString& Section, const wxString& Key, int Value) const - { return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0; } - - bool put(const wxString& Section, const wxString& Key, bool Value) const - { return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0; } - - bool put(const wxString& Section, const wxString& Key, const wxString& Value) const - { return ini_puts(Section.utf8_str(), Key.utf8_str(), Value.utf8_str(), iniFilename.utf8_str()) != 0; } - - bool put(const wxString& Section, const wxString& Key, const char* Value) const - { return ini_puts(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; } - -#if defined INI_REAL - bool put(const wxString& Section, const wxString& Key, INI_REAL Value) const - { return ini_putf(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; } -#endif - - bool del(const wxString& Section, const wxString& Key) const - { return ini_puts(Section.utf8_str(), Key.utf8_str(), 0, iniFilename.utf8_str()) != 0; } - - bool del(const wxString& Section) const - { return ini_puts(Section.utf8_str(), 0, 0, iniFilename.utf8_str()) != 0; } -#endif - -private: - wxString iniFilename; -}; - -#endif /* WXMININI_H */ diff --git a/Source/sys-clk/sysmodule/lib/minIni/doc/minIni.pdf b/Source/sys-clk/sysmodule/lib/minIni/doc/minIni.pdf deleted file mode 100644 index 603d13ea..00000000 Binary files a/Source/sys-clk/sysmodule/lib/minIni/doc/minIni.pdf and /dev/null differ diff --git a/Source/sys-clk/sysmodule/lib/minIni/include/minIni.h b/Source/sys-clk/sysmodule/lib/minIni/include/minIni.h deleted file mode 100644 index 26520699..00000000 --- a/Source/sys-clk/sysmodule/lib/minIni/include/minIni.h +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - -#pragma once - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include "../dev/minIni.h" - -#ifdef __cplusplus -} -#endif \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/nxExt/.gitignore b/Source/sys-clk/sysmodule/lib/nxExt/.gitignore deleted file mode 100644 index 0806f7bf..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/.gitignore +++ /dev/null @@ -1,13 +0,0 @@ -# Editor files -*.swp -*~ - -# Objects -*.o -*.a -*.so - -# Lib -lib -release -debug \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/nxExt/Makefile b/Source/sys-clk/sysmodule/lib/nxExt/Makefile deleted file mode 100644 index 34be0db8..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/Makefile +++ /dev/null @@ -1,132 +0,0 @@ -#--------------------------------------------------------------------------------- -.SUFFIXES: -#--------------------------------------------------------------------------------- - -ifeq ($(strip $(DEVKITPRO)),) -$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") -endif - -include $(DEVKITPRO)/libnx/switch_rules - -#--------------------------------------------------------------------------------- -# TARGET is the name of the output -# SOURCES is a list of directories containing source code -# DATA is a list of directories containing data files -# INCLUDES is a list of directories containing header files -#--------------------------------------------------------------------------------- -TARGET := $(notdir $(CURDIR)) -SOURCES := src -DATA := data -INCLUDES := include - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIC -ftls-model=local-exec - -CFLAGS := -g -Wall -Werror \ - -ffunction-sections \ - -fdata-sections \ - $(ARCH) \ - $(BUILD_CFLAGS) - -CFLAGS += $(INCLUDE) -std=gnu11 - -CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions - -ASFLAGS := -g $(ARCH) - -#--------------------------------------------------------------------------------- -# list of directories containing libraries, this must be the top level containing -# include and lib -#--------------------------------------------------------------------------------- -LIBDIRS := $(PORTLIBS) $(LIBNX) - -#--------------------------------------------------------------------------------- -# no real need to edit anything past this point unless you need to add additional -# rules for different file extensions -#--------------------------------------------------------------------------------- -ifneq ($(BUILD),$(notdir $(CURDIR))) -#--------------------------------------------------------------------------------- - -export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ - $(foreach dir,$(DATA),$(CURDIR)/$(dir)) - -CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) -CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) -SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) -BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) - -#--------------------------------------------------------------------------------- -# use CXX for linking C++ projects, CC for standard C -#--------------------------------------------------------------------------------- -ifeq ($(strip $(CPPFILES)),) -#--------------------------------------------------------------------------------- - export LD := $(CC) -#--------------------------------------------------------------------------------- -else -#--------------------------------------------------------------------------------- - export LD := $(CXX) -#--------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------- - -export OFILES_BIN := $(addsuffix .o,$(BINFILES)) -export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) -export OFILES := $(OFILES_BIN) $(OFILES_SRC) -export HFILES := $(addsuffix .h,$(subst .,_,$(BINFILES))) - -export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ - $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ - -I$(CURDIR)/$(BUILD) - -.PHONY: clean all lib/lib$(TARGET).a lib/lib$(TARGET)d.a - -#--------------------------------------------------------------------------------- -all: lib/lib$(TARGET).a lib/lib$(TARGET)d.a - -lib: - @[ -d $@ ] || mkdir -p $@ - -release: - @[ -d $@ ] || mkdir -p $@ - -debug: - @[ -d $@ ] || mkdir -p $@ - -lib/lib$(TARGET).a : lib release $(SOURCES) $(INCLUDES) - @$(MAKE) BUILD=release OUTPUT=$(CURDIR)/$@ \ - BUILD_CFLAGS="-DNDEBUG=1 -O2" \ - DEPSDIR=$(CURDIR)/release \ - --no-print-directory -C release \ - -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean: - @echo clean ... - @rm -fr release debug lib - -#--------------------------------------------------------------------------------- -else - -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- -$(OUTPUT) : $(OFILES) - -$(OFILES_SRC) : $(HFILES) - -#--------------------------------------------------------------------------------- -%_bin.h %.bin.o : %.bin -#--------------------------------------------------------------------------------- - @echo $(notdir $<) - @$(bin2o) - - --include $(DEPENDS) - -#--------------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt.h deleted file mode 100644 index 29369887..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt.h +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include "nxExt/apm_ext.h" -#include "nxExt/i2c.h" -#include "nxExt/t210.h" -#include "nxExt/max17050.h" -#include "nxExt/tmp451.h" -#include "nxExt/ipc_server.h" -#include "nxExt/cpp/lockable_mutex.h" diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/apm_ext.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/apm_ext.h deleted file mode 100644 index e032fb35..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/apm_ext.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - -Result apmExtInitialize(void); -void apmExtExit(void); - -Result apmExtGetPerformanceMode(u32* out_mode); -Result apmExtSysRequestPerformanceMode(u32 mode); -Result apmExtGetCurrentPerformanceConfiguration(u32* out_conf); -Result apmExtSysRequestPerformanceMode(u32 mode); -Result apmExtSysSetCpuBoostMode(u32 mode); - -Result apmExtGetPerformanceMode(u32 *out_mode); -Result apmExtGetCurrentPerformanceConfiguration(u32 *out_conf); - -inline bool apmExtIsCPUBoosted(u32 conf_id) { // CPU boosted to 1785 MHz - return (conf_id == 0x92220009 || conf_id == 0x9222000A); -}; -inline bool apmExtIsBoostMode(u32 conf_id) { // GPU throttled to 76.8 MHz - return (conf_id >= 0x92220009 && conf_id <= 0x9222000C); -}; - -#ifdef __cplusplus -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/cpp/lockable_mutex.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/cpp/lockable_mutex.h deleted file mode 100644 index f2c9f60a..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/cpp/lockable_mutex.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __cplusplus - -#include -#include - -class LockableMutex -{ -public: - LockableMutex() - { - mutexInit(&this->m); - } - - virtual ~LockableMutex() {} - - void Lock() - { - mutexLock(&this->m); - } - - bool TryLock() - { - return mutexTryLock(&this->m); - } - - void Unlock() - { - mutexUnlock(&this->m); - } - - // snake_case aliases in order to implement Lockable - - void lock() - { - this->Lock(); - } - - bool try_lock() - { - return this->TryLock(); - } - - void unlock() - { - this->Unlock(); - } - -private: - Mutex m; -}; - -#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/i2c.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/i2c.h deleted file mode 100644 index c3dbe340..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/i2c.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - -Result i2csessionExtRegReceive(I2cSession* s, u8 in, void* out, u8 out_size); - -#ifdef __cplusplus -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/ipc_server.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/ipc_server.h deleted file mode 100644 index 0c8f294b..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/ipc_server.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - -#define IPC_SERVER_EXT_RESPONSE_MAX_DATA_SIZE (0x100 - 0x10 - sizeof(IpcServerRawHeader)) - -typedef struct -{ - u64 magic; - union - { - u64 cmdId; - u64 result; - }; -} IpcServerRawHeader; - -typedef struct -{ - SmServiceName srvName; - Handle handles[MAX_WAIT_OBJECTS]; - u32 max; - u32 count; -} IpcServer; - -typedef struct -{ - u64 cmdId; - void* ptr; - size_t size; -} IpcServerRequestData; - -typedef struct -{ - HipcParsedRequest hipc; - IpcServerRequestData data; -} IpcServerRequest; - -typedef Result (*IpcServerRequestHandler)(void* userdata, const IpcServerRequest* r, u8* out_data, size_t* out_dataSize); - -Result ipcServerInit(IpcServer* server, const char* name, u32 max_sessions); -Result ipcServerExit(IpcServer* server); -Result ipcServerProcess(IpcServer* server, IpcServerRequestHandler handler, void* userdata); -Result ipcServerParseCommand(const IpcServerRequest* r, size_t* out_datasize, void** out_data, u64* out_cmd); - -#ifdef __cplusplus -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/max17050.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/max17050.h deleted file mode 100644 index a22046db..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/max17050.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - -Result max17050Initialize(void); -void max17050Exit(void); -s32 max17050PowerNow(void); -s32 max17050PowerAvg(void); - -#ifdef __cplusplus -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/t210.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/t210.h deleted file mode 100644 index 9e5b41e0..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/t210.h +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - -u32 t210ClkCpuFreq(void); -u32 t210ClkMemFreq(void); -u32 t210ClkGpuFreq(void); -u32 t210EmcLoadAll(void); -u32 t210EmcLoadCpu(void); - -#ifdef __cplusplus -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/tmp451.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/tmp451.h deleted file mode 100644 index 9faf2480..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/tmp451.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#ifdef __cplusplus -extern "C" -{ -#endif - -#include - -Result tmp451Initialize(void); -void tmp451Exit(void); -s32 tmp451TempPcb(void); -s32 tmp451TempSoc(void); - -#ifdef __cplusplus -} -#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/apm_ext.c b/Source/sys-clk/sysmodule/lib/nxExt/src/apm_ext.c deleted file mode 100644 index fba71f4f..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/src/apm_ext.c +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "nxExt/apm_ext.h" - -#include - -static Service g_apmSrv; -static Service g_apmSysSrv; -static atomic_size_t g_refCnt; - -Result apmExtInitialize(void) -{ - g_refCnt++; - - if (serviceIsActive(&g_apmSrv)) - { - return 0; - } - - Result rc = 0; - - rc = smGetService(&g_apmSrv, "apm"); - if(R_SUCCEEDED(rc)) - { - rc = smGetService(&g_apmSysSrv, "apm:sys"); - } - - if (R_FAILED(rc)) - { - apmExtExit(); - } - - return rc; -} - -void apmExtExit(void) -{ - if (--g_refCnt == 0) - { - serviceClose(&g_apmSrv); - serviceClose(&g_apmSysSrv); - } -} - -Result apmExtGetPerformanceMode(u32* out_mode) -{ - return serviceDispatchOut(&g_apmSrv, 1, *out_mode); -} - -Result apmExtSysRequestPerformanceMode(u32 mode) -{ - return serviceDispatchIn(&g_apmSysSrv, 0, mode); -} - -Result apmExtGetCurrentPerformanceConfiguration(u32* out_conf) -{ - return serviceDispatchOut(&g_apmSysSrv, 7, *out_conf); -} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c b/Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c deleted file mode 100644 index d5db4ac1..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "nxExt/i2c.h" - -#define I2C_CMD_SND 0 -#define I2C_CMD_RCV 1 - -Result i2csessionExtRegReceive(I2cSession* s, u8 in, void* out, u8 out_size) -{ - u8 cmdlist[5] = { - I2C_CMD_SND | (I2cTransactionOption_Start << 6), - sizeof(in), - in, - - I2C_CMD_RCV | (I2cTransactionOption_All << 6), - out_size - }; - - return i2csessionExecuteCommandList(s, out, out_size, cmdlist, sizeof(cmdlist)); -} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/ipc_server.c b/Source/sys-clk/sysmodule/lib/nxExt/src/ipc_server.c deleted file mode 100644 index 68e92ff8..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/src/ipc_server.c +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "nxExt/ipc_server.h" -#include - -Result ipcServerInit(IpcServer* server, const char* name, u32 max_sessions) -{ - if(max_sessions < 1 || max_sessions > (MAX_WAIT_OBJECTS - 1)) - { - return MAKERESULT(Module_Libnx, LibnxError_BadInput); - } - - server->srvName = smEncodeName(name); - server->max = max_sessions + 1; - server->count = 0; - - Result rc = smRegisterService(&server->handles[0], server->srvName, false, max_sessions); - if(R_SUCCEEDED(rc)) - { - server->count = 1; - } - return rc; -} - -Result ipcServerExit(IpcServer* server) -{ - for(u32 i = 0; i < server->count; i++) - { - svcCloseHandle(server->handles[i]); - } - server->count = 0; - return smUnregisterService(server->srvName); -} - -static Result _ipcServerAddSession(IpcServer* server, Handle session) -{ - if(server->count >= server->max) - { - return MAKERESULT(Module_Libnx, LibnxError_OutOfMemory); - } - - server->handles[server->count] = session; - server->count++; - return 0; -} - -static Result _ipcServerDeleteSession(IpcServer* server, u32 index) -{ - if(!index || index >= server->count) - { - return MAKERESULT(Module_Libnx, LibnxError_BadInput); - } - - svcCloseHandle(server->handles[index]); - - for(u32 j = index; j < (server->count - 1); j++) - { - server->handles[j] = server->handles[j + 1]; - } - server->count--; - return 0; -} - -static Result _ipcServerParseRequest(IpcServerRequest* r) -{ - u8* base = armGetTls(); - - r->hipc = hipcParseRequest(base); - r->data.cmdId = 0; - r->data.size = 0; - r->data.ptr = NULL; - - if(r->hipc.meta.type == CmifCommandType_Request) - { - IpcServerRawHeader* header = cmifGetAlignedDataStart(r->hipc.data.data_words, base); - size_t dataSize = r->hipc.meta.num_data_words * 4; - - if(!header || dataSize < sizeof(IpcServerRawHeader) || header->magic != CMIF_IN_HEADER_MAGIC) - { - return MAKERESULT(Module_Libnx, LibnxError_BadInput); - } - - r->data.cmdId = header->cmdId; - if(dataSize > sizeof(IpcServerRawHeader)) - { - r->data.size = dataSize - sizeof(IpcServerRawHeader); - r->data.ptr = ((u8*)header) + sizeof(IpcServerRawHeader); - } - } - - return 0; -} - -static void _ipcServerPrepareResponse(Result rc, void* data, size_t dataSize) -{ - u8* base = armGetTls(); - HipcRequest hipc = hipcMakeRequestInline(base, - .type = CmifCommandType_Request, - .num_data_words = (sizeof(IpcServerRawHeader) + dataSize + 0x10) / 4, - ); - - IpcServerRawHeader* rawHeader = cmifGetAlignedDataStart(hipc.data_words, base); - rawHeader->magic = CMIF_OUT_HEADER_MAGIC; - rawHeader->result = rc; - - if(R_SUCCEEDED(rc)) - { - memcpy(((u8*)rawHeader) + sizeof(IpcServerRawHeader), data, dataSize); - } -} - -static Result _ipcServerProcessNewSession(IpcServer* server) -{ - Handle session; - Result rc = svcAcceptSession(&session, server->handles[0]); - if(R_SUCCEEDED(rc) && R_FAILED(rc = _ipcServerAddSession(server, session))) - { - svcCloseHandle(session); - } - return rc; -} - -static Result _ipcServerProcessSession(IpcServer* server, IpcServerRequestHandler handler, void* userdata, u32 handleIndex) -{ - s32 unusedIndex; - IpcServerRequest r; - size_t dataSize = 0; - u8 data[IPC_SERVER_EXT_RESPONSE_MAX_DATA_SIZE]; - bool close = false; - - Result rc = svcReplyAndReceive(&unusedIndex, &server->handles[handleIndex], 1, 0, UINT64_MAX); - if(R_SUCCEEDED(rc)) - { - rc = _ipcServerParseRequest(&r); - } - - if(R_SUCCEEDED(rc)) - { - switch(r.hipc.meta.type) - { - case CmifCommandType_Request: - _ipcServerPrepareResponse( - handler(userdata, &r, data, &dataSize), - data, - dataSize - ); - break; - case CmifCommandType_Close: - _ipcServerPrepareResponse(0, NULL, 0); - close = true; - break; - default: - _ipcServerPrepareResponse(MAKERESULT(11, 403), NULL, 0); - break; - } - - rc = svcReplyAndReceive(&unusedIndex, &server->handles[handleIndex], 0, server->handles[handleIndex], 0); - if(rc == KERNELRESULT(TimedOut)) - { - rc = 0; - } - } - - if(R_FAILED(rc) || close) - { - _ipcServerDeleteSession(server, handleIndex); - } - - return rc; -} - -Result ipcServerProcess(IpcServer* server, IpcServerRequestHandler handler, void* userdata) -{ - s32 handleIndex = -1; - Result rc = svcWaitSynchronization(&handleIndex, server->handles, server->count, UINT64_MAX); - - if(R_SUCCEEDED(rc) && (handleIndex < 0 || handleIndex >= server->count)) - { - rc = MAKERESULT(Module_Libnx, LibnxError_NotFound); - } - - if(R_SUCCEEDED(rc)) - { - if(handleIndex) - { - rc = _ipcServerProcessSession(server, handler, userdata, handleIndex); - } - else - { - rc = _ipcServerProcessNewSession(server); - } - } - - return rc; -} - diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/max17050.c b/Source/sys-clk/sysmodule/lib/nxExt/src/max17050.c deleted file mode 100644 index fe6d00bc..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/src/max17050.c +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Fuel gauge driver for Nintendo Switch's Maxim 17050 - * - * Copyright (c) 2011 Samsung Electronics - * MyungJoo Ham - * Copyright (c) 2018 CTCaer - * Copyright (c) 2022 p-sam - * - * 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 2 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, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - */ - -#include "nxExt/max17050.h" -#include "nxExt/i2c.h" - -#define MAX17050_WAIT_NS 1000000000UL - -#define MAX17050_VCELL 0x09 -#define MAX17050_Current 0x0A -#define MAX17050_AvgCurrent 0x0B -#define MAX17050_AvgVCELL 0x19 - -#define MAX17050_BOARD_CGAIN 2 -#define MAX17050_BOARD_SNS_RESISTOR_UOHM 5000 - -static I2cSession g_i2c_session; -static u64 g_update_ticks = 0; -static s32 g_power_now = 0; -static s32 g_power_avg = 0; - -static Result _max17050_get_power(s32 *out_mw_now, s32 *out_mw_avg) -{ - s64 ma, mv; - u16 values[3] = {0}; - - Result rc = i2csessionExtRegReceive(&g_i2c_session, MAX17050_VCELL, values, sizeof(values)); - - if (R_SUCCEEDED(rc)) - { - ma = (s16)values[1]; - ma = ma * 1562500 / (MAX17050_BOARD_SNS_RESISTOR_UOHM * MAX17050_BOARD_CGAIN); - - mv = (int)(values[0] >> 3) * 625 / 1000; - - *out_mw_now = ma * mv / 1000000; - } - - if (R_SUCCEEDED(rc)) - { - rc = i2csessionExtRegReceive(&g_i2c_session, MAX17050_AvgVCELL, values, sizeof(u16)); - } - - if (R_SUCCEEDED(rc)) - { - ma = (s16)values[2]; - ma = ma * 1562500 / (MAX17050_BOARD_SNS_RESISTOR_UOHM * MAX17050_BOARD_CGAIN); - - mv = (int)(values[0] >> 3) * 625 / 1000; - - *out_mw_avg = ma * mv / 1000000; - } - - return rc; -} - -static void _max17050_update() -{ - u64 ticks = armGetSystemTick(); - if(armTicksToNs(ticks - g_update_ticks) <= MAX17050_WAIT_NS) - { - return; - } - - g_update_ticks = ticks; - - if(!serviceIsActive(&g_i2c_session.s)) - { - return; - } - - _max17050_get_power(&g_power_now, &g_power_avg); -} - -Result max17050Initialize(void) -{ - Result rc = i2cInitialize(); - - if(R_SUCCEEDED(rc)) - { - rc = i2cOpenSession(&g_i2c_session, I2cDevice_Max17050); - } - - return rc; -} - -void max17050Exit(void) -{ - i2csessionClose(&g_i2c_session); - i2cExit(); -} - -s32 max17050PowerNow(void) -{ - _max17050_update(); - return g_power_now; -} - -s32 max17050PowerAvg(void) -{ - _max17050_update(); - return g_power_avg; -} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/t210.c b/Source/sys-clk/sysmodule/lib/nxExt/src/t210.c deleted file mode 100644 index 91ce4ec2..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/src/t210.c +++ /dev/null @@ -1,290 +0,0 @@ -/* - * Copyright (c) 2020-2023 CTCaer - * Copyright (c) 2023 p-sam - * Copyright (c) 2026 Souldbminer - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - */ - -#include "nxExt/t210.h" - -#define WAIT_NS 1000000000UL - -#define usleep(x) svcSleepThread(1000UL * x) - -#define GPU_TRIM_SYS_GPCPLL_COEFF 0x4 -#define GPU_TRIM_SYS_GPCPLL(x) (*(volatile u32 *)(g_gpu_base + 0x137000ul + (x))) - -#define CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL 0x60 -#define CLK_RST_CONTROLLER_PTO_CLK_CNT_STATUS 0x64 -#define CLK_RST_CONTROLLER_CLK_OUT_ENB_X 0x280 -#define CLK_RST_CONTROLLER_RST_DEVICES_X 0x28C - -/*! PTO_CLK_CNT */ -#define PTO_REF_CLK_WIN_CFG_MASK 0xF -#define PTO_REF_CLK_WIN_CFG_16P 0xF -#define PTO_CNT_EN BIT(9) -#define PTO_CNT_RST BIT(10) -#define PTO_CLK_ENABLE BIT(13) -#define PTO_SRC_SEL_SHIFT 14 -#define PTO_SRC_SEL_MASK 0x1FF -#define PTO_DIV_SEL_MASK (3 << 23) -#define PTO_DIV_SEL_GATED (0 << 23) -#define PTO_DIV_SEL_DIV1 (1 << 23) -#define PTO_DIV_SEL_DIV2_RISING (2 << 23) -#define PTO_DIV_SEL_DIV2_FALLING (3 << 23) -#define PTO_DIV_SEL_CPU_EARLY (0 << 23) -#define PTO_DIV_SEL_CPU_LATE (1 << 23) - -#define PTO_CLK_CNT_BUSY BIT(31) -#define PTO_CLK_CNT 0xFFFFFF -#define CLK_PTO_CCLK_G_DIV2 0x13 -#define CLK_PTO_EMC 0x24 - -#define CLOCK(x) (*(volatile u32 *)(g_clk_base + (x))) - -/* Actmon Global registers */ -#define ACTMON_GLB_STATUS 0x0 -#define ACTMON_MCCPU_MON_ACT BIT(8) -#define ACTMON_MCALL_MON_ACT BIT(9) -#define ACTMON_CPU_FREQ_MON_ACT BIT(10) -#define ACTMON_BPMP_MON_ACT BIT(14) -#define ACTMON_CPU_MON_ACT BIT(15) - -#define ACTMON_GLB_PERIOD_CTRL 0x4 -#define ACTMON_GLB_PERIOD_USEC BIT(8) -#define ACTMON_GLB_PERIOD_SAMPLE(n) (((n) - 1) & 0xFF) - -/* Actmon Device Registers */ -#define ACTMON_DEV_SIZE 0x40 -/* Actmon CTRL */ -#define ACTMON_DEV_CTRL_K_VAL(k) (((k) & 7) << 10) -#define ACTMON_DEV_CTRL_ENB_PERIODIC BIT(18) -#define ACTMON_DEV_CTRL_ENB BIT(31) - -#define ACTMON_PERIOD_MS 20 -#define DEV_COUNT_WEIGHT 1024 - -#define ACTMON_BASE (g_act_base + 0x800) -#define ACTMON_DEV_BASE (ACTMON_BASE + 0x80) -#define ACTMON(x) (*(volatile u32 *)(ACTMON_BASE + (x))) - -typedef enum _actmon_dev_t -{ - ACTMON_DEV_CPU, - ACTMON_DEV_BPMP, - ACTMON_DEV_AHB, - ACTMON_DEV_APB, - ACTMON_DEV_CPU_FREQ, - ACTMON_DEV_MC_ALL, - ACTMON_DEV_MC_CPU, - - ACTMON_DEV_NUM, -} actmon_dev_t; - -typedef struct _actmon_dev_reg_t -{ - vu32 ctrl; - vu32 upper_wnark; - vu32 lower_wmark; - vu32 init_avg; - vu32 avg_upper_wmark; - vu32 avg_lower_wmark; - vu32 count_weight; - vu32 count; - vu32 avg_count; - vu32 intr_status; - vu32 ctrl2; - vu32 rsvd[5]; -} actmon_dev_reg_t; - -static uintptr_t g_clk_base = 0; -static uintptr_t g_gpu_base = 0; -static uintptr_t g_act_base = 0; -static u64 g_update_ticks = 0; -static u32 g_cpu_freq = 0; -static u32 g_gpu_freq = 0; -static u32 g_mem_freq = 0; -static u32 g_emc_lall = 0; -static u32 g_emc_lcpu = 0; - -static u32 _clock_get_dev_freq(u32 id, u32 multiplier) -{ - const u32 pto_win = 16; - const u32 pto_osc = 32768; - - u32 val = ((id & PTO_SRC_SEL_MASK) << PTO_SRC_SEL_SHIFT) | PTO_DIV_SEL_DIV1 | PTO_CLK_ENABLE | (pto_win - 1); - CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val; - (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); - usleep(2); - - CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val | PTO_CNT_RST; - (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); - usleep(2); - - CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val; - (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); - usleep(2); - - CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val | PTO_CNT_EN; - (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); - usleep((1000000ULL * pto_win / pto_osc) + 12 + 2); // 502 us. - - while (CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_STATUS) & PTO_CLK_CNT_BUSY) - ; - - u32 cnt = CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_STATUS) & PTO_CLK_CNT; - - CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = 0; - (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); - usleep(2); - - u32 freq_khz = (u64)cnt * multiplier * pto_osc / pto_win; - - return freq_khz; -} - -static void _actmon_dev_enable(actmon_dev_t dev, u32 freq, u32 weight) -{ - actmon_dev_reg_t *regs = (actmon_dev_reg_t *)(ACTMON_DEV_BASE + (dev * ACTMON_DEV_SIZE)); - - regs->init_avg = (u32)freq * ACTMON_PERIOD_MS / 2; - regs->count_weight = weight; - - regs->ctrl = ACTMON_DEV_CTRL_ENB | ACTMON_DEV_CTRL_ENB_PERIODIC | ACTMON_DEV_CTRL_K_VAL(3); // 8 samples average. -} - -static u32 _actmon_dev_get_count_avg(actmon_dev_t dev) -{ - actmon_dev_reg_t *regs = (actmon_dev_reg_t *)(ACTMON_DEV_BASE + (dev * ACTMON_DEV_SIZE)); - - return regs->avg_count; -} - -static inline Result _svcQueryMemoryMappingFallback(u64* virtaddr, u64 physaddr, u64 size) -{ - if(hosversionAtLeast(10,0,0)) - { - u64 out_size; - return svcQueryMemoryMapping(virtaddr, &out_size, physaddr, size); - } - else - { - return svcLegacyQueryIoMapping(virtaddr, physaddr, size); - } -} - -static void _clock_update_freqs(void) -{ - u64 ticks = armGetSystemTick(); - if(armTicksToNs(ticks - g_update_ticks) <= WAIT_NS) - { - return; - } - - g_update_ticks = ticks; - - if (!g_clk_base) - { - _svcQueryMemoryMappingFallback(&g_clk_base, 0x60006000ul, 0x1000); - } - - if(!g_clk_base) - { - return; - } - - g_mem_freq = _clock_get_dev_freq(CLK_PTO_EMC, 1); - g_cpu_freq = _clock_get_dev_freq(CLK_PTO_CCLK_G_DIV2, 2); - - if (!g_gpu_base) - { - _svcQueryMemoryMappingFallback(&g_gpu_base, 0x57000000ul, 0x1000000); - } - - if (!g_gpu_base) - { - return; - } - - bool gpu_enabled = (CLOCK(CLK_RST_CONTROLLER_CLK_OUT_ENB_X) & BIT(24)) && !(CLOCK(CLK_RST_CONTROLLER_RST_DEVICES_X) & BIT(24)); - if(!gpu_enabled) - { - return; - } - - if (!g_act_base) - { - _svcQueryMemoryMappingFallback(&g_act_base, 0x6000C000ul, 0x1000); - } - - if(!g_act_base) - { - return; - } - - const u32 osc = 38400000; - u32 coeff = GPU_TRIM_SYS_GPCPLL(GPU_TRIM_SYS_GPCPLL_COEFF); - u32 divm = coeff & 0xFF; - u32 divn = (coeff >> 8) & 0xFF; - u32 divp = (coeff >> 16) & 0x3F; - g_gpu_freq = osc * divn / (divm * divp) / 2; - - u32 emc_freq = g_mem_freq / 1000; - - // Check if actmon is disabled - if (!(ACTMON(ACTMON_GLB_STATUS) & ACTMON_MCALL_MON_ACT)) - { - ACTMON(ACTMON_GLB_PERIOD_CTRL) = ACTMON_GLB_PERIOD_SAMPLE(ACTMON_PERIOD_MS); - _actmon_dev_enable(ACTMON_DEV_MC_ALL, emc_freq, 256 * 4); - } - - // Check if actmon is disabled - if (!(ACTMON(ACTMON_GLB_STATUS) & ACTMON_MCCPU_MON_ACT)) - _actmon_dev_enable(ACTMON_DEV_MC_CPU, emc_freq, 256 * 4); - - // Get 1000 -> 100.0. - g_emc_lall = (u64)_actmon_dev_get_count_avg(ACTMON_DEV_MC_ALL) * 10 * 100 / (emc_freq * ACTMON_PERIOD_MS); - g_emc_lcpu = (u64)_actmon_dev_get_count_avg(ACTMON_DEV_MC_CPU) * 10 * 100 / (emc_freq * ACTMON_PERIOD_MS); -} - - -u32 t210ClkCpuFreq(void) -{ - _clock_update_freqs(); - return g_cpu_freq; -} - -u32 t210ClkMemFreq(void) -{ - _clock_update_freqs(); - return g_mem_freq; -} - -u32 t210ClkGpuFreq(void) -{ - _clock_update_freqs(); - return g_gpu_freq; -} - -u32 t210EmcLoadAll() -{ - _clock_update_freqs(); - return g_emc_lall; -} - -u32 t210EmcLoadCpu() -{ - _clock_update_freqs(); - return g_emc_lcpu; -} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/tmp451.c b/Source/sys-clk/sysmodule/lib/nxExt/src/tmp451.c deleted file mode 100644 index 90c8d1c2..00000000 --- a/Source/sys-clk/sysmodule/lib/nxExt/src/tmp451.c +++ /dev/null @@ -1,102 +0,0 @@ -/* - * SOC/PCB Temperature driver for Nintendo Switch's TI TMP451 - * - * Copyright (c) 2018-2024 CTCaer - * Copyright (c) 2024 p-sam - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - */ - -#include "nxExt/tmp451.h" -#include "nxExt/i2c.h" - -#define TMP451_WAIT_NS 1000000000UL - -#define TMP451_PCB_TEMP_REG 0x00 -#define TMP451_SOC_TEMP_REG 0x01 - -#define TMP451_SOC_TMP_DEC_REG 0x10 -#define TMP451_PCB_TMP_DEC_REG 0x15 - -static I2cSession g_i2c_session; -static u64 g_update_ticks = 0; -static s32 g_temp_pcb = 0; -static s32 g_temp_soc = 0; - -static Result _tmp451_get_temp(u8 reg, u8 dec_reg, s32* out) -{ - u8 val = 0; - Result rc = i2csessionExtRegReceive(&g_i2c_session, reg, &val, sizeof(val)); - - if(R_SUCCEEDED(rc)) - { - *out = (s32)val * 1000; - rc = i2csessionExtRegReceive(&g_i2c_session, dec_reg, &val, sizeof(val)); - } - - if(R_SUCCEEDED(rc)) - { - *out += ((s32)(val >> 4) * 625) / 10; - } - - return rc; -} - -static void _tmp451_update() -{ - u64 ticks = armGetSystemTick(); - if(armTicksToNs(ticks - g_update_ticks) <= TMP451_WAIT_NS) - { - return; - } - - g_update_ticks = ticks; - - if(!serviceIsActive(&g_i2c_session.s)) - { - return; - } - - _tmp451_get_temp(TMP451_PCB_TEMP_REG, TMP451_PCB_TMP_DEC_REG, &g_temp_pcb); - _tmp451_get_temp(TMP451_SOC_TEMP_REG, TMP451_SOC_TMP_DEC_REG, &g_temp_soc); -} - -Result tmp451Initialize(void) -{ - Result rc = i2cInitialize(); - - if(R_SUCCEEDED(rc)) - { - rc = i2cOpenSession(&g_i2c_session, I2cDevice_Tmp451); - } - - return rc; -} - -void tmp451Exit(void) -{ - i2csessionClose(&g_i2c_session); - i2cExit(); -} - -s32 tmp451TempPcb(void) -{ - _tmp451_update(); - return g_temp_pcb; -} - -s32 tmp451TempSoc(void) -{ - _tmp451_update(); - return g_temp_soc; -} diff --git a/Source/sys-clk/sysmodule/perms.json b/Source/sys-clk/sysmodule/perms.json deleted file mode 100644 index 7bee6a64..00000000 --- a/Source/sys-clk/sysmodule/perms.json +++ /dev/null @@ -1,240 +0,0 @@ -{ - "name": "hoc:clk", - "title_id": "0x00FF0000636C6BFF", - "title_id_range_min": "0x00FF0000636C6BFF", - "title_id_range_max": "0x00FF0000636C6BFF", - "main_thread_stack_size": "0x0000D000", - "main_thread_priority": 16, - "default_cpu_id": 3, - "process_category": 1, - "is_retail": true, - "pool_partition": 2, - "is_64_bit": true, - "address_space_type": 3, - "filesystem_access": { - "permissions": "0xFFFFFFFFFFFFFFFF" - }, - "service_access": [ - "*" - ], - "service_host": [ - "hoc:clk" - ], - "kernel_capabilities": [ - { - "type": "kernel_flags", - "value": { - "highest_thread_priority": 63, - "lowest_thread_priority": 16, - "lowest_cpu_id": 0, - "highest_cpu_id": 3 - } - }, - { - "type": "map", - "value": { - "address": "0x60006000", - "size": "0x1000", - "is_ro": false, - "is_io": true - } - }, - { - "type": "map", - "value": { - "address": "0x57000000", - "size": "0x1000000", - "is_ro": false, - "is_io": true - } - }, - { - "type": "map", - "value": { - "address": "0x6000C000", - "size": "0x1000", - "is_ro": false, - "is_io": true - } - }, - { - "type": "map", - "value": { - "address": "0x70110000", - "size": "0x1000", - "is_ro": false, - "is_io": true - } - }, - { - "type": "syscalls", - "value": { - "svcUnknown": "0x00", - "svcSetHeapSize": "0x01", - "svcSetMemoryPermission": "0x02", - "svcSetMemoryAttribute": "0x03", - "svcMapMemory": "0x04", - "svcUnmapMemory": "0x05", - "svcQueryMemory": "0x06", - "svcExitProcess": "0x07", - "svcCreateThread": "0x08", - "svcStartThread": "0x09", - "svcExitThread": "0x0a", - "svcSleepThread": "0x0b", - "svcGetThreadPriority": "0x0c", - "svcSetThreadPriority": "0x0d", - "svcGetThreadCoreMask": "0x0e", - "svcSetThreadCoreMask": "0x0f", - "svcGetCurrentProcessorNumber": "0x10", - "svcSignalEvent": "0x11", - "svcClearEvent": "0x12", - "svcMapSharedMemory": "0x13", - "svcUnmapSharedMemory": "0x14", - "svcCreateTransferMemory": "0x15", - "svcCloseHandle": "0x16", - "svcResetSignal": "0x17", - "svcWaitSynchronization": "0x18", - "svcCancelSynchronization": "0x19", - "svcArbitrateLock": "0x1a", - "svcArbitrateUnlock": "0x1b", - "svcWaitProcessWideKeyAtomic": "0x1c", - "svcSignalProcessWideKey": "0x1d", - "svcGetSystemTick": "0x1e", - "svcConnectToNamedPort": "0x1f", - "svcSendSyncRequestLight": "0x20", - "svcSendSyncRequest": "0x21", - "svcSendSyncRequestWithUserBuffer": "0x22", - "svcSendAsyncRequestWithUserBuffer": "0x23", - "svcGetProcessId": "0x24", - "svcGetThreadId": "0x25", - "svcBreak": "0x26", - "svcOutputDebugString": "0x27", - "svcReturnFromException": "0x28", - "svcGetInfo": "0x29", - "svcFlushEntireDataCache": "0x2a", - "svcFlushDataCache": "0x2b", - "svcMapPhysicalMemory": "0x2c", - "svcUnmapPhysicalMemory": "0x2d", - "svcGetFutureThreadInfo": "0x2e", - "svcGetLastThreadInfo": "0x2f", - "svcGetResourceLimitLimitValue": "0x30", - "svcGetResourceLimitCurrentValue": "0x31", - "svcSetThreadActivity": "0x32", - "svcGetThreadContext3": "0x33", - "svcWaitForAddress": "0x34", - "svcSignalToAddress": "0x35", - "svcUnknown": "0x36", - "svcUnknown": "0x37", - "svcUnknown": "0x38", - "svcUnknown": "0x39", - "svcUnknown": "0x3a", - "svcUnknown": "0x3b", - "svcDumpInfo": "0x3c", - "svcDumpInfoNew": "0x3d", - "svcUnknown": "0x3e", - "svcUnknown": "0x3f", - "svcCreateSession": "0x40", - "svcAcceptSession": "0x41", - "svcReplyAndReceiveLight": "0x42", - "svcReplyAndReceive": "0x43", - "svcReplyAndReceiveWithUserBuffer": "0x44", - "svcCreateEvent": "0x45", - "svcUnknown": "0x46", - "svcUnknown": "0x47", - "svcMapPhysicalMemoryUnsafe": "0x48", - "svcUnmapPhysicalMemoryUnsafe": "0x49", - "svcSetUnsafeLimit": "0x4a", - "svcCreateCodeMemory": "0x4b", - "svcControlCodeMemory": "0x4c", - "svcSleepSystem": "0x4d", - "svcReadWriteRegister": "0x4e", - "svcSetProcessActivity": "0x4f", - "svcCreateSharedMemory": "0x50", - "svcMapTransferMemory": "0x51", - "svcUnmapTransferMemory": "0x52", - "svcCreateInterruptEvent": "0x53", - "svcQueryPhysicalAddress": "0x54", - "svcQueryMemoryMapping": "0x55", - "svcCreateDeviceAddressSpace": "0x56", - "svcAttachDeviceAddressSpace": "0x57", - "svcDetachDeviceAddressSpace": "0x58", - "svcMapDeviceAddressSpaceByForce": "0x59", - "svcMapDeviceAddressSpaceAligned": "0x5a", - "svcMapDeviceAddressSpace": "0x5b", - "svcUnmapDeviceAddressSpace": "0x5c", - "svcInvalidateProcessDataCache": "0x5d", - "svcStoreProcessDataCache": "0x5e", - "svcFlushProcessDataCache": "0x5f", - "svcDebugActiveProcess": "0x60", - "svcBreakDebugProcess": "0x61", - "svcTerminateDebugProcess": "0x62", - "svcGetDebugEvent": "0x63", - "svcContinueDebugEvent": "0x64", - "svcGetProcessList": "0x65", - "svcGetThreadList": "0x66", - "svcGetDebugThreadContext": "0x67", - "svcSetDebugThreadContext": "0x68", - "svcQueryDebugProcessMemory": "0x69", - "svcReadDebugProcessMemory": "0x6a", - "svcWriteDebugProcessMemory": "0x6b", - "svcSetHardwareBreakPoint": "0x6c", - "svcGetDebugThreadParam": "0x6d", - "svcUnknown": "0x6e", - "svcGetSystemInfo": "0x6f", - "svcCreatePort": "0x70", - "svcManageNamedPort": "0x71", - "svcConnectToPort": "0x72", - "svcSetProcessMemoryPermission": "0x73", - "svcMapProcessMemory": "0x74", - "svcUnmapProcessMemory": "0x75", - "svcQueryProcessMemory": "0x76", - "svcMapProcessCodeMemory": "0x77", - "svcUnmapProcessCodeMemory": "0x78", - "svcCreateProcess": "0x79", - "svcStartProcess": "0x7a", - "svcTerminateProcess": "0x7b", - "svcGetProcessInfo": "0x7c", - "svcCreateResourceLimit": "0x7d", - "svcSetResourceLimitLimitValue": "0x7e", - "svcCallSecureMonitor": "0x7f" - } - }, { - "type": "min_kernel_version", - "value": "0x0060" - }, { - "type": "handle_table_size", - "value": 1023 - }, { - "type": "debug_flags", - "value": { - "allow_debug": false, - "force_debug_prod": false, - "force_debug": true - } - }, { - "type": "map", - "value": { - "address": "0x60006000", - "size": "0x1000", - "is_ro": false, - "is_io": true - } - }, { - "type": "map", - "value": { - "address": "0x54300000", - "size": "0x40000", - "is_ro": false, - "is_io": true - } - }, { - "type": "map", - "value": { - "address": "0x7001b000", - "size": "0x1000", - "is_ro": false, - "is_io": true - } - } - ] -} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/board.cpp b/Source/sys-clk/sysmodule/src/board.cpp deleted file mode 100644 index e98cf955..00000000 --- a/Source/sys-clk/sysmodule/src/board.cpp +++ /dev/null @@ -1,1322 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - -#include -#include "board.h" -#include "errors.h" -#include "rgltr.h" -#include "file_utils.h" -#include // for std::clamp -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#define MAX(A, B) std::max(A, B) -#define MIN(A, B) std::min(A, B) -#define CEIL(A) std::ceil(A) -#define FLOOR(A) std::floor(A) -#define ROUND(A) std::lround(A) - -#define HOSSVC_HAS_CLKRST (hosversionAtLeast(8,0,0)) -#define HOSSVC_HAS_TC (hosversionAtLeast(5,0,0)) -#define NVGPU_GPU_IOCTL_PMU_GET_GPU_LOAD 0x80044715 -#define NVSCHED_CTRL_ENABLE 0x00000601 -#define NVSCHED_CTRL_DISABLE 0x00000602 - -constexpr u64 CpuTimeOutNs = 500'000'000; -constexpr double Systemtickfrequency = 19200000.0 * (static_cast(CpuTimeOutNs) / 1'000'000'000.0); -Result nvInitialize_rc; -Result nvCheck = 1; -Result nvCheck_sched = 1; - -LEvent threadexit; -Thread gpuLThread; -Thread cpuCore0Thread; -Thread cpuCore1Thread; -Thread cpuCore2Thread; -Thread cpuCore3Thread; -Thread miscThread; -double temp = 0; - -PwmChannelSession g_ICon; -Result pwmCheck = 1; -Result pwmDutyCycleCheck = 1; -double Rotation_Duty = 0; -u8 fanLevel; - -uint32_t GPU_Load_u = 0, fd = 0, fd2 = 0; -BatteryChargeInfo info; - -static SysClkSocType g_socType = SysClkSocType_Erista; -static HorizonOCConsoleType g_consoleType = HorizonOCConsoleType_Iowa; - -u64 idletick0 = 0; -u64 idletick1 = 0; -u64 idletick2 = 0; -// u64 idletick3 = 0; - -u32 cpu0, cpu1, cpu2, cpu3, cpuAvg; -u16 cpuSpeedo0, cpuSpeedo2, socSpeedo0; // CPU, GPU, SOC -u32 speedoBracket; -u16 cpuIDDQ, gpuIDDQ, socIDDQ; -u16 BwaferX, BwaferY; -u8 g_dramID = 0; -u64 cldvfs, cldvfs_temp; -u32 cachedEristaUvLowTune0 = 0, cachedEristaUvLowTune1 = 0, cachedMarikoUvHighTune0 = 0; - -static const u32 ramBrackets[][22] = { - { 2133, 2200, 2266, 2300, 2366, 2400, 2433, 2466, 2533, 2566, 2600, 2633, 2700, 2733, 2766, 2833, 2866, 2900, 2933, 3033, 3066, 3100, }, - { 2300, 2366, 2433, 2466, 2533, 2566, 2633, 2700, 2733, 2800, 2833, 2900, 2933, 2966, 3033, 3066, 3100, 3133, 3166, 3200, 3233, 3266, }, - { 2433, 2466, 2533, 2600, 2666, 2733, 2766, 2800, 2833, 2866, 2933, 2966, 3033, 3066, 3100, 3133, 3166, 3200, 3233, 3300, 3333, 3366, }, - { 2500, 2533, 2600, 2633, 2666, 2733, 2800, 2866, 2900, 2966, 3033, 3100, 3166, 3200, 3233, 3266, 3300, 3333, 3366, 3400, 3400, 3400, }, -}; - -static const u32 gpuDvfsArray[] = { 590, 600, 610, 620, 630, 640, 650, 660, 670, 680, 690, 700, 710, 720, 730, 740, 750, 760, 770, 780, 790, 800}; - -u32 dvfsTable[6][32] = {}; -u64 dvfsAddress; -u32 ramVmin; -bool isRetro = false; - -const char* Board::GetModuleName(SysClkModule module, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkModule, module); - return sysclkFormatModule(module, pretty); -} - -const char* Board::GetProfileName(SysClkProfile profile, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkProfile, profile); - return sysclkFormatProfile(profile, pretty); -} - -const char* Board::GetThermalSensorName(SysClkThermalSensor sensor, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkThermalSensor, sensor); - return sysclkFormatThermalSensor(sensor, pretty); -} - -const char* Board::GetPowerSensorName(SysClkPowerSensor sensor, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkPowerSensor, sensor); - return sysclkFormatPowerSensor(sensor, pretty); -} - -PcvModule Board::GetPcvModule(SysClkModule sysclkModule) -{ - switch(sysclkModule) - { - case SysClkModule_CPU: - return PcvModule_CpuBus; - case SysClkModule_GPU: - return PcvModule_GPU; - case SysClkModule_MEM: - return PcvModule_EMC; - default: - ASSERT_ENUM_VALID(SysClkModule, sysclkModule); - } - - return (PcvModule)0; -} - -PcvModuleId Board::GetPcvModuleId(SysClkModule sysclkModule) -{ - PcvModuleId pcvModuleId; - Result rc = pcvGetModuleId(&pcvModuleId, GetPcvModule(sysclkModule)); - ASSERT_RESULT_OK(rc, "pcvGetModuleId"); - - return pcvModuleId; -} - -void CheckCore(void *idletickPtr) { - u64* idletick = static_cast(idletickPtr); - while(true) { - u64 idletickA; - u64 idletickB; - svcGetInfo(&idletickB, InfoType_IdleTickCount, INVALID_HANDLE, -1); - svcWaitForAddress(&threadexit, ArbitrationType_WaitIfEqual, 0, CpuTimeOutNs); - svcGetInfo(&idletickA, InfoType_IdleTickCount, INVALID_HANDLE, -1); - *idletick = idletickA - idletickB; - } -} - -void gpuLoadThread(void*) { - #define gpu_samples_average 8 - uint32_t gpu_load_array[gpu_samples_average] = {0}; - size_t i = 0; - if (R_SUCCEEDED(nvCheck)) do { - u32 temp; - if (R_SUCCEEDED(nvIoctl(fd, NVGPU_GPU_IOCTL_PMU_GET_GPU_LOAD, &temp))) { - gpu_load_array[i++ % gpu_samples_average] = temp; - GPU_Load_u = std::accumulate(&gpu_load_array[0], &gpu_load_array[gpu_samples_average], 0) / gpu_samples_average; - } - svcSleepThread(16'666'000); // wait a bit (this is the perfect amount of time to keep the reading accurate) - } while(true); -} - -void miscThreadFunc(void*) { - for(;;) { - if (R_SUCCEEDED(pwmCheck)) { - if (R_SUCCEEDED(pwmChannelSessionGetDutyCycle(&g_ICon, &temp))) { - temp *= 10; - temp = trunc(temp); - temp /= 10; - Rotation_Duty = 100.0 - temp; - } - } - fanLevel = (u8)Rotation_Duty; - svcSleepThread(300'000'000); - } -} - -void Board::Initialize() -{ - Result rc = 0; - if(HOSSVC_HAS_CLKRST) - { - rc = clkrstInitialize(); - ASSERT_RESULT_OK(rc, "clkrstInitialize"); - } - else - { - rc = pcvInitialize(); - ASSERT_RESULT_OK(rc, "pcvInitialize"); - } - - rc = apmExtInitialize(); - ASSERT_RESULT_OK(rc, "apmExtInitialize"); - - rc = psmInitialize(); - ASSERT_RESULT_OK(rc, "psmInitialize"); - - if(HOSSVC_HAS_TC) - { - rc = tcInitialize(); - ASSERT_RESULT_OK(rc, "tcInitialize"); - } - - rc = max17050Initialize(); - ASSERT_RESULT_OK(rc, "max17050Initialize"); - - rc = tmp451Initialize(); - ASSERT_RESULT_OK(rc, "tmp451Initialize"); - nvInitialize_rc = nvInitialize(); - if (R_SUCCEEDED(nvInitialize_rc)) { - nvCheck = nvOpen(&fd, "/dev/nvhost-ctrl-gpu"); - nvCheck_sched = nvOpen(&fd2, "/dev/nvsched-ctrl"); - } - - rc = rgltrInitialize(); - ASSERT_RESULT_OK(rc, "rgltrInitialize"); - - // if (R_SUCCEEDED(fanInitialize())) { - // if (hosversionAtLeast(7,0,0)) fanCheck = fanOpenController(&fanController, 0x3D000001); - // else fanCheck = fanOpenController(&fanController, 1); - // } - - rc = pmdmntInitialize(); - ASSERT_RESULT_OK(rc, "pmdmntInitialize"); - - threadCreate(&gpuLThread, gpuLoadThread, NULL, NULL, 0x1000, 0x3F, -2); - threadStart(&gpuLThread); - leventClear(&threadexit); - threadCreate(&cpuCore0Thread, CheckCore, &idletick0, NULL, 0x1000, 0x10, 0); - threadCreate(&cpuCore1Thread, CheckCore, &idletick1, NULL, 0x1000, 0x10, 1); - threadCreate(&cpuCore2Thread, CheckCore, &idletick2, NULL, 0x1000, 0x10, 2); - // threadCreate(&cpuCore3Thread, CheckCore, &idletick3, NULL, 0x1000, 0x10, 3); - threadCreate(&miscThread, miscThreadFunc, NULL, NULL, 0x1000, 0x10, 3); - - threadStart(&cpuCore0Thread); - threadStart(&cpuCore1Thread); - threadStart(&cpuCore2Thread); - // threadStart(&cpuCore3Thread); - threadStart(&miscThread); - batteryInfoInitialize(); - FetchHardwareInfos(); - - if (hosversionAtLeast(6,0,0) && R_SUCCEEDED(pwmInitialize())) { - pwmCheck = pwmOpenSession2(&g_ICon, 0x3D000001); - } - - struct stat st = {0}; - isRetro = (stat("sdmc:/" FILE_CONFIG_DIR "/retro.flag", &st) == 0); - - u64 clkVirtAddr, dsiVirtAddr, outsize; - rc = svcQueryMemoryMapping(&clkVirtAddr, &outsize, 0x60006000, 0x1000); - ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping (clk)"); - rc = svcQueryMemoryMapping(&dsiVirtAddr, &outsize, 0x54300000, 0x40000); - ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping (dsi)"); - - DisplayRefreshConfig cfg = {.clkVirtAddr = clkVirtAddr, .dsiVirtAddr = dsiVirtAddr, .isLite = IsHoag(), .isRetroSUPER = isRetro, .isPossiblySpoofedRetro = isRetro}; - - DisplayRefresh_Initialize(&cfg); - - rc = svcQueryMemoryMapping(&cldvfs, &cldvfs_temp, CLDVFS_REGION_BASE, CLDVFS_REGION_SIZE); - ASSERT_RESULT_OK(rc, "svcQueryMemoryMapping (cldvfs)"); - - if(Board::GetSocType() == SysClkSocType_Erista) { - cachedEristaUvLowTune0 = *(u32*)(cldvfs + CL_DVFS_TUNE0_0); - cachedEristaUvLowTune1 = *(u32*)(cldvfs + CL_DVFS_TUNE1_0); - } else { - Board::SetHz(SysClkModule_CPU, 1785000000); - cachedMarikoUvHighTune0 = *(u32*)(cldvfs + CL_DVFS_TUNE0_0); - Board::ResetToStockCpu(); - } - - -} - -bool Board::IsUsingRetroSuperDisplay() { - return isRetro; -} - -void Board::GetWaferPosition(u16* x, u16* y) { - *x = BwaferX; - *y = BwaferY; -} - -void Board::fuseReadSpeedos() { - - u64 pid = 0; - if (R_FAILED(pmdmntGetProcessId(&pid, 0x0100000000000006))) { - return; - } - - Handle debug; - if (R_FAILED(svcDebugActiveProcess(&debug, pid))) { - return; - } - - MemoryInfo mem_info = {0}; - u32 pageinfo = 0; - u64 addr = 0; - - char stack[0x10] = {0}; - const char compare[0x10] = {0}; - char dump[0x400] = {0}; - - while (true) { - if (R_FAILED(svcQueryDebugProcessMemory(&mem_info, &pageinfo, debug, addr)) || mem_info.addr < addr) { - break; - } - - if (mem_info.type == MemType_Io && mem_info.size == 0x1000) { - if (R_FAILED(svcReadDebugProcessMemory(stack, debug, mem_info.addr, sizeof(stack)))) { - break; - } - - if (memcmp(stack, compare, sizeof(stack)) == 0) { - if (R_FAILED(svcReadDebugProcessMemory(dump, debug, mem_info.addr + 0x800, sizeof(dump)))) { - break; - } - - cpuSpeedo0 = *reinterpret_cast(dump + FUSE_CPU_SPEEDO_0_CALIB); - cpuSpeedo2 = *reinterpret_cast(dump + FUSE_CPU_SPEEDO_2_CALIB); - socSpeedo0 = *reinterpret_cast(dump + FUSE_SOC_SPEEDO_0_CALIB); - cpuIDDQ = *reinterpret_cast(dump + FUSE_CPU_IDDQ_CALIB) * 4; - gpuIDDQ = *reinterpret_cast(dump + FUSE_GPU_IDDQ_CALIB) * 5; - socIDDQ = *reinterpret_cast(dump + FUSE_SOC_IDDQ_CALIB) * 4; - BwaferX = *reinterpret_cast(dump + FUSE_OPT_X_COORDINATE); - BwaferY = *reinterpret_cast(dump + FUSE_OPT_Y_COORDINATE); - - svcCloseHandle(debug); - return; - } - } - - addr = mem_info.addr + mem_info.size; - } - - svcCloseHandle(debug); -} - -u16 Board::getSpeedo(HorizonOCSpeedo speedoType) { - switch(speedoType) { - case HorizonOCSpeedo_CPU: - return cpuSpeedo0; - case HorizonOCSpeedo_GPU: - return cpuSpeedo2; - case HorizonOCSpeedo_SOC: - return socSpeedo0; - default: - ASSERT_ENUM_VALID(HorizonOCSpeedo, speedoType); - return 0; - } -} - -u16 Board::getIDDQ(HorizonOCSpeedo speedoType) { - switch(speedoType) { - case HorizonOCSpeedo_CPU: - return cpuIDDQ; - case HorizonOCSpeedo_GPU: - return gpuIDDQ; - case HorizonOCSpeedo_SOC: - return socIDDQ; - default: - ASSERT_ENUM_VALID(HorizonOCSpeedo, speedoType); - return 0; - } -} - - -void Board::Exit() -{ - if(HOSSVC_HAS_CLKRST) - { - clkrstExit(); - } - else - { - pcvExit(); - } - - apmExtExit(); - psmExit(); - - if(HOSSVC_HAS_TC) - { - tcExit(); - } - - max17050Exit(); - tmp451Exit(); - - threadClose(&gpuLThread); - threadClose(&cpuCore0Thread); - threadClose(&cpuCore1Thread); - threadClose(&cpuCore2Thread); - // threadClose(&cpuCore3Thread); - threadClose(&miscThread); - - DisplayRefresh_Shutdown(); - - pwmChannelSessionClose(&g_ICon); - pwmExit(); - rgltrExit(); - batteryInfoExit(); - pmdmntExit(); - nvExit(); - -} - -SysClkProfile Board::GetProfile() -{ - std::uint32_t mode = 0; - Result rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - if(mode) - { - return SysClkProfile_Docked; - } - - PsmChargerType chargerType; - - rc = psmGetChargerType(&chargerType); - ASSERT_RESULT_OK(rc, "psmGetChargerType"); - - if(chargerType == PsmChargerType_EnoughPower) - { - return SysClkProfile_HandheldChargingOfficial; - } - else if(chargerType == PsmChargerType_LowPower) - { - return SysClkProfile_HandheldChargingUSB; - } - - return SysClkProfile_Handheld; -} - -void Board::SetHz(SysClkModule module, std::uint32_t hz) -{ - Result rc = 0; - if(module == HorizonOCModule_Display) { - DisplayRefresh_SetRate(hz); - return; - } - if(module > SysClkModule_MEM) - return; - if(HOSSVC_HAS_CLKRST) - { - ClkrstSession session = {0}; - - rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); - ASSERT_RESULT_OK(rc, "clkrstOpenSession"); - rc = clkrstSetClockRate(&session, hz); - ASSERT_RESULT_OK(rc, "clkrstSetClockRate"); - if (module == SysClkModule_CPU) { - svcSleepThread(250'000); - rc = clkrstSetClockRate(&session, hz); - ASSERT_RESULT_OK(rc, "clkrstSetClockRate"); - } - clkrstCloseSession(&session); - } - else - { - rc = pcvSetClockRate(Board::GetPcvModule(module), hz); - ASSERT_RESULT_OK(rc, "pcvSetClockRate"); - if (module == SysClkModule_CPU) { - svcSleepThread(250'000); - rc = pcvSetClockRate(Board::GetPcvModule(module), hz); - ASSERT_RESULT_OK(rc, "pcvSetClockRate"); - } - } -} - -std::uint32_t Board::GetHz(SysClkModule module) -{ - Result rc = 0; - std::uint32_t hz = 0; - - if(module == HorizonOCModule_Display) { - DisplayRefresh_GetRate(&hz, false); - return hz; - } - - if(HOSSVC_HAS_CLKRST) - { - ClkrstSession session = {0}; - - rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); - ASSERT_RESULT_OK(rc, "clkrstOpenSession"); - - rc = clkrstGetClockRate(&session, &hz); - ASSERT_RESULT_OK(rc, "clkrstGetClockRate"); - - clkrstCloseSession(&session); - } - else - { - rc = pcvGetClockRate(Board::GetPcvModule(module), &hz); - ASSERT_RESULT_OK(rc, "pcvGetClockRate"); - } - - return hz; -} - -std::uint32_t Board::GetRealHz(SysClkModule module) -{ - u32 hz = 0; - switch(module) - { - case SysClkModule_CPU: - return t210ClkCpuFreq(); - case SysClkModule_GPU: - return t210ClkGpuFreq(); - case SysClkModule_MEM: - return t210ClkMemFreq(); - case HorizonOCModule_Display: - DisplayRefresh_GetRate(&hz, false); - return hz; - default: - ASSERT_ENUM_VALID(SysClkModule, module); - } - - return 0; -} - -void Board::GetFreqList(SysClkModule module, std::uint32_t* outList, std::uint32_t maxCount, std::uint32_t* outCount) -{ - Result rc = 0; - PcvClockRatesListType type; - s32 tmpInMaxCount = maxCount; - s32 tmpOutCount = 0; - - - - if(HOSSVC_HAS_CLKRST) - { - ClkrstSession session = {0}; - - rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); - ASSERT_RESULT_OK(rc, "clkrstOpenSession"); - - rc = clkrstGetPossibleClockRates(&session, outList, tmpInMaxCount, &type, &tmpOutCount); - ASSERT_RESULT_OK(rc, "clkrstGetPossibleClockRates"); - - clkrstCloseSession(&session); - } - else - { - rc = pcvGetPossibleClockRates(Board::GetPcvModule(module), outList, tmpInMaxCount, &type, &tmpOutCount); - ASSERT_RESULT_OK(rc, "pcvGetPossibleClockRates"); - } - - if(type != PcvClockRatesListType_Discrete) - { - ERROR_THROW("Unexpected PcvClockRatesListType: %u (module = %s)", type, Board::GetModuleName(module, false)); - } - - *outCount = tmpOutCount; -} - -void Board::ResetToStock() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_CPU, apmConfiguration->cpu_hz); - Board::SetHz(SysClkModule_GPU, apmConfiguration->gpu_hz); - Board::SetHz(SysClkModule_MEM, apmConfiguration->mem_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockCpu() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_CPU, apmConfiguration->cpu_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockMem() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_MEM, apmConfiguration->mem_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockGpu() -{ - Result rc = 0; - if(hosversionAtLeast(9,0,0)) - { - std::uint32_t confId = 0; - rc = apmExtGetCurrentPerformanceConfiguration(&confId); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - SysClkApmConfiguration* apmConfiguration = NULL; - for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) - { - if(sysclk_g_apm_configurations[i].id == confId) - { - apmConfiguration = &sysclk_g_apm_configurations[i]; - break; - } - } - - if(!apmConfiguration) - { - ERROR_THROW("Unknown apm configuration: %x", confId); - } - - Board::SetHz(SysClkModule_GPU, apmConfiguration->gpu_hz); - } - else - { - std::uint32_t mode = 0; - rc = apmExtGetPerformanceMode(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); - - rc = apmExtSysRequestPerformanceMode(mode); - ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); - } -} - -void Board::ResetToStockDisplay() { - DisplayRefresh_SetRate(60); -} - -u8 Board::GetHighestDockedDisplayRate() { - if(Board::GetConsoleType() != HorizonOCConsoleType_Hoag) { - return DisplayRefresh_GetDockedHighestAllowed(); - } else - return 60; -} - -std::uint32_t Board::GetTemperatureMilli(SysClkThermalSensor sensor) -{ - std::int32_t millis = 0; - - if(sensor == SysClkThermalSensor_SOC) - { - millis = tmp451TempSoc(); - } - else if(sensor == SysClkThermalSensor_PCB) - { - millis = tmp451TempPcb(); - } - else if(sensor == SysClkThermalSensor_Skin) - { - if(HOSSVC_HAS_TC) - { - Result rc; - rc = tcGetSkinTemperatureMilliC(&millis); - ASSERT_RESULT_OK(rc, "tcGetSkinTemperatureMilliC"); - } - } - else if (sensor == HorizonOCThermalSensor_Battery) { - batteryInfoGetChargeInfo(&info); - millis = batteryInfoGetTemperatureMiliCelsius(&info); - } - else if (sensor == HorizonOCThermalSensor_PMIC) { - millis = 50000; - } - else - { - ASSERT_ENUM_VALID(SysClkThermalSensor, sensor); - } - - return std::max(0, millis); -} - -std::int32_t Board::GetPowerMw(SysClkPowerSensor sensor) -{ - switch(sensor) - { - case SysClkPowerSensor_Now: - return max17050PowerNow(); - case SysClkPowerSensor_Avg: - return max17050PowerAvg(); - default: - ASSERT_ENUM_VALID(SysClkPowerSensor, sensor); - } - - return 0; -} - -u32 GetMaxCpuLoad() { - float cpuUsage0 = std::clamp(((Systemtickfrequency - idletick0) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - float cpuUsage1 = std::clamp(((Systemtickfrequency - idletick1) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - float cpuUsage2 = std::clamp(((Systemtickfrequency - idletick2) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - // float cpuUsage3 = std::clamp(((Systemtickfrequency - idletick3) / static_cast(Systemtickfrequency)) * 1000.0, 0.0, 1000.0); - - return std::round(std::max({cpuUsage0, cpuUsage1, cpuUsage2})); -} - -std::uint32_t Board::GetPartLoad(SysClkPartLoad loadSource) -{ - switch(loadSource) - { - case SysClkPartLoad_EMC: - return t210EmcLoadAll(); - case SysClkPartLoad_EMCCpu: - return t210EmcLoadCpu(); - case HocClkPartLoad_GPU: - return GPU_Load_u; - case HocClkPartLoad_CPUMax: - return GetMaxCpuLoad(); - case HocClkPartLoad_BAT: - batteryInfoGetChargeInfo(&info); - return info.RawBatteryCharge; - case HocClkPartLoad_FAN: - return fanLevel; - default: - ASSERT_ENUM_VALID(SysClkPartLoad, loadSource); - } - - return 0; -} - - -SysClkSocType Board::GetSocType() { - return g_socType; -} - -HorizonOCConsoleType Board::GetConsoleType() { - return g_consoleType; -} - -u8 Board::GetDramID() { - return g_dramID; -} - -void Board::FetchHardwareInfos() -{ - fuseReadSpeedos(); - SetSpeedoBracket(); - u64 sku = 0, dramID = 0; - Result rc = splInitialize(); - ASSERT_RESULT_OK(rc, "splInitialize"); - - rc = splGetConfig(SplConfigItem_HardwareType, &sku); - ASSERT_RESULT_OK(rc, "splGetConfig"); - - rc = splGetConfig(SplConfigItem_DramId, &dramID); - ASSERT_RESULT_OK(rc, "splGetConfig"); - - splExit(); - - switch(sku) - { - case 2: - case 3: - case 4: - case 5: - g_socType = SysClkSocType_Mariko; - break; - default: - g_socType = SysClkSocType_Erista; - } - - if (g_socType == SysClkSocType_Mariko) { - CacheDvfsTable(); - } - - g_consoleType = (HorizonOCConsoleType)sku; - g_dramID = (u8)dramID; -} - -/* -* Switch Power domains (max77620): -* Name | Usage | uV step | uV min | uV default | uV max | Init -*-------+---------------+---------+--------+------------+---------+------------------ -* sd0 | SoC | 12500 | 600000 | 625000 | 1400000 | 1.125V (pkg1.1) -* sd1 | SDRAM | 12500 | 600000 | 1125000 | 1125000 | 1.1V (pkg1.1) -* sd2 | ldo{0-1, 7-8} | 12500 | 600000 | 1325000 | 1350000 | 1.325V (pcv) -* sd3 | 1.8V general | 12500 | 600000 | 1800000 | 1800000 | -* ldo0 | Display Panel | 25000 | 800000 | 1200000 | 1200000 | 1.2V (pkg1.1) -* ldo1 | XUSB, PCIE | 25000 | 800000 | 1050000 | 1050000 | 1.05V (pcv) -* ldo2 | SDMMC1 | 50000 | 800000 | 1800000 | 3300000 | -* ldo3 | GC ASIC | 50000 | 800000 | 3100000 | 3100000 | 3.1V (pcv) -* ldo4 | RTC | 12500 | 800000 | 850000 | 850000 | 0.85V (AO, pcv) -* ldo5 | GC Card | 50000 | 800000 | 1800000 | 1800000 | 1.8V (pcv) -* ldo6 | Touch, ALS | 50000 | 800000 | 2900000 | 2900000 | 2.9V (pcv) -* ldo7 | XUSB | 50000 | 800000 | 1050000 | 1050000 | 1.05V (pcv) -* ldo8 | XUSB, DP, MCU | 50000 | 800000 | 1050000 | 2800000 | 1.05V/2.8V (pcv) - -typedef enum { - PcvPowerDomainId_Max77620_Sd0 = 0x3A000080, - PcvPowerDomainId_Max77620_Sd1 = 0x3A000081, // vdd2 - PcvPowerDomainId_Max77620_Sd2 = 0x3A000082, - PcvPowerDomainId_Max77620_Sd3 = 0x3A000083, - PcvPowerDomainId_Max77620_Ldo0 = 0x3A0000A0, - PcvPowerDomainId_Max77620_Ldo1 = 0x3A0000A1, - PcvPowerDomainId_Max77620_Ldo2 = 0x3A0000A2, - PcvPowerDomainId_Max77620_Ldo3 = 0x3A0000A3, - PcvPowerDomainId_Max77620_Ldo4 = 0x3A0000A4, - PcvPowerDomainId_Max77620_Ldo5 = 0x3A0000A5, - PcvPowerDomainId_Max77620_Ldo6 = 0x3A0000A6, - PcvPowerDomainId_Max77620_Ldo7 = 0x3A0000A7, - PcvPowerDomainId_Max77620_Ldo8 = 0x3A0000A8, - PcvPowerDomainId_Max77621_Cpu = 0x3A000003, - PcvPowerDomainId_Max77621_Gpu = 0x3A000004, - PcvPowerDomainId_Max77812_Cpu = 0x3A000003, - PcvPowerDomainId_Max77812_Gpu = 0x3A000004, - PcvPowerDomainId_Max77812_Dram = 0x3A000005, // vddq -} PowerDomainId; - -*/ - -std::uint32_t Board::GetVoltage(HocClkVoltage voltage) -{ - RgltrSession session; - Result rc = 0; - u32 out = 0; - switch(voltage) - { - case HocClkVoltage_SOC: - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77620_Sd0); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_EMCVDD2: - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77620_Sd1); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_CPU: - if(Board::GetSocType() == SysClkSocType_Mariko) - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77621_Cpu); - else - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77812_Cpu); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_GPU: - if(Board::GetSocType() == SysClkSocType_Mariko) - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77621_Gpu); - else - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77812_Gpu); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_EMCVDDQ_MarikoOnly: - if(Board::GetSocType() == SysClkSocType_Mariko) { - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77812_Dram); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - } else { - out = Board::GetVoltage(HocClkVoltage_EMCVDD2); - } - break; - case HocClkVoltage_Display: - rc = rgltrOpenSession(&session, PcvPowerDomainId_Max77620_Ldo0); - ASSERT_RESULT_OK(rc, "rgltrOpenSession") - rgltrGetVoltage(&session, &out); - rgltrCloseSession(&session); - break; - case HocClkVoltage_Battery: - batteryInfoGetChargeInfo(&info); - out = info.VoltageAvg; - break; - default: - ASSERT_ENUM_VALID(HocClkVoltage, voltage); - } - - return out > 0 ? out : 0; -} - -void Board::SetSpeedoBracket() { - if (cpuSpeedo2 >= 1754) { - speedoBracket = 3; - } else if (cpuSpeedo2 >= 1690) { - speedoBracket = 2; - } else if (cpuSpeedo2 > 1625) { - speedoBracket = 1; - } else { - speedoBracket = 0; - } -} - -u32 Board::GetMinimumGpuVoltage(u32 freqMhz) { - if (freqMhz <= 1600) - return 0; - - for (u32 voltageIndex = 0; voltageIndex < 22; ++voltageIndex) { - if (freqMhz <= ramBrackets[speedoBracket][voltageIndex]) { - return gpuDvfsArray[voltageIndex]; - } - } - - return 800; -} - -Handle Board::GetPcvHandle() { - constexpr u64 PcvID = 0x10000000000001a; - u64 processIDList[80]{}; - s32 processCount = 0; - Handle handle = INVALID_HANDLE; - - DebugEventInfo debugEvent{}; - - /* Get all running processes. */ - Result resultGetProcessList = svcGetProcessList(&processCount, processIDList, std::size(processIDList)); - if (R_FAILED(resultGetProcessList)) { - return INVALID_HANDLE; - } - - /* Try to find pcv. */ - for (int i = 0; i < processCount; ++i) { - if (handle != INVALID_HANDLE) { - svcCloseHandle(handle); - handle = INVALID_HANDLE; - } - - /* Try to debug process, if it fails, try next process. */ - Result resultSvcDebugProcess = svcDebugActiveProcess(&handle, processIDList[i]); - if (R_FAILED(resultSvcDebugProcess)) { - continue; - } - - /* Try to get a debug event. */ - Result resultDebugEvent = svcGetDebugEvent(&debugEvent, handle); - if (R_SUCCEEDED(resultDebugEvent)) { - if (debugEvent.info.create_process.program_id == PcvID) { - return handle; - } - } - } - - /* Failed to get handle. */ - return INVALID_HANDLE; -} - -void Board::CacheDvfsTable() { - const u32 voltagePattern[] = { 600000, 12500, 1400000, }; - - Handle handle = GetPcvHandle(); - if (handle == INVALID_HANDLE) { - FileUtils::LogLine("[Board] Invalid handle!"); - return; - } - - MemoryInfo memoryInfo = {}; - u64 address = 0; - u32 pageInfo = 0; - constexpr u32 PageSize = 0x1000; - u8 buffer[PageSize]; - - /* Loop until failure. */ - while (true) { - /* Find pcv heap. */ - while (true) { - Result resultProcessMemory = svcQueryDebugProcessMemory(&memoryInfo, &pageInfo, handle, address); - address = memoryInfo.addr + memoryInfo.size; - - if (R_FAILED(resultProcessMemory) || !address) { - svcCloseHandle(handle); - FileUtils::LogLine("[Board] Failed to get process data. %u", R_DESCRIPTION(resultProcessMemory)); - handle = INVALID_HANDLE; - return; - } - - if (memoryInfo.size && (memoryInfo.perm & 3) == 3 && static_cast(memoryInfo.type) == 0x04) { - /* Found valid memory. */ - break; - } - } - - for (u64 base = 0; base < memoryInfo.size; base += PageSize) { - u32 memorySize = std::min(memoryInfo.size, static_cast(PageSize)); - if (R_FAILED(svcReadDebugProcessMemory(buffer, handle, base + memoryInfo.addr, memorySize))) { - break; - } - - u8 *resultPattern = static_cast(memmem_impl(buffer, sizeof(buffer), voltagePattern, sizeof(voltagePattern))); - u32 index = resultPattern - buffer; - - if (!resultPattern) { - continue; - } - - /* Assuming mariko. */ - const u32 vmax = 800; - constexpr u32 DvfsTableOffset = 312; - if (!std::memcmp(&buffer[index + DvfsTableOffset], &vmax, sizeof(vmax))) { - std::memcpy(dvfsTable, &buffer[index + DvfsTableOffset], sizeof(dvfsTable)); - dvfsAddress = base + memoryInfo.addr + DvfsTableOffset + index; - } - - svcCloseHandle(handle); - handle = INVALID_HANDLE; - return; - } - } - - svcCloseHandle(handle); - handle = INVALID_HANDLE; - return; -} - -void Board::PcvHijackDvfs(u32 vmin) { - u32 table[192]; - static_assert(sizeof(table) == sizeof(dvfsTable)); - std::memcpy(table, dvfsTable, sizeof(dvfsTable)); - - if (ramVmin == vmin) { - return; - } - - for (u32 i = 0; i < std::size(table); ++i) { - if (table[i] && table[i] <= vmin) { - table[i] = vmin; - } - } - - Handle handle = GetPcvHandle(); - if (handle == INVALID_HANDLE) { - FileUtils::LogLine("Invalid handle!"); - return; - } - - Result rc = svcWriteDebugProcessMemory(handle, table, dvfsAddress, sizeof(table)); - - if (R_SUCCEEDED(rc)) { - ramVmin = vmin; - } - - svcCloseHandle(handle); - FileUtils::LogLine("[dvfs] voltage set to %u mV", vmin); -} - -bool Board::IsDram8GB() { - SecmonArgs args = {}; - args.X[0] = 0xF0000002; - args.X[1] = MC_REGISTER_BASE + MC_EMEM_CFG_0; - svcCallSecureMonitor(&args); - - if(args.X[1] == (MC_REGISTER_BASE + MC_EMEM_CFG_0)) { // if param 1 is identical read failed - writeNotification("Horizon OC\nSecmon read failed!\n This may be a hardware issue!"); - return false; - } else - return args.X[1] == 0x00002000 ? true : false; -} - -void Board::SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method) { - if (nvCheck_sched == 1 && method == GpuSchedulingOverrideMethod_NvService) { - return; - } - u32 temp; - bool enabled = false; - switch(mode) { - case GpuSchedulingMode_DoNotOverride: break; - case GpuSchedulingMode_Disabled: - if(method == GpuSchedulingOverrideMethod_NvService) - nvIoctl(fd2, NVSCHED_CTRL_DISABLE, &temp); - else - enabled = false; - break; - case GpuSchedulingMode_Enabled: - if(method == GpuSchedulingOverrideMethod_NvService) - nvIoctl(fd2, NVSCHED_CTRL_ENABLE, &temp); - else - enabled = true; - break; - default: - ASSERT_ENUM_VALID(GpuSchedulingMode, mode); - } - if(method == GpuSchedulingOverrideMethod_Ini) { - const char* ini_path = "sdmc:/atmosphere/config/system_settings.ini"; - const char* section = "am.gpu"; - const char* key = "gpu_scheduling_enabled"; - - const char* value = enabled ? "u8!0x1" : "u8!0x0"; - - ini_puts(section, key, value, ini_path); - } -} -void Board::SetDisplayRefreshDockedState(bool docked) { - if(Board::GetConsoleType() != HorizonOCConsoleType_Hoag) { - DisplayRefresh_SetDockedState(docked); - } -} - - -typedef struct EristaCpuUvEntry { - u32 tune0; - u32 tune1; -} EristaCpuUvEntry; -typedef struct MarikoCpuUvEntry { - u32 tune0_low; - u32 tune0_high; - u32 tune1_low; - u32 tune1_high; -} MarikoCpuUvEntry; - -EristaCpuUvEntry eristaCpuUvTable[5] = { - {0xffff, 0x27007ff}, - {0xefff, 0x27407ff}, - {0xdfff, 0x27807ff}, - {0xdfdf, 0x27a07ff}, - {0xcfdf, 0x37007ff}, -}; - -MarikoCpuUvEntry marikoCpuUvLow[12] = { - {0xffa0, 0xffff, 0x21107ff, 0}, - {0x0, 0xffdf, 0x21107ff, 0x27207ff}, - {0xffdf, 0xffdf, 0x21107ff, 0x27307ff}, - {0xffff, 0xffdf, 0x21107ff, 0x27407ff}, - {0x0, 0xffdf, 0x21607ff, 0x27707ff}, - {0x0, 0xffdf, 0x21607ff, 0x27807ff}, - {0x0, 0xdfff, 0x21607ff, 0x27b07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27b07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27c07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27d07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27e07ff}, - {0xdfff, 0xdfff, 0x21707ff, 0x27f07ff}, -}; - -MarikoCpuUvEntry marikoCpuUvHigh[12] = { - {0x0, 0xffff, 0, 0}, - {0x0, 0xffdf, 0, 0x27207ff}, - {0x0, 0xffdf, 0, 0x27307ff}, - {0x0, 0xffdf, 0, 0x27407ff}, - {0x0, 0xffdf, 0, 0x27707ff}, - {0x0, 0xffdf, 0, 0x27807ff}, - {0x0, 0xdfff, 0, 0x27b07ff}, - {0x0, 0xdfff, 0, 0x27c07ff}, - {0x0, 0xdfff, 0, 0x27d07ff}, - {0x0, 0xdfff, 0, 0x27e07ff}, - {0x0, 0xdfff, 0, 0x27f07ff}, - {0x0, 0xdfff, 0, 0x27f07ff}, -}; -void Board::SetCpuUvLevel(u32 levelLow, u32 levelHigh, u32 tbreakPoint) { - u32* tune0_ptr = (u32*)(cldvfs + CL_DVFS_TUNE0_0); - u32* tune1_ptr = (u32*)(cldvfs + CL_DVFS_TUNE1_0); - if(Board::GetSocType() == SysClkSocType_Mariko) { - if(Board::GetHz(SysClkModule_CPU) < tbreakPoint && (levelLow || levelHigh)) { - if(levelLow) { - *tune0_ptr = marikoCpuUvLow[levelLow-1].tune0_low; - *tune1_ptr = marikoCpuUvLow[levelLow-1].tune1_low; - } - return; - } else { - if(levelLow) { - *tune0_ptr = marikoCpuUvLow[levelLow-1].tune0_low; - *tune1_ptr = marikoCpuUvLow[levelLow-1].tune1_low; - } - if(levelHigh) { - *tune0_ptr = marikoCpuUvHigh[levelHigh-1].tune0_high; - *tune1_ptr = marikoCpuUvHigh[levelHigh-1].tune1_high; - } - return; - } - if(Board::GetHz(SysClkModule_CPU) < tbreakPoint || (!levelLow)) { // account for tbreak - *tune0_ptr = 0xCFFF; - *tune1_ptr = 0xFF072201; - return; - } else if (Board::GetHz(SysClkModule_CPU) >= tbreakPoint || (!levelHigh)) { - *tune0_ptr = cachedMarikoUvHighTune0; // per console? - *tune1_ptr = 0xFFF7FF3F; - return; - } - } else { - if(Board::GetHz(SysClkModule_CPU) < tbreakPoint || (!levelLow)) { // account for tbreak - *tune0_ptr = cachedEristaUvLowTune0; // I think each erista has a different tune0/tune1? - *tune1_ptr = cachedEristaUvLowTune1; - return; - } else { - if(levelLow) { - *tune0_ptr = eristaCpuUvTable[levelLow-1].tune0; - *tune1_ptr = eristaCpuUvTable[levelLow-1].tune1; - } else { - *tune0_ptr = 0x0; - *tune1_ptr = 0x0; - } - } - } -} -/* -enum TableConfig: u32 { - DEFAULT_TABLE = 1, - TBREAK_1581 = 2, - TBREAK_1683 = 3, - EXTREME_TABLE = 4, -}; -*/ -u32 Board::CalculateTbreak(u32 table) { - if(Board::GetSocType() == SysClkSocType_Erista) - return 1581000000; - else { - switch(table) { - case 1 ... 2: - case 4: - return 1581000000; - case 3: - return 1683000000; - default: - return 1581000000; - } - } - -} - -bool Board::IsHoag() { - return Board::GetConsoleType() == HorizonOCConsoleType_Hoag; -} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/board.h b/Source/sys-clk/sysmodule/src/board.h deleted file mode 100644 index d40e604a..00000000 --- a/Source/sys-clk/sysmodule/src/board.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once -#include -#include -#include - -class Board -{ - public: - static void PcvHijackDvfs(u32 vmin); - static u32 GetMinimumGpuVoltage(u32 freqMhz); - static void fuseReadSpeedos(); - static u16 getSpeedo(HorizonOCSpeedo speedoType); - static u16 getIDDQ(HorizonOCSpeedo speedoType); - static const char* GetProfileName(SysClkProfile profile, bool pretty); - static const char* GetModuleName(SysClkModule module, bool pretty); - static const char* GetThermalSensorName(SysClkThermalSensor sensor, bool pretty); - static const char* GetPowerSensorName(SysClkPowerSensor sensor, bool pretty); - static void Initialize(); - static void Exit(); - static void ResetToStock(); - static void ResetToStockCpu(); - static void ResetToStockMem(); - static void ResetToStockGpu(); - static void ResetToStockDisplay(); - static void GetWaferPosition(u16* x, u16* y); - static u8 GetHighestDockedDisplayRate(); - static SysClkProfile GetProfile(); - static void SetHz(SysClkModule module, std::uint32_t hz); - static std::uint32_t GetHz(SysClkModule module); - static std::uint32_t GetRealHz(SysClkModule module); - static void GetFreqList(SysClkModule module, std::uint32_t* outList, std::uint32_t maxCount, std::uint32_t* outCount); - static std::uint32_t GetTemperatureMilli(SysClkThermalSensor sensor); - static std::int32_t GetPowerMw(SysClkPowerSensor sensor); - static std::uint32_t GetPartLoad(SysClkPartLoad load); - static SysClkSocType GetSocType(); - static HorizonOCConsoleType GetConsoleType(); - static std::uint32_t GetVoltage(HocClkVoltage voltage); - static u8 GetFanRotationLevel(); - static u8 GetDramID(); - static bool IsDram8GB(); - static void SetGpuSchedulingMode(GpuSchedulingMode mode, GpuSchedulingOverrideMethod method); - static void SetDisplayRefreshDockedState(bool docked); - static void SetCpuUvLevel(u32 levelLow, u32 levelHigh, u32 tbreakPoint); - static u32 CalculateTbreak(u32 table); - static bool IsHoag(); - static bool IsUsingRetroSuperDisplay(); - protected: - static void FetchHardwareInfos(); - static PcvModule GetPcvModule(SysClkModule sysclkModule); - static PcvModuleId GetPcvModuleId(SysClkModule sysclkModule); - private: - static void SetSpeedoBracket(); - static void CacheDvfsTable(); - static Handle GetPcvHandle(); -}; diff --git a/Source/sys-clk/sysmodule/src/clock_manager.cpp b/Source/sys-clk/sysmodule/src/clock_manager.cpp deleted file mode 100644 index cd64da70..00000000 --- a/Source/sys-clk/sysmodule/src/clock_manager.cpp +++ /dev/null @@ -1,1307 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "clock_manager.h" -#include -#include "file_utils.h" -#include "board.h" -#include "process_management.h" -#include "errors.h" -#include "ipc_service.h" -#include "kip.h" -#include -#include "notification.h" -#include -#include -#include -#include - -#define HOSPPC_HAS_BOOST (hosversionAtLeast(7,0,0)) - -// governor constants -#define POLL_NS 5'000'000 // 5 ms – governor poll rate -#define DOWN_HOLD_TICKS 10 // 50 ms – how long to in POLL_NS to hold while ramping down -#define STEP_UTIL 900 // multiplier for step calculations - -bool isGpuGovernorEnabled = false; -bool isCpuGovernorEnabled = false; -bool lastGpuGovernorState = false; -bool lastCpuGovernorState = false; -bool lastVrrGovernorState = false; -bool hasChanged = true; -ClockManager *ClockManager::instance = NULL; -Thread cpuGovernorTHREAD; -Thread gpuGovernorTHREAD; -Thread vrrTHREAD; -u32 initialConfigValues[SysClkConfigValue_EnumMax]; // initial config. used for safety checks -bool kipAvailable = false; -bool isCpuGovernorInBoostMode = false; -bool isVRREnabled = false; - -ClockManager *ClockManager::GetInstance() -{ - return instance; -} - -void ClockManager::Exit() -{ - if (instance) - { - delete instance; - } -} - -void ClockManager::Initialize() -{ - if (!instance) - { - instance = new ClockManager(); - } -} - -ClockManager::ClockManager() -{ - this->config = Config::CreateDefault(); - this->context = new SysClkContext; - this->context->applicationId = 0; - this->context->profile = SysClkProfile_Handheld; - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - this->context->freqs[module] = 0; - this->context->realFreqs[module] = 0; - this->context->overrideFreqs[module] = 0; - this->RefreshFreqTableRow((SysClkModule)module); - } - - this->running = false; - this->lastTempLogNs = 0; - this->lastCsvWriteNs = 0; - - this->sysDockIntegration = new SysDockIntegration; - this->saltyNXIntegration = new SaltyNXIntegration; - - memset(&initialConfigValues, 0, sizeof(initialConfigValues)); - this->GetKipData(); - - threadCreate( - &cpuGovernorTHREAD, - ClockManager::CpuGovernorThread, - this, - NULL, - 0x2000, - 0x3F, - -2 - ); - - threadCreate( - &gpuGovernorTHREAD, - ClockManager::GovernorThread, - this, - NULL, - 0x2000, - 0x3F, - -2 - ); - - threadCreate( - &vrrTHREAD, - ClockManager::VRRThread, - this, - NULL, - 0x2000, - 0x3F, - -2 - ); - - for(int i = 0; i < HorizonOCSpeedo_EnumMax; i++) { - this->context->speedos[i] = Board::getSpeedo((HorizonOCSpeedo)i); - this->context->iddq[i] = Board::getIDDQ((HorizonOCSpeedo)i); - } - - this->context->dramID = Board::GetDramID(); - this->context->isDram8GB = Board::IsDram8GB(); - Board::SetGpuSchedulingMode((GpuSchedulingMode)this->config->GetConfigValue(HorizonOCConfigValue_GPUScheduling), (GpuSchedulingOverrideMethod)this->config->GetConfigValue(HorizonOCConfigValue_GPUSchedulingMethod)); - this->context->gpuSchedulingMode = (GpuSchedulingMode)this->config->GetConfigValue(HorizonOCConfigValue_GPUScheduling); - - this->context->isSysDockInstalled = this->sysDockIntegration->getCurrentSysDockState(); - this->context->isSaltyNXInstalled = this->saltyNXIntegration->getCurrentSaltyNXState(); - if(this->context->isSaltyNXInstalled) { - this->saltyNXIntegration->LoadSaltyNX(); - } - - this->context->isUsingRetroSuper = Board::IsUsingRetroSuperDisplay(); - Board::GetWaferPosition(&this->context->waferX, &this->context->waferY); - threadStart(&cpuGovernorTHREAD); - threadStart(&gpuGovernorTHREAD); - threadStart(&vrrTHREAD); -} - -ClockManager::~ClockManager() -{ - threadClose(&cpuGovernorTHREAD); - threadClose(&gpuGovernorTHREAD); - threadClose(&vrrTHREAD); - - delete this->sysDockIntegration; - delete this->saltyNXIntegration; - delete this->config; - delete this->context; -} - -SysClkContext ClockManager::GetCurrentContext() -{ - std::scoped_lock lock{this->contextMutex}; - return *this->context; -} - -Config *ClockManager::GetConfig() -{ - return this->config; -} - -void ClockManager::SetRunning(bool running) -{ - this->running = running; -} - -bool ClockManager::Running() -{ - return this->running; -} - -void ClockManager::GetFreqList(SysClkModule module, std::uint32_t *list, std::uint32_t maxCount, std::uint32_t *outCount) -{ - ASSERT_ENUM_VALID(SysClkModule, module); - - *outCount = std::min(maxCount, this->freqTable[module].count); - memcpy(list, &this->freqTable[module].list[0], *outCount * sizeof(this->freqTable[0].list[0])); -} - -bool ClockManager::IsAssignableHz(SysClkModule module, std::uint32_t hz) -{ - switch (module) - { - case SysClkModule_CPU: - return hz >= 500000000; - case SysClkModule_MEM: - return hz >= 665600000; - default: - return true; - } -} - -std::uint32_t ClockManager::GetMaxAllowedHz(SysClkModule module, SysClkProfile profile) -{ - if (this->config->GetConfigValue(HocClkConfigValue_UncappedClocks)) - { - return ~0; // Integer limit, uncapped clocks ON - } - else - { - if (module == SysClkModule_GPU) - { - if (profile < SysClkProfile_HandheldCharging) - { - switch(Board::GetSocType()) { - case SysClkSocType_Erista: - return 460800000; - case SysClkSocType_Mariko: - switch(this->config->GetConfigValue(KipConfigValue_marikoGpuUV)) { - case 0: - return 614400000; - case 1: - return 691200000; - case 2: - return 768000000; - default: - return 614400000; - } - default: - return 460800000; - } - } - else if (profile <= SysClkProfile_HandheldChargingUSB) - { - switch(Board::GetSocType()) { - case SysClkSocType_Erista: - return 768000000; - case SysClkSocType_Mariko: - switch(this->config->GetConfigValue(KipConfigValue_marikoGpuUV)) { - case 0: - return 844800000; - case 1: - return 921600000; - case 2: - return 998400000; - default: - return 844800000; - } - default: - return 768000000; - } - } - } else if(module == SysClkModule_CPU) { - if(profile < SysClkProfile_HandheldCharging && Board::GetSocType() == SysClkSocType_Erista) { - return 1581000000; - } else { - return ~0; - } - } - } - return 0; -} - -std::uint32_t ClockManager::GetNearestHz(SysClkModule module, std::uint32_t inHz, std::uint32_t maxHz) -{ - std::uint32_t *freqs = &this->freqTable[module].list[0]; - size_t count = this->freqTable[module].count - 1; - - size_t i = 0; - while (i < count) - { - if (maxHz > 0 && freqs[i] >= maxHz) - { - break; - } - - if (inHz <= ((std::uint64_t)freqs[i] + freqs[i + 1]) / 2) - { - break; - } - - i++; - } - - return freqs[i]; -} - -bool ClockManager::ConfigIntervalTimeout(SysClkConfigValue intervalMsConfigValue, std::uint64_t ns, std::uint64_t *lastLogNs) -{ - std::uint64_t logInterval = this->GetConfig()->GetConfigValue(intervalMsConfigValue) * 1000000ULL; - bool shouldLog = logInterval && ((ns - *lastLogNs) > logInterval); - - if (shouldLog) - { - *lastLogNs = ns; - } - - return shouldLog; -} - -void ClockManager::RefreshFreqTableRow(SysClkModule module) -{ - std::scoped_lock lock{this->contextMutex}; - - std::uint32_t freqs[SYSCLK_FREQ_LIST_MAX]; - std::uint32_t count; - - FileUtils::LogLine("[mgr] %s freq list refresh", Board::GetModuleName(module, true)); - Board::GetFreqList(module, &freqs[0], SYSCLK_FREQ_LIST_MAX, &count); - - std::uint32_t *hz = &this->freqTable[module].list[0]; - this->freqTable[module].count = 0; - for (std::uint32_t i = 0; i < count; i++) - { - if (!this->IsAssignableHz(module, freqs[i])) - { - continue; - } - - *hz = freqs[i]; - FileUtils::LogLine("[mgr] %02u - %u - %u.%u MHz", this->freqTable[module].count, *hz, *hz / 1000000, *hz / 100000 - *hz / 1000000 * 10); - - this->freqTable[module].count++; - hz++; - } - - FileUtils::LogLine("[mgr] count = %u", this->freqTable[module].count); -} - -u32 ClockManager::SchedutilTargetHz(u32 util, u32 tableMaxHz) { - u64 hz = (u64)tableMaxHz * util / STEP_UTIL; - return (u32)(std::min(hz, static_cast(tableMaxHz))); -} - -u32 ClockManager::TableIndexForHz(const FreqTable& table, u32 targetHz) { // must pass in a freqTable as tables are different for cpu/gpu - for (u32 i = 0; i < table.count; i++) - if (table.list[i] >= targetHz) - return i; - return table.count - 1; -} - -u32 ClockManager::ResolveTargetHz(ClockManager* mgr, SysClkModule module) { - u32 hz = mgr->context->overrideFreqs[module]; - if (!hz) - hz = mgr->config->GetAutoClockHz( - mgr->context->applicationId, module, - mgr->context->profile, false); - if (!hz) - hz = mgr->config->GetAutoClockHz( - GLOBAL_PROFILE_ID, module, - mgr->context->profile, false); - return hz; -} - -void ClockManager::CpuGovernorThread(void* arg) { - ClockManager* mgr = static_cast(arg); - - u32 downHoldRemaining = 0; - u32 lastHz = 0; - u32 minHz = 612; - u32 tick = 0; - for (;;) { - if (!mgr->running || !isCpuGovernorEnabled) { - downHoldRemaining = 0; - lastHz = 0; - svcSleepThread(POLL_NS); - continue; - } - - u32 mode = 0; - Result rc = apmExtGetCurrentPerformanceConfiguration(&mode); - - if (R_SUCCEEDED(rc) && apmExtIsBoostMode(mode)) { - isCpuGovernorInBoostMode = true; - downHoldRemaining = 0; - lastHz = 0; - continue; // TODO: figure out a way to get boost clock easily and set it instead of just skipping the governor - } else if(!apmExtIsBoostMode(mode)) { - isCpuGovernorInBoostMode = false; - } - - auto& table = mgr->freqTable[SysClkModule_CPU]; - - if (table.count == 0) - continue; - - std::scoped_lock lock{mgr->contextMutex}; - - u32 cpuLoad = Board::GetPartLoad(HocClkPartLoad_CPUMax); - - u32 tableMaxHz = table.list[table.count - 1]; - u32 desiredHz = ClockManager::SchedutilTargetHz(cpuLoad, tableMaxHz); - u32 targetHz = ClockManager::ResolveTargetHz(mgr, SysClkModule_CPU); - u32 maxHz = mgr->GetMaxAllowedHz(SysClkModule_CPU, mgr->context->profile); - - if (targetHz && desiredHz > targetHz) - desiredHz = targetHz; - - if (maxHz && desiredHz > maxHz) - desiredHz = maxHz; - - u32 newHz = table.list[ClockManager::TableIndexForHz(table, desiredHz)]; - - // ramp up fast, go down slow - bool goingDown = (lastHz != 0) && (newHz < lastHz); - - if (!goingDown) - downHoldRemaining = 0; - else if (downHoldRemaining == 0) - downHoldRemaining = DOWN_HOLD_TICKS; - - if (downHoldRemaining > 0) - downHoldRemaining--; - - if(++tick > 50) { - minHz = mgr->config->GetConfigValue(HorizonOCConfigValue_CpuGovernorMinimumFreq); - tick = 0; - } - - if(newHz < minHz) - newHz = minHz; - - if ((!goingDown || (downHoldRemaining == 0)) && mgr->IsAssignableHz(SysClkModule_CPU, newHz)) { - Board::SetHz(SysClkModule_CPU, newHz); - mgr->context->freqs[SysClkModule_CPU] = newHz; - lastHz = newHz; - } - - svcSleepThread(POLL_NS); - } -} - -void ClockManager::GovernorThread(void* arg) { - ClockManager* mgr = static_cast(arg); - - u32 downHoldRemaining = 0; - u32 lastHz = 0; - - for (;;) { - if (!mgr->running || !isGpuGovernorEnabled) { - downHoldRemaining = 0; - lastHz = 0; - svcSleepThread(POLL_NS); - continue; - } - - auto& table = mgr->freqTable[SysClkModule_GPU]; - if (table.count == 0) - continue; - - std::scoped_lock lock{mgr->contextMutex}; - - u32 gpuLoad = Board::GetPartLoad(HocClkPartLoad_GPU); - u32 tableMaxHz = table.list[table.count - 1]; - u32 desiredHz = ClockManager::SchedutilTargetHz(gpuLoad, tableMaxHz); - u32 targetHz = ClockManager::ResolveTargetHz(mgr, SysClkModule_GPU); - u32 maxHz = mgr->GetMaxAllowedHz(SysClkModule_GPU, mgr->context->profile); - - if (targetHz && desiredHz > targetHz) - desiredHz = targetHz; - - if (maxHz && desiredHz > maxHz) - desiredHz = maxHz; - - u32 newHz = table.list[ClockManager::TableIndexForHz(table, desiredHz)]; - bool goingDown = (lastHz != 0) && (newHz < lastHz); - - if (!goingDown) - downHoldRemaining = 0; - else if (downHoldRemaining == 0) - downHoldRemaining = DOWN_HOLD_TICKS; - - if (downHoldRemaining > 0) - downHoldRemaining--; - - if ((!goingDown || (downHoldRemaining == 0)) && mgr->IsAssignableHz(SysClkModule_GPU, newHz)) { - Board::SetHz(SysClkModule_GPU, newHz); - mgr->context->freqs[SysClkModule_GPU] = newHz; - lastHz = newHz; - } - - svcSleepThread(POLL_NS); - } -} - -void ClockManager::VRRThread(void* arg) { - ClockManager* mgr = static_cast(arg); - u8 tick = 0; - for (;;) { - if (!mgr->running || mgr->context->profile == SysClkProfile_Docked || !isVRREnabled) { - svcSleepThread(POLL_NS); - continue; - } - - std::scoped_lock lock{mgr->contextMutex}; - - u8 fps; - - if(mgr->context->isSaltyNXInstalled) { - fps = mgr->saltyNXIntegration->GetFPS(); - } else { - svcSleepThread(~0ULL); // effectively disable the thread if SaltyNX isn't installed, as there's no point in it running - continue; - } - - - if(fps == 254) { - svcSleepThread(POLL_NS); - continue; - } - // if(appletGetFocusState() != AppletFocusState_InFocus) { - // Board::ResetToStockDisplay(); - // continue; - // } - - u32 targetHz = mgr->context->overrideFreqs[HorizonOCModule_Display]; - if (!targetHz) - { - targetHz = mgr->config->GetAutoClockHz(mgr->context->applicationId, HorizonOCModule_Display, mgr->context->profile, false); - if(!targetHz) - targetHz = mgr->config->GetAutoClockHz(GLOBAL_PROFILE_ID, HorizonOCModule_Display, mgr->context->profile, false); - } - - u8 maxDisplay; - if(targetHz) { - maxDisplay = targetHz; - } else { - maxDisplay = 60; // don't assume display stuff! - } - - u8 minDisplay = Board::GetConsoleType() == HorizonOCConsoleType_Aula ? 45 : 40; - if(maxDisplay == minDisplay) - continue; - - if(fps >= minDisplay && fps <= maxDisplay) { - Board::SetHz(HorizonOCModule_Display, fps); - mgr->context->freqs[HorizonOCModule_Display] = fps; - mgr->context->realFreqs[HorizonOCModule_Display] = fps; - } else { - for(u32 i = 0; i < 10; i++) { - u32 compareHz = fps * i; - if(compareHz >= minDisplay && compareHz <= maxDisplay) { - Board::SetHz(HorizonOCModule_Display, compareHz); - mgr->context->freqs[HorizonOCModule_Display] = compareHz; - mgr->context->realFreqs[HorizonOCModule_Display] = compareHz; - break; - } - } - } - - - if(++tick > 50) { - Board::SetHz(HorizonOCModule_Display, maxDisplay); - tick = 0; - svcSleepThread(50'000'000); - } - - svcSleepThread(POLL_NS); - } -} - -void ClockManager::HandleSafetyFeatures() { - if(this->config->GetConfigValue(HocClkConfigValue_HandheldTDP) && (this->context->profile != SysClkProfile_Docked)) { // Enable while charging as non-PD charger can cause lack of power - if(Board::GetConsoleType() == HorizonOCConsoleType_Hoag) { - if(Board::GetPowerMw(SysClkPowerSensor_Avg) < -(int)this->config->GetConfigValue(HocClkConfigValue_LiteTDPLimit)) { - ResetToStockClocks(); - return; - } - } else { - if(Board::GetPowerMw(SysClkPowerSensor_Avg) < -(int)this->config->GetConfigValue(HocClkConfigValue_HandheldTDPLimit)) { - ResetToStockClocks(); - return; - } - } - } - - if(((tmp451TempSoc() / 1000) > (int)this->config->GetConfigValue(HocClkConfigValue_ThermalThrottleThreshold)) && this->config->GetConfigValue(HocClkConfigValue_ThermalThrottle)) { - ResetToStockClocks(); - return; - } -} - -void ClockManager::HandleMiscFeatures() { - if(this->config->GetConfigValue(HorizonOCConfigValue_BatteryChargeCurrent)) { - I2c_Bq24193_SetFastChargeCurrentLimit(this->config->GetConfigValue(HorizonOCConfigValue_BatteryChargeCurrent)); - } -} - -void ClockManager::HandleGovernor(uint32_t targetHz) { - u32 tempTargetHz = this->context->overrideFreqs[HorizonOCModule_Governor]; - if (!tempTargetHz) - { - tempTargetHz = this->config->GetAutoClockHz(this->context->applicationId, HorizonOCModule_Governor, this->context->profile, true); - if (!tempTargetHz) - tempTargetHz = this->config->GetAutoClockHz(GLOBAL_PROFILE_ID, HorizonOCModule_Governor, this->context->profile, true); - } - - auto resolve = [](u8 app, u8 temp) -> u8 { - if (temp == ComponentGovernor_Disabled) return ComponentGovernor_Disabled; - if (temp != ComponentGovernor_DoNotOverride) return temp; - return app; - }; - - u8 effectiveCpu = resolve(GovernorStateCpu(targetHz), GovernorStateCpu(tempTargetHz)); - u8 effectiveGpu = resolve(GovernorStateGpu(targetHz), GovernorStateGpu(tempTargetHz)); - u8 effectiveVrr = resolve(GovernorStateVrr(targetHz), GovernorStateVrr(tempTargetHz)); - - bool newCpuGovernorState = (effectiveCpu == ComponentGovernor_Enabled); - bool newGpuGovernorState = (effectiveGpu == ComponentGovernor_Enabled); - bool newVrrGovernorState = (effectiveVrr == ComponentGovernor_Enabled); - - isCpuGovernorEnabled = newCpuGovernorState; - isGpuGovernorEnabled = newGpuGovernorState; - isVRREnabled = newVrrGovernorState; - - if(newCpuGovernorState == false && lastCpuGovernorState == true) { - svcSleepThread(100'000'000); // thread syncing. probably a cleaner way to do this but hey, it works! - Board::ResetToStockCpu(); - } - if(newGpuGovernorState == false && lastGpuGovernorState == true) { - svcSleepThread(100'000'000); - Board::ResetToStockGpu(); - } - if (newVrrGovernorState == false && lastVrrGovernorState == true) { - svcSleepThread(100'000'000); - Board::ResetToStockDisplay(); - } - if(newCpuGovernorState != lastCpuGovernorState || newGpuGovernorState != lastGpuGovernorState || newVrrGovernorState != lastVrrGovernorState) { - FileUtils::LogLine("[mgr] Governor state changed: CPU %s, GPU %s, VRR %s", newCpuGovernorState ? "enabled" : "disabled", newGpuGovernorState ? "enabled" : "disabled", newVrrGovernorState ? "enabled" : "disabled"); - lastCpuGovernorState = newCpuGovernorState; - lastGpuGovernorState = newGpuGovernorState; - lastVrrGovernorState = newVrrGovernorState; - } -} - -void ClockManager::DVFSBeforeSet(u32 targetHz) { - s32 dvfsOffset = this->config->GetConfigValue(HorizonOCConfigValue_DVFSOffset); - u32 vmin = Board::GetMinimumGpuVoltage(targetHz / 1000000) + dvfsOffset; - - Board::PcvHijackDvfs(vmin); - - /* Update the voltage. */ - if (I2c_BuckConverter_GetMvOut(&I2c_Mariko_GPU) < vmin) { - I2c_BuckConverter_SetMvOut(&I2c_Mariko_GPU, vmin); - } - - this->context->voltages[HocClkVoltage_GPU] = vmin * 1000; -} - -void ClockManager::DVFSAfterSet(u32 targetHz) { - s32 dvfsOffset = this->config->GetConfigValue(HorizonOCConfigValue_DVFSOffset); - dvfsOffset = std::max(dvfsOffset, -80); - u32 vmin = Board::GetMinimumGpuVoltage(targetHz / 1000000); - - if (vmin) { - vmin += dvfsOffset; - } - - u32 maxHz = this->GetMaxAllowedHz(SysClkModule_GPU, this->context->profile); - u32 nearestHz = this->GetNearestHz(SysClkModule_GPU, targetHz, maxHz); - Board::PcvHijackDvfs(vmin); - - if (targetHz) { - Board::SetHz(SysClkModule_GPU, ~0); - Board::SetHz(SysClkModule_GPU, nearestHz); - } else { - Board::SetHz(SysClkModule_GPU, ~0); - Board::ResetToStockGpu(); - } -} - -void ClockManager::HandleCpuUv() { - if(Board::GetSocType() == SysClkSocType_Erista) - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); - else - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), Board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); -} - -void ClockManager::DVFSReset() { - if (Board::GetSocType() == SysClkSocType_Mariko && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { - Board::PcvHijackDvfs(0); - - u32 targetHz = this->context->overrideFreqs[SysClkModule_GPU]; - if (!targetHz) { - targetHz = this->config->GetAutoClockHz(this->context->applicationId, SysClkModule_GPU, this->context->profile, false); - if(!targetHz) { - targetHz = this->config->GetAutoClockHz(GLOBAL_PROFILE_ID, SysClkModule_GPU, this->context->profile, false); - } - } - u32 maxHz = this->GetMaxAllowedHz(SysClkModule_GPU, this->context->profile); - u32 nearestHz = this->GetNearestHz(SysClkModule_GPU, targetHz, maxHz); - - Board::SetHz(SysClkModule_GPU, ~0); - if(targetHz) { - Board::SetHz(SysClkModule_GPU, nearestHz); - } else { - Board::ResetToStockGpu(); - } - } -} - -void ClockManager::HandleFreqReset(SysClkModule module, bool isBoost) { - switch (module) - { - case SysClkModule_CPU: - if(!(isBoost || (this->config->GetConfigValue(HocClkConfigValue_OverwriteBoostMode) && isBoost))) - Board::ResetToStockCpu(); - if(this->config->GetConfigValue(HorizonOCConfigValue_LiveCpuUv)) { - if(Board::GetSocType() == SysClkSocType_Erista) - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); - else - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), Board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); - } - - break; - case SysClkModule_GPU: - Board::ResetToStockGpu(); - break; - case SysClkModule_MEM: - Board::ResetToStockMem(); - DVFSReset(); - break; - case HorizonOCModule_Display: - if(this->config->GetConfigValue(HorizonOCConfigValue_OverwriteRefreshRate)) { - Board::ResetToStockDisplay(); - } - break; - default: - break; - } - -} - -void ClockManager::SetClocks(bool isBoost) { - std::uint32_t targetHz = 0; - std::uint32_t maxHz = 0; - std::uint32_t nearestHz = 0; - - if(isBoost && !this->config->GetConfigValue(HocClkConfigValue_OverwriteBoostMode)) { - u32 boostFreq = Board::GetHz(SysClkModule_CPU); - if (boostFreq / 1000000 > 1785) { - Board::SetHz(SysClkModule_CPU, boostFreq); - } - return; // Return if we are't overwriting boost mode - } - - bool returnRaw = false; // Return a value scaled to MHz instead of raw value - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - u32 oldHz = Board::GetHz((SysClkModule)module); // Get Old hz (used primarily for DVFS Logic) - - if(module > SysClkModule_MEM) - returnRaw = true; - else - returnRaw = false; - targetHz = this->context->overrideFreqs[module]; - if (!targetHz) - { - targetHz = this->config->GetAutoClockHz(this->context->applicationId, (SysClkModule)module, this->context->profile, returnRaw); - if(!targetHz) - targetHz = this->config->GetAutoClockHz(GLOBAL_PROFILE_ID, (SysClkModule)module, this->context->profile, returnRaw); - } - - if(module == HorizonOCModule_Governor) { - HandleGovernor(targetHz); - } - - bool noCPU = isCpuGovernorEnabled; - bool noGPU = isGpuGovernorEnabled; - bool noDisp = isVRREnabled; - if(noDisp && module == HorizonOCModule_Display) - continue; - - if(module == HorizonOCModule_Display && this->config->GetConfigValue(HorizonOCConfigValue_OverwriteRefreshRate) && !noDisp) { - if(targetHz) { - Board::SetHz(HorizonOCModule_Display, targetHz); - this->context->freqs[HorizonOCModule_Display] = targetHz; - this->context->realFreqs[HorizonOCModule_Display] = targetHz; - } else { - HandleFreqReset(HorizonOCModule_Display, isBoost); - } - - } - - // Skip GPU and CPU if governors handle them - if(module > SysClkModule_MEM) { - continue; - } - - - if(noCPU && module == SysClkModule_CPU) - continue; - if(noGPU && module == SysClkModule_GPU) - continue; - - if (targetHz) - { - maxHz = this->GetMaxAllowedHz((SysClkModule)module, this->context->profile); - nearestHz = this->GetNearestHz((SysClkModule)module, targetHz, maxHz); - - if (nearestHz != this->context->freqs[module]) { - FileUtils::LogLine( - "[mgr] %s clock set : %u.%u MHz (target = %u.%u MHz)", - Board::GetModuleName((SysClkModule)module, true), - nearestHz / 1000000, nearestHz / 100000 - nearestHz / 1000000 * 10, - targetHz / 1000000, targetHz / 100000 - targetHz / 1000000 * 10 - ); - - if(module == SysClkModule_MEM && Board::GetSocType() == SysClkSocType_Mariko && targetHz > oldHz && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { - DVFSBeforeSet(targetHz); - } - - Board::SetHz((SysClkModule)module, nearestHz); - this->context->freqs[module] = nearestHz; - - if(module == SysClkModule_CPU && (this->config->GetConfigValue(HorizonOCConfigValue_LiveCpuUv))) { - HandleCpuUv(); - } - - if(module == SysClkModule_MEM && Board::GetSocType() == SysClkSocType_Mariko && targetHz < oldHz && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { - DVFSAfterSet(targetHz); - } - } - } else { - HandleFreqReset((SysClkModule)module, isBoost); - } - } - -} - -void ClockManager::Tick() -{ - std::scoped_lock lock{this->contextMutex}; - std::uint32_t mode = 0; - Result rc = apmExtGetCurrentPerformanceConfiguration(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - bool isBoost = apmExtIsBoostMode(mode); - - HandleSafetyFeatures(); - - if (this->RefreshContext() || this->config->Refresh()) - { - HandleMiscFeatures(); - SetClocks(isBoost); - } -} - -void ClockManager::ResetToStockClocks() { - Board::ResetToStockCpu(); - if(this->config->GetConfigValue(HorizonOCConfigValue_LiveCpuUv)) - { - if(Board::GetSocType() == SysClkSocType_Erista) - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_eristaCpuUV), 0, 1581000000); - else - Board::SetCpuUvLevel(this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow), this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh), Board::CalculateTbreak(this->config->GetConfigValue(KipConfigValue_tableConf))); - } - - Board::ResetToStockGpu(); -} - -void ClockManager::WaitForNextTick() -{ - if(!(Board::GetHz(SysClkModule_MEM) < 665000000)) - svcSleepThread(this->GetConfig()->GetConfigValue(SysClkConfigValue_PollingIntervalMs) * 1000000ULL); - else - svcSleepThread(5000 * 1000000ULL); // 5 seconds in sleep mode -} - -bool ClockManager::RefreshContext() -{ - bool hasChanged = false; - - std::uint32_t mode = 0; - Result rc = apmExtGetCurrentPerformanceConfiguration(&mode); - ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); - - std::uint64_t applicationId = ProcessManagement::GetCurrentApplicationId(); - if (applicationId != this->context->applicationId) - { - FileUtils::LogLine("[mgr] TitleID change: %016lX", applicationId); - this->context->applicationId = applicationId; - hasChanged = true; - } - - SysClkProfile profile = Board::GetProfile(); - if (profile != this->context->profile) - { - FileUtils::LogLine("[mgr] Profile change: %s", Board::GetProfileName(profile, true)); - this->context->profile = profile; - hasChanged = true; - } - - // restore clocks to stock values on app or profile change - if (hasChanged) - { - Board::ResetToStock(); - if (Board::GetSocType() == SysClkSocType_Mariko && this->config->GetConfigValue(HorizonOCConfigValue_DVFSMode) == DVFSMode_Hijack) { - Board::PcvHijackDvfs(0); - Board::SetHz(SysClkModule_GPU, ~0); - Board::ResetToStockGpu(); - } - this->WaitForNextTick(); - } - - std::uint32_t hz = 0; - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - hz = Board::GetHz((SysClkModule)module); - if (hz != 0 && hz != this->context->freqs[module]) - { - FileUtils::LogLine("[mgr] %s clock change: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); - this->context->freqs[module] = hz; - hasChanged = true; - } - - hz = this->GetConfig()->GetOverrideHz((SysClkModule)module); - if (hz != this->context->overrideFreqs[module]) - { - if (hz) - { - FileUtils::LogLine("[mgr] %s override change: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); - } - this->context->overrideFreqs[module] = hz; - hasChanged = true; - } - } - - std::uint64_t ns = armTicksToNs(armGetSystemTick()); - - // temperatures do not and should not force a refresh, hasChanged untouched - std::uint32_t millis = 0; - bool shouldLogTemp = this->ConfigIntervalTimeout(SysClkConfigValue_TempLogIntervalMs, ns, &this->lastTempLogNs); - for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++) - { - millis = Board::GetTemperatureMilli((SysClkThermalSensor)sensor); - if (shouldLogTemp) - { - FileUtils::LogLine("[mgr] %s temp: %u.%u °C", Board::GetThermalSensorName((SysClkThermalSensor)sensor, true), millis / 1000, (millis - millis / 1000 * 1000) / 100); - } - this->context->temps[sensor] = millis; - } - - // power stats do not and should not force a refresh, hasChanged untouched - std::int32_t mw = 0; - bool shouldLogPower = this->ConfigIntervalTimeout(SysClkConfigValue_PowerLogIntervalMs, ns, &this->lastPowerLogNs); - for (unsigned int sensor = 0; sensor < SysClkPowerSensor_EnumMax; sensor++) - { - mw = Board::GetPowerMw((SysClkPowerSensor)sensor); - if (shouldLogPower) - { - FileUtils::LogLine("[mgr] Power %s: %d mW", Board::GetPowerSensorName((SysClkPowerSensor)sensor, false), mw); - } - this->context->power[sensor] = mw; - } - - // real freqs do not and should not force a refresh, hasChanged untouched - std::uint32_t realHz = 0; - bool shouldLogFreq = this->ConfigIntervalTimeout(SysClkConfigValue_FreqLogIntervalMs, ns, &this->lastFreqLogNs); - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - realHz = Board::GetRealHz((SysClkModule)module); - if (shouldLogFreq) - { - FileUtils::LogLine("[mgr] %s real freq: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), realHz / 1000000, realHz / 100000 - realHz / 1000000 * 10); - } - this->context->realFreqs[module] = realHz; - } - - // ram load do not and should not force a refresh, hasChanged untouched - for (unsigned int loadSource = 0; loadSource < SysClkPartLoad_EnumMax; loadSource++) - { - this->context->partLoad[loadSource] = Board::GetPartLoad((SysClkPartLoad)loadSource); - } - - for (unsigned int voltageSource = 0; voltageSource < HocClkVoltage_EnumMax; voltageSource++) - { - this->context->voltages[voltageSource] = Board::GetVoltage((HocClkVoltage)voltageSource); - } - - if (this->ConfigIntervalTimeout(SysClkConfigValue_CsvWriteIntervalMs, ns, &this->lastCsvWriteNs)) - { - FileUtils::WriteContextToCsv(this->context); - } - - // this->context->maxDisplayFreq = Board::GetHighestDockedDisplayRate(); - u32 targetHz = this->context->overrideFreqs[HorizonOCModule_Display]; - if (!targetHz) - { - targetHz = this->config->GetAutoClockHz(this->context->applicationId, HorizonOCModule_Display, this->context->profile, true); - if(!targetHz) - targetHz = this->config->GetAutoClockHz(GLOBAL_PROFILE_ID, HorizonOCModule_Display, this->context->profile, true); - } - - if(targetHz && this->context->realFreqs[HorizonOCModule_Display] > targetHz && this->context->profile != SysClkProfile_Docked) { - this->context->realFreqs[HorizonOCModule_Display] = targetHz; // clean up display real freqs, should probably be moved to the real freqs loop? - hasChanged = true; - } - - if(!Board::IsHoag()) - Board::SetDisplayRefreshDockedState(this->context->profile == SysClkProfile_Docked); - if(this->context->isSaltyNXInstalled) - this->context->fps = saltyNXIntegration->GetFPS(); - else - this->context->fps = 254; // N/A - - if(this->context->isSaltyNXInstalled) - this->context->resolutionHeight = saltyNXIntegration->GetResolutionHeight(); - else - this->context->resolutionHeight = 0; // N/A - - return hasChanged; -} - -void ClockManager::SetKipData() { - // TODO: figure out if this REALLY causes issues (i doubt it) - // if(Board::GetSocType() == SysClkSocType_Mariko) { - // if(R_FAILED(I2c_BuckConverter_SetMvOut(&I2c_Mariko_DRAM_VDDQ, this->config->GetConfigValue(KipConfigValue_marikoEmcVddqVolt) / 1000))) { - // FileUtils::LogLine("[clock_manager] Failed set i2c vddq"); - // writeNotification("Horizon OC\nFailed to write I2C\nwhile setting vddq"); - // } - // } - CustomizeTable table; - FILE* fp; - fp = fopen("sdmc:/atmosphere/kips/hoc.kip", "r"); - - if (fp == NULL) { - writeNotification("Horizon OC\nKip opening failed"); - kipAvailable = false; - return; - } else { - kipAvailable = true; - fclose(fp); - } - - if (!cust_read_and_cache("sdmc:/atmosphere/kips/hoc.kip", &table)) { - FileUtils::LogLine("[clock_manager] Failed to read KIP file"); - writeNotification("Horizon OC\nKip read failed"); - return; - } - - CUST_WRITE_FIELD_BATCH(&table, custRev, this->config->GetConfigValue(KipConfigValue_custRev)); - // CUST_WRITE_FIELD_BATCH(&table, mtcConf, this->config->GetConfigValue(KipConfigValue_mtcConf)); - CUST_WRITE_FIELD_BATCH(&table, hpMode, this->config->GetConfigValue(KipConfigValue_hpMode)); - - CUST_WRITE_FIELD_BATCH(&table, commonEmcMemVolt, this->config->GetConfigValue(KipConfigValue_commonEmcMemVolt)); - CUST_WRITE_FIELD_BATCH(&table, eristaEmcMaxClock, this->config->GetConfigValue(KipConfigValue_eristaEmcMaxClock)); - CUST_WRITE_FIELD_BATCH(&table, eristaEmcMaxClock1, this->config->GetConfigValue(KipConfigValue_eristaEmcMaxClock1)); - CUST_WRITE_FIELD_BATCH(&table, eristaEmcMaxClock2, this->config->GetConfigValue(KipConfigValue_eristaEmcMaxClock2)); - CUST_WRITE_FIELD_BATCH(&table, marikoEmcMaxClock, this->config->GetConfigValue(KipConfigValue_marikoEmcMaxClock)); - CUST_WRITE_FIELD_BATCH(&table, marikoEmcVddqVolt, this->config->GetConfigValue(KipConfigValue_marikoEmcVddqVolt)); - CUST_WRITE_FIELD_BATCH(&table, emcDvbShift, this->config->GetConfigValue(KipConfigValue_emcDvbShift)); - - CUST_WRITE_FIELD_BATCH(&table, t1_tRCD, this->config->GetConfigValue(KipConfigValue_t1_tRCD)); - CUST_WRITE_FIELD_BATCH(&table, t2_tRP, this->config->GetConfigValue(KipConfigValue_t2_tRP)); - CUST_WRITE_FIELD_BATCH(&table, t3_tRAS, this->config->GetConfigValue(KipConfigValue_t3_tRAS)); - CUST_WRITE_FIELD_BATCH(&table, t4_tRRD, this->config->GetConfigValue(KipConfigValue_t4_tRRD)); - CUST_WRITE_FIELD_BATCH(&table, t5_tRFC, this->config->GetConfigValue(KipConfigValue_t5_tRFC)); - CUST_WRITE_FIELD_BATCH(&table, t6_tRTW, this->config->GetConfigValue(KipConfigValue_t6_tRTW)); - CUST_WRITE_FIELD_BATCH(&table, t7_tWTR, this->config->GetConfigValue(KipConfigValue_t7_tWTR)); - CUST_WRITE_FIELD_BATCH(&table, t8_tREFI, this->config->GetConfigValue(KipConfigValue_t8_tREFI)); - CUST_WRITE_FIELD_BATCH(&table, mem_burst_read_latency, this->config->GetConfigValue(KipConfigValue_mem_burst_read_latency)); - CUST_WRITE_FIELD_BATCH(&table, mem_burst_write_latency, this->config->GetConfigValue(KipConfigValue_mem_burst_write_latency)); - CUST_WRITE_FIELD_BATCH(&table, eristaCpuUV, this->config->GetConfigValue(KipConfigValue_eristaCpuUV)); - CUST_WRITE_FIELD_BATCH(&table, eristaCpuVmin, this->config->GetConfigValue(KipConfigValue_eristaCpuVmin)); - CUST_WRITE_FIELD_BATCH(&table, eristaCpuMaxVolt, this->config->GetConfigValue(KipConfigValue_eristaCpuMaxVolt)); - CUST_WRITE_FIELD_BATCH(&table, eristaCpuUnlock, this->config->GetConfigValue(KipConfigValue_eristaCpuUnlock)); - - CUST_WRITE_FIELD_BATCH(&table, marikoCpuUVLow, this->config->GetConfigValue(KipConfigValue_marikoCpuUVLow)); - CUST_WRITE_FIELD_BATCH(&table, marikoCpuUVHigh, this->config->GetConfigValue(KipConfigValue_marikoCpuUVHigh)); - CUST_WRITE_FIELD_BATCH(&table, tableConf, this->config->GetConfigValue(KipConfigValue_tableConf)); - CUST_WRITE_FIELD_BATCH(&table, marikoCpuLowVmin, this->config->GetConfigValue(KipConfigValue_marikoCpuLowVmin)); - CUST_WRITE_FIELD_BATCH(&table, marikoCpuHighVmin, this->config->GetConfigValue(KipConfigValue_marikoCpuHighVmin)); - CUST_WRITE_FIELD_BATCH(&table, marikoCpuMaxVolt, this->config->GetConfigValue(KipConfigValue_marikoCpuMaxVolt)); - CUST_WRITE_FIELD_BATCH(&table, marikoCpuMaxClock, this->config->GetConfigValue(KipConfigValue_marikoCpuMaxClock)); - - CUST_WRITE_FIELD_BATCH(&table, eristaCpuBoostClock, this->config->GetConfigValue(KipConfigValue_eristaCpuBoostClock)); - CUST_WRITE_FIELD_BATCH(&table, marikoCpuBoostClock, this->config->GetConfigValue(KipConfigValue_marikoCpuBoostClock)); - - CUST_WRITE_FIELD_BATCH(&table, eristaGpuUV, this->config->GetConfigValue(KipConfigValue_eristaGpuUV)); - CUST_WRITE_FIELD_BATCH(&table, eristaGpuVmin, this->config->GetConfigValue(KipConfigValue_eristaGpuVmin)); - - CUST_WRITE_FIELD_BATCH(&table, marikoGpuUV, this->config->GetConfigValue(KipConfigValue_marikoGpuUV)); - CUST_WRITE_FIELD_BATCH(&table, marikoGpuVmin, this->config->GetConfigValue(KipConfigValue_marikoGpuVmin)); - CUST_WRITE_FIELD_BATCH(&table, marikoGpuVmax, this->config->GetConfigValue(KipConfigValue_marikoGpuVmax)); - - CUST_WRITE_FIELD_BATCH(&table, commonGpuVoltOffset, this->config->GetConfigValue(KipConfigValue_commonGpuVoltOffset)); - CUST_WRITE_FIELD_BATCH(&table, gpuSpeedo, this->config->GetConfigValue(KipConfigValue_gpuSpeedo)); - - for (int i = 0; i < 24; i++) { - table.marikoGpuVoltArray[i] = this->config->GetConfigValue((SysClkConfigValue)(KipConfigValue_g_volt_76800 + i)); - } - - for (int i = 0; i < 27; i++) { - table.eristaGpuVoltArray[i] = this->config->GetConfigValue((SysClkConfigValue)(KipConfigValue_g_volt_e_76800 + i)); - } - - CUST_WRITE_FIELD_BATCH(&table, t6_tRTW_fine_tune, this->config->GetConfigValue(KipConfigValue_t6_tRTW_fine_tune)); - CUST_WRITE_FIELD_BATCH(&table, t7_tWTR_fine_tune, this->config->GetConfigValue(KipConfigValue_t7_tWTR_fine_tune)); - - if (!cust_write_table("sdmc:/atmosphere/kips/hoc.kip", &table)) { - FileUtils::LogLine("[clock_manager] Failed to write KIP file"); - writeNotification("Horizon OC\nKip write failed"); - } - - SysClkConfigValueList configValues; - this->config->GetConfigValues(&configValues); - - configValues.values[KipCrc32] = (u64)checksum_file("sdmc:/atmosphere/kips/hoc.kip"); // write checksum - - if (this->config->SetConfigValues(&configValues, false)) { - FileUtils::LogLine("[clock_manager] Successfully loaded KIP data into config"); - } else { - FileUtils::LogLine("[clock_manager] Warning: Failed to set config values from KIP"); - writeNotification("Horizon OC\nKip config set failed"); - } -} - -// I know this is very hacky, but the config system in the sysmodule doesn't really support writing - -void ClockManager::GetKipData() { - FILE* fp; - if(this->config->Refresh()) { - - fp = fopen("sdmc:/atmosphere/kips/hoc.kip", "r"); - - if (fp == NULL) { - writeNotification("Horizon OC\nKip opening failed"); - kipAvailable = false; - return; - } else { - kipAvailable = true; - fclose(fp); - } - - - - SysClkConfigValueList configValues; - this->config->GetConfigValues(&configValues); - - CustomizeTable table; - - if (!cust_read_and_cache("sdmc:/atmosphere/kips/hoc.kip", &table)) { - FileUtils::LogLine("[clock_manager] Failed to read KIP file for GetKipData"); - writeNotification("Horizon OC\nKip read failed"); - return; - } - - if((u64)checksum_file("sdmc:/atmosphere/kips/hoc.kip") != this->config->GetConfigValue(KipCrc32) && !this->config->GetConfigValue(HocClkConfigValue_IsFirstLoad)) { - SetKipData(); - writeNotification("Horizon OC\nKIP has been updated"); - writeNotification("Horizon OC\nPlease reboot your console"); - writeNotification("Horizon OC\nto complete the update"); - return; - } - if(this->config->GetConfigValue(HocClkConfigValue_IsFirstLoad) == true) { - configValues.values[HocClkConfigValue_IsFirstLoad] = (u64)false; - writeNotification("Horizon OC has been installed"); - } - static bool writeBootConfigValues = true; - - configValues.values[KipCrc32] = (u64)checksum_file("sdmc:/atmosphere/kips/hoc.kip"); // write checksum - - - if(writeBootConfigValues) { - writeBootConfigValues = false; - - // initialConfigValues[KipConfigValue_mtcConf] = cust_get_mtc_conf(&table); - initialConfigValues[KipConfigValue_hpMode] = cust_get_hp_mode(&table); - - initialConfigValues[KipConfigValue_commonEmcMemVolt] = cust_get_common_emc_volt(&table); - initialConfigValues[KipConfigValue_eristaEmcMaxClock] = cust_get_erista_emc_max(&table); - initialConfigValues[KipConfigValue_eristaEmcMaxClock1] = cust_get_erista_emc_max1(&table); - initialConfigValues[KipConfigValue_eristaEmcMaxClock2] = cust_get_erista_emc_max2(&table); - initialConfigValues[KipConfigValue_marikoEmcMaxClock] = cust_get_mariko_emc_max(&table); - initialConfigValues[KipConfigValue_marikoEmcVddqVolt] = cust_get_mariko_emc_vddq(&table); - initialConfigValues[KipConfigValue_emcDvbShift] = cust_get_emc_dvb_shift(&table); - - initialConfigValues[KipConfigValue_t1_tRCD] = cust_get_tRCD(&table); - initialConfigValues[KipConfigValue_t2_tRP] = cust_get_tRP(&table); - initialConfigValues[KipConfigValue_t3_tRAS] = cust_get_tRAS(&table); - initialConfigValues[KipConfigValue_t4_tRRD] = cust_get_tRRD(&table); - initialConfigValues[KipConfigValue_t5_tRFC] = cust_get_tRFC(&table); - initialConfigValues[KipConfigValue_t6_tRTW] = cust_get_tRTW(&table); - initialConfigValues[KipConfigValue_t7_tWTR] = cust_get_tWTR(&table); - initialConfigValues[KipConfigValue_t8_tREFI] = cust_get_tREFI(&table); - initialConfigValues[KipConfigValue_mem_burst_read_latency] = cust_get_burst_read_lat(&table); - initialConfigValues[KipConfigValue_mem_burst_write_latency] = cust_get_burst_write_lat(&table); - - initialConfigValues[KipConfigValue_eristaCpuUV] = cust_get_erista_cpu_uv(&table); - initialConfigValues[KipConfigValue_eristaCpuVmin] = cust_get_eristaCpuVmin(&table); - initialConfigValues[KipConfigValue_eristaCpuMaxVolt] = cust_get_erista_cpu_max_volt(&table); - initialConfigValues[KipConfigValue_eristaCpuUnlock] = cust_get_eristaCpuUnlock(&table); - - initialConfigValues[KipConfigValue_marikoCpuUVLow] = cust_get_mariko_cpu_uv_low(&table); - initialConfigValues[KipConfigValue_marikoCpuUVHigh] = cust_get_mariko_cpu_uv_high(&table); - initialConfigValues[KipConfigValue_tableConf] = cust_get_table_conf(&table); - initialConfigValues[KipConfigValue_marikoCpuLowVmin] = cust_get_mariko_cpu_low_vmin(&table); - initialConfigValues[KipConfigValue_marikoCpuHighVmin] = cust_get_mariko_cpu_high_vmin(&table); - initialConfigValues[KipConfigValue_marikoCpuMaxVolt] = cust_get_mariko_cpu_max_volt(&table); - initialConfigValues[KipConfigValue_marikoCpuMaxClock] = cust_get_marikoCpuMaxClock(&table); - initialConfigValues[KipConfigValue_eristaCpuBoostClock] = cust_get_erista_cpu_boost(&table); - initialConfigValues[KipConfigValue_marikoCpuBoostClock] = cust_get_mariko_cpu_boost(&table); - - initialConfigValues[KipConfigValue_eristaGpuUV] = cust_get_erista_gpu_uv(&table); - initialConfigValues[KipConfigValue_eristaGpuVmin] = cust_get_erista_gpu_vmin(&table); - initialConfigValues[KipConfigValue_marikoGpuUV] = cust_get_mariko_gpu_uv(&table); - initialConfigValues[KipConfigValue_marikoGpuVmin] = cust_get_mariko_gpu_vmin(&table); - initialConfigValues[KipConfigValue_marikoGpuVmax] = cust_get_mariko_gpu_vmax(&table); - initialConfigValues[KipConfigValue_commonGpuVoltOffset] = cust_get_common_gpu_offset(&table); - initialConfigValues[KipConfigValue_gpuSpeedo] = cust_get_gpu_speedo(&table); - initialConfigValues[KipConfigValue_t6_tRTW_fine_tune] = cust_get_tRTW_fine_tune(&table); - initialConfigValues[KipConfigValue_t7_tWTR_fine_tune] = cust_get_tWTR_fine_tune(&table); - } - - // configValues.values[KipConfigValue_mtcConf] = cust_get_mtc_conf(&table); - configValues.values[KipConfigValue_hpMode] = cust_get_hp_mode(&table); - - configValues.values[KipConfigValue_commonEmcMemVolt] = cust_get_common_emc_volt(&table); - configValues.values[KipConfigValue_eristaEmcMaxClock] = cust_get_erista_emc_max(&table); - configValues.values[KipConfigValue_eristaEmcMaxClock1] = cust_get_erista_emc_max1(&table); - configValues.values[KipConfigValue_eristaEmcMaxClock2] = cust_get_erista_emc_max2(&table); - configValues.values[KipConfigValue_marikoEmcMaxClock] = cust_get_mariko_emc_max(&table); - configValues.values[KipConfigValue_marikoEmcVddqVolt] = cust_get_mariko_emc_vddq(&table); - configValues.values[KipConfigValue_emcDvbShift] = cust_get_emc_dvb_shift(&table); - - configValues.values[KipConfigValue_t1_tRCD] = cust_get_tRCD(&table); - configValues.values[KipConfigValue_t2_tRP] = cust_get_tRP(&table); - configValues.values[KipConfigValue_t3_tRAS] = cust_get_tRAS(&table); - configValues.values[KipConfigValue_t4_tRRD] = cust_get_tRRD(&table); - configValues.values[KipConfigValue_t5_tRFC] = cust_get_tRFC(&table); - configValues.values[KipConfigValue_t6_tRTW] = cust_get_tRTW(&table); - configValues.values[KipConfigValue_t7_tWTR] = cust_get_tWTR(&table); - configValues.values[KipConfigValue_t8_tREFI] = cust_get_tREFI(&table); - configValues.values[KipConfigValue_mem_burst_read_latency] = cust_get_burst_read_lat(&table); - configValues.values[KipConfigValue_mem_burst_write_latency] = cust_get_burst_write_lat(&table); - - configValues.values[KipConfigValue_eristaCpuUV] = cust_get_erista_cpu_uv(&table); - configValues.values[KipConfigValue_eristaCpuVmin] = cust_get_eristaCpuVmin(&table); - configValues.values[KipConfigValue_eristaCpuMaxVolt] = cust_get_erista_cpu_max_volt(&table); - configValues.values[KipConfigValue_eristaCpuUnlock] = cust_get_eristaCpuUnlock(&table); - - - configValues.values[KipConfigValue_marikoCpuUVLow] = cust_get_mariko_cpu_uv_low(&table); - configValues.values[KipConfigValue_marikoCpuUVHigh] = cust_get_mariko_cpu_uv_high(&table); - configValues.values[KipConfigValue_tableConf] = cust_get_table_conf(&table); - configValues.values[KipConfigValue_marikoCpuLowVmin] = cust_get_mariko_cpu_low_vmin(&table); - configValues.values[KipConfigValue_marikoCpuHighVmin] = cust_get_mariko_cpu_high_vmin(&table); - configValues.values[KipConfigValue_marikoCpuMaxVolt] = cust_get_mariko_cpu_max_volt(&table); - configValues.values[KipConfigValue_marikoCpuMaxClock] = cust_get_marikoCpuMaxClock(&table); - configValues.values[KipConfigValue_eristaCpuBoostClock] = cust_get_erista_cpu_boost(&table); - configValues.values[KipConfigValue_marikoCpuBoostClock] = cust_get_mariko_cpu_boost(&table); - - configValues.values[KipConfigValue_eristaGpuUV] = cust_get_erista_gpu_uv(&table); - configValues.values[KipConfigValue_eristaGpuVmin] = cust_get_erista_gpu_vmin(&table); - configValues.values[KipConfigValue_marikoGpuUV] = cust_get_mariko_gpu_uv(&table); - configValues.values[KipConfigValue_marikoGpuVmin] = cust_get_mariko_gpu_vmin(&table); - configValues.values[KipConfigValue_marikoGpuVmax] = cust_get_mariko_gpu_vmax(&table); - configValues.values[KipConfigValue_commonGpuVoltOffset] = cust_get_common_gpu_offset(&table); - configValues.values[KipConfigValue_gpuSpeedo] = Board::getSpeedo(HorizonOCSpeedo_GPU); // cust_get_gpu_speedo(&table); - - for (int i = 0; i < 24; i++) { - configValues.values[KipConfigValue_g_volt_76800 + i] = cust_get_mariko_gpu_volt(&table, i); - initialConfigValues[KipConfigValue_g_volt_76800 + i] = cust_get_mariko_gpu_volt(&table, i); - } - - for (int i = 0; i < 27; i++) { - configValues.values[KipConfigValue_g_volt_e_76800 + i] = cust_get_erista_gpu_volt(&table, i); - initialConfigValues[KipConfigValue_g_volt_e_76800 + i] = cust_get_erista_gpu_volt(&table, i); - } - - configValues.values[KipConfigValue_t7_tWTR_fine_tune] = cust_get_tWTR_fine_tune(&table); - configValues.values[KipConfigValue_t6_tRTW_fine_tune] = cust_get_tRTW_fine_tune(&table); - - // if(cust_get_cust_rev(&table) == KIP_CUST_REV) - // return; - - if (sizeof(SysClkConfigValueList) <= sizeof(configValues)) { - if (this->config->SetConfigValues(&configValues, false)) { - FileUtils::LogLine("[clock_manager] Successfully loaded KIP data into config"); - } else { - FileUtils::LogLine("[clock_manager] Warning: Failed to set config values from KIP"); - writeNotification("Horizon OC\nKip config set failed"); - } - } else { - FileUtils::LogLine("[clock_manager] Error: Config value list buffer size mismatch"); - writeNotification("Horizon OC\nConfig Buffer Mismatch"); - } - } else { - FileUtils::LogLine("[clock_manager] Config refresh error in GetKipData!"); - writeNotification("Horizon OC\nConfig refresh failed"); - } -} diff --git a/Source/sys-clk/sysmodule/src/clock_manager.h b/Source/sys-clk/sysmodule/src/clock_manager.h deleted file mode 100644 index b09d10e1..00000000 --- a/Source/sys-clk/sysmodule/src/clock_manager.h +++ /dev/null @@ -1,261 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ -#pragma once -#include -#include -#include -#include "config.h" -#include "board.h" -#include -#include "integrations.h" - -class SysDockIntegration; -class SaltyNXIntegration; -class ClockManager -{ - public: - /** - * Get instance - * @return Pointer to a ClockManager instance - */ - static ClockManager* GetInstance(); - static void Initialize(); - static void Exit(); - ClockManager(); - virtual ~ClockManager(); - - /** - * Get context object - * @return Context instance - */ - SysClkContext GetCurrentContext(); - - /** - * Get config object - * @return Pointer to a config instance - */ - Config* GetConfig(); - - /** - * Set clock manager running - * @param running Is running or not? - */ - void SetRunning(bool running); - - /** - * Is clock manager running - * @return running or not? - */ - bool Running(); - - /** - * Get frequency list from clkrst - * - * @param module Module to get frequency list for - * @param list List of frequencies - * @param maxCount How many entries to expect in list. Usually 32 - * @param outCount How many entries were retrived - */ - void GetFreqList(SysClkModule module, std::uint32_t* list, std::uint32_t maxCount, std::uint32_t* outCount); - - /** - * Handles safety features - * - */ - void HandleSafetyFeatures(); - - /** - * Handles misc features (currently only battery charge current). - * - */ - void HandleMiscFeatures(); - - /** - * Handles governor state resolution and applies CPU/GPU governor transitions. - * - * @param targetHz Governor override value for the current profile. - */ - void HandleGovernor(uint32_t targetHz); - - /** - * Handles DVFS logic before the frequency set - * - * @param targetHz Governor override value for the current profile. - */ - void DVFSBeforeSet(u32 targetHz); - - /** - * Handles DVFS logic after the frequency set - * - * @param targetHz Governor override value for the current profile. - */ - void DVFSAfterSet(u32 targetHz); - - /** - * Reset the GPU vMin - * - */ - void DVFSReset(); - - /** - * Handles the Live CPU UV Feature - * - */ - void HandleCpuUv(); - - /** - * Handles frequency resets - * - * @param module The module to reset frequency for - * @param isBoost Is in boost mode - */ - void HandleFreqReset(SysClkModule module, bool isBoost); - - /** - * Sets clocks - * - * @param isBoost Is in boost mode - */ - void SetClocks(bool isBoost); - - /** - * Main function, runs every 5s in sleep mode, and a user specified amount when awake - * - */ - void Tick(); - - /** - * Reset CPU/GPU to stock values - * - */ - void ResetToStockClocks(); - - /** - * Wait for the next tick event - * - */ - void WaitForNextTick(); - - /** - * Set the data in the KIP - * - */ - void SetKipData(); - - /** - * Get the data from the KIP - * - */ - void GetKipData(); - - /** - * Runs the CPU Governor - * - * @param arg Cast to ClockManager* for context - */ - static void CpuGovernorThread(void* arg); - - /** - * Runs the GPU Governor - * - * @param arg Cast to ClockManager* for context - */ - static void GovernorThread(void* arg); - - /** - * Runs the VRR Algorithm - * - * @param arg Cast to ClockManager* for context - */ - static void VRRThread(void* arg); - - /** - * Frequency table - * - */ - struct FreqTable { - std::uint32_t count; - std::uint32_t list[SYSCLK_FREQ_LIST_MAX]; - } freqTable[SysClkModule_EnumMax]; - - /** - * Gets the current GPU speedo bracket - * - * @param speedo GPU Speedo - */ - int GetSpeedoBracket (int speedo); - - /** - * Gets the required vMin for a ram frequency for a speedo - * - * @param freq RAM Freq in MHz - * @param speedo GPU Speedo - */ - unsigned int GetGpuVoltage (unsigned int freq, int speedo); - - /** - * Gets the required vMin for a ram frequency for a speedo - * - * @param util Utilization in percentile - * @param tableMaxHz Table Max Hz - */ - static u32 SchedutilTargetHz(u32 util, u32 tableMaxHz); - - /** - * Gets the required vMin for a ram frequency for a speedo - * - * @param table FreqTable for module - * @param targetHz Hz to search for - */ - static u32 TableIndexForHz(const FreqTable& table, u32 targetHz); - - /** - * Gets the required vMin for a ram frequency for a speedo - * - * @param mgr ClockManager instance (runs in a thread so must be passed) - * @param module Module for which to resolve target Hz - */ - static u32 ResolveTargetHz(ClockManager* mgr, SysClkModule module); - - protected: - bool IsAssignableHz(SysClkModule module, std::uint32_t hz); - inline std::uint32_t GetMaxAllowedHz(SysClkModule module, SysClkProfile profile); - std::uint32_t GetNearestHz(SysClkModule module, std::uint32_t inHz, std::uint32_t maxHz); - bool ConfigIntervalTimeout(SysClkConfigValue intervalMsConfigValue, std::uint64_t ns, std::uint64_t* lastLogNs); - void RefreshFreqTableRow(SysClkModule module); - bool RefreshContext(); - static ClockManager *instance; - std::atomic_bool running; - LockableMutex contextMutex; - Config* config; - SysClkContext* context; - std::uint64_t lastTempLogNs; - std::uint64_t lastFreqLogNs; - std::uint64_t lastPowerLogNs; - std::uint64_t lastCsvWriteNs; - SysDockIntegration *sysDockIntegration; - SaltyNXIntegration *saltyNXIntegration; -}; \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/config.cpp b/Source/sys-clk/sysmodule/src/config.cpp deleted file mode 100644 index 06722105..00000000 --- a/Source/sys-clk/sysmodule/src/config.cpp +++ /dev/null @@ -1,520 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "config.h" -#include -#include -#include -#include -#include -#include -#include "errors.h" -#include "file_utils.h" - -Config::Config(std::string path) -{ - this->path = path; - this->loaded = false; - this->profileMHzMap = std::map, std::uint32_t>(); - this->profileCountMap = std::map(); - this->mtime = 0; - this->enabled = false; - for(unsigned int i = 0; i < SysClkModule_EnumMax; i++) - { - this->overrideFreqs[i] = 0; - } - - for(unsigned int i = 0; i < SysClkConfigValue_EnumMax; i++) - { - this->configValues[i] = sysclkDefaultConfigValue((SysClkConfigValue)i); - } -} - -Config::~Config() -{ - std::scoped_lock lock{this->configMutex}; - this->Close(); -} - -Config* Config::CreateDefault() -{ - return new Config(FILE_CONFIG_DIR "/config.ini"); -} - -void Config::Load() -{ - FileUtils::LogLine("[cfg] Reading %s", this->path.c_str()); - - this->Close(); - this->mtime = this->CheckModificationTime(); - if(!this->mtime) - { - FileUtils::LogLine("[cfg] Error finding file"); - } - else if (!ini_browse(&BrowseIniFunc, this, this->path.c_str())) - { - FileUtils::LogLine("[cfg] Error loading file"); - } - - this->loaded = true; -} - -void Config::Close() -{ - this->loaded = false; - this->profileMHzMap.clear(); - this->profileCountMap.clear(); - - for(unsigned int i = 0; i < SysClkConfigValue_EnumMax; i++) - { - this->configValues[i] = sysclkDefaultConfigValue((SysClkConfigValue)i); - } -} - -bool Config::Refresh() -{ - std::scoped_lock lock{this->configMutex}; - if (!this->loaded || this->mtime != this->CheckModificationTime()) - { - this->Load(); - return true; - } - return false; -} - -bool Config::HasProfilesLoaded() -{ - std::scoped_lock lock{this->configMutex}; - return this->loaded; -} - -time_t Config::CheckModificationTime() -{ - time_t mtime = 0; - struct stat st; - if (stat(this->path.c_str(), &st) == 0) - { - mtime = st.st_mtime; - } - - return mtime; -} - -std::uint32_t Config::FindClockMHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile) -{ - if (this->loaded) - { - std::map, std::uint32_t>::const_iterator it = this->profileMHzMap.find(std::make_tuple(tid, profile, module)); - if (it != this->profileMHzMap.end()) - { - return it->second; - } - } - - return 0; -} - -std::uint32_t Config::FindClockHzFromProfiles(std::uint64_t tid, SysClkModule module, std::initializer_list profiles, u32 mhzMultiplier) -{ - std::uint32_t mhz = 0; - - if (this->loaded) - { - for(auto profile: profiles) - { - mhz = FindClockMHz(tid, module, profile); - - if(mhz) - { - break; - } - } - } - - return std::max((std::uint32_t)0, mhz * mhzMultiplier); -} - -std::uint32_t Config::GetAutoClockHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile, bool returnRaw) -{ - std::scoped_lock lock{this->configMutex}; - switch(profile) - { - case SysClkProfile_Handheld: - return FindClockHzFromProfiles(tid, module, {SysClkProfile_Handheld}, returnRaw ? 1 : 1000000); - case SysClkProfile_HandheldCharging: - case SysClkProfile_HandheldChargingUSB: - return FindClockHzFromProfiles(tid, module, {SysClkProfile_HandheldChargingUSB, SysClkProfile_HandheldCharging, SysClkProfile_Handheld}, returnRaw ? 1 : 1000000); - case SysClkProfile_HandheldChargingOfficial: - return FindClockHzFromProfiles(tid, module, {SysClkProfile_HandheldChargingOfficial, SysClkProfile_HandheldCharging, SysClkProfile_Handheld}, returnRaw ? 1 : 1000000); - case SysClkProfile_Docked: - return FindClockHzFromProfiles(tid, module, {SysClkProfile_Docked}, returnRaw ? 1 : 1000000); - default: - ERROR_THROW("Unhandled SysClkProfile: %u", profile); - } - - return 0; -} - -void Config::GetProfiles(std::uint64_t tid, SysClkTitleProfileList* out_profiles) -{ - std::scoped_lock lock{this->configMutex}; - - for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) - { - for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - out_profiles->mhzMap[profile][module] = FindClockMHz(tid, (SysClkModule)module, (SysClkProfile)profile); - } - } -} - -bool Config::SetProfiles(std::uint64_t tid, SysClkTitleProfileList* profiles, bool immediate) -{ - std::scoped_lock lock{this->configMutex}; - uint8_t numProfiles = 0; - - char section[17] = {0}; - snprintf(section, sizeof(section), "%016lX", tid); - - std::vector keys; - std::vector values; - keys.reserve(SysClkProfile_EnumMax * SysClkModule_EnumMax); - values.reserve(SysClkProfile_EnumMax * SysClkModule_EnumMax); - - std::uint32_t* mhz = &profiles->mhz[0]; - - for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) - { - for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - if(*mhz) - { - numProfiles++; - - std::string key = std::string(Board::GetProfileName((SysClkProfile)profile, false)) + - "_" + - Board::GetModuleName((SysClkModule)module, false); - std::string value = std::to_string(*mhz); - - keys.push_back(key); - values.push_back(value); - } - mhz++; - } - } - - std::vector keyPointers; - std::vector valuePointers; - keyPointers.reserve(keys.size() + 1); - valuePointers.reserve(values.size() + 1); - - for(size_t i = 0; i < keys.size(); i++) { - keyPointers.push_back(keys[i].c_str()); - valuePointers.push_back(values[i].c_str()); - } - keyPointers.push_back(NULL); - valuePointers.push_back(NULL); - - if(!ini_putsection(section, keyPointers.data(), valuePointers.data(), this->path.c_str())) - { - return false; - } - - if(immediate) - { - mhz = &profiles->mhz[0]; - this->profileCountMap[tid] = numProfiles; - for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) - { - for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - if(*mhz) - { - this->profileMHzMap[std::make_tuple(tid, (SysClkProfile)profile, (SysClkModule)module)] = *mhz; - } - else - { - this->profileMHzMap.erase(std::make_tuple(tid, (SysClkProfile)profile, (SysClkModule)module)); - } - mhz++; - } - } - } - - return true; -} - -std::uint8_t Config::GetProfileCount(std::uint64_t tid) -{ - std::map::iterator it = this->profileCountMap.find(tid); - if (it == this->profileCountMap.end()) - { - return 0; - } - - return it->second; -} - -int Config::BrowseIniFunc(const char* section, const char* key, const char* value, void* userdata) -{ - Config* config = (Config*)userdata; - std::uint64_t input; - if(!strcmp(section, CONFIG_VAL_SECTION)) - { - for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) - { - if(!strcmp(key, sysclkFormatConfigValue((SysClkConfigValue)kval, false))) - { - input = strtoul(value, NULL, 0); - if(!sysclkValidConfigValue((SysClkConfigValue)kval, input)) - { - input = sysclkDefaultConfigValue((SysClkConfigValue)kval); - FileUtils::LogLine("[cfg] Invalid value for key '%s' in section '%s': using default %d", key, section, input); - } - config->configValues[kval] = input; - return 1; - } - } - - FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Unrecognized config value", key, section); - return 1; - } - - std::uint64_t tid = strtoul(section, NULL, 16); - - if(!tid || strlen(section) != 16) - { - FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Invalid TitleID", key, section); - return 1; - } - - SysClkProfile parsedProfile = SysClkProfile_EnumMax; - SysClkModule parsedModule = SysClkModule_EnumMax; - - for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) - { - const char* profileCode = Board::GetProfileName((SysClkProfile)profile, false); - size_t profileCodeLen = strlen(profileCode); - - if(!strncmp(key, profileCode, profileCodeLen) && key[profileCodeLen] == '_') - { - const char* subkey = key + profileCodeLen + 1; - - for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - const char* moduleCode = Board::GetModuleName((SysClkModule)module, false); - size_t moduleCodeLen = strlen(moduleCode); - if(!strncmp(subkey, moduleCode, moduleCodeLen) && subkey[moduleCodeLen] == '\0') - { - parsedProfile = (SysClkProfile)profile; - parsedModule = (SysClkModule)module; - } - } - } - } - - if(parsedModule == SysClkModule_EnumMax || parsedProfile == SysClkProfile_EnumMax) - { - FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Unrecognized key", key, section); - return 1; - } - - std::uint32_t mhz = strtoul(value, NULL, 10); - if(!mhz) - { - FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Invalid value", key, section); - return 1; - } - - config->profileMHzMap[std::make_tuple(tid, parsedProfile, parsedModule)] = mhz; - std::map::iterator it = config->profileCountMap.find(tid); - if (it == config->profileCountMap.end()) - { - config->profileCountMap[tid] = 1; - } - else - { - it->second++; - } - - return 1; -} - -void Config::SetEnabled(bool enabled) -{ - this->enabled = enabled; -} - -bool Config::Enabled() -{ - return this->enabled; -} - -void Config::SetOverrideHz(SysClkModule module, std::uint32_t hz) -{ - ASSERT_ENUM_VALID(SysClkModule, module); - - std::scoped_lock lock{this->overrideMutex}; - - this->overrideFreqs[module] = hz; -} - -std::uint32_t Config::GetOverrideHz(SysClkModule module) -{ - ASSERT_ENUM_VALID(SysClkModule, module); - - std::scoped_lock lock{this->overrideMutex}; - - return this->overrideFreqs[module]; -} - -std::uint64_t Config::GetConfigValue(SysClkConfigValue kval) -{ - ASSERT_ENUM_VALID(SysClkConfigValue, kval); - - std::scoped_lock lock{this->configMutex}; - - return this->configValues[kval]; -} - -const char* Config::GetConfigValueName(SysClkConfigValue kval, bool pretty) -{ - ASSERT_ENUM_VALID(SysClkConfigValue, kval); - - const char* result = sysclkFormatConfigValue(kval, pretty); - - return result; -} - -void Config::GetConfigValues(SysClkConfigValueList* out_configValues) -{ - std::scoped_lock lock{this->configMutex}; - - for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) - { - out_configValues->values[kval] = this->configValues[kval]; - } -} - -bool Config::SetConfigValues(SysClkConfigValueList* configValues, bool immediate) -{ - std::scoped_lock lock{this->configMutex}; - - std::vector iniKeys; - std::vector iniValues; - - iniKeys.reserve(SysClkConfigValue_EnumMax + 1); - iniValues.reserve(SysClkConfigValue_EnumMax); - - for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) - { - if(!sysclkValidConfigValue((SysClkConfigValue)kval, configValues->values[kval]) || - configValues->values[kval] == sysclkDefaultConfigValue((SysClkConfigValue)kval)) - { - continue; - } - - iniValues.push_back(std::to_string(configValues->values[kval])); - iniKeys.push_back(sysclkFormatConfigValue((SysClkConfigValue)kval, false)); - } - - // Null terminate - iniKeys.push_back(NULL); - - // Build pointer array for ini function - std::vector valuePointers; - valuePointers.reserve(iniValues.size() + 1); - for(const auto& val : iniValues) { - valuePointers.push_back(val.c_str()); - } - valuePointers.push_back(NULL); - - if(!ini_putsection(CONFIG_VAL_SECTION, iniKeys.data(), valuePointers.data(), this->path.c_str())) - { - return false; - } - - // Only actually apply changes in memory after a successful save - if(immediate) - { - for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) - { - if(sysclkValidConfigValue((SysClkConfigValue)kval, configValues->values[kval])) - { - this->configValues[kval] = configValues->values[kval]; - } - else - { - this->configValues[kval] = sysclkDefaultConfigValue((SysClkConfigValue)kval); - } - } - } - - return true; -} - -bool Config::ResetConfigValue(SysClkConfigValue kval) -{ - if (!SYSCLK_ENUM_VALID(SysClkConfigValue, kval)) { - FileUtils::LogLine("[cfg] Invalid SysClkConfigValue: %u", kval); - return false; - } - - std::scoped_lock lock{this->configMutex}; - - std::uint64_t defaultValue = sysclkDefaultConfigValue(kval); - - std::vector iniKeys; - std::vector iniValues; - - iniKeys.reserve(2); - iniValues.reserve(1); - - const char* keyStr = sysclkFormatConfigValue(kval, false); - - iniKeys.push_back(keyStr); - iniValues.push_back(""); - - iniKeys.push_back(NULL); - - std::vector valuePointers; - valuePointers.reserve(iniValues.size() + 1); - for (const auto& val : iniValues) { - valuePointers.push_back(val.c_str()); - } - valuePointers.push_back(NULL); - - if (!ini_putsection(CONFIG_VAL_SECTION, iniKeys.data(), valuePointers.data(), this->path.c_str())) { - FileUtils::LogLine("[cfg] Failed to reset config value %u in INI", kval); - return false; - } - - this->configValues[kval] = defaultValue; - FileUtils::LogLine("[cfg] Reset config value %u to default: %llu", kval, defaultValue); - - return true; -} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/config.h b/Source/sys-clk/sysmodule/src/config.h deleted file mode 100644 index 23a72acf..00000000 --- a/Source/sys-clk/sysmodule/src/config.h +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "board.h" - -#define CONFIG_VAL_SECTION "values" - -class Config -{ - public: - Config(std::string path); - virtual ~Config(); - - static Config* CreateDefault(); - - bool Refresh(); - - bool HasProfilesLoaded(); - - std::uint8_t GetProfileCount(std::uint64_t tid); - void GetProfiles(std::uint64_t tid, SysClkTitleProfileList* out_profiles); - bool SetProfiles(std::uint64_t tid, SysClkTitleProfileList* profiles, bool immediate); - std::uint32_t GetAutoClockHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile, bool returnRaw); - - void SetEnabled(bool enabled); - bool Enabled(); - void SetOverrideHz(SysClkModule module, std::uint32_t hz); - std::uint32_t GetOverrideHz(SysClkModule module); - - std::uint64_t GetConfigValue(SysClkConfigValue val); - const char* GetConfigValueName(SysClkConfigValue val, bool pretty); - void GetConfigValues(SysClkConfigValueList* out_configValues); - bool SetConfigValues(SysClkConfigValueList* configValues, bool immediate); - bool ResetConfigValue(SysClkConfigValue kval); - bool SetInternalValues(bool immediate); - bool SetConfigValue(SysClkConfigValue kval, std::uint64_t value, bool immediate = true); - - uint64_t configValues[SysClkConfigValue_EnumMax]; - protected: - void Load(); - void Close(); - bool kipOverride[SysClkConfigValue_EnumMax]; - time_t CheckModificationTime(); - std::uint32_t FindClockMHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile); - std::uint32_t FindClockHzFromProfiles(std::uint64_t tid, SysClkModule module, std::initializer_list profiles, u32 mhzMultiplier = 1000000); - static int BrowseIniFunc(const char* section, const char* key, const char* value, void* userdata); - - std::map, std::uint32_t> profileMHzMap; - std::map profileCountMap; - bool loaded; - std::string path; - time_t mtime; - LockableMutex configMutex; - LockableMutex overrideMutex; - std::atomic_bool enabled; - std::uint32_t overrideFreqs[SysClkModule_EnumMax]; -}; diff --git a/Source/sys-clk/sysmodule/src/errors.cpp b/Source/sys-clk/sysmodule/src/errors.cpp deleted file mode 100644 index b7949432..00000000 --- a/Source/sys-clk/sysmodule/src/errors.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "errors.h" -#include -#include -#include "file_utils.h" -void Errors::ThrowException(const char* format, ...) -{ - va_list args; - va_start(args, format); - const char* msg = Errors::FormatMessage(format, args); - va_end(args); - FileUtils::LogLine(format, args); - throw std::runtime_error(msg); -} - -const char* Errors::FormatMessage(const char* format, va_list args) -{ - size_t len = vsnprintf(NULL, 0, format, args) * sizeof(char); - char* buf = (char*)malloc(len + 1); - if (buf == NULL) - { - return format; - } - - vsnprintf(buf, len + 1, format, args); - - return buf; -} diff --git a/Source/sys-clk/sysmodule/src/errors.h b/Source/sys-clk/sysmodule/src/errors.h deleted file mode 100644 index f7575cf1..00000000 --- a/Source/sys-clk/sysmodule/src/errors.h +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include - -#define ERROR_THROW(format, ...) Errors::ThrowException(format "\n in %s:%u", ##__VA_ARGS__, __FILE__, __LINE__) -#define ERROR_RESULT_THROW(rc, format, ...) ERROR_THROW(format "\n RC: [0x%x] %04d-%04d", ##__VA_ARGS__, rc, R_MODULE(rc), R_DESCRIPTION(rc)) -#define ASSERT_RESULT_OK(rc, format, ...) \ - if (R_FAILED(rc)) \ - { \ - ERROR_RESULT_THROW(rc, "ASSERT_RESULT_OK: " format, ##__VA_ARGS__); \ - } -#define ASSERT_ENUM_VALID(n, v) \ - if(!SYSCLK_ENUM_VALID(n, v)) { \ - ERROR_THROW("No such %s: %u", #n, v); \ - } - -class Errors -{ - public: - static void ThrowException(const char* format, ...); - - protected: - static const char* FormatMessage(const char* format, va_list args); -}; diff --git a/Source/sys-clk/sysmodule/src/file_utils.cpp b/Source/sys-clk/sysmodule/src/file_utils.cpp deleted file mode 100644 index a99494e8..00000000 --- a/Source/sys-clk/sysmodule/src/file_utils.cpp +++ /dev/null @@ -1,217 +0,0 @@ -/* - * Copyright (c) Souldbminer and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "file_utils.h" -#include - -static LockableMutex g_log_mutex; -static LockableMutex g_csv_mutex; -static std::atomic_bool g_has_initialized = false; -static bool g_log_enabled = false; -static std::uint64_t g_last_flag_check = 0; - -extern "C" void __libnx_init_time(void); - -static void _FileUtils_InitializeThreadFunc(void* args) -{ - FileUtils::Initialize(); -} - -bool FileUtils::IsInitialized() -{ - return g_has_initialized; -} - -void FileUtils::LogLine(const char* format, ...) -{ - std::scoped_lock lock{g_log_mutex}; - - va_list args; - va_start(args, format); - if (g_has_initialized) - { - FileUtils::RefreshFlags(false); - - if(g_log_enabled) - { - FILE* file = fopen(FILE_LOG_FILE_PATH, "a"); - - if (file) - { - struct timespec now; - clock_gettime(CLOCK_REALTIME, &now); - struct tm* nowTm = localtime(&now.tv_sec); - - fprintf(file, "[%04d-%02d-%02d %02d:%02d:%02d.%03ld] ", nowTm->tm_year+1900, nowTm->tm_mon+1, nowTm->tm_mday, nowTm->tm_hour, nowTm->tm_min, nowTm->tm_sec, now.tv_nsec / 1000000UL); - vfprintf(file, format, args); - fprintf(file, "\n"); - fclose(file); - } - } - } - va_end(args); -} - -void FileUtils::WriteContextToCsv(const SysClkContext* context) -{ - std::scoped_lock lock{g_csv_mutex}; - - FILE* file = fopen(FILE_CONTEXT_CSV_PATH, "a"); - - if (file) - { - // Print header - if(!ftell(file)) - { - fprintf(file, "timestamp,profile,app_tid"); - - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - fprintf(file, ",%s_hz", sysclkFormatModule((SysClkModule)module, false)); - } - - for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++) - { - fprintf(file, ",%s_milliC", sysclkFormatThermalSensor((SysClkThermalSensor)sensor, false)); - } - - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - fprintf(file, ",%s_real_hz", sysclkFormatModule((SysClkModule)module, false)); - } - - for (unsigned int sensor = 0; sensor < SysClkPowerSensor_EnumMax; sensor++) - { - fprintf(file, ",%s_mw", sysclkFormatPowerSensor((SysClkPowerSensor)sensor, false)); - } - - fprintf(file, "\n"); - } - - struct timespec now; - clock_gettime(CLOCK_REALTIME, &now); - - fprintf(file, "%ld%03ld,%s,%016lx", now.tv_sec, now.tv_nsec / 1000000UL, sysclkFormatProfile(context->profile, false), context->applicationId); - - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - fprintf(file, ",%d", context->freqs[module]); - } - - for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++) - { - fprintf(file, ",%d", context->temps[sensor]); - } - - for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) - { - fprintf(file, ",%d", context->realFreqs[module]); - } - - for (unsigned int sensor = 0; sensor < SysClkPowerSensor_EnumMax; sensor++) - { - fprintf(file, ",%d", context->power[sensor]); - } - - fprintf(file, "\n"); - fclose(file); - } -} - -void FileUtils::RefreshFlags(bool force) -{ - std::uint64_t now = armTicksToNs(armGetSystemTick()); - if(!force && (now - g_last_flag_check) < FILE_FLAG_CHECK_INTERVAL_NS) - { - return; - } - - FILE* file = fopen(FILE_LOG_FLAG_PATH, "r"); - if (file) - { - g_log_enabled = true; - fclose(file); - } else { - g_log_enabled = false; - } - - g_last_flag_check = now; -} - -void FileUtils::InitializeAsync() -{ - Thread initThread = {0}; - threadCreate(&initThread, _FileUtils_InitializeThreadFunc, NULL, NULL, 0x4000, 0x15, 0); - threadStart(&initThread); -} - -Result FileUtils::Initialize() -{ - Result rc = 0; - - if (R_SUCCEEDED(rc)) - { - rc = timeInitialize(); - } - - __libnx_init_time(); - timeExit(); - - if (R_SUCCEEDED(rc)) - { - rc = fsInitialize(); - } - - if (R_SUCCEEDED(rc)) - { - rc = fsdevMountSdmc(); - } - - if (R_SUCCEEDED(rc)) - { - FileUtils::RefreshFlags(true); - g_has_initialized = true; - FileUtils::LogLine("=== hoc-clk " TARGET_VERSION " ==="); - FileUtils::LogLine("by m4xw, natinusala, p-sam, Souldbminer and Lightos_"); - } - - return rc; -} - -void FileUtils::Exit() -{ - if (!g_has_initialized) - { - return; - } - - g_has_initialized = false; - g_log_enabled = false; - - fsdevUnmountAll(); - fsExit(); -} diff --git a/Source/sys-clk/sysmodule/src/file_utils.h b/Source/sys-clk/sysmodule/src/file_utils.h deleted file mode 100644 index 993420de..00000000 --- a/Source/sys-clk/sysmodule/src/file_utils.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once -#include -#include -#include -#include -#include -#include -#include - -#define FILE_CONFIG_DIR "/config/" TARGET -#define FILE_FLAG_CHECK_INTERVAL_NS (10000ULL * 1000000000ULL) -#define FILE_CONTEXT_CSV_PATH FILE_CONFIG_DIR "/context.csv" -#define FILE_LOG_FLAG_PATH FILE_CONFIG_DIR "/log.flag" -#define FILE_LOG_FILE_PATH FILE_CONFIG_DIR "/log.txt" - -class FileUtils -{ - public: - static void Exit(); - static Result Initialize(); - static bool IsInitialized(); - static bool IsLogEnabled(); - static void InitializeAsync(); - static void LogLine(const char* format, ...); - static void WriteContextToCsv(const SysClkContext* context); - protected: - static void RefreshFlags(bool force); -}; diff --git a/Source/sys-clk/sysmodule/src/integrations.cpp b/Source/sys-clk/sysmodule/src/integrations.cpp deleted file mode 100644 index 64077895..00000000 --- a/Source/sys-clk/sysmodule/src/integrations.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - - -#include "integrations.h" -#include -#include -#include "process_management.h" - -SysDockIntegration::SysDockIntegration() { -} - -bool SysDockIntegration::getCurrentSysDockState() { - struct stat st = {0}; - return stat("sdmc:/atmosphere/contents/42000000000000A0/flags/boot2.flag", &st) == 0; -} - -SaltyNXIntegration::SaltyNXIntegration() { -} - -void SaltyNXIntegration::LoadSaltyNX() { - if (!CheckPort()) - return; - LoadSharedMemory(); -} - -bool SaltyNXIntegration::getCurrentSaltyNXState() { - struct stat st = {0}; - return stat("sdmc:/atmosphere/contents/0000000000534C56/flags/boot2.flag", &st) == 0; -} - -bool SaltyNXIntegration::CheckPort() { - Handle saltysd; - - for (int i = 0; i < 67; i++) { - if (R_SUCCEEDED(svcConnectToNamedPort(&saltysd, "InjectServ"))) { - svcCloseHandle(saltysd); - break; - } - if (i == 66) return false; - svcSleepThread(1'000'000); - } - - for (int i = 0; i < 67; i++) { - if (R_SUCCEEDED(svcConnectToNamedPort(&saltysd, "InjectServ"))) { - svcCloseHandle(saltysd); - return true; - } - svcSleepThread(1'000'000); - } - - return false; -} - -void SaltyNXIntegration::LoadSharedMemory() { - if (SaltySD_Connect()) - return; - SaltySD_GetSharedMemoryHandle(&remoteSharedMemory); - SaltySD_Term(); - shmemLoadRemote(&_sharedmemory, remoteSharedMemory, 0x1000, Perm_Rw); - if (!shmemMap(&_sharedmemory)) - SharedMemoryUsed = true; -} - -void SaltyNXIntegration::searchSharedMemoryBlock(uintptr_t base) { - ptrdiff_t search_offset = 0; - while (search_offset < 0x1000) { - NxFps = (NxFpsSharedBlock*)(base + search_offset); - if (NxFps->MAGIC == 0x465053) - return; - search_offset += 4; - } - NxFps = 0; -} - -u64 prevTid = 0; - -u8 SaltyNXIntegration::GetFPS() { - if (!SharedMemoryUsed) - return 254; - - u64 tid = ProcessManagement::GetCurrentApplicationId(); - if (tid == 0) - return 254; - - if (prevTid != tid) { - NxFps = 0; - prevTid = tid; - } - - if (!NxFps) { - uintptr_t base = (uintptr_t)shmemGetAddr(&_sharedmemory); - searchSharedMemoryBlock(base); - } - - return NxFps ? NxFps->FPS : 254; -} - -u16 SaltyNXIntegration::GetResolutionHeight() { - if (!SharedMemoryUsed) - return 0; - - u64 tid = ProcessManagement::GetCurrentApplicationId(); - if (tid == 0) - return 0; - - if (prevTid != tid) { - NxFps = 0; - prevTid = tid; - } - - if (!NxFps) { - uintptr_t base = (uintptr_t)shmemGetAddr(&_sharedmemory); - searchSharedMemoryBlock(base); - } - if(NxFps) { - NxFps->renderCalls[0].calls = 0xFFFF; - svcSleepThread(10*1000); - - return NxFps->renderCalls[0].height == 0 ? NxFps->viewportCalls[0].height : NxFps->renderCalls[0].height; - } - return 0; -} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/integrations.h b/Source/sys-clk/sysmodule/src/integrations.h deleted file mode 100644 index 466e2f7d..00000000 --- a/Source/sys-clk/sysmodule/src/integrations.h +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include "errors.h" -#include "file_utils.h" - -#include "clock_manager.h" - -class SysDockIntegration { -public: - SysDockIntegration(); - - bool getCurrentSysDockState(); -}; - -class SaltyNXIntegration { -public: - struct resolutionCalls { - uint16_t width; - uint16_t height; - uint16_t calls; - }; - - struct NxFpsSharedBlock { - uint32_t MAGIC; - uint8_t FPS; - float FPSavg; - bool pluginActive; - uint8_t FPSlocked; - uint8_t FPSmode; - uint8_t ZeroSync; - uint8_t patchApplied; - uint8_t API; - uint32_t FPSticks[10]; - uint8_t Buffers; - uint8_t SetBuffers; - uint8_t ActiveBuffers; - uint8_t SetActiveBuffers; - union { - struct { - bool handheld: 1; - bool docked: 1; - unsigned int reserved: 6; - } NX_PACKED ds; - uint8_t general; - } displaySync; - resolutionCalls renderCalls[8]; - resolutionCalls viewportCalls[8]; - bool forceOriginalRefreshRate; - bool dontForce60InDocked; - bool forceSuspend; - uint8_t currentRefreshRate; - float readSpeedPerSecond; - uint8_t FPSlockedDocked; - uint64_t frameNumber; - } NX_PACKED; - - NxFpsSharedBlock* NxFps = 0; - SharedMemory _sharedmemory = {}; - bool SharedMemoryUsed = false; - Handle remoteSharedMemory = 1; - SaltyNXIntegration(); - void LoadSaltyNX(); - bool getCurrentSaltyNXState(); - - bool CheckPort(); - void LoadSharedMemory(); - void searchSharedMemoryBlock(uintptr_t base); - u8 GetFPS(); - u16 GetResolutionHeight(); -}; \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/ipc_service.cpp b/Source/sys-clk/sysmodule/src/ipc_service.cpp deleted file mode 100644 index 4dea5685..00000000 --- a/Source/sys-clk/sysmodule/src/ipc_service.cpp +++ /dev/null @@ -1,374 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "ipc_service.h" -#include -#include -#include "file_utils.h" -#include "errors.h" -#include "clock_manager.h" -IpcService::IpcService(ClockManager* clockMgr) -{ - std::int32_t priority; - Result rc = svcGetThreadPriority(&priority, CUR_THREAD_HANDLE); - ASSERT_RESULT_OK(rc, "svcGetThreadPriority"); - rc = ipcServerInit(&this->server, SYSCLK_IPC_SERVICE_NAME, 42); - ASSERT_RESULT_OK(rc, "ipcServerInit"); - rc = threadCreate(&this->thread, &IpcService::ProcessThreadFunc, this, NULL, 0x2000, priority, -2); - ASSERT_RESULT_OK(rc, "threadCreate"); - - this->running = false; - this->clockMgr = clockMgr; - -} - -void IpcService::SetRunning(bool running) -{ - std::scoped_lock lock{this->threadMutex}; - if(this->running == running) - { - return; - } - - this->running = running; - - if(running) - { - Result rc = threadStart(&this->thread); - ASSERT_RESULT_OK(rc, "threadStart"); - } - else - { - svcCancelSynchronization(this->thread.handle); - threadWaitForExit(&this->thread); - } -} - -IpcService::~IpcService() -{ - this->SetRunning(false); - Result rc = threadClose(&this->thread); - ASSERT_RESULT_OK(rc, "threadClose"); - rc = ipcServerExit(&this->server); - ASSERT_RESULT_OK(rc, "ipcServerExit"); -} - -void IpcService::ProcessThreadFunc(void* arg) -{ - Result rc; - IpcService* ipcSrv = (IpcService*)arg; - while(true) - { - rc = ipcServerProcess(&ipcSrv->server, &IpcService::ServiceHandlerFunc, arg); - if(R_FAILED(rc)) - { - if(rc == KERNELRESULT(Cancelled)) - { - return; - } - if(rc != KERNELRESULT(ConnectionClosed)) - { - FileUtils::LogLine("[ipc] ipcServerProcess: [0x%x] %04d-%04d", rc, R_MODULE(rc), R_DESCRIPTION(rc)); - } - } - } -} - -Result IpcService::ServiceHandlerFunc(void* arg, const IpcServerRequest* r, u8* out_data, size_t* out_dataSize) -{ - IpcService* ipcSrv = (IpcService*)arg; - - switch(r->data.cmdId) - { - case SysClkIpcCmd_GetApiVersion: - *out_dataSize = sizeof(u32); - return ipcSrv->GetApiVersion((u32*)out_data); - - case SysClkIpcCmd_GetVersionString: - if(r->hipc.meta.num_recv_buffers >= 1) - { - return ipcSrv->GetVersionString( - (char*)hipcGetBufferAddress(r->hipc.data.recv_buffers), - hipcGetBufferSize(r->hipc.data.recv_buffers) - ); - } - break; - - case SysClkIpcCmd_GetCurrentContext: - if(r->data.size >= sizeof(std::uint64_t) && r->hipc.meta.num_recv_buffers >= 1) - { - size_t bufSize = hipcGetBufferSize(r->hipc.data.recv_buffers); - if(bufSize >= sizeof(SysClkContext)) - { - return ipcSrv->GetCurrentContext((SysClkContext*)hipcGetBufferAddress(r->hipc.data.recv_buffers)); - } - } - break; - case SysClkIpcCmd_Exit: - return ipcSrv->Exit(); - - case SysClkIpcCmd_GetProfileCount: - if(r->data.size >= sizeof(std::uint64_t)) - { - *out_dataSize = sizeof(std::uint8_t); - return ipcSrv->GetProfileCount((std::uint64_t*)r->data.ptr, (std::uint8_t*)out_data); - } - break; - - case SysClkIpcCmd_GetProfiles: - if(r->data.size >= sizeof(std::uint64_t) && r->hipc.meta.num_recv_buffers >= 1) - { - size_t bufSize = hipcGetBufferSize(r->hipc.data.recv_buffers); - if(bufSize >= sizeof(SysClkTitleProfileList)) - { - return ipcSrv->GetProfiles((std::uint64_t*)r->data.ptr, (SysClkTitleProfileList*)hipcGetBufferAddress(r->hipc.data.recv_buffers)); - } - } - break; - - case SysClkIpcCmd_SetProfiles: - if(r->data.size >= sizeof(SysClkIpc_SetProfiles_Args)) - { - return ipcSrv->SetProfiles((SysClkIpc_SetProfiles_Args*)r->data.ptr); - } - break; - - case SysClkIpcCmd_SetEnabled: - if(r->data.size >= sizeof(std::uint8_t)) - { - return ipcSrv->SetEnabled((std::uint8_t*)r->data.ptr); - } - break; - - case SysClkIpcCmd_SetOverride: - if(r->data.size >= sizeof(SysClkIpc_SetOverride_Args)) - { - return ipcSrv->SetOverride((SysClkIpc_SetOverride_Args*)r->data.ptr); - } - break; - - case SysClkIpcCmd_GetConfigValues: - if(r->hipc.meta.num_recv_buffers >= 1) - { - size_t bufSize = hipcGetBufferSize(r->hipc.data.recv_buffers); - if(bufSize >= sizeof(SysClkConfigValueList)) - { - return ipcSrv->GetConfigValues((SysClkConfigValueList*)hipcGetBufferAddress(r->hipc.data.recv_buffers)); - } - } - break; - - case SysClkIpcCmd_SetConfigValues: - if(r->hipc.meta.num_send_buffers >= 1) - { - size_t bufSize = hipcGetBufferSize(r->hipc.data.send_buffers); - if(bufSize >= sizeof(SysClkConfigValueList)) - { - return ipcSrv->SetConfigValues((SysClkConfigValueList*)hipcGetBufferAddress(r->hipc.data.send_buffers)); - } - } - break; - case SysClkIpcCmd_GetFreqList: - if(r->data.size >= sizeof(SysClkIpc_GetFreqList_Args) && r->hipc.meta.num_recv_buffers >= 1) - { - *out_dataSize = sizeof(std::uint32_t); - return ipcSrv->GetFreqList( - (SysClkIpc_GetFreqList_Args*)r->data.ptr, - (std::uint32_t*)hipcGetBufferAddress(r->hipc.data.recv_buffers), - hipcGetBufferSize(r->hipc.data.recv_buffers), - (std::uint32_t*)out_data - ); - } - break; - case HocClkIpcCmd_SetKipData: - if (r->data.size >= 0) { - return ipcSrv->SetKipData(); - } - break; - } - - return SYSCLK_ERROR(Generic); -} - -Result IpcService::GetApiVersion(u32* out_version) -{ - *out_version = SYSCLK_IPC_API_VERSION; - - return 0; -} - -Result IpcService::GetVersionString(char* out_buf, size_t bufSize) -{ - if(bufSize) - { - strncpy(out_buf, TARGET_VERSION, bufSize-1); - } - - return 0; -} - -Result IpcService::GetCurrentContext(SysClkContext* out_ctx) -{ - *out_ctx = this->clockMgr->GetCurrentContext(); - - return 0; -} - -Result IpcService::Exit() -{ - this->clockMgr->SetRunning(false); - - return 0; -} - -Result IpcService::GetProfileCount(std::uint64_t* tid, std::uint8_t* out_count) -{ - Config* config = this->clockMgr->GetConfig(); - if(!config->HasProfilesLoaded()) - { - return SYSCLK_ERROR(ConfigNotLoaded); - } - - *out_count = config->GetProfileCount(*tid); - - return 0; -} - -Result IpcService::GetProfiles(std::uint64_t* tid, SysClkTitleProfileList* out_profiles) -{ - Config* config = this->clockMgr->GetConfig(); - if(!config->HasProfilesLoaded()) - { - return SYSCLK_ERROR(ConfigNotLoaded); - } - - config->GetProfiles(*tid, out_profiles); - - return 0; -} - -Result IpcService::SetProfiles(SysClkIpc_SetProfiles_Args* args) -{ - Config* config = this->clockMgr->GetConfig(); - if(!config->HasProfilesLoaded()) - { - return SYSCLK_ERROR(ConfigNotLoaded); - } - - SysClkTitleProfileList profiles = args->profiles; - - if(!config->SetProfiles(args->tid, &profiles, true)) - { - return SYSCLK_ERROR(ConfigSaveFailed); - } - - return 0; -} - -Result IpcService::SetEnabled(std::uint8_t* enabled) -{ - Config* config = this->clockMgr->GetConfig(); - config->SetEnabled(*enabled); - - return 0; -} - -Result IpcService::SetOverride(SysClkIpc_SetOverride_Args* args) -{ - SysClkModule module = args->module; - std::uint32_t hz = args->hz; - - if(!SYSCLK_ENUM_VALID(SysClkModule, args->module)) - { - return SYSCLK_ERROR(Generic); - } - - Config* config = this->clockMgr->GetConfig(); - config->SetOverrideHz(module, hz); - - return 0; -} - -Result IpcService::GetConfigValues(SysClkConfigValueList* out_configValues) -{ - Config* config = this->clockMgr->GetConfig(); - if(!config->HasProfilesLoaded()) - { - return SYSCLK_ERROR(ConfigNotLoaded); - } - - config->GetConfigValues(out_configValues); - - return 0; -} - -Result IpcService::SetConfigValues(SysClkConfigValueList* configValues) -{ - Config* config = this->clockMgr->GetConfig(); - if(!config->HasProfilesLoaded()) - { - return SYSCLK_ERROR(ConfigNotLoaded); - } - - SysClkConfigValueList configValuesCopy = *configValues; - - if(!config->SetConfigValues(&configValuesCopy, true)) - { - return SYSCLK_ERROR(ConfigSaveFailed); - } - - return 0; -} - -Result IpcService::GetFreqList(SysClkIpc_GetFreqList_Args* args, std::uint32_t* out_list, std::size_t size, std::uint32_t* out_count) -{ - if(!SYSCLK_ENUM_VALID(SysClkModule, args->module)) - { - return SYSCLK_ERROR(Generic); - } - - if(args->maxCount != size/sizeof(*out_list)) - { - return SYSCLK_ERROR(Generic); - } - - this->clockMgr->GetFreqList(args->module, out_list, args->maxCount, out_count); - - return 0; -} - -Result IpcService::SetKipData() { - this->clockMgr->SetKipData(); - - return 0; -} - -Result IpcService::GetKipData() { - this->clockMgr->GetKipData(); - - return 0; -} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/ipc_service.h b/Source/sys-clk/sysmodule/src/ipc_service.h deleted file mode 100644 index cded785c..00000000 --- a/Source/sys-clk/sysmodule/src/ipc_service.h +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once - -#include -#include -#include -#include "clock_manager.h" - -class IpcService -{ - public: - - IpcService(ClockManager* clockMgr); - virtual ~IpcService(); - void SetRunning(bool running); - static void ProcessThreadFunc(void* arg); - static Result ServiceHandlerFunc(void* arg, const IpcServerRequest* r, std::uint8_t* out_data, size_t* out_dataSize); - - Result GetApiVersion(u32* out_version); - Result GetVersionString(char* out_buf, size_t bufSize); - Result GetCurrentContext(SysClkContext* out_ctx); - Result Exit(); - Result GetProfileCount(std::uint64_t* tid, std::uint8_t* out_count); - Result GetProfiles(std::uint64_t* tid, SysClkTitleProfileList* out_profiles); - Result SetProfiles(SysClkIpc_SetProfiles_Args* args); - Result SetEnabled(std::uint8_t* enabled); - Result SetOverride(SysClkIpc_SetOverride_Args* args); - Result GetConfigValues(SysClkConfigValueList* out_configValues); - Result SetConfigValues(SysClkConfigValueList* configValues); - Result GetFreqList(SysClkIpc_GetFreqList_Args* args, std::uint32_t* out_list, std::size_t size, std::uint32_t* out_count); - Result SetKipData(); - Result GetKipData(); - bool running; - Thread thread; - LockableMutex threadMutex; - IpcServer server; - ClockManager* clockMgr; - protected: - -}; diff --git a/Source/sys-clk/sysmodule/src/kip.h b/Source/sys-clk/sysmodule/src/kip.h deleted file mode 100644 index 818b4937..00000000 --- a/Source/sys-clk/sysmodule/src/kip.h +++ /dev/null @@ -1,450 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - - -#pragma once -#include -#include -#include -#include -#include - -#pragma pack(push, 1) - -typedef struct { - u8 cust[4]; - u32 custRev; - u32 placeholder; - u32 hpMode; - u32 commonEmcMemVolt; - u32 eristaEmcMaxClock; - u32 eristaEmcMaxClock1; - u32 eristaEmcMaxClock2; - u32 marikoEmcMaxClock; - u32 marikoEmcVddqVolt; - u32 emcDvbShift; - // advanced config - u32 t1_tRCD; - u32 t2_tRP; - u32 t3_tRAS; - u32 t4_tRRD; - u32 t5_tRFC; - u32 t6_tRTW; - u32 t7_tWTR; - u32 t8_tREFI; - - u32 mem_burst_read_latency; - u32 mem_burst_write_latency; - - u32 eristaCpuUV; - u32 eristaCpuVmin; - u32 eristaCpuMaxVolt; - u32 eristaCpuUnlock; - - u32 marikoCpuUVLow; - u32 marikoCpuUVHigh; - u32 tableConf; - u32 marikoCpuLowVmin; - u32 marikoCpuHighVmin; - u32 marikoCpuMaxVolt; - u32 marikoCpuMaxClock; - - u32 eristaCpuBoostClock; - u32 marikoCpuBoostClock; - - u32 eristaGpuUV; - u32 eristaGpuVmin; - - u32 marikoGpuUV; - u32 marikoGpuVmin; - u32 marikoGpuVmax; - - u32 commonGpuVoltOffset; - - u32 gpuSpeedo; - - u32 eristaGpuVoltArray[27]; - u32 marikoGpuVoltArray[24]; - - u32 t6_tRTW_fine_tune; - u32 t7_tWTR_fine_tune; - - u32 reserved[60]; -} CustomizeTable; - -#pragma pack(pop) - -#define CUST_MAGIC "CUST" -#define CUST_MAGIC_LEN 4 - -typedef struct { - FILE* file; - long offset; - CustomizeTable cached_table; - bool has_cache; -} CustHandle; - -static inline bool cust_find_offset(FILE* f, long* out_offset) { - u8 buf[512]; - long pos = 0; - fseek(f, 0, SEEK_SET); - - while (1) { - size_t r = fread(buf, 1, sizeof(buf), f); - if (r < CUST_MAGIC_LEN) break; - - for (size_t i = 0; i <= r - CUST_MAGIC_LEN; i++) { - if (memcmp(&buf[i], CUST_MAGIC, CUST_MAGIC_LEN) == 0) { - *out_offset = pos + (long)i; - return true; - } - } - pos += (long)(r - (CUST_MAGIC_LEN - 1)); - fseek(f, pos, SEEK_SET); - } - return false; -} - -static inline bool cust_read_table(const char* path, CustomizeTable* out) { - FILE* f = fopen(path, "rb"); - if (!f) return false; - - long off; - if (!cust_find_offset(f, &off)) { - fclose(f); - return false; - } - - fseek(f, 0, SEEK_END); - long size = ftell(f); - - if (off + (long)sizeof(CustomizeTable) > size) { - fclose(f); - return false; - } - - fseek(f, off, SEEK_SET); - bool ok = fread(out, 1, sizeof(CustomizeTable), f) == sizeof(CustomizeTable); - fclose(f); - - return ok && memcmp(out->cust, CUST_MAGIC, CUST_MAGIC_LEN) == 0; -} - -static inline bool cust_write_table(const char* path, const CustomizeTable* in) { - FILE* f = fopen(path, "r+b"); - if (!f) return false; - - long off; - if (!cust_find_offset(f, &off)) { - fclose(f); - return false; - } - - fseek(f, 0, SEEK_END); - long size = ftell(f); - - if (off + (long)sizeof(CustomizeTable) > size) { - fclose(f); - return false; - } - - fseek(f, off, SEEK_SET); - bool ok = fwrite(in, 1, sizeof(CustomizeTable), f) == sizeof(CustomizeTable); - fflush(f); - fclose(f); - - return ok; -} - - -static inline bool cust_read_and_cache(const char* path, CustomizeTable* out) { - return cust_read_table(path, out); -} - -#define CUST_WRITE_FIELD_BATCH(table, field, val) \ - do { \ - (table)->field = (val); \ - } while (0) - -#define CUST_WRITE_FIELD(path, field, val) \ - do { \ - CustomizeTable t; \ - if (!cust_read_table(path, &t)) return false; \ - t.field = (val); \ - return cust_write_table(path, &t); \ - } while (0) - -static inline bool cust_set_cust_rev(const char* p, u32 v) { CUST_WRITE_FIELD(p, custRev, v); } -// static inline bool cust_set_mtc_conf(const char* p, u32 v) { CUST_WRITE_FIELD(p, mtcConf, v); } -static inline bool cust_set_hp_mode(const char* p, u32 v) { CUST_WRITE_FIELD(p, hpMode, v); } - -static inline bool cust_set_common_emc_volt(const char* p, u32 v) { CUST_WRITE_FIELD(p, commonEmcMemVolt, v); } -static inline bool cust_set_erista_emc_max(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaEmcMaxClock, v); } -static inline bool cust_set_erista_emc_max1(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaEmcMaxClock1, v); } -static inline bool cust_set_erista_emc_max2(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaEmcMaxClock2, v); } -static inline bool cust_set_mariko_emc_max(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoEmcMaxClock, v); } -static inline bool cust_set_mariko_emc_vddq(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoEmcVddqVolt, v); } -static inline bool cust_set_emc_dvb_shift(const char* p, u32 v) { CUST_WRITE_FIELD(p, emcDvbShift, v); } - -static inline bool cust_set_tRCD(const char* p, u32 v) { CUST_WRITE_FIELD(p, t1_tRCD, v); } -static inline bool cust_set_tRP(const char* p, u32 v) { CUST_WRITE_FIELD(p, t2_tRP, v); } -static inline bool cust_set_tRAS(const char* p, u32 v) { CUST_WRITE_FIELD(p, t3_tRAS, v); } -static inline bool cust_set_tRRD(const char* p, u32 v) { CUST_WRITE_FIELD(p, t4_tRRD, v); } -static inline bool cust_set_tRFC(const char* p, u32 v) { CUST_WRITE_FIELD(p, t5_tRFC, v); } -static inline bool cust_set_tRTW(const char* p, u32 v) { CUST_WRITE_FIELD(p, t6_tRTW, v); } -static inline bool cust_set_tWTR(const char* p, u32 v) { CUST_WRITE_FIELD(p, t7_tWTR, v); } -static inline bool cust_set_tREFI(const char* p, u32 v) { CUST_WRITE_FIELD(p, t8_tREFI, v); } -static inline bool cust_set_tRTW_fine_tune(const char* p, u32 v) { CUST_WRITE_FIELD(p, t6_tRTW_fine_tune, v); } -static inline bool cust_set_tWTR_fine_tune(const char* p, u32 v) { CUST_WRITE_FIELD(p, t7_tWTR_fine_tune, v); } -static inline bool cust_set_burst_read_lat(const char* p, u32 v) { CUST_WRITE_FIELD(p, mem_burst_read_latency, v); } -static inline bool cust_set_burst_write_lat(const char* p, u32 v) { CUST_WRITE_FIELD(p, mem_burst_write_latency, v); } - -static inline bool cust_set_erista_cpu_uv(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaCpuUV, v); } -static inline bool cust_set_eristaCpuVmin(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaCpuVmin, v); } -static inline bool cust_set_erista_cpu_max_volt(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaCpuMaxVolt, v); } -static inline bool cust_set_eristaCpuUnlock(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaCpuUnlock, v); } - -static inline bool cust_set_mariko_cpu_uv_low(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoCpuUVLow, v); } -static inline bool cust_set_mariko_cpu_uv_high(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoCpuUVHigh, v); } -static inline bool cust_set_mariko_cpu_low_vmin(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoCpuLowVmin, v); } -static inline bool cust_set_mariko_cpu_high_vmin(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoCpuHighVmin, v); } -static inline bool cust_set_mariko_cpu_max_volt(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoCpuMaxVolt, v); } -static inline bool cust_set_erista_cpu_boost(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaCpuBoostClock, v); } -static inline bool cust_set_mariko_cpu_boost(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoCpuBoostClock, v); } - -static inline bool cust_set_erista_gpu_uv(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaGpuUV, v); } -static inline bool cust_set_erista_gpu_vmin(const char* p, u32 v) { CUST_WRITE_FIELD(p, eristaGpuVmin, v); } -static inline bool cust_set_mariko_gpu_uv(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoGpuUV, v); } -static inline bool cust_set_mariko_gpu_vmin(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoGpuVmin, v); } -static inline bool cust_set_mariko_gpu_vmax(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoGpuVmax, v); } -static inline bool cust_set_common_gpu_offset(const char* p, u32 v) { CUST_WRITE_FIELD(p, commonGpuVoltOffset, v); } -static inline bool cust_set_gpu_speedo(const char* p, u32 v) { CUST_WRITE_FIELD(p, gpuSpeedo, v); } -static inline bool cust_set_marikoCpuMaxClock(const char* p, u32 v) { CUST_WRITE_FIELD(p, marikoCpuMaxClock, v); } - -/* GPU VOLT ARRAY HELPERS */ -static inline bool cust_set_erista_gpu_volt(const char* p, int idx, u32 v) { - if (idx < 0 || idx >= 27) return false; - CustomizeTable t; - if (!cust_read_table(p, &t)) return false; - t.eristaGpuVoltArray[idx] = v; - return cust_write_table(p, &t); -} - -static inline bool cust_set_mariko_gpu_volt(const char* p, int idx, u32 v) { - if (idx < 0 || idx >= 24) return false; - CustomizeTable t; - if (!cust_read_table(p, &t)) return false; - t.marikoGpuVoltArray[idx] = v; - return cust_write_table(p, &t); -} - -static inline u32 cust_get_field(const CustomizeTable* t, u32 offset) { - if (!t) return 0; - return *(u32*)((u8*)t + offset); -} - -#define CUST_GET_FIELD(table, field) ((table) ? (table)->field : 0) - -static inline u32 cust_get_cust_rev(const CustomizeTable* t) { return CUST_GET_FIELD(t, custRev); } -// static inline u32 cust_get_mtc_conf(const CustomizeTable* t) { return CUST_GET_FIELD(t, mtcConf); } -static inline u32 cust_get_hp_mode(const CustomizeTable* t) { return CUST_GET_FIELD(t, hpMode); } - -static inline u32 cust_get_common_emc_volt(const CustomizeTable* t) { return CUST_GET_FIELD(t, commonEmcMemVolt); } -static inline u32 cust_get_erista_emc_max(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaEmcMaxClock); } -static inline u32 cust_get_erista_emc_max1(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaEmcMaxClock1); } -static inline u32 cust_get_erista_emc_max2(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaEmcMaxClock2); } -static inline u32 cust_get_mariko_emc_max(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoEmcMaxClock); } -static inline u32 cust_get_mariko_emc_vddq(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoEmcVddqVolt); } -static inline u32 cust_get_emc_dvb_shift(const CustomizeTable* t) { return CUST_GET_FIELD(t, emcDvbShift); } - -static inline u32 cust_get_tRCD(const CustomizeTable* t) { return CUST_GET_FIELD(t, t1_tRCD); } -static inline u32 cust_get_tRP(const CustomizeTable* t) { return CUST_GET_FIELD(t, t2_tRP); } -static inline u32 cust_get_tRAS(const CustomizeTable* t) { return CUST_GET_FIELD(t, t3_tRAS); } -static inline u32 cust_get_tRRD(const CustomizeTable* t) { return CUST_GET_FIELD(t, t4_tRRD); } -static inline u32 cust_get_tRFC(const CustomizeTable* t) { return CUST_GET_FIELD(t, t5_tRFC); } -static inline u32 cust_get_tRTW(const CustomizeTable* t) { return CUST_GET_FIELD(t, t6_tRTW); } -static inline u32 cust_get_tWTR(const CustomizeTable* t) { return CUST_GET_FIELD(t, t7_tWTR); } -static inline u32 cust_get_tREFI(const CustomizeTable* t) { return CUST_GET_FIELD(t, t8_tREFI); } -static inline u32 cust_get_tRTW_fine_tune(const CustomizeTable* t) { return CUST_GET_FIELD(t, t6_tRTW_fine_tune); } -static inline u32 cust_get_tWTR_fine_tune(const CustomizeTable* t) { return CUST_GET_FIELD(t, t7_tWTR_fine_tune); } -static inline u32 cust_get_burst_read_lat(const CustomizeTable* t) { return CUST_GET_FIELD(t, mem_burst_read_latency); } -static inline u32 cust_get_burst_write_lat(const CustomizeTable* t) { return CUST_GET_FIELD(t, mem_burst_write_latency); } - -static inline u32 cust_get_erista_cpu_uv(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaCpuUV); } -static inline u32 cust_get_eristaCpuVmin(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaCpuVmin); } -static inline u32 cust_get_erista_cpu_max_volt(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaCpuMaxVolt); } -static inline u32 cust_get_eristaCpuUnlock(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaCpuUnlock); } - -static inline u32 cust_get_mariko_cpu_uv_low(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoCpuUVLow); } -static inline u32 cust_get_mariko_cpu_uv_high(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoCpuUVHigh); } -static inline u32 cust_get_mariko_cpu_low_vmin(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoCpuLowVmin); } -static inline u32 cust_get_mariko_cpu_high_vmin(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoCpuHighVmin); } -static inline u32 cust_get_mariko_cpu_max_volt(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoCpuMaxVolt); } -static inline u32 cust_get_erista_cpu_boost(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaCpuBoostClock); } -static inline u32 cust_get_mariko_cpu_boost(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoCpuBoostClock); } -static inline u32 cust_get_table_conf(const CustomizeTable* t) { return CUST_GET_FIELD(t, tableConf); } - -static inline u32 cust_get_erista_gpu_uv(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaGpuUV); } -static inline u32 cust_get_erista_gpu_vmin(const CustomizeTable* t) { return CUST_GET_FIELD(t, eristaGpuVmin); } -static inline u32 cust_get_mariko_gpu_uv(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoGpuUV); } -static inline u32 cust_get_mariko_gpu_vmin(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoGpuVmin); } -static inline u32 cust_get_mariko_gpu_vmax(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoGpuVmax); } -static inline u32 cust_get_common_gpu_offset(const CustomizeTable* t) { return CUST_GET_FIELD(t, commonGpuVoltOffset); } -static inline u32 cust_get_gpu_speedo(const CustomizeTable* t) { return CUST_GET_FIELD(t, gpuSpeedo); } -static inline u32 cust_get_marikoCpuMaxClock(const CustomizeTable* t) { return CUST_GET_FIELD(t, marikoCpuMaxClock); } - -static inline u32 cust_get_erista_gpu_volt(const CustomizeTable* t, int idx) { - if (!t || idx < 0 || idx >= 27) return 0; - return t->eristaGpuVoltArray[idx]; -} - -static inline u32 cust_get_mariko_gpu_volt(const CustomizeTable* t, int idx) { - if (!t || idx < 0 || idx >= 24) return 0; - return t->marikoGpuVoltArray[idx]; -} - -#define DECL_ERISTA_GPU_VOLT_HELPER(freq, idx) \ -static inline bool cust_set_erista_gpu_volt_##freq( \ - const char* p, u32 v) { \ - return cust_set_erista_gpu_volt(p, idx, v); \ -} - -#define DECL_MARIKO_GPU_VOLT_HELPER(freq, idx) \ -static inline bool cust_set_mariko_gpu_volt_##freq( \ - const char* p, u32 v) { \ - return cust_set_mariko_gpu_volt(p, idx, v); \ -} - -DECL_ERISTA_GPU_VOLT_HELPER(76800, 0) -DECL_ERISTA_GPU_VOLT_HELPER(115200, 1) -DECL_ERISTA_GPU_VOLT_HELPER(153600, 2) -DECL_ERISTA_GPU_VOLT_HELPER(192000, 3) -DECL_ERISTA_GPU_VOLT_HELPER(230400, 4) -DECL_ERISTA_GPU_VOLT_HELPER(268800, 5) -DECL_ERISTA_GPU_VOLT_HELPER(307200, 6) -DECL_ERISTA_GPU_VOLT_HELPER(345600, 7) -DECL_ERISTA_GPU_VOLT_HELPER(384000, 8) -DECL_ERISTA_GPU_VOLT_HELPER(422400, 9) -DECL_ERISTA_GPU_VOLT_HELPER(460800, 10) -DECL_ERISTA_GPU_VOLT_HELPER(499200, 11) -DECL_ERISTA_GPU_VOLT_HELPER(537600, 12) -DECL_ERISTA_GPU_VOLT_HELPER(576000, 13) -DECL_ERISTA_GPU_VOLT_HELPER(614400, 14) -DECL_ERISTA_GPU_VOLT_HELPER(652800, 15) -DECL_ERISTA_GPU_VOLT_HELPER(691200, 16) -DECL_ERISTA_GPU_VOLT_HELPER(729600, 17) -DECL_ERISTA_GPU_VOLT_HELPER(768000, 18) -DECL_ERISTA_GPU_VOLT_HELPER(806400, 19) -DECL_ERISTA_GPU_VOLT_HELPER(844800, 20) -DECL_ERISTA_GPU_VOLT_HELPER(883200, 21) -DECL_ERISTA_GPU_VOLT_HELPER(921600, 22) -DECL_ERISTA_GPU_VOLT_HELPER(960000, 23) -DECL_ERISTA_GPU_VOLT_HELPER(998400, 24) -DECL_ERISTA_GPU_VOLT_HELPER(1036800, 25) -DECL_ERISTA_GPU_VOLT_HELPER(1075200, 26) - -DECL_MARIKO_GPU_VOLT_HELPER(76800, 0) -DECL_MARIKO_GPU_VOLT_HELPER(153600, 1) -DECL_MARIKO_GPU_VOLT_HELPER(230400, 2) -DECL_MARIKO_GPU_VOLT_HELPER(307200, 3) -DECL_MARIKO_GPU_VOLT_HELPER(384000, 4) -DECL_MARIKO_GPU_VOLT_HELPER(460800, 5) -DECL_MARIKO_GPU_VOLT_HELPER(537600, 6) -DECL_MARIKO_GPU_VOLT_HELPER(614400, 7) -DECL_MARIKO_GPU_VOLT_HELPER(691200, 8) -DECL_MARIKO_GPU_VOLT_HELPER(768000, 9) -DECL_MARIKO_GPU_VOLT_HELPER(844800, 10) -DECL_MARIKO_GPU_VOLT_HELPER(921600, 11) -DECL_MARIKO_GPU_VOLT_HELPER(998400, 12) -DECL_MARIKO_GPU_VOLT_HELPER(1075200, 13) -DECL_MARIKO_GPU_VOLT_HELPER(1152000, 14) -DECL_MARIKO_GPU_VOLT_HELPER(1228800, 15) -DECL_MARIKO_GPU_VOLT_HELPER(1267200, 16) -DECL_MARIKO_GPU_VOLT_HELPER(1305600, 17) -DECL_MARIKO_GPU_VOLT_HELPER(1344000, 18) -DECL_MARIKO_GPU_VOLT_HELPER(1382400, 19) -DECL_MARIKO_GPU_VOLT_HELPER(1420800, 20) -DECL_MARIKO_GPU_VOLT_HELPER(1459200, 21) -DECL_MARIKO_GPU_VOLT_HELPER(1497600, 22) -DECL_MARIKO_GPU_VOLT_HELPER(1536000, 23) - - -#define DECL_ERISTA_GPU_VOLT_GET(freq, idx) \ -static inline u32 cust_get_erista_gpu_volt_##freq##_val(const char* p) { \ - CustomizeTable t; \ - if (!cust_read_table(p, &t)) return 0; \ - return cust_get_erista_gpu_volt(&t, idx); \ -} -#define DECL_MARIKO_GPU_VOLT_GET(freq, idx) \ -static inline u32 cust_get_mariko_gpu_volt_##freq##_val(const char* p) { \ - CustomizeTable t; \ - if (!cust_read_table(p, &t)) return 0; \ - return cust_get_mariko_gpu_volt(&t, idx); \ -} - -DECL_ERISTA_GPU_VOLT_GET(76800, 0) -DECL_ERISTA_GPU_VOLT_GET(115200, 1) -DECL_ERISTA_GPU_VOLT_GET(153600, 2) -DECL_ERISTA_GPU_VOLT_GET(192000, 3) -DECL_ERISTA_GPU_VOLT_GET(230400, 4) -DECL_ERISTA_GPU_VOLT_GET(268800, 5) -DECL_ERISTA_GPU_VOLT_GET(307200, 6) -DECL_ERISTA_GPU_VOLT_GET(345600, 7) -DECL_ERISTA_GPU_VOLT_GET(384000, 8) -DECL_ERISTA_GPU_VOLT_GET(422400, 9) -DECL_ERISTA_GPU_VOLT_GET(460800, 10) -DECL_ERISTA_GPU_VOLT_GET(499200, 11) -DECL_ERISTA_GPU_VOLT_GET(537600, 12) -DECL_ERISTA_GPU_VOLT_GET(576000, 13) -DECL_ERISTA_GPU_VOLT_GET(614400, 14) -DECL_ERISTA_GPU_VOLT_GET(652800, 15) -DECL_ERISTA_GPU_VOLT_GET(691200, 16) -DECL_ERISTA_GPU_VOLT_GET(729600, 17) -DECL_ERISTA_GPU_VOLT_GET(768000, 18) -DECL_ERISTA_GPU_VOLT_GET(806400, 19) -DECL_ERISTA_GPU_VOLT_GET(844800, 20) -DECL_ERISTA_GPU_VOLT_GET(883200, 21) -DECL_ERISTA_GPU_VOLT_GET(921600, 22) -DECL_ERISTA_GPU_VOLT_GET(960000, 23) -DECL_ERISTA_GPU_VOLT_GET(998400, 24) -DECL_ERISTA_GPU_VOLT_GET(1036800, 25) -DECL_ERISTA_GPU_VOLT_GET(1075200, 26) - -DECL_MARIKO_GPU_VOLT_GET(76800, 0) -DECL_MARIKO_GPU_VOLT_GET(153600, 1) -DECL_MARIKO_GPU_VOLT_GET(230400, 2) -DECL_MARIKO_GPU_VOLT_GET(307200, 3) -DECL_MARIKO_GPU_VOLT_GET(384000, 4) -DECL_MARIKO_GPU_VOLT_GET(460800, 5) -DECL_MARIKO_GPU_VOLT_GET(537600, 6) -DECL_MARIKO_GPU_VOLT_GET(614400, 7) -DECL_MARIKO_GPU_VOLT_GET(691200, 8) -DECL_MARIKO_GPU_VOLT_GET(768000, 9) -DECL_MARIKO_GPU_VOLT_GET(844800, 10) -DECL_MARIKO_GPU_VOLT_GET(921600, 11) -DECL_MARIKO_GPU_VOLT_GET(998400, 12) -DECL_MARIKO_GPU_VOLT_GET(1075200, 13) -DECL_MARIKO_GPU_VOLT_GET(1152000, 14) -DECL_MARIKO_GPU_VOLT_GET(1228800, 15) -DECL_MARIKO_GPU_VOLT_GET(1267200, 16) -DECL_MARIKO_GPU_VOLT_GET(1305600, 17) -DECL_MARIKO_GPU_VOLT_GET(1344000, 18) -DECL_MARIKO_GPU_VOLT_GET(1382400, 19) -DECL_MARIKO_GPU_VOLT_GET(1420800, 20) -DECL_MARIKO_GPU_VOLT_GET(1459200, 21) -DECL_MARIKO_GPU_VOLT_GET(1497600, 22) -DECL_MARIKO_GPU_VOLT_GET(1536000, 23) \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/main.cpp b/Source/sys-clk/sysmodule/src/main.cpp deleted file mode 100644 index d38a9ae4..00000000 --- a/Source/sys-clk/sysmodule/src/main.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - -#include -#include -#include - -#include - -#include "errors.h" -#include "file_utils.h" -#include "board.h" -#include "process_management.h" -#include "clock_manager.h" -#include "ipc_service.h" -#define INNER_HEAP_SIZE 0x45000 - - -extern "C" -{ - void virtmemSetup(void); - - extern std::uint32_t __start__; - - std::uint32_t __nx_applet_type = AppletType_None; - TimeServiceType __nx_time_service_type = TimeServiceType_System; - std::uint32_t __nx_fs_num_sessions = 1; - u32 __nx_nv_transfermem_size = 0x8000; - size_t nx_inner_heap_size = INNER_HEAP_SIZE; - char nx_inner_heap[INNER_HEAP_SIZE]; - NvServiceType __nx_nv_service_type = NvServiceType_Factory; - - - void __libnx_initheap(void) - { - void* addr = nx_inner_heap; - size_t size = nx_inner_heap_size; - - /* Newlib Heap Management */ - extern char* fake_heap_start; - extern char* fake_heap_end; - - fake_heap_start = (char*)addr; - fake_heap_end = (char*)addr + size; - - virtmemSetup(); - } - - void __appInit(void) - { - if (R_FAILED(smInitialize())) - { - fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_SM)); - } - - Result rc = setsysInitialize(); - if (R_SUCCEEDED(rc)) - { - SetSysFirmwareVersion fw; - rc = setsysGetFirmwareVersion(&fw); - if (R_SUCCEEDED(rc)) - hosversionSet(MAKEHOSVERSION(fw.major, fw.minor, fw.micro)); - setsysExit(); - } - - // rc = fanInitialize(); - // if (R_FAILED(rc)) - // diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_ShouldNotHappen)); - - rc = i2cInitialize(); - if (R_FAILED(rc)) - diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_ShouldNotHappen)); - rc = appletInitialize(); - if (R_FAILED(rc)) - diagAbortWithResult(MAKERESULT(Module_Libnx, LibnxError_ShouldNotHappen)); - } - - void __appExit(void) - { - // CloseFanControllerThread(); - // fanExit(); - i2cExit(); - fsExit(); - fsdevUnmountAll(); - appletExit(); - } -} - -int main(int argc, char** argv) -{ - Result rc = FileUtils::Initialize(); - if (R_FAILED(rc)) - { - fatalThrow(rc); - return 1; - } - - try - { - Board::Initialize(); - ProcessManagement::Initialize(); - - ProcessManagement::WaitForQLaunch(); - - ClockManager* clockMgr = new ClockManager(); - IpcService* ipcSrv = new IpcService(clockMgr); - - FileUtils::LogLine("Ready"); - - clockMgr->SetRunning(true); - clockMgr->GetConfig()->SetEnabled(true); - ipcSrv->SetRunning(true); - // TemperaturePoint *table; - // ReadConfigFile(&table); - // InitFanController(table); - // StartFanControllerThread(); - - while (clockMgr->Running()) - { - clockMgr->Tick(); - clockMgr->WaitForNextTick(); - } - - ipcSrv->SetRunning(false); - delete ipcSrv; - delete clockMgr; - ProcessManagement::Exit(); - Board::Exit(); - } - catch (const std::exception &ex) - { - FileUtils::LogLine("[!] %s", ex.what()); - } - catch (...) - { - std::exception_ptr p = std::current_exception(); - FileUtils::LogLine("[!?] %s", p ? p.__cxa_exception_type()->name() : "..."); - } - - FileUtils::LogLine("Exit"); - svcSleepThread(1000000ULL); - FileUtils::Exit(); - - return 0; -} diff --git a/Source/sys-clk/sysmodule/src/process_management.cpp b/Source/sys-clk/sysmodule/src/process_management.cpp deleted file mode 100644 index 6c0f6953..00000000 --- a/Source/sys-clk/sysmodule/src/process_management.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#include "process_management.h" -#include "file_utils.h" -#include "errors.h" -#define IS_QLAUNCH 0x20f - -void ProcessManagement::Initialize() -{ - Result rc = 0; - - rc = pmdmntInitialize(); - ASSERT_RESULT_OK(rc, "pmdmntInitialize"); - - rc = pminfoInitialize(); - ASSERT_RESULT_OK(rc, "pminfoInitialize"); -} - -void ProcessManagement::WaitForQLaunch() -{ - Result rc = 0; - std::uint64_t pid = 0; - do - { - rc = pmdmntGetProcessId(&pid, PROCESS_MANAGEMENT_QLAUNCH_TID); - svcSleepThread(50 * 1000000ULL); // 50ms - } while (R_FAILED(rc)); -} - -std::uint64_t ProcessManagement::GetCurrentApplicationId() -{ - Result rc = 0; - std::uint64_t pid = 0; - std::uint64_t tid = 0; - rc = pmdmntGetApplicationProcessId(&pid); - - if (rc == IS_QLAUNCH) - { - return PROCESS_MANAGEMENT_QLAUNCH_TID; - } - - ASSERT_RESULT_OK(rc, "pmdmntGetApplicationProcessId"); - - rc = pminfoGetProgramId(&tid, pid); - - if (rc == IS_QLAUNCH) - { - return PROCESS_MANAGEMENT_QLAUNCH_TID; - } - - ASSERT_RESULT_OK(rc, "pminfoGetProgramId"); - - return tid; -} - -void ProcessManagement::Exit() -{ - pmdmntExit(); - pminfoExit(); -} diff --git a/Source/sys-clk/sysmodule/src/process_management.h b/Source/sys-clk/sysmodule/src/process_management.h deleted file mode 100644 index 65abe792..00000000 --- a/Source/sys-clk/sysmodule/src/process_management.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (c) Souldbminer, Lightos_ and Horizon OC Contributors - * - * This program is free software; you can redistribute it and/or modify it - * under the terms and conditions of the GNU General Public License, - * version 2, as published by the Free Software Foundation. - * - * This program is distributed in the hope 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 . - * - */ - -/* -------------------------------------------------------------------------- - * "THE BEER-WARE LICENSE" (Revision 42): - * , , - * wrote this file. As long as you retain this notice you can do whatever you - * want with this stuff. If you meet any of us some day, and you think this - * stuff is worth it, you can buy us a beer in return. - The sys-clk authors - * -------------------------------------------------------------------------- - */ - - -#pragma once -#include -#include - -#define PROCESS_MANAGEMENT_QLAUNCH_TID 0x0100000000001000ULL - -class ProcessManagement -{ - public: - static void Initialize(); - static void WaitForQLaunch(); - static std::uint64_t GetCurrentApplicationId(); - static void Exit(); -}; diff --git a/Source/sys-clk/sysmodule/toolbox.json b/Source/sys-clk/sysmodule/toolbox.json deleted file mode 100644 index 83ac964c..00000000 --- a/Source/sys-clk/sysmodule/toolbox.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "name" : "hoc-clk", - "tid" : "00FF0000636C6BFF", - "requires_reboot": false -} \ No newline at end of file diff --git a/Source/sys-clk/template_gen.py b/Source/sys-clk/template_gen.py deleted file mode 100644 index c2be942e..00000000 --- a/Source/sys-clk/template_gen.py +++ /dev/null @@ -1,200 +0,0 @@ -#!/usr/bin/env python3 -import os -import re -import json - -SOURCE_DIR = os.path.join("overlay", "src", "ui", "gui") -OUTPUT_FILE = os.path.join("overlay", "lang", "en.json") - -IGNORED_PREFIXES = ( - "/", - "sysclk", "hocclk", "horizonoc" -) - - -UNTRANSLATABLE = { - # Developers - "Souldbminer", - "Lightos_", - # Contributors - "Blaise25", - # Testers - "Samybigio2011", - "Delta", - "Miki1305", - "Happy", - "Flopsider", - "Winnerboi77", - "WE1ZARD", - "Alvise", - "agjeococh", - "Xenshen", - "Frost", - # Special Thanks - "ScriesM - Atmosphere CFW", - "KazushiMe - Switch OC Suite", - "hanai3bi - Switch OC Suite & EOS", - "NaGaa95 - L4T-OC-Kernel", - "B3711 - EOS", - "RetroNX - sys-clk", - "b0rd2death - Ultrahand", - "MasaGratoR - Status Monitor", - # RAM modules - "HB-MGCH 4GB", - "HM-MGCH 6GB", - "HM-MGXX 8GB", - "AM-MGCJ 4GB", - "AM-MGCJ 8GB", - "AA-MGCL 4GB", - "AA-MGCL 8GB", - "AB-MGCL 4GB", - "x267 4GB", - "NLE 4GB", - "NEE 4GB", - "NME 4GB", - "WT:C 4GB", - "WT:E 4GB", - "WT:F 4GB", - "WT:B 4GB", - # Technical labels that must not be translated - "NV Service", - "Governor", - "Speedo:", - "%u.%u%u mV", - "1333 RL", - "1600 RL", - "1866 RL", - "2133 RL", - "VDD2 + VDDQ", - "VDD2 + Usage", - "VDDQ + Usage", - "SoC DVB Shift", - "PCV Hijack", - "Horizon OC Zeus", - # Timing labels - "t1 tRCD", - "t2 tRP", - "t3 tRAS", - "t4 tRRD", - "t5 tRFC", - "t6 tRTW", - "t7 tWTR", - "t8 tREFI", - "tREFI", - "JEDEC", - "App ID", - "Profile", - "USB Charger", - "Handheld", - "PD Charger", - "Docked", - - # MHz warning strings with mixed technical terms - "1581MHz Tbreak", - "1683MHz Tbreak", -} - - -def extract_strings_from_file(filepath: str) -> list[str]: - with open(filepath, "r", encoding="utf-8", errors="ignore") as f: - content = f.read() - pattern = r'"((?:[^"\\]|\\.)*)"' - return re.findall(pattern, content) - - -def should_include(s: str) -> bool: - if not s or s.isspace(): - return False - - stripped = s.strip() - - # --- Skip strings 5 characters or less --- - if len(stripped) <= 5: - return False - - # --- Prefix filters --- - for prefix in IGNORED_PREFIXES: - if s.startswith(prefix): - return False - - # Skip raw unicode escape sequences - if re.match(r"^\\u[0-9a-fA-F]", s): - return False - - # --- File paths / includes --- - if re.fullmatch(r"[a-zA-Z0-9_./\\-]+\.(h|hpp|cpp|c)", stripped): - return False - - # --- Format specifiers --- - if re.fullmatch(r"[%\d.*\-+lfdsuxXpLh ]*", stripped) and "%" in stripped: - return False - - # --- Whitespace / escape sequences only --- - if re.fullmatch(r"[\\nt ]*", stripped): - return False - - # --- Pure numeric values with units --- - if re.fullmatch(r"[+\- ]*\d+\.?\d*\s*(MHz|mV|mA|mW|Hz|ms|°C|%%|p)?", stripped): - return False - - # --- Mixed format/unit junk --- - if re.fullmatch(r"[%\d./*+\-ufdsxXlLhp ,°CM:HzWmVA\\n]+", stripped): - return False - - # --- IPC function names --- - if re.match(r"^hocClkIpc", stripped): - return False - - # --- Escape sequences only --- - if re.fullmatch(r"(\\[nt])+", stripped): - return False - - # --- Unicode escape sequences only --- - if re.fullmatch(r"[\s]*(\\u[0-9a-fA-F]{4}[\s]*)+", stripped): - return False - - # --- Untranslatable set --- - if stripped in UNTRANSLATABLE: - return False - - return True - - -def main(): - seen: set[str] = set() - strings: list[str] = [] - - if not os.path.isdir(SOURCE_DIR): - print(f"Error: directory '{SOURCE_DIR}' not found.") - return - - for filename in sorted(os.listdir(SOURCE_DIR)): - if not filename.endswith((".cpp", ".h")): - continue - - filepath = os.path.join(SOURCE_DIR, filename) - for s in extract_strings_from_file(filepath): - if s not in seen and should_include(s): - seen.add(s) - strings.append(s) - - translations = {s: s for s in strings} - - os.makedirs(os.path.dirname(OUTPUT_FILE), exist_ok=True) - - with open(OUTPUT_FILE, "w", encoding="utf-8") as f: - f.write("{\n") - items = list(translations.items()) - for i, (key, val) in enumerate(items): - k = json.dumps(key, ensure_ascii=False) - v = json.dumps(val, ensure_ascii=False) - comma = "," if i < len(items) - 1 else "" - f.write(f" {k}: {v}{comma}\n") - f.write("}\n") - - print(f"Extracted {len(translations)} unique strings from {SOURCE_DIR}") - print(f"Written to {OUTPUT_FILE}") - - -if __name__ == "__main__": - main() \ No newline at end of file diff --git a/Source/sys-clk/translate.py b/Source/sys-clk/translate.py deleted file mode 100644 index 2542f911..00000000 --- a/Source/sys-clk/translate.py +++ /dev/null @@ -1,147 +0,0 @@ -#!/usr/bin/env python3 -""" -Usage: - python translate_json.py # translate to all languages - python translate_json.py fr de ja # translate to specific languages only -""" - -import json -import os -import re -import ssl -import sys -import time -import urllib.parse -import urllib.request - -INPUT_FILE = os.path.join("overlay", "lang", "en.json") -BATCH_SIZE = 75 -DELAY = 0.3 - -ALL_LANGUAGES = [ - "es", "fr", "de", "ja", "ko", "it", "nl", "pt", "ru", "uk", "pl", "zh-cn", "zh-tw", -] - -SSL_CTX = ssl.create_default_context() -SSL_CTX.check_hostname = False -SSL_CTX.verify_mode = ssl.CERT_NONE - -SEPARATOR = "\n\n###\n\n" - - -def load_json(path: str) -> dict: - with open(path, "r", encoding="utf-8") as f: - content = f.read() - content = re.sub(r",\s*}", "}", content) - return json.loads(content) - - -def save_json(data: dict, path: str): - os.makedirs(os.path.dirname(path) or ".", exist_ok=True) - with open(path, "w", encoding="utf-8") as f: - f.write("{\n") - items = list(data.items()) - for i, (key, val) in enumerate(items): - k = json.dumps(key, ensure_ascii=False) - v = json.dumps(val, ensure_ascii=False) - comma = "," if i < len(items) - 1 else "" - f.write(f" {k}: {v}{comma}\n") - f.write("}\n") - - -def translate_batch(texts: list[str], dest: str) -> list[str]: - combined = SEPARATOR.join(texts) - encoded = urllib.parse.quote(combined) - url = ( - f"https://translate.googleapis.com/translate_a/single" - f"?client=gtx&sl=en&tl={dest}&dt=t&q={encoded}" - ) - - req = urllib.request.Request(url) - req.add_header("User-Agent", "Mozilla/5.0") - - with urllib.request.urlopen(req, timeout=30, context=SSL_CTX) as resp: - data = json.loads(resp.read().decode("utf-8")) - full = "".join(part[0] for part in data[0] if part[0]) - - parts = re.split(r"\s*###\s*", full) - - if len(parts) == len(texts): - return [p.strip() for p in parts] - - print(f"\n Split mismatch ({len(parts)} vs {len(texts)}), retrying individually...", end=" ") - results = [] - for t in texts: - try: - enc = urllib.parse.quote(t) - u = f"https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl={dest}&dt=t&q={enc}" - r = urllib.request.Request(u) - r.add_header("User-Agent", "Mozilla/5.0") - with urllib.request.urlopen(r, timeout=10, context=SSL_CTX) as rsp: - d = json.loads(rsp.read().decode("utf-8")) - results.append("".join(p[0] for p in d[0] if p[0])) - time.sleep(0.3) - except Exception: - results.append(t) - return results - - -def translate_language(keys: list[str], values: list[str], lang: str): - total = len(values) - total_batches = (total + BATCH_SIZE - 1) // BATCH_SIZE - translated_values = [] - - for i in range(0, total, BATCH_SIZE): - batch = values[i:i + BATCH_SIZE] - batch_num = (i // BATCH_SIZE) + 1 - print(f" Batch {batch_num}/{total_batches} ({len(batch)} strings)...", - end=" ", flush=True) - - retries = 3 - for attempt in range(retries): - try: - results = translate_batch(batch, lang) - translated_values.extend(results) - print("OK") - break - except Exception as e: - if attempt < retries - 1: - wait = DELAY * (attempt + 2) - print(f"retry in {wait}s ({e})") - time.sleep(wait) - else: - print(f"FAILED ({e}), keeping original") - translated_values.extend(batch) - - if i + BATCH_SIZE < total: - time.sleep(DELAY) - - output_file = os.path.join("lang", f"{lang}.json") - output = dict(zip(keys, translated_values)) - save_json(output, output_file) - print(f" -> {output_file}\n") - - -def main(): - if not os.path.isfile(INPUT_FILE): - print(f"Error: {INPUT_FILE} not found. Run extract_translations.py first.") - sys.exit(1) - - languages = sys.argv[1:] if len(sys.argv) > 1 else ALL_LANGUAGES - - data = load_json(INPUT_FILE) - keys = list(data.keys()) - values = list(data.values()) - - print(f"Loaded {len(values)} strings from {INPUT_FILE}") - print(f"Translating to {len(languages)} languages: {', '.join(languages)}\n") - - for idx, lang in enumerate(languages): - print(f"[{idx + 1}/{len(languages)}] Translating to '{lang}'...") - translate_language(keys, values, lang) - - print("All done!") - - -if __name__ == "__main__": - main() \ No newline at end of file