From 39e666599d145aae23c1a97045f63bfb8bcc3c70 Mon Sep 17 00:00:00 2001 From: souldbminersmwc Date: Wed, 21 Jan 2026 18:30:32 -0500 Subject: [PATCH] finish submodule linking --- .../lib/libultrahand/.github/FUNDING.yml | 2 - .../overlay/lib/libultrahand/.gitmodules | 0 .../lib/libultrahand/.pics/libultrahand.png | Bin 390117 -> 0 bytes .../sys-clk/overlay/lib/libultrahand/LICENSE | 339 - .../overlay/lib/libultrahand/README.md | 211 - .../overlay/lib/libultrahand/SUB_LICENSE | 395 - .../overlay/lib/libultrahand/common/cJSON.c | 3191 ---- .../overlay/lib/libultrahand/common/cJSON.h | 306 - .../overlay/lib/libultrahand/libtesla/LICENSE | 339 - .../lib/libultrahand/libtesla/README.md | 32 - .../libultrahand/libtesla/example/Makefile | 209 - .../libtesla/example/source/main.cpp | 100 - .../libtesla/include/stb_truetype.h | 5210 ------ .../libultrahand/libtesla/include/tesla.hpp | 14531 ---------------- .../overlay/lib/libultrahand/libultra/LICENSE | 339 - .../lib/libultrahand/libultra/README.md | 69 - .../lib/libultrahand/libultra/SUB_LICENSE | 395 - .../libultrahand/libultra/include/audio.hpp | 97 - .../libultra/include/debug_funcs.hpp | 53 - .../libultra/include/download_funcs.hpp | 83 - .../libultra/include/get_funcs.hpp | 160 - .../libultra/include/global_vars.hpp | 182 - .../libultrahand/libultra/include/haptics.hpp | 41 - .../libultra/include/hex_funcs.hpp | 214 - .../libultra/include/ini_funcs.hpp | 374 - .../libultra/include/json_funcs.hpp | 108 - .../libultra/include/list_funcs.hpp | 110 - .../libultra/include/mod_funcs.hpp | 121 - .../libultra/include/path_funcs.hpp | 288 - .../libultra/include/string_funcs.hpp | 274 - .../libultra/include/tsl_utils.hpp | 813 - .../libultrahand/libultra/include/ultra.hpp | 49 - .../libultrahand/libultra/source/audio.cpp | 312 - .../libultra/source/debug_funcs.cpp | 63 - .../libultra/source/download_funcs.cpp | 897 - .../libultra/source/get_funcs.cpp | 506 - .../libultra/source/global_vars.cpp | 188 - .../libultrahand/libultra/source/haptics.cpp | 261 - .../libultra/source/hex_funcs.cpp | 1018 -- .../libultra/source/ini_funcs.cpp | 2563 --- .../libultra/source/json_funcs.cpp | 400 - .../libultra/source/list_funcs.cpp | 531 - .../libultra/source/mod_funcs.cpp | 736 - .../libultra/source/path_funcs.cpp | 1522 -- .../libultra/source/string_funcs.cpp | 641 - .../libultra/source/tsl_utils.cpp | 1882 -- .../overlay/lib/libultrahand/ultrahand.mk | 30 - 47 files changed, 40185 deletions(-) delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/.gitmodules delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/.pics/libultrahand.png delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/LICENSE delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/README.md delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/common/cJSON.c delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/common/cJSON.h delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/README.md delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/README.md delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/audio.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/audio.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp delete mode 100644 Source/sys-clk/overlay/lib/libultrahand/ultrahand.mk diff --git a/Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml b/Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml deleted file mode 100644 index 57fdec3d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml +++ /dev/null @@ -1,2 +0,0 @@ -github: ppkantorski -ko_fi: ppkantorski diff --git a/Source/sys-clk/overlay/lib/libultrahand/.gitmodules b/Source/sys-clk/overlay/lib/libultrahand/.gitmodules deleted file mode 100644 index e69de29b..00000000 diff --git a/Source/sys-clk/overlay/lib/libultrahand/.pics/libultrahand.png b/Source/sys-clk/overlay/lib/libultrahand/.pics/libultrahand.png deleted file mode 100644 index 7165fb92ba7c7558d3cf1b1005dd8285ac2af77b..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 390117 zcmeFZhhLLV);AoAVgW%>5s)ffniQ!46#)SO>Agt}Ep!Nh0HPo&MXL1Pd+$L-YUsTN z1VV=ZA#}nMcYk~DK6|sz`~CsT=L4C{HFKt1r+nv}GlaZRkte%Ba{~YXkSV-+sSW^; z;ETk7Ygh3f%NNS;{(Q53uKXMTC=b7RW_AVtozeW2x-tOZ%?1GYzXt$L@Kye+0DwC` z0I+Tf0EmAB0H~aj8q_554{R)T6|9t%0bKa7^crywub#hUMln3xzJ zzW|?r01v(ek1NE{&CH9((e=^aiTs1kOG{UC7m$-12<*uChpyRMu)7tD;lFOcug6TTxZ-mjOFCxmdco z;-@9`MDlL~{9kqdoZjEtt6RE)?cM*ZLdy~4CMED!mw&7N_g-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+w{kTF4B0xbwiK-$<;D5T?OZu6y?XwZcMf z2n&b0+3LA}aekr1FXMz^py=#g%|F=6=VJbPwq3>A>?-!~?v34b1tPnyVAmB032VE- hYd0(Szqx|RZNT6sQ$K+P6)hrsob7>j^|m43{0rThh+6;v diff --git a/Source/sys-clk/overlay/lib/libultrahand/LICENSE b/Source/sys-clk/overlay/lib/libultrahand/LICENSE deleted file mode 100644 index d159169d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/LICENSE +++ /dev/null @@ -1,339 +0,0 @@ - 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/sys-clk/overlay/lib/libultrahand/README.md b/Source/sys-clk/overlay/lib/libultrahand/README.md deleted file mode 100644 index 6863e166..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/README.md +++ /dev/null @@ -1,211 +0,0 @@ -# ☆ 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-2025 ppkantorski diff --git a/Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE b/Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE deleted file mode 100644 index 2f244ac8..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE +++ /dev/null @@ -1,395 +0,0 @@ -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/sys-clk/overlay/lib/libultrahand/common/cJSON.c b/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.c deleted file mode 100644 index ca824f0e..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.c +++ /dev/null @@ -1,3191 +0,0 @@ -/* - 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/sys-clk/overlay/lib/libultrahand/common/cJSON.h b/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.h deleted file mode 100644 index 37520bbc..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.h +++ /dev/null @@ -1,306 +0,0 @@ -/* - 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/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE deleted file mode 100644 index d159169d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE +++ /dev/null @@ -1,339 +0,0 @@ - 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/sys-clk/overlay/lib/libultrahand/libtesla/README.md b/Source/sys-clk/overlay/lib/libultrahand/libtesla/README.md deleted file mode 100644 index 5782d161..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/README.md +++ /dev/null @@ -1,32 +0,0 @@ -# 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/lib/libultrahand/libtesla/example/Makefile b/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile deleted file mode 100644 index cdb011ae..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile +++ /dev/null @@ -1,209 +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 -# 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. -#--------------------------------------------------------------------------------- - -APP_TITLE := Tesla Example -APP_VERSION := 1.3.0 - -TARGET := $(notdir $(CURDIR)) -BUILD := build -SOURCES := source -DATA := data -INCLUDES := ../include - -NO_ICON := 1 - -#--------------------------------------------------------------------------------- -# options for code generation -#--------------------------------------------------------------------------------- -ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE - -CFLAGS := -g -Wall -O2 -ffunction-sections \ - $(ARCH) $(DEFINES) - -CFLAGS += $(INCLUDE) -D__SWITCH__ - -CXXFLAGS := $(CFLAGS) -fno-exceptions -std=c++20 - -ASFLAGS := -g $(ARCH) -LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) - -LIBS := -lnx - -#--------------------------------------------------------------------------------- -# 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 OUTPUT := $(CURDIR)/$(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_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) \ - -I$(CURDIR)/$(BUILD) - -export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) - -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 $@ - @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile - -#--------------------------------------------------------------------------------- -clean: - @rm -fr $(BUILD) $(TARGET).ovl $(TARGET).nro $(TARGET).nacp $(TARGET).elf - - -#--------------------------------------------------------------------------------- -else -.PHONY: all - -DEPENDS := $(OFILES:.o=.d) - -#--------------------------------------------------------------------------------- -# main targets -#--------------------------------------------------------------------------------- -all : $(OUTPUT).ovl - -$(OUTPUT).ovl : $(OUTPUT).elf $(OUTPUT).nacp - @elf2nro $< $@ $(NROFLAGS) - @echo "built ... $(notdir $(OUTPUT).ovl)" - -$(OUTPUT).elf : $(OFILES) - -$(OFILES_SRC) : $(HFILES_BIN) - -#--------------------------------------------------------------------------------- -# you need a rule like this for each extension you use as binary data -#--------------------------------------------------------------------------------- -%.bin.o %_bin.h : %.bin -#--------------------------------------------------------------------------------- - @echo $(notdir $<) - @$(bin2o) - --include $(DEPENDS) - -#--------------------------------------------------------------------------------------- -endif -#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp b/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp deleted file mode 100644 index bf4c2522..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp +++ /dev/null @@ -1,100 +0,0 @@ -#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/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h b/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h deleted file mode 100644 index 04c154f5..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h +++ /dev/null @@ -1,5210 +0,0 @@ -// 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/sys-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp b/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp deleted file mode 100644 index 546ea636..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp +++ /dev/null @@ -1,14531 +0,0 @@ -/******************************************************************************** - * 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-2025 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 // despite being commented out, it must still be being imported via other libs -#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! -// #define TESLA_INIT_IMPL - -#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 GlyphInfo { -// u8* pointer; -// int width; -// int height; -//}; - -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 { - //static constexpr float epsilon = 0.00001f; - return lhs.first == rhs.first && - std::abs(lhs.second - rhs.second) < 0.00001f; - } -}; - -//std::unordered_map, GlyphInfo, KeyPairHash, KeyPairEqual> cache; - -u8 TeslaFPS = 60; -//u8 alphabackground = 0xD; -std::atomic triggerExitNow{false}; -std::atomic isRendering{false}; -std::atomic delayUpdate{false}; -std::atomic pendingExit{false}; -std::atomic wasRendering{false}; - -LEvent renderingStopEvent; -bool FullMode = true; -bool deactivateOriginalFooter = false; -//bool fontCache = true; -bool disableJumpTo = false; - -// Check for mini/micro mode flags -//bool isMiniOrMicroMode = false; -inline std::string lastMode; -inline std::set overlayModes = {"full", "mini", "micro", "fps_graph", "fps_counter", "game_resolutions"}; - -bool isValidOverlayMode() { - return overlayModes.count(lastMode) > 0; -} - -#endif - -#if USING_FPS_INDICATOR_DIRECTIVE -float fps = 0.0; -int frameCount = 0; -double elapsedTime; -#endif - - -// Custom variables -//static bool jumpToListItem = false; -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 g_overlayFilename;; -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}; - -//#if IS_LAUNCHER_DIRECTIVE -inline bool hideHidden = false; -//#endif - -//inline std::atomic isLaunchingNextOverlay{false}; -inline std::atomic mainComboHasTriggered{false}; -inline std::atomic launchComboHasTriggered{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 disableSound{false}; -//inline std::atomic clearSoundCacheNow{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}; - - -static inline void triggerNavigationFeedback() { - triggerRumbleClick.store(true, std::memory_order_release); - triggerNavigationSound.store(true, std::memory_order_release); -} - -static inline void triggerEnterFeedback() { - triggerRumbleClick.store(true, std::memory_order_release); - triggerEnterSound.store(true, std::memory_order_release); -} - -static inline void triggerExitFeedback() { - triggerRumbleDoubleClick.store(true, std::memory_order_release); - triggerExitSound.store(true, std::memory_order_release); -} - - -/** - * @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. - */ -static inline 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) - { - const uint32_t libnx = *reinterpret_cast(mod0_ptr + 56); - isNew = (libnx >= 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) - { - const uint32_t libnx = *reinterpret_cast(mod0Buf + 56); - isNew = (libnx >= 1); - } - } - } - } - - free(frontBuf); - fclose(file); - return isNew; -} - -/** - * @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 - */ -static 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); -} - -static bool requiresLNY2 = false; - - - - - - - -namespace tsl { - - // 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(u16 raw): rgba(raw) {} - constexpr inline Color(u8 r, u8 g, u8 b, u8 a): r(r), g(g), b(b), a(a) {} - - }; - - //#if USING_WIDGET_DIRECTIVE - // Ultra-fast version - zero variables, optimized calculations - inline constexpr Color GradientColor(float temperature) { - if (temperature <= 35.0f) return Color(7, 7, 15, 0xFF); - if (temperature >= 65.0f) return Color(15, 0, 0, 0xFF); - - 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, 0xFF); - } - - if (temperature < 55.0f) { - return Color(15 * (temperature - 45.0f) * 0.1f, 15, 0, 0xFF); - } - - return Color(15, 15 - 15 * (temperature - 55.0f) * 0.1f, 0, 0xFF); - } - //#endif - - - // 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 - ); - } - - - 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 // CUSTOM MODIFICATION - 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 - //static bool disableColorfulLogo = false; - - - static Color logoColor1 = RGB888(ult::whiteColor); - static Color logoColor2 = RGB888("F7253E"); - - - static size_t defaultBackgroundAlpha = 13; - - static Color defaultBackgroundColor = RGB888(ult::blackColor, defaultBackgroundAlpha); - static Color defaultTextColor = RGB888(ult::whiteColor); - static Color notificationTextColor = RGB888(ult::whiteColor); - static Color headerTextColor = RGB888(ult::whiteColor); - static Color headerSeparatorColor = RGB888(ult::whiteColor); - static Color starColor = RGB888(ult::whiteColor); - static Color selectionStarColor = RGB888(ult::whiteColor); - static Color buttonColor = RGB888(ult::whiteColor); - static Color bottomTextColor = RGB888(ult::whiteColor); - static Color bottomSeparatorColor = RGB888(ult::whiteColor); - static Color topSeparatorColor = RGB888("404040"); - - static Color defaultOverlayColor = RGB888(ult::whiteColor); - static Color defaultPackageColor = RGB888(ult::whiteColor);//RGB888("#00FF00"); - static Color defaultScriptColor = RGB888("FF33FF"); - static Color clockColor = RGB888(ult::whiteColor); - static Color temperatureColor = RGB888(ult::whiteColor); - static Color batteryColor = RGB888("ffff45"); - static Color batteryChargingColor = RGB888("00FF00"); - static Color batteryLowColor = RGB888("FF0000"); - static size_t widgetBackdropAlpha = 15; - static Color widgetBackdropColor = RGB888(ult::blackColor, widgetBackdropAlpha); - - static Color overlayTextColor = RGB888(ult::whiteColor); - static Color ultOverlayTextColor = RGB888("9ed0ff"); - static Color packageTextColor = RGB888(ult::whiteColor); - static Color ultPackageTextColor = RGB888("9ed0ff"); - - static Color bannerVersionTextColor = RGB888(ult::greyColor); - static Color overlayVersionTextColor = RGB888(ult::greyColor); - static Color ultOverlayVersionTextColor = RGB888("00FFDD"); - static Color packageVersionTextColor = RGB888(ult::greyColor); - static Color ultPackageVersionTextColor = RGB888("00FFDD"); - static Color onTextColor = RGB888("00FFDD"); - static Color offTextColor = RGB888(ult::greyColor); - - #if IS_LAUNCHER_DIRECTIVE - static Color dynamicLogoRGB1 = RGB888("00E669"); - static Color dynamicLogoRGB2 = RGB888("8080EA"); - #endif - - //static bool disableSelectionBG = false; - //static bool disableSelectionValueColor = false; - static bool invertBGClickColor = false; - - static size_t selectionBGAlpha = 11; - static Color selectionBGColor = RGB888(ult::blackColor, selectionBGAlpha); - - static Color highlightColor1 = RGB888("2288CC"); - static Color highlightColor2 = RGB888("88FFFF"); - static Color highlightColor3 = RGB888("FFFF45"); - static Color highlightColor4 = RGB888("F7253E"); - - static Color highlightColor = tsl::style::color::ColorHighlight; - - static size_t clickAlpha = 7; - static Color clickColor = RGB888("3E25F7", clickAlpha); - - static size_t progressAlpha = 7; - static Color progressColor = RGB888("253EF7", progressAlpha); - - static Color scrollBarColor = RGB888("555555"); - static Color scrollBarWallColor = RGB888("AAAAAA"); - - static size_t separatorAlpha = 15; - static Color separatorColor = RGB888("404040", separatorAlpha); - static Color edgeSeparatorColor = RGB888("303030"); - - static Color textSeparatorColor = RGB888("404040"); - - static Color selectedTextColor = RGB888("9ed0ff"); - static Color selectedValueTextColor = RGB888("FF7777"); - static Color inprogressTextColor = RGB888(ult::whiteColor); - static Color invalidTextColor = RGB888("FF0000"); - static Color clickTextColor = RGB888(ult::whiteColor); - - static size_t tableBGAlpha = 14; - static Color tableBGColor = RGB888("2C2C2C", tableBGAlpha); //RGB888("303030", tableBGAlpha); - static Color sectionTextColor = RGB888(ult::whiteColor); - //static Color infoTextColor = RGB888("00FFDD"); - static Color infoTextColor =RGB888("9ed0ff"); - static Color warningTextColor = RGB888("FF7777"); - - static Color healthyRamTextColor = RGB888("00FF00"); - static Color neutralRamTextColor = RGB888("FFAA00"); - static Color badRamTextColor = RGB888("FF0000"); - - static Color trackBarSliderColor = RGB888("606060"); - static Color trackBarSliderBorderColor = RGB888("505050"); - static Color trackBarSliderMalleableColor = RGB888("A0A0A0"); - static Color trackBarFullColor = RGB888("00FFDD"); - static Color trackBarEmptyColor = RGB888("404040"); - - static void initializeThemeVars() { - auto themeData = ult::getParsedDataFromIniFile(ult::THEME_CONFIG_INI_PATH); - if (themeData.count(ult::THEME_STR) == 0) return; - - auto& themeSection = themeData[ult::THEME_STR]; - - auto getValue = [&](const char* key) -> const std::string& { - auto it = themeSection.find(key); - return it != themeSection.end() ? it->second : ult::defaultThemeSettingsMap[key]; - }; - - auto getColor = [&](const char* key, size_t alpha = 15) { - return RGB888(getValue(key), alpha); - }; - - auto getAlpha = [&](const char* key) { - const auto& alphaStr = getValue(key); - return ult::stoi(alphaStr); - }; - - #if IS_LAUNCHER_DIRECTIVE - logoColor1 = getColor("logo_color_1"); - logoColor2 = getColor("logo_color_2"); - 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"); - 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"); - 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"); - } - - #if !IS_LAUNCHER_DIRECTIVE - static void initializeUltrahandSettings() { // only needed for regular overlays - // Load INI data once instead of 4 separate file reads - auto ultrahandSection = ult::getKeyValuePairsFromSection(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME); - - // Helper lambda to safely get string values - auto getStringValue = [&](const std::string& key, const std::string& defaultValue = "") -> std::string { - if (ultrahandSection.count(key) > 0) { - return ultrahandSection.at(key); - } - return defaultValue; - }; - - // Helper lambda to safely get boolean values - auto getBoolValue = [&](const std::string& key, bool defaultValue = false) -> bool { - if (ultrahandSection.count(key) > 0) { - return (ultrahandSection.at(key) == ult::TRUE_STR); - } - return defaultValue; - }; - - // Get default language with fallback - std::string defaultLang = getStringValue(ult::DEFAULT_LANG_STR, "en"); - if (defaultLang.empty()) { - defaultLang = "en"; - } - - #ifdef UI_OVERRIDE_PATH - - std::string UI_PATH = UI_OVERRIDE_PATH; - ult::preprocessPath(UI_PATH); - ult::createDirectory(UI_PATH); // create UI override path automatically (when provided) - - const std::string NEW_THEME_CONFIG_INI_PATH = UI_PATH+"theme.ini"; - const std::string NEW_WALLPAPER_PATH = UI_PATH+"wallpaper.rgba"; - - const std::string TRANSLATION_JSON_PATH = UI_PATH+"lang/"+defaultLang+".json"; - if (ult::isFileOrDirectory(NEW_THEME_CONFIG_INI_PATH)) - ult::THEME_CONFIG_INI_PATH = NEW_THEME_CONFIG_INI_PATH; // Override theme path (optional) - if (ult::isFileOrDirectory(NEW_WALLPAPER_PATH)) - ult::WALLPAPER_PATH = NEW_WALLPAPER_PATH; // Override wallpaper path (optional) - if (ult::isFileOrDirectory(TRANSLATION_JSON_PATH)) - ult::loadTranslationsFromJSON(TRANSLATION_JSON_PATH); // load translations (optional) - #endif - - // Set Ultrahand Globals using loaded section (defaults match initialization function) - ult::useLaunchCombos = getBoolValue("launch_combos", true); // TRUE_STR default - ult::useNotifications = getBoolValue("notifications", true); // TRUE_STR default - if (ult::useNotifications) { - if (!ult::isFile(ult::NOTIFICATIONS_FLAG_FILEPATH)) { - FILE* file = std::fopen((ult::NOTIFICATIONS_FLAG_FILEPATH).c_str(), "w"); - if (file) { - std::fclose(file); - } - } - } else { - ult::deleteFileOrDirectory(ult::NOTIFICATIONS_FLAG_FILEPATH); - } - ult::useSoundEffects = getBoolValue("sound_effects", false); - ult::useHapticFeedback = getBoolValue("haptic_feedback", false); - - ult::useSwipeToOpen = getBoolValue("swipe_to_open", true); // TRUE_STR default - ult::useOpaqueScreenshots = getBoolValue("opaque_screenshots", true); // TRUE_STR default - - ultrahandSection.clear(); - - const std::string langFile = ult::LANG_PATH+defaultLang+".json"; - if (ult::isFileOrDirectory(langFile)) - ult::parseLanguage(langFile); - } - #endif - - - // 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; } - - 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)); - } - - - - } - - static void goBack(u32 count = 1); - - static void pop(u32 count = 1); - - static 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 { - ScopeGuard(const ScopeGuard&) = delete; - ScopeGuard& operator=(const ScopeGuard&) = delete; - private: - F f; - bool canceled = false; - public: - ALWAYS_INLINE ScopeGuard(F f) : f(std::move(f)) { } - ALWAYS_INLINE ~ScopeGuard() { if (!canceled) { f(); } } - void dismiss() { canceled = true; } - }; - - /** - * @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? - */ - static void requestForeground(bool enabled, bool updateGlobalFlag = true) { - 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 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) { - //IniData iniData; - // - //auto lines = split(str, '\n'); - // - //std::string lastHeader = ""; - //for (auto& line : lines) { - // line.erase(std::remove_if(line.begin(), line.end(), ::isspace), line.end()); - // - // if (line[0] == '[' && line[line.size() - 1] == ']') { - // lastHeader = line.substr(1, line.size() - 2); - // iniData.emplace(lastHeader, std::map{}); - // } - // else if (auto keyValuePair = split(line, '='); keyValuePair.size() == 2) { - // iniData[lastHeader].emplace(keyValuePair[0], keyValuePair[1]); - // } - //} - - return ult::parseIni(str); - } - - /** - * @brief Unparses ini data into a string - * - * @param iniData Ini data - * @return Ini string - */ - static 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 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 (std::string key : ult::split(ult::removeWhiteSpaces(value), '+')) { // CUSTOM MODIFICATION (bug fix) - keyCombo |= hlp::stringToKeyCode(key); - } - return keyCombo; - } - - /** - * @brief Encodes key codes into a combo string - * - * @param keys Key codes - * @return Combo string - */ - static 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; - } - - inline static std::mutex comboMutex; - - // Function to load key combo mappings from both overlays.ini and packages.ini - static 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); - //std::string tmpPackageName = packageName; - //ult::removeQuotes(packageName); - if (keys) ult::g_entryCombos[keys] = { ult::OVERLAY_PATH + "ovlmenu.ovl", "--package " + packageName}; - } - } - } - - // 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; - - - #ifdef UI_OVERRIDE_PATH - inline static std::shared_mutex s_translationCacheMutex; - #endif - class FontManager { - public: - struct Glyph { - stbtt_fontinfo *currFont; - float currFontSize; - int bounds[4]; - int xAdvance; - u8 *glyphBmp; - int width, height; - - // Add destructor to ensure cleanup - ~Glyph() { - if (glyphBmp) { - stbtt_FreeBitmap(glyphBmp, nullptr); - glyphBmp = nullptr; - } - } - - // Prevent copying to avoid double-free - Glyph(const Glyph&) = delete; - Glyph& operator=(const Glyph&) = delete; - - // Allow moving - 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; // Prevent double-free - } - - 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; // ascent - descent + lineGap - 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, - Persistent - }; - - private: - inline static std::shared_mutex s_cacheMutex; - inline static std::mutex s_initMutex; - - // Existing caches - inline static std::unordered_map> s_sharedGlyphCache; - //inline static std::unordered_map> s_persistentGlyphCache; - - // NEW: Notification-specific cache - inline static std::unordered_map> s_notificationGlyphCache; - - // Font metrics cache - inline static std::unordered_map s_fontMetricsCache; - - // Add cache size limits - static constexpr size_t MAX_CACHE_SIZE = 600; - static constexpr size_t CLEANUP_THRESHOLD = 500; - static constexpr size_t MAX_NOTIFICATION_CACHE_SIZE = 200; // Separate limit for notifications - - // font handles & state - inline static stbtt_fontinfo* s_stdFont = nullptr; - inline static stbtt_fontinfo* s_localFont = nullptr; - inline static stbtt_fontinfo* s_extFont = nullptr; - inline static bool s_hasLocalFont = false; - inline static bool s_initialized = false; - - // Fix cache key generation to prevent collisions - static u64 generateCacheKey(u32 character, bool monospace, u32 fontSize) { - // Use more bits for fontSize and separate monospace bit - u64 key = static_cast(character); - key = (key << 32) | static_cast(fontSize); - if (monospace) { - key |= (1ULL << 63); // Use the highest bit for monospace - } - return key; - } - - // Generate cache key for font metrics - static u64 generateFontMetricsCacheKey(stbtt_fontinfo* font, u32 fontSize) { - // Use pointer address as font identifier and fontSize - const u64 fontKey = reinterpret_cast(font); - return (fontKey << 32) | static_cast(fontSize); - } - - // Cleanup old entries when cache gets too large - static void cleanupOldEntries() { - if (s_sharedGlyphCache.size() <= CLEANUP_THRESHOLD) return; - - // Simple cleanup: remove oldest entries - // In a real implementation, you might want LRU or other strategies - const size_t toRemove = s_sharedGlyphCache.size() - CLEANUP_THRESHOLD; - auto it = s_sharedGlyphCache.begin(); - for (size_t i = 0; i < toRemove && it != s_sharedGlyphCache.end(); ++i) { - it = s_sharedGlyphCache.erase(it); - } - } - - // NEW: Cleanup notification cache when it gets too large - static void cleanupNotificationCache() { - if (s_notificationGlyphCache.size() <= MAX_NOTIFICATION_CACHE_SIZE) return; - - const size_t toRemove = s_notificationGlyphCache.size() - (MAX_NOTIFICATION_CACHE_SIZE / 2); - auto it = s_notificationGlyphCache.begin(); - for (size_t i = 0; i < toRemove && it != s_notificationGlyphCache.end(); ++i) { - it = s_notificationGlyphCache.erase(it); - } - } - - // NEW: Internal unified glyph creation method - static std::shared_ptr getOrCreateGlyphInternal(u32 character, bool monospace, u32 fontSize, CacheType cacheType) { - const u64 key = generateCacheKey(character, monospace, fontSize); - - // Select target cache based on type - std::unordered_map>* targetCache; - switch (cacheType) { - case CacheType::Notification: - targetCache = &s_notificationGlyphCache; - break; - //case CacheType::Persistent: - // targetCache = &s_persistentGlyphCache; - // break; - default: - targetCache = &s_sharedGlyphCache; - break; - } - - // First, try to find in target cache with shared lock - { - std::shared_lock readLock(s_cacheMutex); - - if (!s_initialized) return nullptr; - - // Check target cache first - auto it = targetCache->find(key); - if (it != targetCache->end()) { - return it->second; - } - - // For notification cache, also check persistent cache (but not regular cache) - // For regular cache, also check persistent cache (existing behavior) - //if (cacheType != CacheType::Persistent) { - // auto persistentIt = s_persistentGlyphCache.find(key); - // if (persistentIt != s_persistentGlyphCache.end()) { - // return persistentIt->second; - // } - //} - } - - // Glyph not found, need to create it with exclusive lock - std::unique_lock writeLock(s_cacheMutex); - - if (!s_initialized) return nullptr; - - // Double-check pattern for target cache - auto it = targetCache->find(key); - if (it != targetCache->end()) { - return it->second; - } - - // Double-check persistent cache - //if (cacheType != CacheType::Persistent) { - // auto persistentIt = s_persistentGlyphCache.find(key); - // if (persistentIt != s_persistentGlyphCache.end()) { - // return persistentIt->second; - // } - //} - - // Check cache size and cleanup if needed - if (cacheType == CacheType::Regular && s_sharedGlyphCache.size() >= MAX_CACHE_SIZE) { - cleanupOldEntries(); - } else if (cacheType == CacheType::Notification && s_notificationGlyphCache.size() >= MAX_NOTIFICATION_CACHE_SIZE) { - cleanupNotificationCache(); - } - - // Create new glyph - 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); - - // Store in target cache - (*targetCache)[key] = glyph; - - return glyph; - } - - public: - // NEW: Preload and persist specific characters - //static void preloadPersistentGlyphs(const std::string& characters, u32 fontSize, bool monospace = false) { - // std::unique_lock writeLock(s_cacheMutex); - // - // if (!s_initialized) return; - // - // // Convert UTF-8 string to UTF-32 codepoints - // #pragma GCC diagnostic push - // #pragma GCC diagnostic ignored "-Wdeprecated-declarations" - // - // std::wstring_convert, char32_t> converter; - // const std::u32string codepoints = converter.from_bytes(characters); - // - // #pragma GCC diagnostic pop - // - // s32 yAdvance; - // for (char32_t character : codepoints) { - // const u64 key = generateCacheKey(character, monospace, fontSize); - // - // if (s_persistentGlyphCache.find(key) != s_persistentGlyphCache.end()) { - // continue; - // } - // - // auto glyph = std::make_shared(); - // glyph->currFont = selectFontForCharacterUnsafe(character); - // if (!glyph->currFont) continue; - // - // 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]); - // - // 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); - // - // s_persistentGlyphCache[key] = glyph; - // } - //} - - - static void initializeFonts(stbtt_fontinfo* stdFont, stbtt_fontinfo* localFont, - stbtt_fontinfo* extFont, bool hasLocalFont) { - std::lock_guard initLock(s_initMutex); - std::unique_lock cacheLock(s_cacheMutex); - - s_stdFont = stdFont; - s_localFont = localFont; - s_extFont = extFont; - s_hasLocalFont = hasLocalFont; - s_initialized = true; - } - - static stbtt_fontinfo* selectFontForCharacter(u32 character) { - std::shared_lock lock(s_cacheMutex); - - if (!s_initialized) return nullptr; - - if (stbtt_FindGlyphIndex(s_extFont, character)) { - return s_extFont; - } else if (s_hasLocalFont && stbtt_FindGlyphIndex(s_localFont, character) != 0) { - // Fix: Always fetch degree symbol "°" from the standard Latin font - return (character != 0x00B0) ? s_localFont : s_stdFont; - } - return s_stdFont; - } - - // Get font metrics with caching - static FontMetrics getFontMetrics(stbtt_fontinfo* font, u32 fontSize) { - if (!font) return FontMetrics(); - - const u64 key = generateFontMetricsCacheKey(font, fontSize); - - // First, try to find existing metrics with shared lock - { - std::shared_lock readLock(s_cacheMutex); - auto it = s_fontMetricsCache.find(key); - if (it != s_fontMetricsCache.end()) { - return it->second; - } - } - - // Metrics not found, need to create them with exclusive lock - std::unique_lock writeLock(s_cacheMutex); - - // Double-check pattern - auto it = s_fontMetricsCache.find(key); - if (it != s_fontMetricsCache.end()) { - return it->second; - } - - // Create new font metrics - FontMetrics metrics(font, static_cast(fontSize)); - s_fontMetricsCache[key] = metrics; - - return metrics; - } - - // Convenience method to get font metrics for a character (selects appropriate font) - static FontMetrics getFontMetricsForCharacter(u32 character, u32 fontSize) { - stbtt_fontinfo* font = selectFontForCharacter(character); - return getFontMetrics(font, fontSize); - } - - // UPDATED: Regular glyph method - now uses internal method - static std::shared_ptr getOrCreateGlyph(u32 character, bool monospace, u32 fontSize) { - return getOrCreateGlyphInternal(character, monospace, fontSize, CacheType::Regular); - } - - // NEW: Notification-specific glyph method - static std::shared_ptr getOrCreateNotificationGlyph(u32 character, bool monospace, u32 fontSize) { - return getOrCreateGlyphInternal(character, monospace, fontSize, CacheType::Notification); - } - - // NEW: Clear only the notification cache - static void clearNotificationCache() { - std::unique_lock cacheLock(s_cacheMutex); - s_notificationGlyphCache.clear(); - s_notificationGlyphCache.rehash(0); - } - - static void clearCache() { - // Note: This is now safe because any code holding a shared_ptr - // will keep the Glyph alive even after the cache is cleared - std::unique_lock cacheLock(s_cacheMutex); - s_sharedGlyphCache.clear(); - s_sharedGlyphCache.rehash(0); - s_fontMetricsCache.clear(); // Also clear font metrics cache - s_fontMetricsCache.rehash(0); - } - - static void clearAllCaches() { - std::unique_lock cacheLock(s_cacheMutex); - s_sharedGlyphCache.clear(); - s_sharedGlyphCache.rehash(0); - //s_persistentGlyphCache.clear(); - //s_persistentGlyphCache.rehash(0); - s_notificationGlyphCache.clear(); - s_notificationGlyphCache.rehash(0); - s_fontMetricsCache.clear(); - s_fontMetricsCache.rehash(0); - } - - static void cleanup() { - std::lock_guard initLock(s_initMutex); - std::unique_lock cacheLock(s_cacheMutex); - - s_sharedGlyphCache.clear(); - s_sharedGlyphCache.rehash(0); - //s_persistentGlyphCache.clear(); - //s_persistentGlyphCache.rehash(0); - s_notificationGlyphCache.clear(); - s_notificationGlyphCache.rehash(0); - s_fontMetricsCache.clear(); - s_initialized = false; - s_stdFont = nullptr; - s_localFont = nullptr; - s_extFont = nullptr; - s_hasLocalFont = false; - } - - static size_t getCacheSize() { - std::shared_lock lock(s_cacheMutex); - return s_sharedGlyphCache.size(); - } - - static size_t getFontMetricsCacheSize() { - std::shared_lock lock(s_cacheMutex); - return s_fontMetricsCache.size(); - } - - static bool isInitialized() { - std::shared_lock lock(s_cacheMutex); - return s_initialized; - } - - //static size_t getPersistentCacheSize() { - // std::shared_lock lock(s_cacheMutex); - // return s_persistentGlyphCache.size(); - //} - - // NEW: Get notification cache size - static size_t getNotificationCacheSize() { - std::shared_lock lock(s_cacheMutex); - return s_notificationGlyphCache.size(); - } - - // Add memory usage monitoring - static size_t getMemoryUsage() { - std::shared_lock lock(s_cacheMutex); - size_t totalMemory = 0; - - // Regular cache - for (const auto& pair : s_sharedGlyphCache) { - const auto& glyph = pair.second; - if (glyph && glyph->glyphBmp) { - totalMemory += glyph->width * glyph->height; - } - } - - // Persistent cache - //for (const auto& pair : s_persistentGlyphCache) { - // const auto& glyph = pair.second; - // if (glyph && glyph->glyphBmp) { - // totalMemory += glyph->width * glyph->height; - // } - //} - - // Notification cache - for (const auto& pair : s_notificationGlyphCache) { - const auto& glyph = pair.second; - if (glyph && glyph->glyphBmp) { - totalMemory += glyph->width * glyph->height; - } - } - - return totalMemory; - } - - private: - static stbtt_fontinfo* selectFontForCharacterUnsafe(u32 character) { - if (!s_initialized) return nullptr; - - if (stbtt_FindGlyphIndex(s_extFont, character)) { - return s_extFont; - } else if (s_hasLocalFont && stbtt_FindGlyphIndex(s_localFont, character) != 0) { - // Fix: Always fetch degree symbol "°" from the standard Latin font - return (character != 0x00B0) ? s_localFont : s_stdFont; - } - return s_stdFont; - } - }; - - - // Static member definitions - //std::shared_mutex FontManager::s_cacheMutex; - //std::mutex FontManager::s_initMutex; - //std::unordered_map> FontManager::s_sharedGlyphCache; - //stbtt_fontinfo* FontManager::s_stdFont = nullptr; - //stbtt_fontinfo* FontManager::s_localFont = nullptr; - //stbtt_fontinfo* FontManager::s_extFont = nullptr; - //bool FontManager::s_hasLocalFont = false; - //bool FontManager::s_initialized = false; - - // Updated thread-safe calculateStringWidth function - static float calculateStringWidth(const std::string& originalString, const float fontSize, const bool monospace = false) { - if (originalString.empty() || !FontManager::isInitialized()) { - return 0.0f; - } - - // Thread-safe translation cache access - std::string text; - #ifdef UI_OVERRIDE_PATH - { - 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; - } - } - #else - text = originalString; - #endif - - // 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); - } - - 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_localFont, m_extFont; - bool m_hasLocalFont = false; - - /** - * @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) { - const u8 opacity_limit = static_cast(0xF); - 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); - } - - /** - * @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; - - - // Draw row by row for better cache locality - for (s32 yi = y_start; yi < y_end; ++yi) { - for (s32 xi = x_start; xi < x_end; ++xi) { - this->setPixelBlendDst(xi, yi, 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(); - } - } - - - /** - * @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; - } - - // Early exit for degenerate rectangles - //if (w <= 0 || h <= 0) { - // 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; - long long dx1 = px2 + sx - cx2; - long long dx2 = px2 - sx - cx2; - long long dy1 = py2 + sy - cy2; - 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; - - // Get framebuffer bounds for early exit check - //const s32 fb_width = static_cast(cfg::FramebufferWidth); - //const s32 fb_height = static_cast(cfg::FramebufferHeight); - - // 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); - //const s32 clampedXEnd = std::min(static_cast(cfg::FramebufferWidth), x + w); - - // 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); - } - - std::function drawRoundedRect; - inline void updateDrawFunction() { - if (ult::expandedMemory) { - drawRoundedRect = [this](s32 x, s32 y, s32 w, s32 h, s32 radius, Color color) { - drawRoundedRectMultiThreaded(x, y, w, h, radius, color); - }; - } else { - drawRoundedRect = [this](s32 x, s32 y, s32 w, s32 h, s32 radius, Color color) { - 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); - } - } - } - } - } - } - } - - // Struct for batch pixel processing with better alignment - //struct alignas(64) PixelBatch { - // s32 baseX, baseY; - // u8 red[32], green[32], blue[32], alpha[32]; // Doubled for 32-pixel batches - // s32 count; - //}; - // - //// Batch pixel setter - process multiple pixels at once if available - //inline void setPixelBatchBlendSrc(const s32 baseX, const s32 baseY, const PixelBatch& batch) { - // // If your graphics system supports batch operations, use them here - // // Otherwise fall back to individual calls - // for (s32 i = 0; i < batch.count; ++i) { - // setPixelBlendSrc(baseX + i, baseY, { - // batch.red[i], batch.green[i], batch.blue[i], batch.alpha[i] - // }); - // } - //} - - // RGBA4444 processing - no expansion needed - const uint8x16_t mask_low = vdupq_n_u8(0x0F); - - inline void processBMPChunk(const s32 x, const s32 y, const s32 screenW, const u8 *preprocessedData, - const s32 startRow, const s32 endRow, const u8 globalAlphaLimit) { - static constexpr s32 bytesPerRow = 448 * 2; - static constexpr s32 endX16 = 448 & ~15; - const uint8x16_t alpha_limit_vec = vdupq_n_u8(globalAlphaLimit); - - // Get framebuffer once for entire chunk - Color* const framebuffer = static_cast(this->getCurrentFramebuffer()); - - for (s32 y1 = startRow; y1 < endRow; ++y1) { - const u8 *rowPtr = preprocessedData + (y1 * bytesPerRow); - const s32 baseY = y + y1; - - s32 x1 = 0; - - // SIMD processing for 16 pixels at once - for (; x1 < endX16; x1 += 16) { - const u8* ptr = rowPtr + (x1 << 1); - - // Load and unpack RGBA4444 data - keep as 4-bit - 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); - - // Store results directly - 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 s32 baseX = x + x1; - - // Optimized pixel loop with direct framebuffer access - for (int i = 0; i < 16; ++i) { - const u8 a = alpha_vals[i]; - if (a == 0) continue; - - const u32 offset = this->getPixelOffset(baseX + i, baseY); - if (offset == UINT32_MAX) continue; - - 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), - src.a - }; - } - } - - // Handle remaining pixels - for (; x1 < screenW; ++x1) { - const u8 p1 = rowPtr[x1 << 1]; - const u8 p2 = rowPtr[(x1 << 1) + 1]; - const u8 alpha = std::min(static_cast(p2 & 0x0F), globalAlphaLimit); - - setPixelBlendSrc(x + x1, baseY, { - static_cast(p1 >> 4), - static_cast(p1 & 0x0F), - static_cast(p2 >> 4), - alpha - }); - } - } - - ult::inPlotBarrier.arrive_and_wait(); - } - - - /** - * @brief Draws a scaled RGBA8888 bitmap from memory - * - * @param x X start position - * @param y Y start position - * @param w Bitmap width (original width of the bitmap) - * @param h Bitmap height (original height of the bitmap) - * @param bmp Pointer to bitmap data - * @param screenW Target screen width - * @param screenH Target screen height - */ - - inline void drawBitmapRGBA4444(const s32 x, const s32 y, const s32 screenW, const s32 screenH, - const u8 *preprocessedData, float opacity = 1.0f) { - // Pre-compute alpha limit once - const u8 globalAlphaLimit = static_cast(0xF * opacity); - - s32 startRow; - - for (unsigned i = 0; i < ult::numThreads; ++i) { - startRow = i * ult::bmpChunkSize; - - // Pass the alpha limit to each thread - ult::renderThreads[i] = std::thread(std::bind(&tsl::gfx::Renderer::processBMPChunk, - this, x, y, screenW, preprocessedData, startRow, - std::min(startRow + ult::bmpChunkSize, screenH), globalAlphaLimit)); - } - - // Join all threads - 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) { - // Use the renderer's opacity directly - drawBitmapRGBA4444(0, 0, cfg::FramebufferWidth, cfg::FramebufferHeight, - ult::wallpaperData.data(), Renderer::s_opacity); - } - - 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; - - #if defined(UI_OVERRIDE_PATH) - { - std::shared_lock readLock(s_translationCacheMutex); - auto translatedIt = ult::translationCache.find(originalString); - if (translatedIt != ult::translationCache.end()) { - translatedText = translatedIt->second; - text = &translatedText; - } - } - #endif - - 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; - #ifdef UI_OVERRIDE_PATH - { - 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; - } - } - #else - text = originalString; - #endif - - 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) { - //const float ratio = 1.5; - //u32 maxX = cfg::ScreenWidth - (int)(ratio * cfg::FramebufferWidth); - //u32 maxY = cfg::ScreenHeight - (int)(ratio * cfg::FramebufferHeight); - 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); - } - } - - static Renderer& getRenderer() { - return get(); - } - - inline void setLayerPosImpl(u32 x, u32 y) { - // Get the underscan pixel values for both horizontal and vertical borders - //const auto [horizontalUnderscanPixels, verticalUnderscanPixels] = getUnderscanPixels(); - - // 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 - - // Single unified glyph cache for all text operations - //inline static std::unordered_map s_unifiedGlyphCache; - - // Helper to select appropriate font for a character - inline std::shared_ptr getOrCreateGlyph(u32 character, bool monospace, u32 fontSize) { - return FontManager::getOrCreateGlyph(character, monospace, fontSize); - } - - inline stbtt_fontinfo* selectFontForCharacter(u32 character) { - return FontManager::selectFontForCharacter(character); - } - - // 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 ? 0xF : 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() { - updateDrawFunction(); - } - - /** - * @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; - - - static inline float s_opacity = 1.0F; - - - /** - * @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()) { - 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(); - //int horizontalUnderscanPixels = 0; - - - ult::useRightAlignment = (ult::parseValueFromIniSection(ult::ULTRAHAND_CONFIG_INI_PATH, ult::ULTRAHAND_PROJECT_NAME, "right_alignment") == ult::TRUE_STR); - - //cfg::LayerPosX = 1280-32; - 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; - - // NEW: Scale down to 1/4 size (0.5x in each dimension) - //static constexpr float scaleFactor = 0.5f; - //cfg::LayerWidth *= scaleFactor; - //cfg::LayerHeight *= scaleFactor; - - if (this->m_initialized) - return; - - //s32 layerZ = 0; - - 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 (s32 layerZ = 0; R_SUCCEEDED(viGetZOrderCountMax(&this->m_display, &layerZ)) && layerZ > 0) - // ASSERT_FATAL(viSetLayerZ(&this->m_layer, layerZ)); - - 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: - case SetLanguage_ZHTW: - case SetLanguage_ZHHANT: - TSL_R_TRY(plGetSharedFontByType(&localFontData, PlSharedFontType_ChineseSimplified)); - 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)); - - // Initialize the shared font manager - FontManager::initializeFonts(&this->m_stdFont, &this->m_localFont, - &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); - } - - /** - * @brief End the current frame - * @warning Don't call this before calling \ref startFrame once - */ - //inline void endFrame() { - //#if IS_STATUS_MONITOR_DIRECTIVE - // if (isRendering) { - // static u32 lastFPS = 0; - // static u64 cachedIntervalNs = 1000000000ULL / 60; // Default to 60 FPS - // - // u32 fps = TeslaFPS; - // if (__builtin_expect(fps != lastFPS, 0)) { - // cachedIntervalNs = (fps > 0) ? (1000000000ULL / fps) : cachedIntervalNs; - // lastFPS = fps; - // } - // - // // Frame pacing before VSync - // leventWait(&renderingStopEvent, cachedIntervalNs); - // } - //#endif - // - // // Then hardware sync - // this->waitForVSync(); - // framebufferEnd(&this->m_framebuffer); - // this->m_currentFramebuffer = nullptr; - // - // if (tsl::clearGlyphCacheNow.exchange(false)) { - // tsl::gfx::FontManager::clearCache(); - // } - //} - - 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 inline 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 inline 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 inline 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 inline 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 inline 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 = armTicksToNs(armGetSystemTick()); // Changed - if (direction != FocusDirection::None && m_isItem) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - } - } - - /** - * @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 = armTicksToNs(armGetSystemTick()); // 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) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x + 4, this->getY() + y, this->getWidth() - 8, this->getHeight(), aWithOpacity(selectionBGColor)); // CUSTOM MODIFICATION - else - renderer->drawRect(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}; - } - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(ELEMENT_BOUNDS(this), aWithOpacity(animColor)); - else - renderer->drawRect(ELEMENT_BOUNDS(this), aWithOpacity(animColor)); - - // Cache time calculation - only compute once - static u64 lastTimeUpdate = 0; - static double cachedProgress = 0.0; - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - // Only recalculate progress if enough time has passed (reduce computation frequency) - if (currentTime_ns - lastTimeUpdate > 16666666) { // ~60 FPS update rate - //double time_seconds = currentTime_ns / 1000000000.0; - 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 - highlightColor = { - static_cast((clickColor1.r - clickColor2.r) * progress + clickColor2.r), - static_cast((clickColor1.g - clickColor2.g) * progress + clickColor2.g), - static_cast((clickColor1.b - clickColor2.b) * progress + clickColor2.b), - 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; - } - } - } - - renderer->drawBorderedRoundedRect(this->getX() + x, this->getY() + y, this->getWidth() +4, this->getHeight(), 5, 5, a(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); - - // Single time calculation and direct millisecond conversion - //const double elapsed_ms = (armTicksToNs(armGetSystemTick()) - this->m_animationStartTime) * 0.000001; // Direct conversion - - // Direct calculation without intermediate multiplication - this->m_clickAnimationProgress = tsl::style::ListItemHighlightLength * (1.0f - ((armTicksToNs(armGetSystemTick()) - 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) { // CUSTOM MODIFICATION start - 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 = armTicksToNs(armGetSystemTick()); - - // Update progress at 60 FPS rate with high-precision calculation - if (currentTime_ns - lastHighlightUpdate > 16666666) { - // High precision time calculation - matches original timing exactly - //double time_seconds = currentTime_ns * 0.000000001; // Direct conversion like original - - // 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 - 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 - 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) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x + 4, this->getY() + y, this->getWidth() - 12 +4, this->getHeight(), aWithOpacity(selectionBGColor)); // CUSTOM MODIFICATION - else - renderer->drawRect(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){ - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x + 4, this->getY() + y, (this->getWidth()- 12 +4)*(activePercentage * 0.01f), this->getHeight(), aWithOpacity(progressColor)); // Direct percentage conversion - else - renderer->drawRect(this->getX() + x + 4, this->getY() + y, (this->getWidth()- 12 +4)*(activePercentage * 0.01f), this->getHeight(), aWithOpacity(progressColor)); // Direct percentage conversion - } - #endif - - renderer->drawBorderedRoundedRect(this->getX() + x, this->getY() + y, this->getWidth() +4, this->getHeight(), 5, 5, a(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 inline 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) { - //static u32 ult::layerEdge = cfg::LayerPosX == 0 ? 0 : (1280-448); - 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 inline 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 inline 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; - - /** - * @brief Shake animation calculation based on a damped sine wave - * - * @param t_ns Passed time in nanoseconds - * @param a Amplitude - * @return Damped sine wave output - */ - //inline int shakeAnimation(u64 t_ns, float a) { - // //float w = 0.2F; - // //float tau = 0.05F; - // - // // Convert nanoseconds to microseconds for the calculation - // const int t_us = t_ns / 1000; - // - // return roundf(a * exp(-(0.05F * t_us) * sin(0.2F * t_us))); - //} - - 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 { - //renderer->enableScissoring(ELEMENT_BOUNDS(this)); - this->m_renderFunc(renderer, ELEMENT_BOUNDS(this)); - //renderer->disableScissoring(); - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - - } - - private: - std::function m_renderFunc; - }; - //#endif - - /** - * @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 = armTicksToNs(armGetSystemTick()); - 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 = { - static_cast(dynamicLogoRGB1.r + (dynamicLogoRGB2.r - dynamicLogoRGB1.r) * blend + 0.5), - static_cast(dynamicLogoRGB1.g + (dynamicLogoRGB2.g - dynamicLogoRGB1.g) * blend + 0.5), - static_cast(dynamicLogoRGB1.b + (dynamicLogoRGB2.b - dynamicLogoRGB1.b) * blend + 0.5), - 15 - }; - - const std::string letterStr(1, letter); - if (useNotificationMethod) { - //const auto [letterWidth, letterHeight] = renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, highlightColor); - 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) { - //const auto [letterWidth, letterHeight] = renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, staticColor); - 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) { - //const auto [lw, lh] = renderer->getNotificationTextDimensions(letterStr, false, fontSize); - totalWidth += renderer->getNotificationTextDimensions(letterStr, false, fontSize).first; - } else { - //const auto [lw, lh] = renderer->getTextDimensions(letterStr, false, fontSize); - totalWidth += renderer->getTextDimensions(letterStr, false, fontSize).first; - } - } - } else { - // Static rendering - measure the whole string at once - if (useNotificationMethod) { - //const auto [uw, uh] = renderer->getNotificationTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize); - totalWidth = renderer->getNotificationTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize).first; - } else { - //const auto [uw, uh] = renderer->getTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize); - totalWidth = renderer->getTextDimensions(ult::SPLIT_PROJECT_NAME_1, false, fontSize).first; - } - } - - return totalWidth; - } - - #endif - - //struct TopCache { - // std::string title; - // std::string subtitle; - // tsl::Color titleColor{0xF, 0xF, 0xF, 0xF}; // white by default - // bool widgetDrawn = false; - // bool useDynamicLogo = false; - // bool disabled = false; - //}; - // - //struct BottomCache { - // std::string bottomText; - // float backWidth = 0.0f; - // float selectWidth = 0.0f; - // float nextPageWidth = 0.0f; - // bool disabled = false; - //}; - // - //// Global or namespace-level variable - //inline TopCache g_cachedTop; - //inline BottomCache g_cachedBottom; - // - //inline std::atomic g_disableMenuCacheOnReturn = false; - - /** - * @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; // CUSTOM MODIFICATION - std::string m_colorSelection; // CUSTOM MODIFICATION - std::string m_pageLeftName; // CUSTOM MODIFICATION - std::string m_pageRightName; // CUSTOM MODIFICATION - - - tsl::Color titleColor = {0xF,0xF,0xF,0xF}; - float letterWidth; - #endif - - #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) - : Element(), m_title(title), m_subtitle(subtitle), m_noClickableItems(_noClickableItems) { - #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 - - // CUSTOM SECTION START - void draw(gfx::Renderer *renderer) override { - if (!ult::themeIsInitialized.exchange(true, std::memory_order_acq_rel)) { - tsl::initializeThemeVars(); - } - - - renderer->fillScreen(a(defaultBackgroundColor)); - renderer->drawWallpaper(); - - y = 50; - offset = 0; - - #if IS_LAUNCHER_DIRECTIVE - // Current interpreter state (atomic) - 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); - } - - // Use cached or current data for rendering - 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; - - // Calculate title widths and handle scrolling - calcScrollWidth(renderer, titleScroll, m_title, 32, widgetDrawn); - - const bool isScript = m_subtitle.find("Ultrahand Script") != std::string::npos; - const tsl::Color titleClr = isScript ? defaultScriptColor : getPackageColor(); - - drawScrollableText(renderer, titleScroll, titleClr, x, y, 32, 27, 35); - } - - // Calculate subtitle widths and handle scrolling - 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); - - static const std::vector specialChars = {""}; - const int subtitleX = 20; - const int subtitleY = y + 25; - - if (m_title == ult::CAPITAL_ULTRAHAND_PROJECT_NAME) { - // Version label - no scrolling needed - renderer->drawStringWithColoredSections(ult::versionLabel, false, specialChars, - subtitleX, subtitleY, 15, - bannerVersionTextColor, textSeparatorColor); - } else { - // Handle scrolling subtitle - if (subScroll.trunc) { - if (!subScroll.active) { - subScroll.active = true; - subScroll.timeIn = armTicksToNs(armGetSystemTick()); - } - - renderer->enableScissoring(subtitleX, subtitleY - 16, subScroll.maxW, 24); - - renderer->drawStringWithColoredSections(subScroll.scrollText, false, specialChars, - subtitleX - static_cast(subScroll.offset), subtitleY, 15, - bannerVersionTextColor, textSeparatorColor); - - renderer->disableScissoring(); - - updateScroll(subScroll); - } else { - // Normal subtitle drawing - renderer->drawStringWithColoredSections(subtitle, false, specialChars, - subtitleX, subtitleY, 15, - bannerVersionTextColor, textSeparatorColor); - } - } - - #else - // NON-LAUNCHER PATH - 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 - - // Calculate title widths and handle scrolling - calcScrollWidth(renderer, titleScroll, m_title, 32, widgetDrawn); - drawScrollableText(renderer, titleScroll, defaultOverlayColor, 20, 50, 32, 27, 35); - - // Calculate subtitle widths and handle scrolling - calcScrollWidth(renderer, subScroll, m_subtitle, 15, widgetDrawn); - - const int subtitleX = 20; - const int subtitleY = y + 25; - - if (subScroll.trunc) { - if (!subScroll.active) { - subScroll.active = true; - subScroll.timeIn = armTicksToNs(armGetSystemTick()); - } - - 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)); - - // Compute gap width once from GAP_1 and derive halfGap - const float gapWidth = renderer->getTextDimensions(ult::GAP_1, false, 23).first; - - // Calculate text widths for buttons depending on launch mode and interpreter state - #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; - if (_halfGap != ult::halfGap.load(std::memory_order_acquire)) - ult::halfGap.store(_halfGap, std::memory_order_release); - - // Total button widths include half-gap padding on both sides - 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 if touched - if (ult::touchingBack) { - renderer->drawRoundedRect(buttonStartX+2 - _halfGap, buttonY, _backWidth-1, 73.0f, 12.0f, a(clickColor)); - } - - // Draw select button (to the right of back) if touched - 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 - // Handle optional next page button when in launcher mode and appropriate conditions are met - if (!interpreterIsRunningNow && (ult::inMainMenu.load(std::memory_order_acquire) || - !m_pageLeftName.empty() || !m_pageRightName.empty())) { - // Construct next-page label inline without creating temporary strings - 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; - - if (_nextPageWidth != ult::nextPageWidth.load(std::memory_order_acquire)) - ult::nextPageWidth.store(_nextPageWidth, std::memory_order_release); - - // Draw next-page button if touched - 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)); - } - } - #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 - : ""); - #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 - : ""); - #endif - - // Render the text - it starts halfGap inside the first button, so edgePadding + halfGap - static const std::vector specialChars2 = {"\uE0E1","\uE0E0","\uE0ED","\uE0EE","\uE0E5"}; - renderer->drawStringWithColoredSections(currentBottomLine, false, specialChars2, - buttonStartX, 693, 23, - bottomTextColor, buttonColor); - - #if USING_FPS_INDICATOR_DIRECTIVE - // Update and display FPS - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const double currentTime_seconds = currentTime_ns / 1e9; - const float currentFps = updateFPS(currentTime_seconds); - - static char fpsBuffer[32]; - static float lastFps = -1.0f; - - // Only update string if FPS changed significantly - 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)); - - } - // CUSTOM SECTION END - - 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 &title) { - if (m_title != title) { - m_title = title; - titleScroll.maxW = 0; // Reset to recalculate - titleScroll.active = titleScroll.trunc = false; - } - } - - /** - * @brief Changes the subtitle of the menu - * - * @param title Subtitle to change to - */ - inline void setSubtitle(const std::string &subtitle) { - if (m_subtitle != subtitle) { - m_subtitle = subtitle; - subScroll.maxW = 0; // Reset to recalculate - subScroll.active = subScroll.trunc = false; - } - } - - 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* r, 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 = r->getTextDimensions(text, false, fontSize).first; - s.trunc = w > s.maxW; - - if (s.trunc) { - s.scrollText = text + " "; - s.textW = r->getTextDimensions(s.scrollText, false, fontSize).first; - s.scrollText += text; - } else { - s.textW = w; - } - } - - #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 && ult::isValidHexColor(m_colorSelection.substr(1))) - ? RGB888(m_colorSelection.substr(1)) : defaultPackageColor; - default: return defaultPackageColor; - } - } - - // Draw scrollable text with common parameters - void drawScrollableText(gfx::Renderer* r, 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 = armTicksToNs(armGetSystemTick()); - } - - r->enableScissoring(xPos, yPos - scissorYOffset, s.maxW, scissorHeight); - r->drawString(s.scrollText, false, xPos - static_cast(s.offset), yPos, fontSize, clr); - r->disableScissoring(); - - updateScroll(s); - } else { - r->drawString(m_title, false, xPos, yPos, fontSize, clr); - } - } - #else - // Non-launcher version - void drawScrollableText(gfx::Renderer* r, 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 = armTicksToNs(armGetSystemTick()); - } - - r->enableScissoring(xPos, yPos - scissorYOffset, s.maxW, scissorHeight); - r->drawString(s.scrollText, false, xPos - static_cast(s.offset), yPos, fontSize, clr); - r->disableScissoring(); - - updateScroll(s); - } else { - r->drawString(m_title, false, xPos, yPos, fontSize, clr); - } - } - #endif - - // Unified scroll update - void updateScroll(ScrollState& s) { - const u64 now = armTicksToNs(armGetSystemTick()); - - // 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; - - // Check if returning from a list that disabled caching - //if (g_disableMenuCacheOnReturn.exchange(false, std::memory_order_acq_rel)) { - // g_cachedTop.disabled = true; - // g_cachedBottom.disabled = true; - //} - } - - - virtual void draw(gfx::Renderer *renderer) override { - if (!ult::themeIsInitialized.load(std::memory_order_acquire) && FullMode) { - ult::themeIsInitialized.store(true, std::memory_order_release); - tsl::initializeThemeVars(); - } - - 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; - - // Determine if we should use cached data (first frame of new overlay) - //const bool useCachedTop = !g_cachedTop.disabled && - // !g_cachedTop.title.empty() && - // (g_cachedTop.title != m_title || g_cachedTop.subtitle != m_subtitle); - - // 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 - : ""); - - // Determine if we should use cached bottom text (first frame of new overlay) - //const bool useCachedBottom = !g_cachedBottom.disabled && - // !g_cachedBottom.bottomText.empty() && - // g_cachedBottom.bottomText != currentBottomLine; - - const std::string& menuBottomLine = currentBottomLine; - - // Render the text with special character handling - if (!deactivateOriginalFooter) { - static const std::vector specialChars = {"\uE0E1","\uE0E0","\uE0ED","\uE0EE","\uE0E5"}; - renderer->drawStringWithColoredSections(menuBottomLine, false, specialChars, buttonStartX, 693, 23, bottomTextColor, buttonColor); - } - - 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)); - } - - // Update top cache after rendering for next frame - //g_cachedTop.title = m_title; - //g_cachedTop.subtitle = m_subtitle; - //g_cachedTop.titleColor = {0xF, 0xF, 0xF, 0xF}; // HeaderOverlayFrame uses default white - //g_cachedTop.widgetDrawn = false; // HeaderOverlayFrame doesn't use widgets - //g_cachedTop.useDynamicLogo = false; // HeaderOverlayFrame doesn't use dynamic logo - //g_cachedTop.disabled = false; - - // Update bottom cache after rendering for next frame - //g_cachedBottom.bottomText = currentBottomLine; - //g_cachedBottom.backWidth = ult::backWidth.load(std::memory_order_acquire); - //g_cachedBottom.selectWidth = ult::selectWidth.load(std::memory_order_acquire); - //g_cachedBottom.nextPageWidth = 0.0f; // HeaderOverlayFrame doesn't use next page - //g_cachedBottom.disabled = false; - } - - - - 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 + 140, parentWidth - 85, parentHeight - 73 - 105); // CUSTOM MODIFICATION - this->m_contentElement->setBoundaries(parentX + 35, parentY + ult::activeHeaderHeight, parentWidth - 85, parentHeight - 73 - 105); - this->m_contentElement->invalidate(); - } - } - virtual inline Element* requestFocus(Element *oldFocus, FocusDirection direction) override { - if (this->m_contentElement != nullptr) - return this->m_contentElement->requestFocus(oldFocus, direction); - else - return nullptr; - } - - virtual inline 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 { - if (!ult::themeIsInitialized.exchange(true, std::memory_order_acq_rel)) { - tsl::initializeThemeVars(); - } - - renderer->fillScreen(a(defaultBackgroundColor)); - renderer->drawWallpaper(); - //renderer->drawRect(tsl::cfg::FramebufferWidth - 1, 0, 1, tsl::cfg::FramebufferHeight, a(0xF222)); - 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 (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 inline 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 inline 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 inline 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}; - static bool s_triggerShakeOnce; - - class List : public Element { - - public: - List() : Element() { - - s_safeToSwap.store(false, std::memory_order_release); - - // Initialize instance state - m_pendingJump = false; - //m_cachingDisabled = 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; - } - - inline void disableCaching(bool preserveTopAndBottom = false) { - //m_cachingDisabled = true; - //clearFrameCache(); - //g_disableMenuCacheOnReturn.store(true, std::memory_order_release); - //if (!preserveTopAndBottom) { - // g_cachedTop.disabled = true; - // g_cachedBottom.disabled = true; - //} - } - - 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; - - // Instance identification - //const size_t m_instanceId; - - // 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_hasForwardCached = false; - //bool m_cachingDisabled = false; // New flag to disable caching - - bool m_justArrivedAtBoundary = false; - bool m_hasSetInitialFocusHack = false; - bool m_hasRenderedInitialFocus = false; - - //bool m_hasRenderedCache = 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 smoothingFactor = 0.15f; - //static constexpr float dampingFactor = 0.3f; - static constexpr float TABLE_SCROLL_STEP_SIZE = 10; - static constexpr float TABLE_SCROLL_STEP_SIZE_CLICK = 22; - 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_items.clear(); - //m_items.shrink_to_fit(); - m_offset = 0; - m_focusedIndex = 0; - invalidate(); - m_clearList = false; - actualItemCount = 0; - m_hasSetInitialFocusHack = false; - } - - 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 = {}; - //m_itemsToRemove.clear(); - //m_itemsToRemove.shrink_to_fit(); - invalidate(); - updateScrollOffset(); - } - - void purgePendingItems() { - for (auto& [_, element] : m_itemsToAdd) { - if (element) { element->invalidate(); delete element; } - } - m_itemsToAdd = {}; - //m_itemsToAdd.clear(); - //m_itemsToAdd.shrink_to_fit(); - - //size_t index; - for (Element* element : m_itemsToRemove) { - auto it = std::find(m_items.begin(), m_items.end(), element); - if (it != m_items.end()) { - //index = static_cast(it - m_items.begin()); - 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 = {}; - //m_itemsToRemove.clear(); - //m_itemsToRemove.shrink_to_fit(); - - 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); - - // 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 = armTicksToNs(armGetSystemTick()); // Start transition immediately - } - - // 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 = armTicksToNs(armGetSystemTick()); // 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 = armTicksToNs(armGetSystemTick()); - 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) { - // Clear touch flag when in controller mode - m_touchScrollActive = false; - - // Calculate distance to target - const float diff = m_nextOffset - m_offset; - const float distance = std::abs(diff); - - // ENHANCED BOUNDARY SNAPPING: More aggressive snapping for boundaries - if (distance < 1.0f) { // Increased threshold from 0.5f - 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; - } - - // SPECIAL CASE: If target is exactly 0 or max, be more aggressive - const float maxOffset = static_cast(m_listHeight - getHeight()); - if (m_nextOffset == 0.0f || m_nextOffset == maxOffset) { - if (distance < 3.0f) { // Larger snap zone for boundaries - 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 item is going out of bounds - 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(); - - //float viewTop = m_offset; - 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; - } - } - - // Rest of your existing smooth scrolling logic... - 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; - } - - // Apply velocity - m_offset += m_scrollVelocity; - - // ENHANCED overshoot prevention with better boundary handling - if ((m_scrollVelocity > 0 && m_offset > m_nextOffset) || - (m_scrollVelocity < 0 && m_offset < m_nextOffset)) { - m_offset = m_nextOffset; - m_scrollVelocity = 0.0f; - } - - // ADDITIONAL: 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) { - // Your existing touch scroll logic... - m_offset = m_nextOffset; - m_scrollVelocity = 0.0f; - - if (m_touchScrollActive) { - const float viewCenter = m_offset + (getHeight() / 2.0f); - float accumHeight = 0.0f; - - //float itemHeight, itemCenter; - 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; - } - } - - //resetNavigationState(); - - // 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) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - - if (m_items.empty()) - 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; - } - } - } - - 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) { - 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; - s_triggerShakeOnce = true; - m_justArrivedAtBoundary = isAtBottom(); - triggerNavigationFeedback(); - return result; - } - - // Check if we can still scroll down - if (!atBottom) { - scrollDown(); - s_triggerShakeOnce = true; - return oldFocus; - } - - // Force boundary hit before allowing wrap - if (m_justArrivedAtBoundary) { - m_justArrivedAtBoundary = false; - m_stoppedAtBoundary = true; - s_triggerShakeOnce = false; - m_lastNavigationResult = NavigationResult::HitBoundary; - 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; - s_triggerShakeOnce = true; - return handleJumpToTop(oldFocus); - } - - // Set boundary flag (for holding) - m_lastNavigationResult = NavigationResult::HitBoundary; - if (m_isHolding) { - m_stoppedAtBoundary = true; - if (s_triggerShakeOnce) { - s_triggerShakeOnce = false; - triggerWallEffect(FocusDirection::Down); - } - } else { - s_triggerShakeOnce = 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()) { - 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; - s_triggerShakeOnce = true; - m_justArrivedAtBoundary = isAtTop(); - triggerNavigationFeedback(); - return result; - } - - // Check if we can still scroll up - if (!atTop) { - scrollUp(); - s_triggerShakeOnce = true; - return oldFocus; - } - - // Force boundary hit before allowing wrap - if (m_justArrivedAtBoundary) { - m_justArrivedAtBoundary = false; - m_stoppedAtBoundary = true; - s_triggerShakeOnce = false; - m_lastNavigationResult = NavigationResult::HitBoundary; - 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; - s_triggerShakeOnce = true; - return handleJumpToBottom(oldFocus); - } - - // Set boundary flag (for holding) - m_lastNavigationResult = NavigationResult::HitBoundary; - if (m_isHolding) { - m_stoppedAtBoundary = true; - if (s_triggerShakeOnce) { - s_triggerShakeOnce = false; - triggerWallEffect(FocusDirection::Up); - } - } else { - s_triggerShakeOnce = 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? - //float maxOffset = static_cast(m_listHeight - getHeight()); - 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(); - //s32 lastItemBottom = lastItem->getBottomBound(); - //s32 viewportBottom = getBottomBound(); - - // 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) { - //Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - // - //if (test) return true; - if (m_items[i]->m_isItem) return true; - } - return false; - } - - - inline void updateHoldState() { - const u64 currentTime = armTicksToNs(armGetSystemTick()); - 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; - - //float itemHeight, itemCenterPos, viewportCenter, idealOffset; - - 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 - //float idealOffset = itemCenterPos - viewportCenter; - - // 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); - } - - // 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; - } - } - - // Cache invariant values (legitimate optimization) - 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()) { - // Table needs scrolling - const s32 tableBottom = item->getBottomBound(); - if (tableBottom > viewBottom) { - isTableScrolling.store(true, std::memory_order_release); - scrollDown(); - return oldFocus; - } - searchIndex++; - continue; - } - - // Try to focus this item - Element* newFocus = item->requestFocus(oldFocus, FocusDirection::Down); - if (newFocus && newFocus != oldFocus) { - // ONLY reset when we successfully focus something - isTableScrolling.store(false, std::memory_order_release); - updateScrollOffset(); - return newFocus; - } else { - // Non-focusable item (gap/header) - const float itemBottom = calculateItemPosition(searchIndex) + item->getHeight(); - if (itemBottom > offsetPlusHeight) { - isTableScrolling.store(true, std::memory_order_release); // Treat gaps/headers like tables - scrollDown(); - return oldFocus; - } - searchIndex++; - } - } - - return oldFocus; - } - - inline Element* navigateUp(Element* oldFocus) { - if (m_focusedIndex == 0) return 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; - } - } - - // Cache invariant values (legitimate optimization) - const s32 viewTop = getTopBound(); - const float offset = m_offset; // Cache in case m_offset is volatile or has accessor overhead - - while (searchIndex >= 0) { - Element* item = m_items[searchIndex]; - m_focusedIndex = static_cast(searchIndex); - - if (item->isTable()) { - // Table needs scrolling - const s32 tableTop = item->getTopBound(); - if (tableTop < viewTop) { - isTableScrolling.store(true, std::memory_order_release); - scrollUp(); - return oldFocus; - } - searchIndex--; - continue; - } - - // Try to focus this item - Element* newFocus = item->requestFocus(oldFocus, FocusDirection::Up); - if (newFocus && newFocus != oldFocus) { - // ONLY reset when we successfully focus something - isTableScrolling.store(false, std::memory_order_release); - updateScrollOffset(); - return newFocus; - } else { - // Non-focusable item (gap/header) - const float itemTop = calculateItemPosition(static_cast(searchIndex)); - if (itemTop < offset) { - isTableScrolling.store(true, std::memory_order_release); // Treat gaps/headers like tables - scrollUp(); - return oldFocus; - } - searchIndex--; - } - } - - 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; - } - - // Enhanced scroll methods that ensure we always reach boundaries - //inline bool canScrollDown() { - // if (m_listHeight <= getHeight()) return false; - // float maxOffset = static_cast(m_listHeight - getHeight()); - // return (m_nextOffset < maxOffset - 0.1f) && (m_offset < maxOffset - 0.1f); - //} - // - //inline bool canScrollUp() { - // return (m_nextOffset > 0.1f) || (m_offset > 0.1f); - //} - - - //u64 m_lastScrollNavigationTime = 0; - //bool m_isHoldingOnTable = false; - - // Enhanced scroll methods that snap to exact boundaries - inline void scrollDown() { - const u64 currentTime = armTicksToNs(armGetSystemTick()); - - // Calculate frame time - float frameTimeMs = 0.0f; - if (m_lastScrollTime != 0) { - frameTimeMs = static_cast(currentTime - m_lastScrollTime) / 1000000.0f; - } - m_lastScrollTime = currentTime; - - // Use original frame-based amounts - float scrollAmount = m_isHolding ? TABLE_SCROLL_STEP_SIZE : TABLE_SCROLL_STEP_SIZE_CLICK; - - // If frame took longer than ~33ms (slower than 30fps), scale up the scroll amount - if (frameTimeMs > 33.0f) { - const float scaleFactor = frameTimeMs / 16.67f; // 16.67ms = 60fps baseline - scrollAmount *= std::min(scaleFactor, 3.0f); // Cap at 3x for very slow frames - } - - m_nextOffset = std::min(m_nextOffset + scrollAmount, - static_cast(m_listHeight - getHeight())); - } - - inline void scrollUp() { - const u64 currentTime = armTicksToNs(armGetSystemTick()); - - // Calculate frame time - float frameTimeMs = 0.0f; - if (m_lastScrollTime != 0) { - frameTimeMs = static_cast(currentTime - m_lastScrollTime) / 1000000.0f; - } - m_lastScrollTime = currentTime; - - // Use original frame-based amounts - float scrollAmount = m_isHolding ? TABLE_SCROLL_STEP_SIZE : TABLE_SCROLL_STEP_SIZE_CLICK; - - // If frame took longer than ~33ms (slower than 30fps), scale up the scroll amount - if (frameTimeMs > 33.0f) { - const float scaleFactor = frameTimeMs / 16.67f; // 16.67ms = 60fps baseline - scrollAmount *= std::min(scaleFactor, 3.0f); // Cap at 3x for very slow frames - } - - m_nextOffset = std::max(m_nextOffset - scrollAmount, 0.0f); - } - - // Jump to Bottom (original behavior + fixed trigger condition) - Element* handleJumpToBottom(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - jumpToBottom.store(false, std::memory_order_release); - - const float targetOffset = (m_listHeight > getHeight()) ? - static_cast(m_listHeight - getHeight()) : 0.0f; - static constexpr float tolerance = 5.0f; - - // Find last focusable item (search backward) - size_t lastFocusableIndex = m_items.size(); - for (ssize_t i = static_cast(m_items.size()) - 1; i >= 0; --i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - lastFocusableIndex = static_cast(i); - break; - } - } - - if (lastFocusableIndex == m_items.size()) - return oldFocus; // no focusable items - - const bool alreadyAtBottom = (m_focusedIndex == lastFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - if (alreadyAtBottom) - return oldFocus; - - const float oldOffset = m_nextOffset; - m_focusedIndex = lastFocusableIndex; - - // NEW: Check if there's a table after the focused item - if (lastFocusableIndex + 1 < m_items.size()) { - Element* nextItem = m_items[lastFocusableIndex + 1]; - if (nextItem->isTable()) { - m_focusedIndex = lastFocusableIndex + 1; // Point at the table - } - } - - m_nextOffset = targetOffset; - - Element* newFocus = m_items[lastFocusableIndex]->requestFocus(oldFocus, FocusDirection::None); - - // Trigger feedback if offset or focus changed - if ((newFocus && newFocus != oldFocus) || - (std::abs(m_nextOffset - oldOffset) > tolerance)) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - return newFocus ? newFocus : oldFocus; - } - - - // Jump to Top (original behavior + fixed trigger condition) - Element* handleJumpToTop(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - jumpToTop.store(false, std::memory_order_release); - - static constexpr float targetOffset = 0.0f; - static constexpr float tolerance = 5.0f; - - // Find first focusable item (search forward) - size_t firstFocusableIndex = m_items.size(); - for (size_t i = 0; i < m_items.size(); ++i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - firstFocusableIndex = i; - break; - } - } - - if (firstFocusableIndex == m_items.size()) - return oldFocus; // no focusable items - - const bool alreadyAtTop = (m_focusedIndex == firstFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - if (alreadyAtTop) - return oldFocus; - - const float oldOffset = m_nextOffset; - m_focusedIndex = firstFocusableIndex; - m_nextOffset = targetOffset; - - Element* newFocus = m_items[firstFocusableIndex]->requestFocus(oldFocus, FocusDirection::None); - - // Trigger feedback if offset or focus changed - if ((newFocus && newFocus != oldFocus) || - (std::abs(m_nextOffset - oldOffset) > tolerance)) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - return newFocus ? newFocus : oldFocus; - } - - Element* handleSkipDown(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - - const float targetOffset = (m_listHeight > getHeight()) ? - static_cast(m_listHeight - getHeight()) : 0.0f; - static constexpr float tolerance = 0.0f; - - // Find last focusable item - size_t lastFocusableIndex = m_items.size(); - for (ssize_t i = static_cast(m_items.size()) - 1; i >= 0; --i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - lastFocusableIndex = static_cast(i); - break; - } - } - - const bool alreadyAtBottom = (lastFocusableIndex < m_items.size()) && - (m_focusedIndex == lastFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - - if (alreadyAtBottom) return oldFocus; - - const float viewHeight = static_cast(getHeight()); - const float maxOffset = (m_listHeight > viewHeight) ? static_cast(m_listHeight - viewHeight) : 0.0f; - const float targetViewportTop = std::min(m_offset + viewHeight, maxOffset); - - const float actualTravelDistance = targetViewportTop - m_offset; - const bool traveledFullViewport = (actualTravelDistance >= viewHeight - tolerance); - const float targetViewportCenter = targetViewportTop + (viewHeight / 2.0f + VIEW_CENTER_OFFSET); - - 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 / 2.0f); - const float distanceFromCenter = std::abs(itemCenter - targetViewportCenter); - - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem && distanceFromCenter < bestDistance) { - targetIndex = i; - bestDistance = distanceFromCenter; - foundFocusable = true; - } - - itemTop += itemHeight; - } - - const float oldOffset = m_nextOffset; - - if (foundFocusable) { - bool nearBottom = true; - if (targetIndex > m_focusedIndex && traveledFullViewport) { - m_focusedIndex = targetIndex; - nearBottom = false; - } - isTableScrolling.store(false, std::memory_order_release); - updateScrollOffset(); - - Element* newFocus = m_items[targetIndex]->requestFocus(oldFocus, FocusDirection::None); - - if (newFocus && newFocus != oldFocus && !nearBottom && traveledFullViewport) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } else { - return handleJumpToBottom(oldFocus); - } - } else { - // Scroll viewport even if no focusable items - isTableScrolling.store(true, std::memory_order_release); - m_nextOffset = targetViewportTop; - - if (std::abs(m_nextOffset - oldOffset) > 0.0f) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - // Focus last visible focusable item - float searchItemTop = 0.0f; - size_t lastVisibleFocusable = m_focusedIndex; - - for (size_t i = 0; i < m_items.size(); ++i) { - const float itemHeight = m_items[i]->getHeight(); - const float itemBottom = searchItemTop + itemHeight; - - if (searchItemTop >= targetViewportTop + viewHeight) break; - - if (itemBottom > targetViewportTop) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem) lastVisibleFocusable = i; - } - - searchItemTop += itemHeight; - } - - if (lastVisibleFocusable != m_focusedIndex) { - m_focusedIndex = lastVisibleFocusable; - Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); - if (newFocus && newFocus != oldFocus) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } - } - } - - return oldFocus; - } - - Element* handleSkipUp(Element* oldFocus) { - if (m_items.empty()) return oldFocus; - - invalidate(); - resetNavigationState(); - - static constexpr float targetOffset = 0.0f; - static constexpr float tolerance = 0.0f; - - // Find first focusable item - size_t firstFocusableIndex = m_items.size(); - for (size_t i = 0; i < m_items.size(); ++i) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test) { - firstFocusableIndex = i; - break; - } - } - - const bool alreadyAtTop = (firstFocusableIndex < m_items.size()) && - (m_focusedIndex == firstFocusableIndex) && - (std::abs(m_nextOffset - targetOffset) <= tolerance); - - if (alreadyAtTop) return oldFocus; - - const float viewHeight = static_cast(getHeight()); - const float targetViewportTop = std::max(0.0f, m_offset - viewHeight); - - const float actualTravelDistance = m_offset - targetViewportTop; - const bool traveledFullViewport = (actualTravelDistance >= viewHeight - tolerance); - const float targetViewportCenter = targetViewportTop + (viewHeight / 2.0f + VIEW_CENTER_OFFSET); - - 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 / 2.0f); - const float distanceFromCenter = std::abs(itemCenter - targetViewportCenter); - - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem && distanceFromCenter < bestDistance) { - targetIndex = i; - bestDistance = distanceFromCenter; - foundFocusable = true; - } - - itemTop += itemHeight; - } - - const float oldOffset = m_nextOffset; - - if (foundFocusable) { - bool nearTop = true; - if (targetIndex < m_focusedIndex && traveledFullViewport) { - m_focusedIndex = targetIndex; - nearTop = false; - } - isTableScrolling.store(false, std::memory_order_release); - updateScrollOffset(); - - Element* newFocus = m_items[targetIndex]->requestFocus(oldFocus, FocusDirection::None); - - if (newFocus && newFocus != oldFocus && !nearTop && traveledFullViewport) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } else { - return handleJumpToTop(oldFocus); - } - } else { - // Scroll viewport even if no focusable items - isTableScrolling.store(true, std::memory_order_release); - m_nextOffset = targetViewportTop; - - if (std::abs(m_nextOffset - oldOffset) > 0.0f) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - } - - // Focus first visible focusable item - float searchItemTop = 0.0f; - size_t firstVisibleFocusable = m_focusedIndex; - - for (size_t i = 0; i < m_items.size(); ++i) { - const float itemHeight = m_items[i]->getHeight(); - const float itemBottom = searchItemTop + itemHeight; - - if (itemBottom > targetViewportTop && searchItemTop < targetViewportTop + viewHeight) { - Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); - if (test && test->m_isItem) { - firstVisibleFocusable = i; - break; - } - } - - searchItemTop += itemHeight; - } - - if (firstVisibleFocusable != m_focusedIndex) { - m_focusedIndex = firstVisibleFocusable; - Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); - if (newFocus && newFocus != oldFocus) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - triggerNavigationFeedback(); - return newFocus; - } - } - } - - return oldFocus; - } - - - 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(); - } - } - - - // Keep your EXACT original updateScrollOffset() method unchanged: - 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 the first focusable item - //if (m_focusedIndex == 0 || itemPos <= viewHeight * 0.3f) { - // // For items at the very top or very close to top, snap to absolute zero - // m_nextOffset = 0.0f; - // return; - //} - - // FIXED: Special handling for items near the bottom - const float maxOffset = static_cast(m_listHeight - getHeight()); - //const float itemBottom = itemPos + itemHeight; - //if (itemBottom >= m_listHeight - (viewHeight * 0.3f)) { - // // For items near the bottom, snap to max offset - // m_nextOffset = maxOffset; - // return; - //} - - // 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 - //float idealOffset = itemCenterPos - viewportCenter; - - // 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; - - //m_nextOffset = std::max(0.0f, std::min(itemPos + itemHeight * 0.5f - (viewHeight * 0.5f + 7.0f), maxOffset)); - } - - }; - - - - - /** - * @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_shortThresholdCrossed = false; - #if IS_LAUNCHER_DIRECTIVE - bool m_longThresholdCrossed = false; - #endif - - #if IS_LAUNCHER_DIRECTIVE - ListItem(const std::string& text, const std::string& value = "", bool isMini = false, bool useScriptKey = true) - : Element(), m_text(text), m_value(value), m_listItemHeight(isMini ? tsl::style::MiniListItemDefaultHeight : tsl::style::ListItemDefaultHeight) { - m_isItem = true; - m_flags.m_useScriptKey = useScriptKey; - m_flags.m_useClickAnimation = true; - m_text_clean = m_text; - ult::removeTag(m_text_clean); - applyInitialTranslations(); - if (!value.empty()) applyInitialTranslations(true); - } - #else - 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); - } - #endif - - virtual ~ListItem() = default; - - virtual void draw(gfx::Renderer *renderer) override { - const bool useClickTextColor = m_flags.m_touched && Element::getInputMode() == InputMode::Touch && ult::touchInBounds; - - if (useClickTextColor) [[unlikely]] { - auto drawFunc = ult::expandedMemory ? &gfx::Renderer::drawRectMultiThreaded : &gfx::Renderer::drawRect; - (renderer->*drawFunc)(this->getX() + 4, this->getY(), this->getWidth() - 8, this->getHeight(), aWithOpacity(clickColor)); - } - - 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 = {ult::DIVIDER_SYMBOL}; - #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; - } - //if (keys & KEY_B) { - // triggerRumbleDoubleClick.store(true, std::memory_order_release); - // triggerExitSound.store(true, std::memory_order_release); - // - //} - 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_flags.m_touched = inBounds(currX, currY))) [[likely]] { - m_touchStartTime_ns = armTicksToNs(armGetSystemTick()); - m_shortThresholdCrossed = false; - #if IS_LAUNCHER_DIRECTIVE - m_longThresholdCrossed = false; - #endif - } - return false; - } - - if (event == TouchEvent::Hold && m_flags.m_touched) [[likely]] { - const u64 touchDuration_ns = armTicksToNs(armGetSystemTick()) - m_touchStartTime_ns; - const float touchDurationInSeconds = static_cast(touchDuration_ns) * 1e-9f; - - #if IS_LAUNCHER_DIRECTIVE - if (!m_longThresholdCrossed && touchDurationInSeconds >= 1.0f && - (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)))) [[unlikely]] { - m_longThresholdCrossed = true; - triggerRumbleClick.store(true, std::memory_order_release); - } else - #endif - if (!m_shortThresholdCrossed && touchDurationInSeconds >= 0.5f) [[unlikely]] { - m_shortThresholdCrossed = true; - triggerRumbleClick.store(true, std::memory_order_release); - } - return false; - } - - if (event == TouchEvent::Release && m_flags.m_touched) [[likely]] { - m_flags.m_touched = false; - if (Element::getInputMode() == InputMode::Touch) [[likely]] { - const bool handled = onClick(determineKeyOnTouchRelease( - #if IS_LAUNCHER_DIRECTIVE - m_flags.m_useScriptKey - #else - false - #endif - )); - m_clickAnimationProgress = 0; - return handled; - } - } - return false; - } - - virtual void setFocused(bool state) override { - if (state != m_focused) [[likely]] { - m_flags.m_scroll = false; - m_scrollOffset = 0; - timeIn_ns = armTicksToNs(armGetSystemTick()); - Element::setFocused(state); - } - } - - virtual inline Element* requestFocus(Element *oldFocus, FocusDirection direction) override { - return this; - } - - inline void setText(const std::string& text) { - if (m_text != text) [[likely]] { - m_text = text; - m_text_clean = m_text; - 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 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_scroll : 1; - bool m_truncated : 1; - bool m_faint : 1; - bool m_touched : 1; - bool m_hasCustomTextColor : 1; - bool m_hasCustomValueColor : 1; - bool m_useClickAnimation : 1; - #if IS_LAUNCHER_DIRECTIVE - bool m_useScriptKey : 1; - #endif - } m_flags = {}; - - Color m_customTextColor = {0}; - Color m_customValueColor = {0}; - - 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); - - #ifdef UI_OVERRIDE_PATH - { - 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; - } - } - } - #endif - } - - 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 = armTicksToNs(armGetSystemTick()); - 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; - - static bool lastRunningInterpreter = false; - const auto textColor = determineValueTextColor(useClickTextColor, lastRunningInterpreter); - - if (m_value != ult::INPROGRESS_SYMBOL) [[likely]] { - static const std::vector specialChars = {ult::DIVIDER_SYMBOL}; - renderer->drawStringWithColoredSections(m_value, false, specialChars, xPosition, yPosition, fontSize, textColor, textSeparatorColor); - } else { - drawThrobber(renderer, xPosition, yPosition, fontSize, textColor); - } - lastRunningInterpreter = ult::runningInterpreter.load(std::memory_order_acquire); - } - - Color determineValueTextColor(bool useClickTextColor, bool lastRunningInterpreter) const { - if (m_focused && ult::useSelectionValue) { - if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { - return useClickTextColor ? (clickTextColor) : - (m_flags.m_faint ? offTextColor : (useClickTextColor ? clickTextColor : (ult::useSelectionText ? selectedTextColor : defaultTextColor))); - } - - 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); - } - - 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 useClickTextColor ? clickTextColor : selectedValueTextColor; - } - - if (m_flags.m_hasCustomValueColor) { - return m_customValueColor; - } - - if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { - return (m_focused ? (useClickTextColor ? clickTextColor : (m_flags.m_faint ? offTextColor : (ult::useSelectionText ? selectedTextColor : defaultTextColor))) : - (useClickTextColor ? clickTextColor : (m_flags.m_faint ? offTextColor : defaultTextColor))); - } - - 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); - } - - 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_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(bool useScriptKey) const { - const u64 touchDuration_ns = armTicksToNs(armGetSystemTick()) - m_touchStartTime_ns; - const float touchDurationInSeconds = static_cast(touchDuration_ns) * 1e-9f; - - #if IS_LAUNCHER_DIRECTIVE - if (touchDurationInSeconds >= 1.0f) [[unlikely]] { - ult::longTouchAndRelease.store(true, std::memory_order_release); - return useScriptKey ? SCRIPT_KEY : STAR_KEY; - } - #endif - if (touchDurationInSeconds >= 0.5f) [[unlikely]] { - ult::shortTouchAndRelease.store(true, std::memory_order_release); - return useScriptKey ? SCRIPT_KEY : SETTINGS_KEY; - } - return KEY_A; - } - - void resetTextProperties() { - m_scrollText.clear(); - m_ellipsisText.clear(); - m_maxWidth = 0; - } - }; - - class MiniListItem : public ListItem { - public: - #if IS_LAUNCHER_DIRECTIVE - // Constructor for MiniListItem, with no `isMini` boolean. - MiniListItem(const std::string& text, const std::string& value = "", bool useScriptKey = false) - : ListItem(text, value, true, useScriptKey) { // Call the parent constructor with `isMini = true` - #else - MiniListItem(const std::string& text, const std::string& value = "") - : ListItem(text, value, true) { // Call the parent constructor with `isMini = true` - #endif - - // Additional MiniListItem-specific initialization can go here, if necessary. - } - - // 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) - */ - #if IS_LAUNCHER_DIRECTIVE - ListItemV2(const std::string& text, - const std::string& value = "", - Color valueColor = onTextColor, - Color faintColor = offTextColor, - bool isMini = false, - bool useScriptKey = true) - : ListItem(text, value, isMini, useScriptKey), - m_valueColorOverride(valueColor), - m_faintColorOverride(faintColor), - m_hasColorOverrides(true) { - - // Set the custom value color on the base ListItem - setValueColor(valueColor); - } - #else - 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); - } - #endif - - 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: - #if IS_LAUNCHER_DIRECTIVE - MiniListItemV2(const std::string& text, - const std::string& value = "", - Color valueColor = onTextColor, - Color faintColor = offTextColor, - bool useScriptKey = false) - : ListItemV2(text, value, valueColor, faintColor, true, useScriptKey) { - } - #else - MiniListItemV2(const std::string& text, - const std::string& value = "", - Color valueColor = onTextColor, - Color faintColor = offTextColor) - : ListItemV2(text, value, valueColor, faintColor, true) { - } - #endif - - 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 (keys & KEY_B) { - // triggerRumbleDoubleClick.store(true, std::memory_order_release); - // triggerExitSound.store(true, std::memory_order_release); - // - //} - - #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 inline bool getState() { - return this->m_state; - } - - /** - * @brief Sets the current state of the toggle. Updates the Value - * - * @param state State - */ - virtual inline 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(parentX, parentY, 0, 0); // Zero size - this->setBoundaries(this->getX(), this->getY(), 0, 0); - } - - // Override the requestFocus method to allow this item to be focusable - virtual inline Element* requestFocus(Element* oldFocus, FocusDirection direction) override { - return this; // Allow this item to be focusable - } - - //// Optionally override onClick and onTouch to handle interactions - //virtual bool onClick(u64 keys) override { - // return true; // Consume the click event - //} - // - //virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { - // return true; // Consume the touch event - //} - }; - - - class CategoryHeader : public Element { - public: - CategoryHeader(const std::string &title, bool hasSeparator = true) - : m_text(title), m_hasSeparator(hasSeparator), timeIn_ns(0), - 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() {} - - virtual void draw(gfx::Renderer *renderer) override { - static const std::vector specialChars = {""}; - - // Calculate widths if not done yet - if (!m_maxWidth) { - calculateWidths(renderer); - } - - // Draw separator if needed - if (this->m_hasSeparator) { - renderer->drawRect(this->getX()+1+1, this->getBottomBound() - 29-4, 4, 22, aWithOpacity(headerSeparatorColor)); - } - - // Determine text position - const int textX = m_hasSeparator ? (this->getX() + 15+1) : this->getX(); - const int textY = this->getBottomBound() - 12-4; - - // Handle scrolling text if truncated - if (m_truncated) { - if (!m_scroll) { - m_scroll = true; - timeIn_ns = armTicksToNs(armGetSystemTick()); - } - - // Calculate scissoring bounds that respect parent clipping - const int scissorX = textX; - const int scissorY = textY - 16; - const int scissorWidth = m_maxWidth; - const int scissorHeight = 24; - - // Get parent bounds (you'll need to implement this based on your parent system) - // This assumes your parent has some way to get its visible bounds - if (Element* parent = this->getParent()) { - const int parentTop = parent->getY()-8; // or whatever method gets the top bound - const int parentBottom = parent->getBottomBound(); // or equivalent - const int parentLeft = parent->getX(); - const int parentRight = parent->getX() + parent->getWidth(); - - // Clip scissor rectangle to parent bounds - const int clipLeft = std::max(scissorX, parentLeft); - const int clipRight = std::min(scissorX + scissorWidth, parentRight); - const int clipTop = std::max(scissorY, parentTop); - const int clipBottom = std::min(scissorY + scissorHeight, parentBottom); - - // Only enable scissoring if there's a visible area - if (clipLeft < clipRight && clipTop < clipBottom) { - renderer->enableScissoring(clipLeft, clipTop, - clipRight - clipLeft, - clipBottom - clipTop); - - renderer->drawStringWithColoredSections(m_scrollText, false, specialChars, - textX - static_cast(m_scrollOffset), textY, 16, - headerTextColor, textSeparatorColor); - - renderer->disableScissoring(); - } else { - // Draw normal or ellipsis text - //const std::string& displayText = m_truncated ? m_ellipsisText : m_text; - renderer->drawStringWithColoredSections(m_text, false, specialChars, - textX, textY, 16, headerTextColor, textSeparatorColor); - } - // If completely clipped, don't draw anything - } else { - // Draw normal or ellipsis text - //const std::string& displayText = m_truncated ? m_ellipsisText : m_text; - renderer->drawStringWithColoredSections(m_text, false, specialChars, - textX, textY, 16, headerTextColor, textSeparatorColor); - } - - handleScrolling(); - } else { - // Draw normal or ellipsis text - //const std::string& displayText = m_truncated ? m_ellipsisText : m_text; - renderer->drawStringWithColoredSections(m_text, false, specialChars, - textX, textY, 16, headerTextColor, textSeparatorColor); - } - } - - virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { - // Check if the CategoryHeader is part of a list and if it's the first entry in it, half it's height - if (List *list = static_cast(this->getParent()); list != nullptr) { - if (list->getIndexInList(this) == 0) { - this->setBoundaries(this->getX(), this->getY(), this->getWidth(), 29+4); - return; - } - } - this->setBoundaries(this->getX(), this->getY(), this->getWidth(), tsl::style::ListItemDefaultHeight *0.90); - } - - virtual bool onClick(u64 keys) { - return false; - } - - virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) override { - return nullptr; - } - - virtual void setFocused(bool state) override {} - - inline void setText(const std::string &text) { - if (this->m_text != text) { - this->m_text = text; - ult::applyLangReplacements(m_text); - ult::convertComboToUnicode(m_text); - //resetTextProperties(); - } - } - - inline const std::string& getText() const { - return this->m_text; - } - - private: - std::string m_text; - bool m_hasSeparator; - - // Scrolling properties (matching ListItem) - u64 timeIn_ns; - std::string m_scrollText; - //std::string m_ellipsisText; - bool m_scroll; - bool m_truncated; - float m_scrollOffset; - u32 m_maxWidth; - u32 m_textWidth; - - - // Frame rate compensation - cache calculations to reduce stutter - u64 lastUpdateTime = 0; - float cachedScrollOffset = 0.0f; - - // Pre-compute constants as statics to avoid recalculation - 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; - - void calculateWidths(gfx::Renderer* renderer) { - // Available width (accounting for separator and margins) - m_maxWidth = getWidth() - (m_hasSeparator ? 20-3 : 4); - - // Get actual text width - const u32 width = renderer->getTextDimensions(m_text, false, 16).first; - m_truncated = width > m_maxWidth; - - if (m_truncated) { - // Build scroll text: "text text" - 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); - - // Create ellipsis text - //m_ellipsisText = renderer->limitStringLength(m_text, false, 16, m_maxWidth); - } else { - m_textWidth = width; - } - } - - void handleScrolling() { - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - const u64 elapsed_ns = currentTime_ns - timeIn_ns; - - - if (!constantsInitialized || minScrollDistance != static_cast(m_textWidth)) { - // Constants for velocity-based scrolling (3 second pauses as requested) - delayDuration = 3.0; // 3 second pause at start - static constexpr double pauseDuration = 2.0; // 3 second pause at end - maxVelocity = 100.0; // Adjust for desired scroll speed - accelTime = 0.5; - static constexpr double decelTime = 0.5; - - // Pre-calculate derived constants - 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; - - // Pre-calculate reciprocals for faster division - invAccelTime = 1.0 / accelTime; - invDecelTime = 1.0 / decelTime; - invBillion = 1.0 / 1000000000.0; - - constantsInitialized = true; - } - - // Fast ns to seconds conversion - const double elapsed_seconds = static_cast(elapsed_ns) * invBillion; - - // Update at consistent intervals regardless of frame rate - if (currentTime_ns - lastUpdateTime >= 8333333ULL) { // ~120 FPS update rate - // Use std::fmod for modulo - it's optimized and faster than loops - const double cyclePosition = std::fmod(elapsed_seconds, totalCycleDuration); - - if (cyclePosition < delayDuration) { - // Delay phase - no scrolling (3 second pause) - cachedScrollOffset = 0.0f; - } else if (cyclePosition < delayDuration + scrollDuration) { - // Scrolling phase - velocity-based movement - const double scrollTime = cyclePosition - delayDuration; - double distance; - - if (scrollTime <= accelTime) { - // Acceleration phase - quadratic ease-in - const double t = scrollTime * invAccelTime; - const double smoothT = t * t; - distance = smoothT * accelDistance; - } else if (scrollTime <= accelTime + constantVelocityTime) { - // Constant velocity phase - const double constantTime = scrollTime - accelTime; - distance = accelDistance + (constantTime * maxVelocity); - } else { - // Deceleration phase - quadratic ease-out - const double decelStartTime = accelTime + constantVelocityTime; - const double t = (scrollTime - decelStartTime) * invDecelTime; - const double oneMinusT = 1.0 - t; - const double smoothT = 1.0 - oneMinusT * oneMinusT; - distance = accelDistance + constantVelocityDistance + (smoothT * (minScrollDistance - accelDistance - constantVelocityDistance)); - } - - // Use branchless min - cachedScrollOffset = static_cast(distance < minScrollDistance ? distance : minScrollDistance); - } else { - // Pause phase - stay at end (3 second pause) - cachedScrollOffset = static_cast(m_textWidth); - } - - lastUpdateTime = currentTime_ns; - } - - // Use cached value for consistent display - m_scrollOffset = cachedScrollOffset; - - // Reset timer when cycle completes - if (elapsed_seconds >= totalCycleDuration) { - timeIn_ns = currentTime_ns; - } - } - - //void resetTextProperties() { - // m_scrollText.clear(); - // m_ellipsisText.clear(); - // m_maxWidth = 0; - //} - }; - - - /** - * @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 = "") - : m_icon(icon), m_usingStepTrackbar(usingStepTrackbar), m_usingNamedStepTrackbar(usingNamedStepTrackbar), - 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 = armTicksToNs(armGetSystemTick()); - 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 = armTicksToNs(armGetSystemTick()); - static u64 lastUpdate_ns = currentTime_ns; - const u64 elapsed_ns = currentTime_ns - lastUpdate_ns; - - if (keysDown & KEY_A) { - this->triggerClickAnimation(); - triggerEnterFeedback(); - } - - 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; - - // Perform initial single tick - 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; - - // Initial delay before repeating starts - static constexpr u64 initialDelay_ns = 300000000ULL; // 300ms - // 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 (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 { - const u16 trackBarWidth = this->getWidth() - 95; - const u16 handlePos = (trackBarWidth * (this->m_value - 0)) / (100 - 0); - const s32 circleCenterX = this->getX() + 59 + handlePos; - const s32 circleCenterY = this->getY() + 40 + 16 - 1 - (m_usingNamedStepTrackbar ? 0 : 11); - 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); - - // Check horizontal bounds only (allow vertical drift) - const s32 trackBarLeft = this->getX() + 59; - const s32 trackBarRight = trackBarLeft + trackBarWidth; - 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); - } - - touchInSliderBounds = false; - return false; - } - - if (touchInCircle || touchInSliderBounds) { - // 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 = 100; - } else if (currX < trackBarLeft) { - this->m_value = 0; - } - this->m_valueChangedListener(this->getProgress()); - - touchInSliderBounds = false; - return false; - } - - // Only update if we're still in horizontal bounds - 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(trackBarWidth)) * 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 { - //static float lastBottomBound; - - if (touchInSliderBounds) { - m_drawFrameless = true; - drawHighlight(renderer); - } else { - m_drawFrameless = false; - } - - - s32 xPos = this->getX() + 59; - s32 yPos = this->getY() + 40 + 16 - 1; - 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) { - yPos -= 11; - } - - s32 iconOffset = 0; - - if (!m_useV2Style && m_icon[0] != '\0') { - s32 iconWidth = 23;//tsl::gfx::calculateStringWidth(m_icon, 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); - - if (!this->m_focused) { - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); - renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(m_drawFrameless ? highlightColor : trackBarSliderBorderColor)); - renderer->drawCircle(xPos + handlePos, yPos, 13, true, a((m_unlockedTrackbar || 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(highlightColor)); - renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a((ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) ? trackBarSliderMalleableColor : trackBarSliderColor)); - } - - // Draw icon (original style) or label + value (V2 style) - if (m_useV2Style) { - // V2 Style: Draw label and value - 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; - - renderer->drawString(labelPart, false, this->getX() + 59, this->getY() + 14 + 16, 16, - ((!this->m_focused || !ult::useSelectionText) ? defaultTextColor : selectedTextColor)); - - renderer->drawString(valuePart, false, this->getWidth() -17 - valueWidth, this->getY() + 14 + 16, 16, (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); - } else { - // Original Style: Draw icon - if (m_icon[0] != '\0') - renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2, 23, 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 { - - // Get current time using ARM system tick for animation timing - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - // High precision time calculation - matches standard cosine wave timing - const double time_seconds = static_cast(currentTime_ns) / 1000000000.0; - - // Standard cosine wave calculation with high precision - progress = (ult::cos(2.0 * ult::_M_PI * std::fmod(time_seconds, 1.0) - ult::_M_PI / 2) + 1.0) / 2.0; - - // Determine which colors to interpolate based on animation state - if (m_clickAnimationActive) { - // Handle click animation color transition - 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) { - highlightColor = { - static_cast((clickColor1.r - clickColor2.r) * progress + clickColor2.r + 0.5), - static_cast((clickColor1.g - clickColor2.g) * progress + clickColor2.g + 0.5), - static_cast((clickColor1.b - clickColor2.b) * progress + clickColor2.b + 0.5), - 0xF - }; - } else { - m_clickAnimationActive = false; - } - } else { - // Normal highlight animation - 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 - }; - } - - // Initialize position offsets - 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 (!m_drawFrameless) { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); // CUSTOM MODIFICATION - else - renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); // CUSTOM MODIFICATION - - - //renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), a(selectionBGColor)); // CUSTOM MODIFICATION - } - - renderer->drawBorderedRoundedRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11, this->getHeight(), 5, 5, a(highlightColor)); - } else { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); // CUSTOM MODIFICATION - else - renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); // CUSTOM MODIFICATION - } - } - - - ult::onTrackBar.exchange(true, std::memory_order_acq_rel); - - // Click animation rendering - checking if animation is active - 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 inline 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 = "") - : TrackBar(icon, true, usingNamedStepTrackbar, useV2Style, label, units), 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 = armTicksToNs(armGetSystemTick()); - static u64 lastUpdate_ns = currentTime_ns; - const u64 elapsed_ns = currentTime_ns - lastUpdate_ns; - - if (keysDown & KEY_A) { - this->triggerClickAnimation(); - triggerEnterFeedback(); - } - - // Calculate actual max value based on steps - const int stepSize = 100 / (this->m_numSteps - 1); - const int maxValue = stepSize * (this->m_numSteps - 1); // For 25 steps: 4 * 24 = 96 - - // 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; - - // Perform initial single tick - 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) { // CHANGED: was < 100 - triggerNavigationFeedback(); - this->m_value = std::min(this->m_value + stepSize, maxValue); // CHANGED: was 100 - 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) { // CHANGED: was < 100 - triggerNavigationFeedback(); - this->m_value = std::min(this->m_value + stepSize, maxValue); // CHANGED: was 100 - 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 { - // Calculate actual max value based on steps FIRST - const int stepSize = 100 / (this->m_numSteps - 1); - const int maxValue = stepSize * (this->m_numSteps - 1); // For 25 steps: 96 - - const u16 trackBarWidth = this->getWidth() - 95; - const u16 handlePos = (trackBarWidth * this->m_value) / maxValue; // CHANGED: was /100 - const s32 circleCenterX = this->getX() + 59 + handlePos; - const s32 circleCenterY = this->getY() + 40 + 16 - 1 - (m_usingNamedStepTrackbar ? 0 : 11); - static constexpr s32 circleRadius = 16; - static bool triggerOnce = true; - - const bool touchInCircle = (std::abs(currX - circleCenterX) <= circleRadius) && (std::abs(currY - circleCenterY) <= circleRadius); - - // Check horizontal bounds only (allow vertical drift) - const s32 trackBarLeft = this->getX() + 59; - const s32 trackBarRight = trackBarLeft + trackBarWidth; - 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); - } - - touchInSliderBounds = false; - return false; - } - - if (touchInCircle || touchInSliderBounds) { - // 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 = maxValue; - } else if (currX < trackBarLeft) { - this->m_value = 0; - } - this->m_valueChangedListener(this->getProgress()); - - touchInSliderBounds = false; - return false; - } - - // Only update if we're still in horizontal bounds - if (currentlyInHorizontalBounds) { - if (triggerOnce){ - triggerOnce = false; - triggerRumbleClick.store(true, std::memory_order_release); - triggerOnSound.store(true, std::memory_order_release); - } - - touchInSliderBounds = true; - - // CHANGED: Scale rawValue to maxValue instead of 100 - float rawValue = (static_cast(currX - trackBarLeft) / static_cast(trackBarWidth)) * maxValue; - s16 newValue; - - if (rawValue < 0) { - newValue = 0; - } else if (rawValue > maxValue) { - newValue = maxValue; - } else { - // Round to nearest step - 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 inline 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 = "") - : StepTrackBar(icon, stepDescriptions.size(), true, useV2Style, label, ""), - m_stepDescriptions(stepDescriptions.begin(), stepDescriptions.end()) { - this->m_usingNamedStepTrackbar = true; - m_numSteps = m_stepDescriptions.size(); - - // Initialize m_selection with first step - 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 - 1; - s32 width = this->getWidth() - 95; - const int maxValue = (100 / (this->m_numSteps - 1)) * (this->m_numSteps - 1); // For 25 steps: 96 - u16 handlePos = width * (this->m_value) / maxValue; // Changed from /100 - - // NOTE: For NamedStepTrackBar, yPos is NOT adjusted down - // (the !m_usingNamedStepTrackbar check is false here) - - s32 iconOffset = 0; - - if (!m_useV2Style && 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); // Not rounded for named step - - if (!this->m_focused) { - drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, false); - renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(m_drawFrameless ? highlightColor : trackBarSliderBorderColor)); - renderer->drawCircle(xPos + handlePos, yPos, 13, true, a((m_unlockedTrackbar || 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(highlightColor)); - renderer->drawCircle(xPos + x + handlePos, yPos +y, 12, true, a((ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) ? trackBarSliderMalleableColor : trackBarSliderColor)); - } - - // CRITICAL FIX: Draw the selection text based on which style is being used - if (m_useV2Style) { - // V2 Style: Draw label on left, value on right - std::string labelPart = this->m_label; - ult::removeTag(labelPart); - - std::string valuePart = this->m_selection; - const auto valueWidth = renderer->getTextDimensions(valuePart, false, 16).first; - - renderer->drawString(labelPart, false, this->getX() + 59, this->getY() + 14 + 16, 16, - ((!this->m_focused || !ult::useSelectionText) ? defaultTextColor : selectedTextColor)); - - renderer->drawString(valuePart, false, this->getWidth() -17 - valueWidth, this->getY() + 14 + 16, 16, - (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); - } else { - // OLD API Style: Draw selection text CENTERED ABOVE the bar - // This is the original libtesla behavior! - - // Calculate text width to center it (same font size and Y position as V2) - const auto textDimensions = renderer->getTextDimensions(this->m_selection, false, 16); - const s32 textWidth = textDimensions.first; - - // Center the text horizontally - account for the left margin (59) and right space - // The actual content area starts at getX() + 59 and the trackbar area is getWidth() - 95 - const s32 contentStart = 59; - const s32 trackbarWidth = this->getWidth() - 95; - const s32 textX = this->getX() + contentStart + (trackbarWidth / 2) - (textWidth / 2); - const s32 textY = this->getY() + 14 + 16; // Same Y position as V2 style - - // Draw the centered selection text - renderer->drawString(this->m_selection.c_str(), false, textX, textY, 16, - a(this->m_focused ? tsl::style::color::ColorHighlight : tsl::style::color::ColorText)); - - // Also draw icon if provided (though usually empty for named step trackbars) - if (m_icon[0] != '\0') - renderer->drawString(this->m_icon, false, this->getX()+42, this->getY() + 50+2, 23, 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 = armTicksToNs(armGetSystemTick()); - } - - 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 inline 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 = armTicksToNs(armGetSystemTick()); - 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)) { - triggerEnterFeedback(); - - if (!m_unlockedTrackbar) { - ult::atomicToggle(ult::allowSlide); - m_holding = false; - } - if (m_unlockedTrackbar || (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire))) { - updateAndExecute(); - triggerClick = true; - } - 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 = armTicksToNs(armGetSystemTick()); - 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 = armTicksToNs(armGetSystemTick()); - 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 = armTicksToNs(armGetSystemTick()); - 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); - } - 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 - 1; - 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 = armTicksToNs(armGetSystemTick()); - 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 = { - static_cast((clickColor1.r - clickColor2.r) * progress + clickColor2.r + 0.5), - static_cast((clickColor1.g - clickColor2.g) * progress + clickColor2.g + 0.5), - static_cast((clickColor1.b - clickColor2.b) * progress + clickColor2.b + 0.5), - 0xF - }; - } 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 = { - static_cast((highlightColor1.r - highlightColor2.r) * progress + highlightColor2.r + 0.5), - static_cast((highlightColor1.g - highlightColor2.g) * progress + highlightColor2.g + 0.5), - static_cast((highlightColor1.b - highlightColor2.b) * progress + highlightColor2.b + 0.5), - 0xF - }; - } else { - highlightColor = { - static_cast((highlightColor3.r - highlightColor4.r) * progress + highlightColor4.r + 0.5), - static_cast((highlightColor3.g - highlightColor4.g) * progress + highlightColor4.g + 0.5), - static_cast((highlightColor3.b - highlightColor4.b) * progress + highlightColor4.b + 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 (!m_drawFrameless) { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(selectionBGColor)); - else - renderer->drawRect(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(highlightColor)); - } else { - if (ult::useSelectionBG) { - if (ult::expandedMemory) - renderer->drawRectMultiThreaded(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); - else - renderer->drawRect(this->getX() + x +19, this->getY() + y, this->getWidth()-11-4, this->getHeight(), aWithOpacity(clickColor)); - } - - } - - 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 inline u8 getIndex() { - return this->m_index; - } - - virtual inline 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 inline 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; - - // ADD THIS LINE: Update KEY_R state for visual appearance - m_keyRHeld = (keysHeld & KEY_R) != 0; - - if ((keysHeld & KEY_R)) { - //auto currentFocus = currentGui->getFocusedElement(); - 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)) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerEnterSound.store(true, std::memory_order_release); - triggerEnterFeedback(); - - - if (!m_unlockedTrackbar) { - ult::atomicToggle(ult::allowSlide); - holding = false; // Reset holding state when KEY_A is pressed - } - if (m_unlockedTrackbar || (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire))) { - updateAndExecute(); - triggerClick = true; - } - return true; - } - - //if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { - // triggerRumbleDoubleClick.store(true, std::memory_order_release); - // triggerExitSound.store(true, std::memory_order_release); - //} - - // 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) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - 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) { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerNavigationSound.store(true, std::memory_order_release); - 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 inline 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)); - } - } - - //protected: - //u8 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) { - //usingNamedStepTrackbar = true; - //logMessage("on initialization"); - - // 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}; - - struct NotificationFile { - std::string filename; - std::string fullPath; - time_t creationTime; - int priority; - }; - - class NotificationPrompt { - public: - NotificationPrompt() - : enabled_(true), - is_active_(false), - //pending_event_fire_(false), - generation_(notificationGeneration.load(std::memory_order_acquire)) - {} - - ~NotificationPrompt() { - shutdown(); // safe cleanup - } - - enum class PromptState { - Inactive, - SlidingIn, - Visible, - SlidingOut - }; - - struct NotificationData { - std::string text; - std::string fileName; - size_t fontSize = 28; - s32 promptWidth = 448; - s32 promptHeight = 88; - u32 durationMs = 2500; - u32 priority = 20; - u64 arrivalNs = 0; - - NotificationData() = default; - - NotificationData(const std::string& t, const std::string& f = "", - size_t fs = 28, s32 w = 448, s32 h = 88, - u32 dur = 2500, u32 prio = 20) - : text(t), fileName(f), fontSize(fs), promptWidth(w), promptHeight(h), - durationMs(dur), priority(prio), arrivalNs(0) {} - }; - - struct NotificationCompare { - bool operator()(const NotificationData& a, const NotificationData& b) const { - if (a.priority == b.priority) { - return a.arrivalNs > b.arrivalNs; // FIFO - } - return a.priority > b.priority; // Max-heap - } - }; - - struct NotificationState { - std::string activeText; - std::string fileName; - size_t fontSize = 28; - s32 promptWidth = 448; - s32 promptHeight = 88; - PromptState state = PromptState::Inactive; - u64 expireNs = 0; - u64 stateStartNs = 0; - - NotificationState() = default; - bool isTextEmpty() const { return activeText.empty(); } - }; - - // ---------------- Public Methods ---------------- - - void show(const std::string& msg, size_t fontSize = 26, u32 priority = 20, - const std::string& fileName = "", u32 durationMs = 2500, - s32 promptWidth = 448, s32 promptHeight = 88, bool immediately = false) - { - if (msg.empty()) return; - - // Quick reject using atomics (fast-path) - if (!enabled_.load(std::memory_order_acquire)) return; - if (!ult::useNotifications) return; - if (generation_ != notificationGeneration.load(std::memory_order_acquire)) return; - - NotificationData data; - data.text = msg; - data.fileName = fileName; - data.fontSize = std::clamp(fontSize, size_t(8), size_t(48)); - data.promptWidth = std::clamp(promptWidth, s32(100), s32(1280)); - data.promptHeight = std::clamp(promptHeight, s32(50), s32(720)); - data.durationMs = std::clamp(durationMs, 500u, 30000u); - data.priority = immediately ? 0 : priority; // Priority 0 for immediate - data.arrivalNs = armTicksToNs(armGetSystemTick()); - - std::lock_guard lg(state_mutex_); - - // Re-check under lock to avoid TOCTOU - if (!enabled_.load(std::memory_order_acquire)) return; - if (generation_ != notificationGeneration.load(std::memory_order_acquire)) return; - if (pending_queue_.size() >= MAX_NOTIFS) return; - - // If immediately = true and there's an active notification, force it to complete - if (immediately && is_active_ && current_state_.state != PromptState::Inactive) { - // Delete current notification's file if exists - const std::string fileToDelete = current_state_.fileName; - if (!fileToDelete.empty()) { - std::lock_guard lg(notificationJsonMutex); - const std::string fullPath = ult::NOTIFICATIONS_PATH + fileToDelete; - remove(fullPath.c_str()); - } - - // Reset current state - current_state_ = NotificationState{}; - is_active_ = false; - } - - pending_queue_.push(data); - - if (!is_active_) { - startNext_NoLock(); - eventFire(¬ificationEvent); - - #if IS_STATUS_MONITOR_DIRECTIVE - if (isRendering) { - isRendering = false; - wasRendering = true; - - leventSignal(&renderingStopEvent); - } - #endif - } - } - - // Immediate notification function - shows immediately with highest priority - void showNow(const std::string& msg, size_t fontSize = 26) { - show(msg, fontSize, 0, "", 2500, 448, 88, true); - } - - - void draw(gfx::Renderer* renderer, bool promptOnly = false) { - if (ult::launchingOverlay.load(std::memory_order_acquire) || - generation_ != notificationGeneration.load(std::memory_order_acquire)) return; - if (!enabled_.load(std::memory_order_acquire)) return; - - NotificationState copy; - { - std::lock_guard lg(state_mutex_); - if (current_state_.state == PromptState::Inactive || current_state_.activeText.empty()) return; - copy = current_state_; - } - - const u64 now = armTicksToNs(armGetSystemTick()); - const u64 elapsedMs = (now - copy.stateStartNs) / 1'000'000ULL; - - s32 x = 0, y = 0; - switch (copy.state) { - case PromptState::SlidingIn: { - const float t = std::min(1.0f, float(elapsedMs) / SLIDE_DURATION_MS); - x = ult::useRightAlignment ? - (tsl::cfg::FramebufferWidth - copy.promptWidth + static_cast((1.0f - t) * copy.promptWidth)) : - static_cast(-copy.promptWidth + t * copy.promptWidth); - break; - } - case PromptState::Visible: - x = ult::useRightAlignment ? (tsl::cfg::FramebufferWidth - copy.promptWidth) : 0; - break; - case PromptState::SlidingOut: { - const float t = std::min(1.0f, float(elapsedMs) / SLIDE_DURATION_MS); - x = ult::useRightAlignment ? - (tsl::cfg::FramebufferWidth - copy.promptWidth + static_cast(t * copy.promptWidth)) : - static_cast(-t * copy.promptWidth); - break; - } - default: return; - } - - const s32 scissorX = std::max(0, x); - const s32 scissorW = std::min(copy.promptWidth, tsl::cfg::FramebufferWidth - scissorX); - - if (scissorX >= 0 && scissorW > 0 && copy.promptHeight > 0) { - renderer->enableScissoring(scissorX, y, scissorW, copy.promptHeight); - - #if IS_STATUS_MONITOR_DIRECTIVE - renderer->drawRect(x, y, copy.promptWidth, copy.promptHeight, defaultBackgroundColor); - #else - if (!promptOnly && ult::expandedMemory) - renderer->drawRectMultiThreaded(x, y, copy.promptWidth, copy.promptHeight, defaultBackgroundColor); - else - renderer->drawRect(x, y, copy.promptWidth, copy.promptHeight, defaultBackgroundColor); - #endif - - if (!copy.activeText.empty()) { - std::vector lines; - const std::string& text = copy.activeText; - - size_t start = 0; - while (start < text.size() && lines.size() < 8) { - // Look for escaped "\n" - const size_t pos = text.find("\n", start); - - if (pos == std::string::npos) { - // No more "\n", take the rest - lines.emplace_back(text.substr(start)); - break; - } else { - // Extract line up to the escape sequence - lines.emplace_back(text.substr(start, pos - start)); - start = pos + 1; // Skip past "\n" - } - } - - const auto fm = tsl::gfx::FontManager::getFontMetricsForCharacter('A', copy.fontSize); - const s32 startY = y + (copy.promptHeight - (static_cast(lines.size()) * fm.lineHeight)) / 2 + fm.ascent; - - for (size_t i = 0; i < lines.size(); ++i) { - const std::string& line = lines[i]; - - #if IS_LAUNCHER_DIRECTIVE - // Check if line contains "Ultrahand" (case insensitive) - const bool hasUltrahand = (line.find(ult::CAPITAL_ULTRAHAND_PROJECT_NAME) != std::string::npos); - - if (hasUltrahand) { - // Draw line with dynamic Ultrahand effect - drawUltrahandLine(renderer, line, x, startY + static_cast(i) * fm.lineHeight, - copy.fontSize, copy.promptWidth); - } else { - // Draw normal line - const auto [lw, lh] = renderer->getNotificationTextDimensions(line, false, copy.fontSize); - renderer->drawNotificationString( - line, false, - x + (copy.promptWidth - lw) / 2, - startY + static_cast(i) * fm.lineHeight, - copy.fontSize, notificationTextColor - ); - } - #else - // Draw normal line - const auto [lw, lh] = renderer->getNotificationTextDimensions(line, false, copy.fontSize); - renderer->drawNotificationString( - line, false, - x + (copy.promptWidth - lw) / 2, - startY + static_cast(i) * fm.lineHeight, - copy.fontSize, notificationTextColor - ); - #endif - } - } - - if (!ult::useRightAlignment) { - renderer->drawRect(x + copy.promptWidth - 1, y, 1, copy.promptHeight, edgeSeparatorColor); - renderer->drawRect(x, y + copy.promptHeight - 1, copy.promptWidth, 1, edgeSeparatorColor); - } else { - renderer->drawRect(x, y, 1, copy.promptHeight, edgeSeparatorColor); - renderer->drawRect(x, y + copy.promptHeight - 1, copy.promptWidth, 1, edgeSeparatorColor); - } - - renderer->disableScissoring(); - } - } - - #if IS_LAUNCHER_DIRECTIVE - void drawUltrahandLine(gfx::Renderer* renderer, const std::string& line, s32 x, s32 y, - u32 fontSize, s32 promptWidth) { - // Find position of "Ultrahand" in the line (case insensitive) - size_t ultrahandPos = std::string::npos; - std::string ultrahandToReplace; - - // Check for "Ultrahand" first - ultrahandPos = line.find(ult::CAPITAL_ULTRAHAND_PROJECT_NAME); - if (ultrahandPos != std::string::npos) { - ultrahandToReplace = ult::CAPITAL_ULTRAHAND_PROJECT_NAME; - } - - if (ultrahandPos == std::string::npos) { - // Fallback to normal drawing if not found - const auto [lw, lh] = renderer->getNotificationTextDimensions(line, false, fontSize); - renderer->drawNotificationString(line, false, x + (promptWidth - lw) / 2, y, fontSize, notificationTextColor); - return; - } - - // Split the line into parts - const std::string before = line.substr(0, ultrahandPos); - const std::string hand = ult::SPLIT_PROJECT_NAME_2; - const std::string after = line.substr(ultrahandPos + ultrahandToReplace.length()); - - // Calculate individual part widths to get accurate total width - s32 beforeWidth = 0, handWidth = 0, afterWidth = 0; - - if (!before.empty()) { - const auto [bw, bh] = renderer->getNotificationTextDimensions(before, false, fontSize); - beforeWidth = bw; - } - - if (!after.empty()) { - const auto [aw, ah] = renderer->getNotificationTextDimensions(after, false, fontSize); - afterWidth = aw; - } - - const auto [hw, hh] = renderer->getNotificationTextDimensions(hand, false, fontSize); - handWidth = hw; - - // Use shared utility to calculate Ultra width - const s32 ultraWidth = tsl::elm::calculateUltraTextWidth(renderer, fontSize, true); - - // Calculate total width and starting position for centering - const s32 totalWidth = beforeWidth + ultraWidth + handWidth + afterWidth; - s32 currentX = x + (promptWidth - totalWidth) / 2; - - // Draw each part in sequence - - // Draw "before" part - if (!before.empty()) { - renderer->drawNotificationString(before, false, currentX, y, fontSize, notificationTextColor); - currentX += beforeWidth; - } - - // Draw dynamic "Ultra" part using shared utility - currentX = tsl::elm::drawDynamicUltraText(renderer, currentX, y, fontSize, logoColor1, true); - - // Draw static "hand" part - renderer->drawNotificationString(hand, false, currentX, y, fontSize, logoColor2); - currentX += handWidth; - - // Draw "after" part - if (!after.empty()) { - renderer->drawNotificationString(after, false, currentX, y, fontSize, notificationTextColor); - } - } - #endif - - void update() { - if (!isActive()) { - return; - } - std::lock_guard lg(state_mutex_); - // Optional extra safety: skip if already inactive and queue empty - if (ult::launchingOverlay.load(std::memory_order_acquire) || - (!is_active_ && current_state_.activeText.empty() && pending_queue_.empty())) { - return; - } - - //std::lock_guard lg(state_mutex_); - if (generation_ != notificationGeneration.load(std::memory_order_acquire) || - !enabled_.load(std::memory_order_acquire)) - { - current_state_ = NotificationState{}; - is_active_ = false; - return; - } - - const u64 now = armTicksToNs(armGetSystemTick()); - const u64 elapsedMs = (current_state_.stateStartNs == 0) ? 0 : (now - current_state_.stateStartNs) / 1'000'000ULL; - - switch (current_state_.state) { - case PromptState::SlidingIn: - if (elapsedMs >= SLIDE_DURATION_MS) { - current_state_.state = PromptState::Visible; - current_state_.stateStartNs = now; - } - break; - case PromptState::Visible: - if (now >= current_state_.expireNs) { - current_state_.state = PromptState::SlidingOut; - current_state_.stateStartNs = now; - } - break; - case PromptState::SlidingOut: - if (elapsedMs >= SLIDE_DURATION_MS) { - const std::string fileToDelete = current_state_.fileName; - // Delete the JSON file safely - if (!fileToDelete.empty()) { - std::lock_guard lg(notificationJsonMutex); - const std::string fullPath = ult::NOTIFICATIONS_PATH + fileToDelete; - remove(fullPath.c_str()); // ignore errors for now - } - - current_state_ = NotificationState{}; - const bool hadNext = startNext_NoLock(); - if (!hadNext) { - is_active_ = false; - } - } - break; - default: break; - } - } - - bool isActive() const { - if (!ult::useNotifications) return false; - if (generation_ != notificationGeneration.load(std::memory_order_acquire)) return false; - std::lock_guard lg(state_mutex_); - if (is_active_) return true; - if (!pending_queue_.empty()) return true; - //if (pending_event_fire_.load(std::memory_order_acquire)) return true; - if (!current_state_.activeText.empty() && current_state_.state != PromptState::Inactive) return true; - return false; - } - - void shutdown() { - enabled_.store(false, std::memory_order_release); - notificationGeneration.fetch_add(1, std::memory_order_acq_rel); - generation_ = notificationGeneration.load(std::memory_order_acquire); - - std::lock_guard lg(state_mutex_); - while (!pending_queue_.empty()) pending_queue_.pop(); - current_state_ = NotificationState{}; - is_active_ = false; - //pending_event_fire_.store(false, std::memory_order_release); - } - - void forceShutdown() { - enabled_.store(false, std::memory_order_release); - //pending_event_fire_.store(false, std::memory_order_release); - } - - - private: - static constexpr size_t MAX_NOTIFS = 30; - static constexpr u32 SLIDE_DURATION_MS = 200; - //static constexpr double cycleDuration = 1.6; - - mutable std::mutex state_mutex_; - NotificationState current_state_; - std::priority_queue, NotificationCompare> pending_queue_; - - std::atomic enabled_{true}; - bool is_active_{false}; // protected by mutex - //std::atomic pending_event_fire_{false}; - uint32_t generation_{0}; - - bool startNext_NoLock() { - if (pending_queue_.empty()) return false; - const NotificationData next = pending_queue_.top(); - pending_queue_.pop(); - - const u64 now = armTicksToNs(armGetSystemTick()); - current_state_.activeText = next.text; - current_state_.fileName = next.fileName; - current_state_.fontSize = next.fontSize; - current_state_.promptWidth = next.promptWidth; - current_state_.promptHeight = next.promptHeight; - current_state_.state = PromptState::SlidingIn; - current_state_.stateStartNs = now; - current_state_.expireNs = now + static_cast(SLIDE_DURATION_MS) * 1'000'000ULL - + static_cast(next.durationMs) * 1'000'000ULL; - is_active_ = true; - return true; - } - }; - - // Optional: pointer to global notification - static 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 - #else - { - #if INITIALIZE_IN_GUI_DIRECTIVE // for different project structures - tsl::initializeThemeVars(); - - // 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 inline 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) - 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; - - //// Function to recursively find the bottom element - //void findBottomElement(elm::Element* currentElement) { - // // Base case: if the current element has no children, it is the bottom element - // if (currentElement->getChildren().empty()) { - // m_bottomElement = currentElement; - // return; - // } - // - // // Recursive case: traverse through all children elements - // for (elm::Element* child : currentElement->getChildren()) { - // findBottomElement(child); - // } - //} - - /** - * @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); - //ult::Audio::reloadIfDockedChanged(); - - - 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); - } - - //if (auto& currGui = this->getCurrentGui(); currGui != nullptr) // TESTING DISABLED (EFFECTS NEED TO BE VERIFIED) - // currGui->restoreFocus(); - } - - /** - * @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 - //float opacity = calculateEaseInOut(static_cast(this->m_animationCounter) / MAX_ANIMATION_COUNTER); - 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); - - //notificationCacheNeedsClearing.store(true, std::memory_order_release); - } 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()) { - 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) { - 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 variables to maintain state between function calls - 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 constexpr u64 CLICK_THRESHOLD_NS = 340000000ULL; // 340ms in nanoseconds - - - static bool hasScrolled = false; - static void* lastGuiPtr = nullptr; // Use void* instead - - auto& currentGui = this->getCurrentGui(); - - // Return early if current GUI is not available or internal touch is not released - 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; - } - - // Retrieve current focus and top/bottom elements of the GUI - auto currentFocus = currentGui->getFocusedElement(); - - - const bool interpreterIsRunning = ult::runningInterpreter.load(std::memory_order_acquire); - #if !IS_STATUS_MONITOR_DIRECTIVE - if (interpreterIsRunning) { - if (keysDown & KEY_UP && !(keysHeld & ~KEY_UP & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Up); - return; - } - else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Down); - return; - } - else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Left); - return; - } - else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) { - currentFocus->shakeHighlight(FocusDirection::Right); - return; - } - } - #endif - - - #if IS_STATUS_MONITOR_DIRECTIVE - if (FullMode && !deactivateOriginalFooter) { - if ((keysDown & ALL_KEYS_MASK) && ult::stillTouching && ult::currentForeground.load(std::memory_order_acquire)) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - 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) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - } - //ult::simulatedBackComplete = true; - } - 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)) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - 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) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - } - //ult::simulatedBackComplete = true; - } - return; - } - } else { - #if IS_LAUNCHER_DIRECTIVE - if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { - if (this->m_guiStack.size() >= 1 && !interpreterIsRunning) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - - triggerExitFeedback(); - - } - } - #endif - } - #endif - - // Reset touch state when GUI changes - if (currentGui.get() != lastGuiPtr) { // or just currentGui != lastGuiPtr if it's not a smart pointer - hasScrolled = false; - oldTouchEvent = elm::TouchEvent::None; - oldTouchDetected = false; - oldTouchPos = { 0 }; - initialTouchPos = { 0 }; - lastGuiPtr = currentGui.get(); // or just currentGui - } - - auto topElement = currentGui->getTopElement(); - - const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - 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); - - // Reset navigation timing to prevent fast scrolling - buttonPressTime_ns = currentTime_ns; - lastKeyEventTime_ns = buttonPressTime_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)) { - hasScrolled = true; - } else if (ult::shortTouchAndRelease.exchange(false, std::memory_order_acq_rel)) { - hasScrolled = true; - } - } - - bool handled = false; - elm::Element* parentElement = currentFocus; - - while (!handled && parentElement) { - handled = parentElement->onClick(keysDown) || parentElement->handleInput(keysDown, keysHeld, touchPos, joyStickPosLeft, joyStickPosRight); - parentElement = parentElement->getParent(); - } - - if (currentGui != this->getCurrentGui()) return; - - handled |= currentGui->handleInput(keysDown, keysHeld, touchPos, joyStickPosLeft, joyStickPosRight); - - - // Navigational boundary cases for handling wrapping - static bool lastDirectionPressed = true; - const bool directionPressed = ((keysHeld & KEY_UP) || (keysHeld & KEY_DOWN) || (keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT)); - - 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); - - if (hasScrolled) { - const bool singleArrowKeyPress = ((keysHeld & KEY_UP) != 0) + ((keysHeld & KEY_DOWN) != 0) + ((keysHeld & KEY_LEFT) != 0) + ((keysHeld & KEY_RIGHT) != 0) == 1 && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_UP : KEY_UP) | KEY_DOWN | KEY_LEFT | KEY_RIGHT) & ALL_KEYS_MASK); - - if (singleArrowKeyPress) { - // const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - buttonPressTime_ns = currentTime_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; - const bool singleArrowKeyPress = ((keysHeld & KEY_UP) != 0) + ((keysHeld & KEY_DOWN) != 0) + ((keysHeld & KEY_LEFT) != 0) + ((keysHeld & KEY_RIGHT) != 0) == 1 && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_UP: KEY_UP) | KEY_DOWN | KEY_LEFT | KEY_RIGHT) & ALL_KEYS_MASK); - - if (singleArrowKeyPress) { - //const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - if (keysDown) { - buttonPressTime_ns = currentTime_ns; - lastKeyEventTime_ns = currentTime_ns; - singlePressHandled = false; - // Immediate single press action - 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->getParent(), FocusDirection::Down, shouldShake); - //isTopElement = false; - } - else if (keysHeld & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Left, shouldShake); - else if (keysHeld & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Right, shouldShake); - } - - if (keysHeld & ~KEY_DOWN & ~KEY_UP & ~KEY_LEFT & ~KEY_RIGHT & ALL_KEYS_MASK) // reset - buttonPressTime_ns = currentTime_ns; - - const u64 durationSincePress_ns = currentTime_ns - buttonPressTime_ns; - const u64 durationSinceLastEvent_ns = currentTime_ns - lastKeyEventTime_ns; - - if (!singlePressHandled && durationSincePress_ns >= CLICK_THRESHOLD_NS) { - singlePressHandled = true; - } - - if (!tsl::elm::isTableScrolling.load(std::memory_order_acquire)) { - // Calculate transition factor (t) from 0 to 1 based on how far we are from the transition point - static constexpr u64 transitionPoint_ns = 2000000000ULL; // 2000ms in nanoseconds - static constexpr u64 initialInterval_ns = 67000000ULL; // 67ms in nanoseconds - static constexpr u64 shortInterval_ns = 10000000ULL; // 10ms in nanoseconds - - const float t = (durationSincePress_ns >= transitionPoint_ns) ? 1.0f : - (float)durationSincePress_ns / (float)transitionPoint_ns; - // Smooth transition between intervals using linear interpolation - keyEventInterval_ns = ((1.0f - t) * initialInterval_ns + t * shortInterval_ns); - } else { - // Table scrolling - faster timing - static constexpr u64 transitionPoint_ns = 200000000ULL; // 300ms (faster transition) - static constexpr u64 initialInterval_ns = 33000000ULL; // 33ms (faster initial) - static constexpr u64 shortInterval_ns = 5000000ULL; // 5ms (faster sustained) - - const float t = (durationSincePress_ns >= transitionPoint_ns) ? 1.0f : - (float)durationSincePress_ns / (float)transitionPoint_ns; - // Smooth transition between intervals using linear interpolation - keyEventInterval_ns = ((1.0f - t) * initialInterval_ns + t * shortInterval_ns); - } - - - - if (singlePressHandled && durationSinceLastEvent_ns >= keyEventInterval_ns) { - lastKeyEventTime_ns = currentTime_ns; - if (keysHeld & KEY_UP && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_UP: KEY_UP)) & ALL_KEYS_MASK)) - currentGui->requestFocus(topElement, FocusDirection::Up, false); - else if (keysHeld & KEY_DOWN && !(keysHeld & ~((currentScrollVelocity != 0.0f ? KEY_A | KEY_DOWN: KEY_DOWN)) & ALL_KEYS_MASK)) { - currentGui->requestFocus(currentFocus->getParent(), FocusDirection::Down, false); - //isTopElement = 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 - // Shared constants used by ZL/ZR buttons - static constexpr u64 INITIAL_HOLD_THRESHOLD_NS = 400000000ULL; - static constexpr u64 HOLD_THRESHOLD_NS = 300000000ULL; // 300ms to start continuous - static constexpr u64 RAPID_CLICK_WINDOW_NS = 500000000ULL; // 500ms window for rapid clicking - static constexpr u64 RAPID_MODE_TIMEOUT_NS = 1000000000ULL; // 1s timeout to exit rapid mode - // Acceleration timing constants - static constexpr u64 ACCELERATION_POINT_NS = 1500000000ULL; // 1.5s transition point - static constexpr u64 INITIAL_INTERVAL_NS = 67000000ULL; // 67ms initial interval - static constexpr u64 FAST_INTERVAL_NS = 10000000ULL; // 10ms fast interval - - //const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); - - // Detect PHYSICAL key states (whether key is actually pressed) - const bool lKeyPressed = (keysHeld & KEY_L); - const bool rKeyPressed = (keysHeld & KEY_R); - const bool zlKeyPressed = (keysHeld & KEY_ZL); - const bool zrKeyPressed = (keysHeld & KEY_ZR); - - // Detect if other keys are pressed (for preventing timer resets) - 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); - - // Handle L button (simple jump to top on release, but not if held too long) - { - static bool lKeyWasPressed = false; - static bool lWasIsolated = false; // Track if L was isolated when first pressed - static u64 lButtonPressStart_ns = 0; - - if (lKeyPressed) { - - if (!lKeyWasPressed) { - // L key physically pressed for the first time (start timer) - lButtonPressStart_ns = currentTime_ns; - lWasIsolated = !notlKeyPressed; // Remember if it started isolated - } - // Don't reset timer if other keys are pressed after L was already held - lKeyWasPressed = true; - } else { - if (lKeyWasPressed) { - // L key physically released - only jump to top if was isolated when first pressed and not held too long - if (lWasIsolated && !(keysHeld & ~KEY_L & ALL_KEYS_MASK)) { // Was isolated initially and no other keys held at release - const u64 holdDuration = currentTime_ns - lButtonPressStart_ns; - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - jumpToTop.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - } - } - } - lKeyWasPressed = false; - lWasIsolated = false; - } - } - - // Handle R button (simple jump to bottom on release, but not if held too long) - { - static bool rKeyWasPressed = false; - static bool rWasIsolated = false; // Track if R was isolated when first pressed - static u64 rButtonPressStart_ns = 0; - - if (rKeyPressed) { - if (!rKeyWasPressed) { - // R key physically pressed for the first time (start timer) - rButtonPressStart_ns = currentTime_ns; - rWasIsolated = !notrKeyPressed; // Remember if it started isolated - } - // Don't reset timer if other keys are pressed after R was already held - rKeyWasPressed = true; - } else { - if (rKeyWasPressed) { - // R key physically released - only jump to bottom if was isolated when first pressed and not held too long - if (rWasIsolated && !(keysHeld & ~KEY_R & ALL_KEYS_MASK)) { // Was isolated initially and no other keys held at release - const u64 holdDuration = currentTime_ns - rButtonPressStart_ns; - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - jumpToBottom.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - } - } - } - rKeyWasPressed = false; - rWasIsolated = false; - } - } - - // Handle ZL button (skip up with hold) - { - static u64 zlLastClickTime_ns = 0; - static bool zlKeyWasPressed = false; - static bool zlWasIsolated = false; // Track if ZL was isolated when first pressed - static bool zlInRapidClickMode = false; - static u64 zlFirstClickPressStart_ns = 0; // Track timing for first clicks only - - // Check if we should exit rapid click mode due to timeout - if (zlInRapidClickMode && (currentTime_ns - zlLastClickTime_ns) > RAPID_MODE_TIMEOUT_NS) { - zlInRapidClickMode = false; - } - - if (zlKeyPressed) { - if (!zlKeyWasPressed) { - // ZL key physically pressed for the first time - const u64 timeSinceLastClick = currentTime_ns - zlLastClickTime_ns; - - zlWasIsolated = !notzlKeyPressed; // Remember if it started isolated - - // Track press start time for first clicks (when not in rapid mode) - if (!zlInRapidClickMode) { - zlFirstClickPressStart_ns = currentTime_ns; - } - - // Enter rapid click mode if clicking within window - if (timeSinceLastClick <= RAPID_CLICK_WINDOW_NS) { - zlInRapidClickMode = true; - } - - // Only trigger immediately if in rapid click mode AND was isolated initially - if (zlInRapidClickMode && zlWasIsolated) { - skipUp.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zlLastClickTime_ns = currentTime_ns; - } - } - - // Check for hold behavior - ONLY if in rapid click mode AND was isolated initially - if (zlInRapidClickMode && zlWasIsolated) { - static u64 zlButtonPressStart_ns = 0; - static u64 zlLastHoldTrigger_ns = 0; - static bool zlHoldTriggered = false; - - // Initialize on new press - if (!zlKeyWasPressed) { - zlButtonPressStart_ns = currentTime_ns; - zlLastHoldTrigger_ns = currentTime_ns; - zlHoldTriggered = false; - } - - const u64 holdDuration = currentTime_ns - zlButtonPressStart_ns; - - if (holdDuration >= HOLD_THRESHOLD_NS) { - // Calculate dynamic interval based on hold duration (accelerating) - const float t = (holdDuration >= ACCELERATION_POINT_NS) ? 1.0f : - (float)holdDuration / (float)ACCELERATION_POINT_NS; - const u64 currentInterval = ((1.0f - t) * INITIAL_INTERVAL_NS + t * FAST_INTERVAL_NS); - - const u64 timeSinceLastHoldTrigger = currentTime_ns - zlLastHoldTrigger_ns; - - if (!zlHoldTriggered || timeSinceLastHoldTrigger >= currentInterval) { - // Trigger skip - skipUp.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zlHoldTriggered = true; - zlLastHoldTrigger_ns = currentTime_ns; - zlLastClickTime_ns = currentTime_ns; // Keep rapid mode active - } - } - } - - zlKeyWasPressed = true; - } else { - if (zlKeyWasPressed) { - // ZL key physically released - only trigger if was isolated initially and no other keys held at release - if (!zlInRapidClickMode && zlWasIsolated && !(keysHeld & ~KEY_ZL & ALL_KEYS_MASK)) { - const u64 holdDuration = currentTime_ns - zlFirstClickPressStart_ns; - - // Only trigger if not held too long - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - skipUp.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zlLastClickTime_ns = currentTime_ns; - zlInRapidClickMode = true; // Enter rapid mode after first release - } - } - } - zlKeyWasPressed = false; - zlWasIsolated = false; - } - } - - // Handle ZR button (skip down with hold) - { - static u64 zrLastClickTime_ns = 0; - static bool zrKeyWasPressed = false; - static bool zrWasIsolated = false; // Track if ZR was isolated when first pressed - static bool zrInRapidClickMode = false; - static u64 zrFirstClickPressStart_ns = 0; // Track timing for first clicks only - - // Check if we should exit rapid click mode due to timeout - if (zrInRapidClickMode && (currentTime_ns - zrLastClickTime_ns) > RAPID_MODE_TIMEOUT_NS) { - zrInRapidClickMode = false; - } - - if (zrKeyPressed) { - if (!zrKeyWasPressed) { - // ZR key physically pressed for the first time - const u64 timeSinceLastClick = currentTime_ns - zrLastClickTime_ns; - - zrWasIsolated = !notzrKeyPressed; // Remember if it started isolated - - // Track press start time for first clicks (when not in rapid mode) - if (!zrInRapidClickMode) { - zrFirstClickPressStart_ns = currentTime_ns; - } - - // Enter rapid click mode if clicking within window - if (timeSinceLastClick <= RAPID_CLICK_WINDOW_NS) { - zrInRapidClickMode = true; - } - - // Only trigger immediately if in rapid click mode AND was isolated initially - if (zrInRapidClickMode && zrWasIsolated) { - skipDown.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zrLastClickTime_ns = currentTime_ns; - } - } - - // Check for hold behavior - ONLY if in rapid click mode AND was isolated initially - if (zrInRapidClickMode && zrWasIsolated) { - static u64 zrButtonPressStart_ns = 0; - static u64 zrLastHoldTrigger_ns = 0; - static bool zrHoldTriggered = false; - - // Initialize on new press - if (!zrKeyWasPressed) { - zrButtonPressStart_ns = currentTime_ns; - zrLastHoldTrigger_ns = currentTime_ns; - zrHoldTriggered = false; - } - - const u64 holdDuration = currentTime_ns - zrButtonPressStart_ns; - - if (holdDuration >= HOLD_THRESHOLD_NS) { - // Calculate dynamic interval based on hold duration (accelerating) - const float t = (holdDuration >= ACCELERATION_POINT_NS) ? 1.0f : - (float)holdDuration / (float)ACCELERATION_POINT_NS; - const u64 currentInterval = ((1.0f - t) * INITIAL_INTERVAL_NS + t * FAST_INTERVAL_NS); - - const u64 timeSinceLastHoldTrigger = currentTime_ns - zrLastHoldTrigger_ns; - - if (!zrHoldTriggered || timeSinceLastHoldTrigger >= currentInterval) { - // Trigger skip - skipDown.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zrHoldTriggered = true; - zrLastHoldTrigger_ns = currentTime_ns; - zrLastClickTime_ns = currentTime_ns; // Keep rapid mode active - } - } - } - - zrKeyWasPressed = true; - } else { - if (zrKeyWasPressed) { - // ZR key physically released - only trigger if was isolated initially and no other keys held at release - if (!zrInRapidClickMode && zrWasIsolated && !(keysHeld & ~KEY_ZR & ALL_KEYS_MASK)) { - const u64 holdDuration = currentTime_ns - zrFirstClickPressStart_ns; - - // Only trigger if not held too long - if (holdDuration < INITIAL_HOLD_THRESHOLD_NS) { - skipDown.store(true, std::memory_order_release); - currentGui->requestFocus(topElement, FocusDirection::None); - zrLastClickTime_ns = currentTime_ns; - zrInRapidClickMode = true; // Enter rapid mode after first release - } - } - } - zrKeyWasPressed = false; - zrWasIsolated = false; - } - } - } - - //if (keysDown & KEY_ZL) { - // //while (tsl::notification && tsl::notification->isActive()) { - // // tsl::notification->update(true, true); // No file ops, allow state transitions - // // svcSleepThread(10'000'000); // 1ms sleep - // //} - // if (notification) - // notification->forceShutdown(); - //} - - - if (!touchDetected && oldTouchDetected && currentGui && topElement) { - topElement->onTouch(elm::TouchEvent::Release, oldTouchPos.x, oldTouchPos.y, oldTouchPos.x, oldTouchPos.y, initialTouchPos.x, initialTouchPos.y); - } - - // Cache common calculations - // Use consistent edge padding equal to halfGap (matching drawing code) - const float edgePadding = ult::halfGap.load(std::memory_order_acquire) - 5; - const float buttonStartX = edgePadding; - - // Calculate button positions matching the drawing code - const float backLeftEdge = buttonStartX + 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 float nextPageLeftEdge = ult::noClickableItems.load(std::memory_order_acquire) ? 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; - static std::vector lastSimulatedTouch = {false, false, false, false}; - - // Touch region calculations - const bool backTouched = (touchPos.x >= backLeftEdge && touchPos.x < backRightEdge && touchPos.y > footerY) && - (initialTouchPos.x >= backLeftEdge && initialTouchPos.x < backRightEdge && initialTouchPos.y > footerY); - - const bool selectTouched = !ult::noClickableItems.load(std::memory_order_acquire) && - (touchPos.x >= selectLeftEdge && touchPos.x < selectRightEdge && touchPos.y > footerY) && - (initialTouchPos.x >= selectLeftEdge && initialTouchPos.x < selectRightEdge && initialTouchPos.y > footerY); - - const bool nextPageTouched = (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); - - //ult::touchingBack.store(backTouched, std::memory_order_release); - //ult::touchingSelect.store(selectTouched, std::memory_order_release); - //ult::touchingNextPage.store(nextPageTouched, std::memory_order_release); - //ult::touchingMenu.store(menuTouched, std::memory_order_release); - - // Only update and trigger rumble on state changes - bool shouldTriggerRumble = false; - - if (backTouched != ult::touchingBack.exchange(backTouched, std::memory_order_acq_rel)) { - if (backTouched) shouldTriggerRumble = true; - } - - if (selectTouched != ult::touchingSelect.exchange(selectTouched, std::memory_order_acq_rel)) { - if (selectTouched) shouldTriggerRumble = true; - } - - if (nextPageTouched != ult::touchingNextPage.exchange(nextPageTouched, std::memory_order_acq_rel)) { - if (nextPageTouched) shouldTriggerRumble = true; - } - - 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) { - triggerRumbleClick.store(true, std::memory_order_release); - } - - - if (touchDetected) { - // Update lastSimulatedTouch with current touch states - lastSimulatedTouch = { - backTouched, - selectTouched, - nextPageTouched, - menuTouched - }; - - ult::interruptedTouch.store(((keysHeld & ALL_KEYS_MASK) != 0), std::memory_order_release); - - const u32 xDistance = std::abs(static_cast(initialTouchPos.x) - static_cast(touchPos.x)); - const u32 yDistance = std::abs(static_cast(initialTouchPos.y) - static_cast(touchPos.y)); - - const bool isScroll = (xDistance * xDistance + yDistance * yDistance) > 1000; - if (isScroll) { - 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) { - triggerRumbleClick.store(true, std::memory_order_release); - currentGui->removeFocus(); - } - } - touchEvent = elm::TouchEvent::Touch; - } - - if (currentGui && topElement && !interpreterIsRunning) { - topElement->onTouch(touchEvent, touchPos.x, touchPos.y, oldTouchPos.x, oldTouchPos.y, initialTouchPos.x, initialTouchPos.y); - if (touchPos.x > 40U + ult::layerEdge && touchPos.x <= cfg::FramebufferWidth - 30U + ult::layerEdge && - touchPos.y > 73U && touchPos.y <= footerY) { - currentGui->removeFocus(); - } - } - - 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 { - // Process touch release using stored touch states - no need to recalculate boundaries - for (int i = 0; i < 4; ++i) { - if (lastSimulatedTouch[i]) { - if (!ult::interruptedTouch.load(std::memory_order_acquire) && !interpreterIsRunning) { - switch (i) { - case 0: // Back button - ult::simulatedBack.store(true, std::memory_order_release); - break; - case 1: // Select button - ult::simulatedSelect.store(true, std::memory_order_release); - break; - case 2: // Next page button - ult::simulatedNextPage.store(true, std::memory_order_release); - break; - case 3: // Menu button - ult::simulatedMenu.store(true, std::memory_order_release); - break; - } - } else if (interpreterIsRunning) { - switch (i) { - case 0: // Back button when interpreter is running - this->hide(); - break; - case 1: // Select button when interpreter is running - ult::externalAbortCommands.store(true, std::memory_order_release); - break; - // cases 2 and 3 don't have interpreter running logic in original code - } - } - } - } - - // Update lastSimulatedTouch with current touch states - lastSimulatedTouch = { - false, - false, - false, - 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)); - //if (clearGlyphCache) - // tsl::gfx::FontManager::clearCache(); - 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 = true; - - 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) { - //tsl::elm::skipDeconstruction.store(true, std::memory_order_release); - // Pop the specified number of GUIs - for (u32 i = 0; i < actualCount; ++i) { - this->m_guiStack.pop(); - } - //tsl::elm::skipDeconstruction.store(false, std::memory_order_release); - } 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); - - // 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)); - //if (clearGlyphCache) - // tsl::gfx::FontManager::clearCache(); - 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)) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - return; - } - - //tsl::elm::g_disableMenuCacheOnReturn.store(true, std::memory_order_release); - - // 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; - } - - //if (actualCount > 1) - // tsl::elm::skipDeconstruction.store(true, std::memory_order_release); - - // Pop the specified number of GUIs - for (u32 i = 0; i < actualCount && !this->m_guiStack.empty(); ++i) { - this->m_guiStack.pop(); - } - - //tsl::elm::skipDeconstruction.exchange(false, std::memory_order_acq_rel); - - // Close overlay if stack is empty - if (this->m_guiStack.empty()) { - this->close(); - } else { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - } - - } - - void pop(u32 count = 1) { - - if (ult::stillTouching && ult::currentForeground.load(std::memory_order_acquire)) { - triggerRumbleClick.store(true, std::memory_order_release); - triggerWallSound.store(true, std::memory_order_release); - 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) { - //tsl::elm::skipDeconstruction.store(true, std::memory_order_release); - // Pop the specified number of GUIs - for (u32 i = 0; i < actualCount; ++i) { - this->m_guiStack.pop(); - } - //tsl::elm::skipDeconstruction.store(false, std::memory_order_release); - } 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 - * - */ - static void parseOverlaySettings() { - hlp::ini::IniData parsedConfig = hlp::ini::readOverlaySettings(ULTRAHAND_CONFIG_FILE); - - u64 decodedKeys = hlp::comboStringToKeys(parsedConfig[ult::ULTRAHAND_PROJECT_NAME][ult::KEY_COMBO_STR]); // CUSTOM MODIFICATION - if (decodedKeys) - tsl::cfg::launchCombo = decodedKeys; - else { - parsedConfig = hlp::ini::readOverlaySettings(TESLA_CONFIG_FILE); - decodedKeys = hlp::comboStringToKeys(parsedConfig["tesla"][ult::KEY_COMBO_STR]); - if (decodedKeys) - tsl::cfg::launchCombo = decodedKeys; - } - - //#if USING_WIDGET_DIRECTIVE - ult::datetimeFormat = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["datetime_format"]; // read datetime_format - ult::removeQuotes(ult::datetimeFormat); - if (ult::datetimeFormat.empty()) { - ult::datetimeFormat = ult::DEFAULT_DT_FORMAT; - ult::removeQuotes(ult::datetimeFormat); - } - - - std::string tempStr; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["hide_clock"]; - ult::removeQuotes(tempStr); - ult::hideClock = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["hide_battery"]; - ult::removeQuotes(tempStr); - ult::hideBattery = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["hide_pcb_temp"]; - ult::removeQuotes(tempStr); - ult::hidePCBTemp = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["hide_soc_temp"]; - ult::removeQuotes(tempStr); - ult::hideSOCTemp = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["dynamic_widget_colors"]; - ult::removeQuotes(tempStr); - ult::dynamicWidgetColors = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["hide_widget_backdrop"]; - ult::removeQuotes(tempStr); - ult::hideWidgetBackdrop = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["center_widget_alignment"]; - ult::removeQuotes(tempStr); - ult::centerWidgetAlignment = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["extended_widget_backdrop"]; - ult::removeQuotes(tempStr); - ult::extendedWidgetBackdrop = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["dynamic_logo"]; - ult::removeQuotes(tempStr); - ult::useDynamicLogo = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["selection_bg"]; - ult::removeQuotes(tempStr); - ult::useSelectionBG = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["selection_text"]; - ult::removeQuotes(tempStr); - ult::useSelectionText = tempStr != ult::FALSE_STR; - - tempStr = parsedConfig[ult::ULTRAHAND_PROJECT_NAME]["selection_value"]; - ult::removeQuotes(tempStr); - ult::useSelectionValue = tempStr != ult::FALSE_STR; - - //#endif - - } - - /** - * @brief Update and save launch combo keys - * - * @param keys the new combo keys - */ - [[maybe_unused]] static void updateCombo(u64 keys) { - tsl::cfg::launchCombo = keys; - hlp::ini::updateOverlaySettings({ - { ult::TESLA_STR, { // CUSTOM MODIFICATION - { ult::KEY_COMBO_STR , tsl::hlp::keysToComboString(keys) } - }} - }, TESLA_CONFIG_FILE); - hlp::ini::updateOverlaySettings({ - { ult::ULTRAHAND_PROJECT_NAME, { // CUSTOM MODIFICATION - { ult::KEY_COMBO_STR , tsl::hlp::keysToComboString(keys) } - }} - }, ULTRAHAND_CONFIG_FILE); - } - - 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); - - // 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 = {}; - hidsysAcquireCaptureButtonEventHandle(&captureButtonPressEvent, false); - eventClear(&captureButtonPressEvent); - hidsysAcquireCaptureButtonEventHandle(&captureButtonPressEvent, false); - eventClear(&captureButtonPressEvent); - tsl::hlp::ScopeGuard captureButtonEventGuard([&] { eventClose(&captureButtonPressEvent); }); - - // Parse Tesla settings - impl::parseOverlaySettings(); - - - // 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 - PadState pad_p1; - PadState pad_handheld; - 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(); - - //u64 elapsedTime_ns; - - // Notification variables - u64 lastNotifCheck = 0; - std::vector shownFiles; - std::string text; - int fontSize; - int priority; - time_t creationTime; - - - - 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; - 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; - } - - //bool expected = true; - //if (fireNotificationEvent.compare_exchange_strong(expected, false, std::memory_order_acq_rel)) { - // if (ult::launchingOverlay.load(std::memory_order_acquire)) - // return; - // eventFire(&shData->notificationEvent); // wake the loop - //} - - // 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) { - const std::string& notifPath = ult::NOTIFICATIONS_PATH; - - // --- Prune missing files from shownFiles --- - for (auto it = shownFiles.begin(); it != shownFiles.end();) { - const std::string fullPath = notifPath + *it; - if (access(fullPath.c_str(), F_OK) != 0) { - it = shownFiles.erase(it); - } else { - ++it; - } - } - - // Reuse existing variables - track best file as we scan - static std::string bestFilename; - static std::string bestFullPath; - static time_t bestCreationTime; - static int bestPriority; - - bestFilename.clear(); - bestFullPath.clear(); - bestPriority = -1; - bestCreationTime = 0; - bool foundAny = false; - - struct dirent* entry; - - // --- Find the best notification file in one pass --- - while ((entry = readdir(dir)) != nullptr) { - if (entry->d_type != DT_REG) continue; - - const char* fname = entry->d_name; - const size_t filenameLen = strlen(fname); - - // Must end with ".notify" - if (filenameLen <= 7 || strcmp(fname + filenameLen - 7, ".notify") != 0) - continue; - - // Skip if already shown - if (std::find(shownFiles.begin(), shownFiles.end(), fname) != shownFiles.end()) - continue; - - // --- Build path --- - static std::string fullPath; - fullPath = notifPath; - fullPath += fname; - - // --- Get file creation/modification time --- - struct stat fileStat; - creationTime = 0; - if (stat(fullPath.c_str(), &fileStat) == 0) { - creationTime = fileStat.st_mtime; - } - - // --- Read priority from JSON --- - priority = 20; // default (reuse existing variable) - std::unique_ptr root( - ult::readJsonFromFile(fullPath), ult::JsonDeleter()); - if (root) { - cJSON* croot = reinterpret_cast(root.get()); - cJSON* priorityObj = cJSON_GetObjectItemCaseSensitive(croot, "priority"); - if (priorityObj && cJSON_IsNumber(priorityObj)) { - priority = static_cast(priorityObj->valuedouble); - } - } - - // --- Is this better than current best? --- - const bool isBetter = !foundAny || - (priority > bestPriority) || - (priority == bestPriority && creationTime < bestCreationTime); - - if (isBetter) { - bestFilename = fname; - bestFullPath = fullPath; - bestCreationTime = creationTime; - bestPriority = priority; - foundAny = true; - } - } - - closedir(dir); - - // --- Process the best file --- - if (foundAny) { - text = ult::getStringFromJsonFile(bestFullPath, "text"); - if (!text.empty()) { - fontSize = 28; // default (reuse existing variable) - - std::unique_ptr root( - ult::readJsonFromFile(bestFullPath), ult::JsonDeleter()); - if (root) { - cJSON* croot = reinterpret_cast(root.get()); - cJSON* fontSizeObj = cJSON_GetObjectItemCaseSensitive(croot, "font_size"); - if (fontSizeObj && cJSON_IsNumber(fontSizeObj)) { - fontSize = std::clamp(static_cast(fontSizeObj->valuedouble), 1, 34); - } - } - - // --- Show notification safely --- - if (notification) { - notification->show(text, fontSize, bestPriority, bestFilename); - } - - // Mark file as shown - shownFiles.push_back(bestFilename); - } - } - - } else { - // --- Notifications disabled: delete all 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); - } - } - } - } - - - if (ult::useHapticFeedback) { - // Process ongoing rumbles - if (ult::clickActive.load(std::memory_order_acquire)) - ult::processRumbleStop(nowNs); - if (ult::doubleClickActive.load(std::memory_order_acquire)) - ult::processRumbleDoubleClick(nowNs); - } - - if (ult::launchingOverlay.load(std::memory_order_acquire)) - break; - std::scoped_lock lock(shData->dataMutex); - if (ult::launchingOverlay.load(std::memory_order_acquire)) - break; - - // Repoll after lock - nowTick = armGetSystemTick(); - nowNs = armTicksToNs(nowTick); - - // Flush any pending rumble triggers when feedback is off - if (ult::useHapticFeedback) { - if (!triggerInitHaptics.load(std::memory_order_acquire)) - ult::checkAndReinitHaptics(); - else - ult::initHaptics(); - - // Double-click takes priority - if (triggerRumbleDoubleClick.exchange(false, std::memory_order_acq_rel)) { - if (!ult::clickActive.load(std::memory_order_acquire) && !ult::doubleClickActive.load(std::memory_order_acquire)) { - ult::rumbleDoubleClick(); - } - // Clear any pending single click since double-click supersedes it - triggerRumbleClick.exchange(false, std::memory_order_acq_rel); - } - - if (triggerRumbleClick.exchange(false, std::memory_order_acq_rel)) { - // Only start single click if nothing else is active - if (!ult::clickActive.load(std::memory_order_acquire) && !ult::doubleClickActive.load(std::memory_order_acquire)) { - ult::rumbleClick(); - } - //triggerRumbleDoubleClick.exchange(false, std::memory_order_acq_rel); - } - - // Process ongoing rumbles - if (ult::clickActive.load(std::memory_order_acquire)) - ult::processRumbleStop(nowNs); - if (ult::doubleClickActive.load(std::memory_order_acquire)) - ult::processRumbleDoubleClick(nowNs); - } else { - triggerRumbleClick.exchange(false, std::memory_order_acq_rel); - triggerRumbleDoubleClick.exchange(false, std::memory_order_acq_rel); - } - - // Flush any pending sound triggers when effects are off - - if (!ult::limitedMemory) { - if (!ult::useSoundEffects || disableSound.load(std::memory_order_acquire)) { - triggerNavigationSound.exchange(false, std::memory_order_acq_rel); - triggerEnterSound.exchange(false, std::memory_order_acq_rel); - triggerExitSound.exchange(false, std::memory_order_acq_rel); - triggerWallSound.exchange(false, std::memory_order_acq_rel); - triggerOnSound.exchange(false, std::memory_order_acq_rel); - triggerOffSound.exchange(false, std::memory_order_acq_rel); - triggerSettingsSound.exchange(false, std::memory_order_acq_rel); - triggerMoveSound.exchange(false, std::memory_order_acq_rel); - } 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)) { - ult::Audio::playNavigateSound(); - } else if (triggerEnterSound.exchange(false)) { - ult::Audio::playEnterSound(); - } else if (triggerExitSound.exchange(false)) { - ult::Audio::playExitSound(); - } else if (triggerWallSound.exchange(false)) { - ult::Audio::playWallSound(); - } else if (triggerOnSound.exchange(false)) { - ult::Audio::playOnSound(); - } else if (triggerOffSound.exchange(false)) { - ult::Audio::playOffSound(); - } else if (triggerSettingsSound.exchange(false)) { - ult::Audio::playSettingsSound(); - } else if (triggerMoveSound.exchange(false)) { - ult::Audio::playMoveSound(); - } - - //if (clearSoundCacheNow.exchange(false, std::memory_order_acq_rel)) { - // //ult::Audio::unloadAllSounds(ult::Audio::SoundType::Wall); - // ult::Audio::unloadAllSounds({ult::Audio::SoundType::Wall}); - // //ult::Audio::unloadAllSounds(); - // //clearSoundCacheNow.store(false, std::memory_order_release); - // clearSoundCacheNow.notify_all(); - //} - } - } - - //else if (triggerNavigationSound.exchange(false)) { - // ult::Audio::playSlideSound(); - //} - - // 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); - - shData->keysDown = kDown_p1 | kDown_handheld; - shData->keysHeld = kHeld_p1 | kHeld_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); - - if (handheldHasInput) { - shData->joyStickPosLeft = leftStick_handheld; - shData->joyStickPosRight = rightStick_handheld; - } else { - shData->joyStickPosLeft = padGetStickPos(&pad_p1, 0); - shData->joyStickPosRight = padGetStickPos(&pad_p1, 1); - } - - - // Read in touch positions - if (hidGetTouchScreenStates(&shData->touchState, 1) > 0) { // Check if any touch event is present - if (!shData->overlayOpen) { - //ult::internalTouchReleased = false; - ult::internalTouchReleased.store(false, std::memory_order_release); - } - - const HidTouchState& currentTouch = shData->touchState.touches[0]; // Correct type is HidTouchPoint - - - const u64 elapsedTime_ns = armTicksToNs(nowTick - currentTouchTick); - - // Check if the touch is within bounds for left-to-right swipe within the time window - 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); - } - // Check if the touch is within bounds for right-to-left swipe within the time window - 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); - } - } - } - - // Handle touch release state - if (currentTouch.x == 0 && currentTouch.y == 0) { - ult::internalTouchReleased.store(true, std::memory_order_release); - //ult::internalTouchReleased = true; // Indicate that the touch has been released - //ult::internalTouchReleased.store(true, std::memory_order_release); - lastTouchX = 0; - lastTouchY = 0; - } - - // If this is the first touch of a gesture, store lastTouchX - else if ((lastTouchX == 0 && lastTouchY == 0) && (currentTouch.x != 0 || currentTouch.y != 0)) { - currentTouchTick = nowTick; - lastTouchX = currentTouch.x; - lastTouchY = currentTouch.y; - } - - } else { - // Reset touch state if no touch is present - shData->touchState = { 0 }; - //ult::internalTouchReleased = true; - ult::internalTouchReleased.store(true, std::memory_order_release); - //ult::internalTouchReleased.store(true, std::memory_order_release); - - // Reset touch history to invalid state - lastTouchX = 0; - lastTouchY = 0; - - // Reset time tracking - //currentTouchTick = nowTick; - } - - #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(); - //tsl::goBack(); - //triggerExitNow = false; - break; - } - #endif - //if ((shData->keysDown & KEY_ZL && shData->keysHeld & KEY_L) || (shData->keysDown & KEY_L && shData->keysHeld & KEY_ZL)) { - // notification->show("Hello world! ¯\\_(ツ)_/¯"); - // eventFire(&shData->notificationEvent); // wake the loop - //} - - - // 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); - #endif - - if (shData->overlayOpen) { - if (!disableHiding) { - tsl::Overlay::get()->hide(); - shData->overlayOpen = false; - } - } - 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 - { - auto iniData = ult::getParsedDataFromIniFile(ult::ULTRAHAND_CONFIG_INI_PATH); - auto& section = iniData[ult::ULTRAHAND_PROJECT_NAME]; - section[ult::IN_OVERLAY_STR] = ult::TRUE_STR; - section["to_packages"] = ult::TRUE_STR; - ult::saveIniFileData(ult::ULTRAHAND_CONFIG_INI_PATH, iniData); - } - - // Reset navigation state variables (these control slide navigation) - ult::allowSlide.store(false, std::memory_order_release); - ult::unlockedSlide.store(false, std::memory_order_release); - - eventClose(&homeButtonPressEvent); - eventClose(&powerButtonPressEvent); - eventClose(&captureButtonPressEvent); - - //hidExit(); - // Launch the overlay using the same mechanism as key combos - //shData->overlayOpen = false; - ult::launchingOverlay.store(true, std::memory_order_release); - tsl::setNextOverlay(requestedPath, requestedArgs+" --direct"); - tsl::Overlay::get()->close(); - eventFire(&shData->comboEvent); - - launchComboHasTriggered.store(true, std::memory_order_release); - return; - } - } - #endif - // Check overlay key combos (only when overlay is not open, keys are pressed, and not conflicting with main combos) - //else if (!shData->overlayOpen && shData->keysDown != 0) { - 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; - } - //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 - ); - - //shData->overlayOpen = false; - //hidExit(); - - eventClose(&homeButtonPressEvent); - eventClose(&powerButtonPressEvent); - eventClose(&captureButtonPressEvent); - - ult::launchingOverlay.store(true, std::memory_order_release); - tsl::setNextOverlay(ult::OVERLAY_PATH + "ovlmenu.ovl", "--direct --comboReturn"); - tsl::Overlay::get()->close(); - eventFire(&shData->comboEvent); - launchComboHasTriggered.store(true, std::memory_order_release); - 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 - auto overlaysIniData = ult::getParsedDataFromIniFile(ult::OVERLAYS_INI_FILEPATH); - std::string useArgs = ""; - std::string launchArgs = ""; - - auto sectionIt = overlaysIniData.find(overlayFileName); - if (sectionIt != overlaysIniData.end()) { - auto useArgsIt = sectionIt->second.find(ult::USE_LAUNCH_ARGS_STR); - if (useArgsIt != sectionIt->second.end()) { - useArgs = useArgsIt->second; - } - - auto argsIt = sectionIt->second.find(ult::LAUNCH_ARGS_STR); - if (argsIt != sectionIt->second.end()) { - launchArgs = argsIt->second; - } - } - - 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 - ); - } - - //shData->overlayOpen = false; - //hidExit(); - eventClose(&homeButtonPressEvent); - eventClose(&powerButtonPressEvent); - eventClose(&captureButtonPressEvent); - - ult::launchingOverlay.store(true, std::memory_order_release); - tsl::setNextOverlay(overlayPath, finalArgs); - tsl::Overlay::get()->close(); - eventFire(&shData->comboEvent); - launchComboHasTriggered.store(true, std::memory_order_release); - 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); - - // 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); - break; - - - case WaiterObject_CaptureButton: - if (screenshotsAreDisabled) { - eventClear(&captureButtonPressEvent); - break; - } - - #if IS_STATUS_MONITOR_DIRECTIVE - 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) { - isRendering = true; - leventClear(&renderingStopEvent); - delayUpdate = false; - } - #endif - - break; - } - } else if (rc != KERNELRESULT(TimedOut)) { - ASSERT_FATAL(rc); - } - } - //hidExit(); - - eventClose(&homeButtonPressEvent); - eventClose(&powerButtonPressEvent); - eventClose(&captureButtonPressEvent); - - } - } - - /** - * @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 - */ - void goBack(u32 count) { - Overlay::get()->goBack(count); - } - - void pop(u32 count) { - Overlay::get()->pop(count); - } - - - static inline std::mutex setNextOverlayMutex; - - static inline std::string nextOverlayName; - static void setNextOverlay(const std::string& ovlPath, std::string origArgs) { - std::lock_guard lk(setNextOverlayMutex); - char buffer[512]; - char* p = buffer; - char* bufferEnd = buffer + sizeof(buffer) - 1; // Leave room for null terminator - - // Store filename and copy it - 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++ = ' '; - - // Single-pass argument filtering - const char* src = origArgs.c_str(); - const char* end = src + origArgs.length(); - bool hasSkipCombo = false; - - while (src < end && p < bufferEnd) { - // Skip whitespace - while (src < end && *src == ' ' && p < bufferEnd) { - *p++ = *src++; - } - - if (src >= end || p >= bufferEnd) break; - - // Check for flags to filter/detect - if (src[0] == '-' && src[1] == '-') { - - // Check what flag this is - if (strncmp(src, "--skipCombo", 11) == 0 && (src[11] == ' ' || src[11] == '\0')) { - hasSkipCombo = true; - // Copy this flag - while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; - } - else if (strncmp(src, "--foregroundFix", 15) == 0) { - // Skip this flag and its value - src += 15; - while (src < end && *src == ' ') src++; // Skip spaces - if (src < end && (*src == '0' || *src == '1')) src++; // Skip value - } - else if (strncmp(src, "--lastTitleID", 13) == 0) { - // Skip this flag and its value - src += 13; - while (src < end && *src == ' ') src++; // Skip spaces - while (src < end && *src != ' ' && *src != '\0') src++; // Skip title ID - } - else { - // Copy unknown flag - while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; - } - } - else { - // Copy regular argument - while (src < end && *src != ' ' && p < bufferEnd) *p++ = *src++; - } - } - - // Add required flags with bounds checking - if (!hasSkipCombo && (p + 12) < bufferEnd) { - memcpy(p, " --skipCombo", 12); - p += 12; - } - - // Add foreground flag with bounds checking - 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'; - } - } - - // Add last title ID with bounds checking - if ((p + 15 + ult::lastTitleID.length()) < bufferEnd) { - memcpy(p, " --lastTitleID ", 15); - p += 15; - const char* titleId = ult::lastTitleID.c_str(); - while (*titleId && p < bufferEnd) *p++ = *titleId++; - } - - // Safety check - if we're at the end, we might have truncated - if (p >= bufferEnd) { - p = bufferEnd; - } - - *p = '\0'; - - //isLaunchingNextOverlay.store(true, std::memory_order_release); - 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) { - //g_overlayFilename = ult::getNameFromPath(argv[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; - //g_overlayFilename = ""; - 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); - - Thread backgroundThread; - threadCreate(&backgroundThread, impl::backgroundEventPoller, &shData, nullptr, 0x2000, 0x2c, -2); - threadStart(&backgroundThread); - - eventCreate(&shData.comboEvent, false); - - #if !IS_LAUNCHER_DIRECTIVE - tsl::initializeUltrahandSettings(); - #endif - - - 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 - - auto& overlay = tsl::Overlay::s_overlayInstance; - overlay = new TOverlay(); - overlay->m_closeOnExit = (u8(launchFlags) & u8(impl::LaunchFlags::CloseOnExit)) == u8(impl::LaunchFlags::CloseOnExit); - - tsl::hlp::doWithSmSession([&overlay]{ - overlay->initServices(); - }); - - overlay->initScreen(); - 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; - - while (shData.running.load(std::memory_order_acquire)) { - // Early exit if launching new overlay - if (ult::launchingOverlay.load(std::memory_order_acquire)) { - //std::scoped_lock lock(shData.dataMutex); - shData.running.store(false, std::memory_order_release); - shData.overlayOpen.store(false, std::memory_order_release); - break; - } - - // Wait for events only if no active notification - if (!(notification && notification->isActive())) { - svcWaitSynchronization(&index, handles, 2, UINT64_MAX); - //eventClear(¬ificationEvent); - //eventClear(&shData.comboEvent); - } - eventClear(¬ificationEvent); - eventClear(&shData.comboEvent); - - if ((notification && notification->isActive() && !firstLoop) || index == 1) { - comboBreakout = false; - - while (shData.running.load(std::memory_order_acquire)) { - { - //std::scoped_lock lock(shData.dataMutex); - 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(true); // Draw prompts while hidden - } - - 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)) { - { - //std::scoped_lock lock(shData.dataMutex); - if (!ult::launchingOverlay.load(std::memory_order_acquire)) { - overlay->clearScreen(); - } - } - if (exitAfterPrompt) { - std::scoped_lock lock(shData.dataMutex); - exitAfterPrompt = false; - shData.running.store(false, std::memory_order_release); - shData.overlayOpen.store(false, std::memory_order_release); - 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; - } - } - - { - //std::scoped_lock lock(shData.dataMutex); - 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; - } - 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) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - //} else { - // triggerRumbleClick.store(true, std::memory_order_release); - } - } - #else - if (!directMode && shouldFireEvent) { - shouldFireEvent = false; - #if IS_STATUS_MONITOR_DIRECTIVE - if (lastMode.compare("returning") == 0) { - //triggerRumbleDoubleClick.store(true, std::memory_order_release); - //triggerExitSound.store(true, std::memory_order_release); - triggerExitFeedback(); - } else { - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerEnterSound.store(true, std::memory_order_release); - triggerEnterFeedback(); - } - #else - //triggerRumbleClick.store(true, std::memory_order_release); - //triggerEnterSound.store(true, std::memory_order_release); - triggerEnterFeedback(); - #endif - } - #endif - } - - #if IS_STATUS_MONITOR_DIRECTIVE - if (pendingExit && wasRendering) { - pendingExit = false; - wasRendering = false; - isRendering = true; - leventClear(&renderingStopEvent); - } - #endif - - if (overlay->shouldHide()) { - if (overlay->shouldCloseAfter()) { - if (!directMode) { - //std::scoped_lock lock(shData.dataMutex); - 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()) { - //std::scoped_lock lock(shData.dataMutex); - 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)) { - //std::scoped_lock lock(shData.dataMutex); - 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); - //launchComboHasTriggered.store(false, std::memory_order_acquire); - eventClear(&shData.comboEvent); - } - } - - // Ensure background thread is fully stopped before overlay cleanup - shData.running.store(false, std::memory_order_release); - threadWaitForExit(&backgroundThread); - threadClose(&backgroundThread); - - - // Cleanup overlay resources - //tsl::elm::fullDeconstruction.store(true, std::memory_order_release); - 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(); - } - } - - - // Brief delay to ensure thread quiescence before nx-ovlloader transition - //svcSleepThread(100'000'000); // 100ms - - 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 - - //tsl::hlp::doWithSmSession([]{ - - 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(); - //i2cInitialize(); - //ASSERT_FATAL(socketInitializeDefault()); - //ASSERT_FATAL(nifmInitialize(NifmServiceType_User)); - - //}); - - //requiresLNY2 = amsVersionAtLeast(1,9,0); // Detect if using HOS 21+ - //ult::currentHeapSize = ult::getCurrentHeapSize(); - //ult::expandedMemory = ult::currentHeapSize >= ult::OverlayHeapSize::Size_8MB; - - #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(); - //tsl::notification = nullptr; - } - - /** - * @brief libtesla service exiting function to override libnx's - * - */ - void __appExit(void) { - delete tsl::notification; - eventClose(&tsl::notificationEvent); - - //deinitHaptics(); - if (!ult::limitedMemory) - ult::Audio::exit(); - - - //socketExit(); - //nifmExit(); - spsmExit(); - splExit(); - fsdevUnmountAll(); - - #if USING_WIDGET_DIRECTIVE - i2cExit(); - ult::powerExit(); // CUSTOM MODIFICATION - #endif - - fsExit(); - hidExit(); - plExit(); - pmdmntExit(); - hidsysExit(); - setsysExit(); - smExit(); - - // Final cleanup - tsl::gfx::FontManager::cleanup(); - } - -} - -#endif diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE deleted file mode 100644 index d159169d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE +++ /dev/null @@ -1,339 +0,0 @@ - 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/sys-clk/overlay/lib/libultrahand/libultra/README.md b/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md deleted file mode 100644 index 9966139d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md +++ /dev/null @@ -1,69 +0,0 @@ -# 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/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE deleted file mode 100644 index 2f244ac8..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE +++ /dev/null @@ -1,395 +0,0 @@ -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/sys-clk/overlay/lib/libultrahand/libultra/include/audio.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/audio.hpp deleted file mode 100644 index ee9eddb9..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/audio.hpp +++ /dev/null @@ -1,97 +0,0 @@ -/******************************************************************************** - * 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 ppkantorski - ********************************************************************************/ - -#pragma once -#include -#include -#include -#include -#include -#include -#include -#include "tsl_utils.hpp" - -namespace ult { - class Audio { - public: - enum class SoundType : uint8_t { // <- uint8_t saves space - Navigate, - Enter, - Exit, - Wall, - On, - Off, - Settings, - Move, - Count - }; - - struct CachedSound { - void* buffer = nullptr; - uint32_t bufferSize = 0; - uint32_t dataSize = 0; - }; - - static bool initialize(); - static void exit(); - static void playSound(SoundType type); - - // Inline wrappers - same API, zero overhead - 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 void setMasterVolume(float volume); - static void setEnabled(bool enabled); - static bool isEnabled(); - //static bool isDocked(); - static bool reloadIfDockedChanged(); - static void reloadAllSounds(); - static void unloadAllSounds(const std::initializer_list& excludeSounds = {}); - static std::mutex m_audioMutex; - - private: - static bool m_initialized; - static std::atomic m_enabled; // <- atomic for lock-free reads - static float m_masterVolume; - static std::vector m_cachedSounds; - - static bool m_lastDockedState; - - 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" - }; - - //static void playAudioBuffer(void* buffer, uint32_t bufferSize); - static bool loadSoundFromWav(SoundType type, const char* path); - - }; -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp deleted file mode 100644 index 3eecbb01..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp +++ /dev/null @@ -1,53 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once -#ifndef DEBUG_FUNCS_HPP -#define DEBUG_FUNCS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif -#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 -} - -#endif // DEBUG_FUNCS_HPP diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp deleted file mode 100644 index f505037d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp +++ /dev/null @@ -1,83 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once -#ifndef DOWNLOAD_FUNCS_HPP -#define DOWNLOAD_FUNCS_HPP - -#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; - - // Path to the CA certificate - //extern const std::string cacertPath; - //extern const std::string cacertURL; - - // Thread-safe atomic flags for operation control - extern std::atomic abortDownload; - extern std::atomic abortUnzip; - extern std::atomic downloadPercentage; - extern std::atomic unzipPercentage; - - - // Thread-safe callback functions - //#if !USING_FSTREAM_DIRECTIVE - //size_t writeCallback(void* ptr, size_t size, size_t nmemb, FILE* stream); - //#else - //size_t writeCallback(void* ptr, size_t size, size_t nmemb, std::ostream* stream); - //#endif - - //int progressCallback(void* ptr, curl_off_t totalToDownload, curl_off_t nowDownloaded, curl_off_t totalToUpload, curl_off_t nowUploaded); - - - // Thread-safe initialization and cleanup functions - //void initializeCurl(); - //void cleanupCurl(); - - // Main API functions - thread-safe and optimized - bool downloadFile(const std::string& url, const std::string& toDestination, bool noPercentagePolling=false); - bool unzipFile(const std::string& zipFilePath, const std::string& extractTo); -} - -#endif // DOWNLOAD_FUNCS_HPP \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp deleted file mode 100644 index a2e05861..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp +++ /dev/null @@ -1,160 +0,0 @@ -/******************************************************************************** - * 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-2025 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 Reads the contents of a file and returns it as a string, normalizing line endings. - * - * @param filePath The path to the file to be read. - * @return The content of the file as a string with line endings normalized to '\n'. - */ - //std::string getFileContents(const std::string& filePath); - - - /** - * @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); - - // Cache to store directory status - // Assuming a very simple cache implementation - //extern std::vector> directoryCache; - - bool isDirectory(struct dirent* entry, const std::string& path); - - /** - * @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); - - // Helper function to check if a path is a directory - //bool isDirectoryCached(const struct dirent* entry, const std::string& fullPath) { - // struct stat st; - // if (stat(fullPath.c_str(), &st) != 0) return false; - // return S_ISDIR(st.st_mode); - //} - - - - 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/sys-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp deleted file mode 100644 index 2c1b3ad3..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp +++ /dev/null @@ -1,182 +0,0 @@ -/******************************************************************************** - * 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-2025 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 SOUNDS_PATH; - extern const std::string FLAGS_PATH; - extern const std::string NOTIFICATIONS_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; - - - //#if IS_LAUNCHER_DIRECTIVE - 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 EXPANSION_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::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 NX_OVLLOADER_ZIP_URL; - //extern const std::string NX_OVLLOADER_PLUS_ZIP_URL; - extern const std::string OLD_NX_OVLLOADER_ZIP_URL; - //extern const std::string OLD_NX_OVLLOADER_PLUS_ZIP_URL; - extern const std::string UPDATER_PAYLOAD_URL; - //extern const std::string SOUND_EFFECTS_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; - - //#endif - - 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 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 TOGGLE_STR; - extern const std::string LEFT_STR; - extern const std::string RIGHT_STR; - extern const std::string CENTER_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::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/sys-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp deleted file mode 100644 index 5cb2ab9f..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/haptics.hpp +++ /dev/null @@ -1,41 +0,0 @@ -/******************************************************************************** - * 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 ppkantorski - ********************************************************************************/ - -#pragma once -#include -#include -#include - -namespace ult { - - //extern bool rumbleInitialized; - 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/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp deleted file mode 100644 index aab69461..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp +++ /dev/null @@ -1,214 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once - -#ifndef HEX_FUNCS_HPP -#define HEX_FUNCS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif - -#include -#include -#include -#include -//#include // Added for FILE and fopen -#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. - */ - - - // Function to convert ASCII string to Hex 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); -} - -#endif diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp deleted file mode 100644 index ca68ae65..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp +++ /dev/null @@ -1,374 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once - -#ifndef INI_FUNCS_HPP -#define INI_FUNCS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -//#include "nx_fstream.hpp" -#endif - -#include // For std::string, strlen(), etc. -#include // For std::string -#include // For std::vector -#include // For std::map -//#include // For std::istringstream -#include // For std::remove_if -//#include // For ::isspace - -#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); - - - //void saveIniFileData(const std::string& filePath, const std::map>& data) { - // std::ofstream file(filePath); - // if (!file.is_open()) { - // // Handle error: could not open file - // return; - // } - // - // for (const auto& section : data) { - // file << "[" << section.first << "]\n"; - // for (const auto& kv : section.second) { - // file << kv.first << "=" << kv.second << "\n"; - // } - // file << "\n"; // Separate sections with a newline - // } - // - // file.close(); - //} - - - 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); - -} - -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp deleted file mode 100644 index e0848e93..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp +++ /dev/null @@ -1,108 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once -#ifndef JSON_FUNCS_HPP -#define JSON_FUNCS_HPP -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif -#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); -} -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp deleted file mode 100644 index ce5a6131..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp +++ /dev/null @@ -1,110 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - - -#pragma once - -#ifndef LIST_FUNCS_HPP -#define LIST_FUNCS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif - -#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); - - - // Helper function to read a text file and process each line with a callback - //void processFileLines(const std::string& filePath, const std::function& callback); - - - void compareWildcardFilesLists(const std::string& wildcardPatternFilePath, const std::string& txtFilePath, const std::string& outputTxtFilePath); -} - -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp deleted file mode 100644 index fc60aaf3..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp +++ /dev/null @@ -1,121 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once - -#ifndef MOD_FUNCS_HPP -#define MOD_FUNCS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif - -//#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"; - - //const std::string CHEAT_HEADER = "// auto generated by pchtxt2cheat\n\n"; - //extern const std::string CHEAT_TYPE; - //extern const std::string CHEAT_EXT; - //extern const std::string CHEAT_ENCODING; - - /** - * @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 - //uint32_t toBigEndian(uint32_t value); - // - //uint16_t toBigEndian(uint16_t value); - - // 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); - } - - // Helper function to convert a vector of bytes to a hex string for logging - - //std::string hexToString(const std::vector& bytes); - - - /** - * @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); -} - -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp deleted file mode 100644 index e350fe29..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp +++ /dev/null @@ -1,288 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once - -#ifndef PATH_FUNCS_HPP -#define PATH_FUNCS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif - -#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. - * Uses FILE* if !USING_FSTREAM_DIRECTIVE is defined, otherwise uses std::ofstream. - * - * @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); -} - -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp deleted file mode 100644 index 1eb86a6f..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp +++ /dev/null @@ -1,274 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#pragma once - -#ifndef STRING_FUNCS_HPP -#define STRING_FUNCS_HPP - -#include -#include -#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); - - //extern bool canConvertToInt(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); - - - /** - * @brief Replaces multiple consecutive slashes with a single slash in a string. - * - * This function replaces sequences of two or more consecutive slashes with a single slash in the input string. - * - * @param input The input string to process. - * @return The string with multiple slashes replaced. - */ - //std::string replaceMultipleSlashes(const std::string& input); - - - 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 -} - -#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp deleted file mode 100644 index ff3084d6..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp +++ /dev/null @@ -1,813 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - - -#pragma once -#ifndef TSL_UTILS_HPP -#define TSL_UTILS_HPP - -#if !USING_FSTREAM_DIRECTIVE // For not using fstream (needs implementing) -#include -#else -#include -#endif - -#include -#include -#include - -#include -#include -//#include - -#include -#include -#include -#include -#include -#include -#include -#include -//#include -#include -#include -#include -#include - -//#ifndef APPROXIMATE_cos -//// Approximation for cos(x) using Taylor series around 0 -//#define APPROXIMATE_cos(x) (1 - (x) * (x) / 2 + (x) * (x) * (x) * (x) / 24) // valid for small x -//#endif -// -// -//#ifndef APPROXIMATE_ifloor -//#define APPROXIMATE_ifloor(x) ((int)((x) >= 0 ? (x) : (x) - 1)) // truncate toward negative infinity -//#define APPROXIMATE_iceil(x) ((int)((x) == (int)(x) ? (x) : ((x) > 0 ? (int)(x) + 1 : (int)(x)))) // truncate toward positive infinity -//#endif -// -//#ifndef APPROXIMATE_sqrt -//// Fast approximation for sqrt using Newton's method -//#define APPROXIMATE_sqrt(x) ((x) <= 0 ? 0 : (x) / 2.0 * (3.0 - ((x) * (x) * 0.5))) // Approximation for x close to 1 -//#define APPROXIMATE_pow(x, y) ((y) == 0 ? 1 : ((y) == 1 ? (x) : APPROXIMATE_sqrt(x))) // limited to approximate sqrt if y=0.5 -//#endif -// -//#ifndef APPROXIMATE_fmod -//#define APPROXIMATE_fmod(x, y) ((x) - ((int)((x) / (y)) * (y))) // equivalent to x - floor(x/y) * y -//#endif -// -//#ifndef APPROXIMATE_cos -//// Approximation for cos(x) using Taylor series around 0 -//#define APPROXIMATE_cos(x) (1 - (x) * (x) / 2 + (x) * (x) * (x) * (x) / 24) // valid for small x -//#endif -// -//#ifndef APPROXIMATE_acos -//#define APPROXIMATE_acos(x) (1.5708 - (x) - (x)*(x)*(x) / 6) // limited approximation for acos in range [-1, 1] -//#endif -// -//#ifndef APPROXIMATE_fabs -//#define APPROXIMATE_fabs(x) ((x) < 0 ? -(x) : (x)) -//#endif - -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 { - // math funcs - inline double cos(double x) { - static constexpr double PI = 3.14159265358979323846; - static constexpr double TWO_PI = 6.28318530717958647692; - static constexpr double HALF_PI = 1.57079632679489661923; - - // Fast normalization using multiply instead of divide when possible - x = x - TWO_PI * static_cast(x * 0.159154943091895); // 1/(2π) - if (x < 0) x += TWO_PI; - - // Use symmetry to reduce range - int sign = 1; - if (x > PI) { - x -= PI; - sign = -1; - } - if (x > HALF_PI) { - x = PI - x; - sign = -sign; - } - - // Horner's method for faster polynomial evaluation (fewer operations) - // 5-term minimax polynomial for [0, π/2] - accurate to ~10^-8 - const double x2 = x * x; - return sign * (1.0 + x2 * (-0.5 + x2 * (0.04166666666666666 + x2 * (-0.001388888888888889 + x2 * (0.0000248015873015873 - x2 * 0.0000002755731922398589))))); - } - - - - 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; - //extern std::mutex simulatedNextPageMutex; - - //void loadOverlayKeyCombos(); - //std::string getOverlayForKeyCombo(u64 keys); - - 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); - - 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 useSoundEffects; - extern bool useHapticFeedback; - extern bool usePageSwap; - extern std::atomic noClickableItems; - - extern bool useDynamicLogo; - extern bool useSelectionBG; - extern bool useSelectionText; - extern bool useSelectionValue; - - - - // Define the duration boundaries (for smooth scrolling) - //extern const std::chrono::milliseconds initialInterval; // Example initial interval - //extern const std::chrono::milliseconds shortInterval; // Short interval after long hold - //extern const std::chrono::milliseconds transitionPoint; // Point at which the shortest interval is reached - - - - //constexpr std::chrono::milliseconds initialInterval = std::chrono::milliseconds(67); // Example initial interval - //constexpr std::chrono::milliseconds shortInterval = std::chrono::milliseconds(10); // Short interval after long hold - //constexpr std::chrono::milliseconds transitionPoint = std::chrono::milliseconds(2000); // Point at which the shortest interval is reached - - // Function to interpolate between two durations - //std::chrono::milliseconds interpolateDuration(std::chrono::milliseconds start, std::chrono::milliseconds end, float t); - -#if IS_LAUNCHER_DIRECTIVE - extern std::atomic overlayLaunchRequested; - extern std::string requestedOverlayPath; - extern std::string requestedOverlayArgs; - extern std::mutex overlayLaunchMutex; -#endif - - - //#include // Comment out filesystem - - // CUSTOM SECTION START - //extern float backWidth, selectWidth, nextPageWidth; - 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 bool firstBoot; // for detecting first boot - - //static std::unordered_map hexSumCache; - - // 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; - - //bool progressAnimation = false; - extern bool disableTransparency; - //bool useCustomWallpaper = false; - //extern bool useMemoryExpansion; - 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 std::array KEYS_INFO; - - std::unordered_map createButtonCharMap(); - - 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_ITEMS; - extern std::string MENU_SETTINGS; - extern std::string USER_GUIDE; - 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 VERSION_LABELS; - 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 UPDATE_LANGUAGES; - 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 NOTICE; - //extern std::string UTILIZES; - - 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 MEMORY_EXPANSION; - //extern std::string REBOOT_REQUIRED; - extern std::string LOCAL_IP; - extern std::string WALLPAPER; - extern std::string THEME; - 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 SOUND_EFFECTS; - 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 USERGUIDE_OFFSET; - 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 NEW_UPDATE_IS_AVAILABLE; - //extern std::string REBOOT_IS_REQUIRED; - //extern std::string HOLD_A_TO_DELETE; - - 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 PACKAGE_VERSIONS; - //extern std::string PROGRESS_ANIMATION; - - 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 DEFAULT_CHAR_WIDTH; - 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; - - //extern std::string EMPTY; - - #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 - - #if IS_LAUNCHER_DIRECTIVE - // Constant string definitions (English) - void reinitializeLangVars(); - #endif - - - // Define the updateIfNotEmpty function - void updateIfNotEmpty(std::string& constant, const char* jsonKey, const json_t* jsonData); - - 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); - - - - //// Map of character widths (pre-calibrated) - //extern std::unordered_map characterWidths; - - //extern float defaultNumericCharWidth; - - - - // Predefined hexMap - //extern const std::array 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; - }(); - - - // Prepare a map of default settings - extern std::map defaultThemeSettingsMap; - - bool isNumericCharacter(char c); - - bool isValidHexColor(const std::string& hexColor); - - - - //float calculateAmplitude(float x, float peakDurationFactor = 0.25f); - - - 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 - void loadWallpaperFile(const std::string& filePath, s32 width = 448, s32 height = 720); - void loadWallpaperFileWhenSafe(); - - void reloadWallpaper(); - - // Global variables for FPS calculation - //extern double lastTimeCount; - //extern int frameCount; - //extern float fps; - //extern double elapsedTime; - - - 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 bool simulatedBackComplete; - extern std::atomic simulatedSelect; - //extern bool simulatedSelectComplete; - extern std::atomic simulatedNextPage; - //extern std::atomic simulatedNextPageComplete; - extern std::atomic simulatedMenu; - //extern bool simulatedMenuComplete; - 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; - - // Define variables to store previous battery charge and time - //extern uint32_t prevBatteryCharge; - //extern s64 timeOut; - - - extern std::atomic batteryCharge; - extern std::atomic isCharging; - - //constexpr std::chrono::seconds min_delay = std::chrono::seconds(3); // Minimum delay between checks - - 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 - //static std::string hideClock, hideBattery, hidePCBTemp, hideSOCTemp; - 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 - static struct { - bool initialized = false; - OverlayHeapSize cachedSize = OverlayHeapSize::Size_6MB; - u64 customSizeMB = 0; // NEW: store custom size in MB - } 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; - - - - static std::barrier inPlotBarrier(numThreads, [](){ - inPlot.store(false, std::memory_order_release); - }); - - - //extern std::atomic barrierCounter; - //extern std::mutex barrierMutex; - //extern std::condition_variable barrierCV; - // - //extern void barrierWait(); - - - void initializeThemeVars(); - - void initializeUltrahandSettings(); - - -} - -#endif diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp deleted file mode 100644 index c761c589..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp +++ /dev/null @@ -1,49 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ -#pragma once - -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-function" - -#ifndef ULTRA_HPP -#define ULTRA_HPP - -// 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" - -#endif // ULTRA_HPP \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/audio.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/audio.cpp deleted file mode 100644 index aaf30159..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/audio.cpp +++ /dev/null @@ -1,312 +0,0 @@ -/******************************************************************************** - * File: audio.cpp - * Author: ppkantorski - * Description: - * Memory-optimized version with reduced allocation overhead and chunked I/O. - * Key changes: - * - Eliminated temporary vector allocations (saves 50% memory during load) - * - Chunked file reading to reduce peak memory usage - * - Reduced alignment padding (saves ~3-4KB per sound) - * - Added lazy loading option via unloadAllSounds() - * - * 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 ppkantorski - ********************************************************************************/ - -#include "audio.hpp" - -namespace ult { - bool Audio::m_initialized = false; - std::atomic Audio::m_enabled{true}; - float Audio::m_masterVolume = 0.6f; - bool Audio::m_lastDockedState = false; - std::vector Audio::m_cachedSounds; - std::mutex Audio::m_audioMutex; - - 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; - } - - void Audio::exit() { - std::lock_guard lock(m_audioMutex); - - // Free all cached sound buffers - for (auto& cached : m_cachedSounds) { - if (cached.buffer) { - free(cached.buffer); - cached.buffer = nullptr; - } - cached.bufferSize = 0; - cached.dataSize = 0; - } - - if (m_initialized) { - audoutStopAudioOut(); - audoutExit(); - m_initialized = false; - } - } - - void Audio::reloadAllSounds() { - for (uint32_t i = 0; i < static_cast(SoundType::Count); ++i) { - loadSoundFromWav(static_cast(i), m_soundPaths[i]); - } - } - - 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) { - SoundType current = static_cast(i); - - // Skip if this sound is in the exclude list - if (std::find(excludeSounds.begin(), excludeSounds.end(), current) != excludeSounds.end()) { - continue; - } - - auto& cached = m_cachedSounds[i]; - if (cached.buffer) { - free(cached.buffer); - cached.buffer = nullptr; - } - cached.bufferSize = 0; - cached.dataSize = 0; - } - } - - 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; - reloadAllSounds(); - - return true; - } - - 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; - - // Free existing buffer - free(m_cachedSounds[idx].buffer); - m_cachedSounds[idx] = { nullptr, 0, 0 }; - - FILE* f = fopen(path, "rb"); - if (!f) return false; - - // Parse WAV 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; - - // Find fmt and data chunks - while (fread(hdr, 1, 8, f) == 8) { - const u32 sz = *(u32*)(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); - fread(&bits, 2, 1, f); - fseek(f, sz - 16, SEEK_CUR); - } else if (!memcmp(hdr, "data", 4)) { - dSize = sz; - dPos = ftell(f); - break; - } else { - fseek(f, sz, SEEK_CUR); - } - } - - // Validate format - if (!dSize || fmt != 1 || ch == 0 || ch > 2 || (bits != 8 && bits != 16)) { - fclose(f); - return false; - } - - // Calculate buffer sizes - // Note: audout REQUIRES stereo (2 channels), so we must duplicate mono - const bool mono = (ch == 1); - const uint32_t inSamples = dSize / (bits / 8); - const uint32_t outSamples = mono ? inSamples * 2 : inSamples; // Duplicate mono to stereo - const uint32_t outSize = outSamples * 2; // 16-bit samples - - // Use smaller alignment to reduce waste (256 bytes instead of 4KB) - const uint32_t align = 0x100; - const uint32_t bufSize = (outSize + align - 1) & ~(align - 1); - - // Allocate output buffer - void* buf = aligned_alloc(align, bufSize); - if (!buf) { - fclose(f); - return false; - } - - fseek(f, dPos, SEEK_SET); - s16* out = (s16*)buf; - - // Calculate volume scaling - float effectiveVolume = m_masterVolume; - if (m_lastDockedState) { - effectiveVolume *= 0.5f; - } - const float scale = std::clamp(effectiveVolume, 0.0f, 1.0f); - - // Process audio in chunks to minimize memory usage - // This eliminates the need for temporary vectors - constexpr uint32_t CHUNK_SIZE = 512; - - if (bits == 8) { - // 8-bit audio: read and convert in chunks - const int32_t scaleInt = static_cast(scale * 256.0f); - u8 chunk[CHUNK_SIZE]; - uint32_t remaining = inSamples; - uint32_t outIdx = 0; - - while (remaining > 0) { - const uint32_t toRead = std::min(remaining, CHUNK_SIZE); - if (fread(chunk, 1, toRead, f) != toRead) { - free(buf); - fclose(f); - return false; - } - - for (uint32_t i = 0; i < toRead; ++i) { - const s16 sample = static_cast((chunk[i] - 128) * scaleInt); - if (mono) { - // Duplicate to both L and R channels for stereo output - out[outIdx++] = sample; // Left - out[outIdx++] = sample; // Right - } else { - out[outIdx++] = sample; - } - } - remaining -= toRead; - } - } else { - // 16-bit audio: read and convert in chunks - s16 chunk[CHUNK_SIZE]; - uint32_t remaining = inSamples; - uint32_t outIdx = 0; - - while (remaining > 0) { - const uint32_t toRead = std::min(remaining, CHUNK_SIZE); - if (fread(chunk, sizeof(s16), toRead, f) != toRead) { - free(buf); - fclose(f); - return false; - } - - for (uint32_t i = 0; i < toRead; ++i) { - const s16 sample = static_cast(chunk[i] * scale); - if (mono) { - // Duplicate to both L and R channels for stereo output - out[outIdx++] = sample; // Left - out[outIdx++] = sample; // Right - } else { - out[outIdx++] = sample; - } - } - remaining -= toRead; - } - } - - fclose(f); - - // Zero-fill any padding - if (outSize < bufSize) { - memset((u8*)buf + outSize, 0, bufSize - outSize); - } - - m_cachedSounds[idx] = { buf, bufSize, outSize }; - return true; - } - - void Audio::playSound(SoundType type) { - // Lock-free check - SAFE with atomic - 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); - - // Check again under lock - if (!m_initialized) return; - - auto& cached = m_cachedSounds[idx]; - if (!cached.buffer) return; - - // Release any finished buffers - AudioOutBuffer* releasedBuffers = nullptr; - u32 releasedCount = 0; - audoutGetReleasedAudioOutBuffer(&releasedBuffers, &releasedCount); - - // Static buffer is safe with mutex protection - static AudioOutBuffer audioBuffer = {}; - audioBuffer = {}; - audioBuffer.buffer = cached.buffer; - audioBuffer.buffer_size = cached.bufferSize; - audioBuffer.data_size = cached.dataSize; - audioBuffer.data_offset = 0; - audioBuffer.next = nullptr; - - AudioOutBuffer* rel = nullptr; - audoutPlayBuffer(&audioBuffer, &rel); - } - - void Audio::setMasterVolume(float v) { - std::lock_guard lock(m_audioMutex); - m_masterVolume = std::clamp(v, 0.0f, 1.0f); - } - - void Audio::setEnabled(bool e) { - m_enabled.store(e, std::memory_order_relaxed); - } - - bool Audio::isEnabled() { - return m_enabled.load(std::memory_order_relaxed); - } - - //bool Audio::isDocked() { - // Result rc = apmInitialize(); - // if (R_FAILED(rc)) return false; - // - // ApmPerformanceMode perfMode = ApmPerformanceMode_Invalid; - // rc = apmGetPerformanceMode(&perfMode); - // apmExit(); - // - // return R_SUCCEEDED(rc) && (perfMode == ApmPerformanceMode_Boost); - //} -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp deleted file mode 100644 index 2599fe97..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp +++ /dev/null @@ -1,63 +0,0 @@ -/******************************************************************************** - * 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-2025 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); - - #if !USING_FSTREAM_DIRECTIVE - { - 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); - } - } - #else - { - std::lock_guard lock(logMutex); - - std::ofstream file(logFilePath.c_str(), std::ios::app); - if (file.is_open()) { - file << timestamp << message << "\n"; - } - } - #endif - } - - // 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/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp deleted file mode 100644 index 6d3c6da6..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp +++ /dev/null @@ -1,897 +0,0 @@ -/******************************************************************************** - * 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-2025 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; - - -// Path to the CA certificate -//const std::string cacertPath = "sdmc:/config/ultrahand/cacert.pem"; -//const std::string cacertURL = "https://curl.se/ca/cacert.pem"; - -// 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); - } - } -}; - -// Callback function to write received data to a file. -#if !USING_FSTREAM_DIRECTIVE -// Using stdio.h functions (FILE*, fwrite) -size_t writeCallback(void* ptr, size_t size, size_t nmemb, FILE* stream) { - if (!ptr || !stream) return 0; - //size_t totalBytes = size * nmemb; - //size_t writtenBytes = fwrite(ptr, 1, totalBytes, stream); - //return writtenBytes; - return fwrite(ptr, 1, size * nmemb, stream); -} -#else -// Using std::ofstream for writing -size_t writeCallback(void* ptr, size_t size, size_t nmemb, std::ostream* stream) { - if (!ptr || !stream) return 0; - auto& file = *static_cast(stream); - const size_t totalBytes = size * nmemb; - file.write(static_cast(ptr), totalBytes); - return totalBytes; -} -#endif - -// 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) { - //int newProgress = static_cast((static_cast(nowDownloaded) / static_cast(totalToDownload)) * 100.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 -} - -// Global initialization function -//void initializeCurl() { -// std::lock_guard lock(curlInitMutex); -// if (!curlInitialized.load(std::memory_order_acquire)) { -// const CURLcode res = curl_global_init(CURL_GLOBAL_DEFAULT); -// if (res != CURLE_OK) { -// #if USING_LOGGING_DIRECTIVE -// if (!disableLogging) -// logMessage("curl_global_init() failed: " + std::string(curl_easy_strerror(res))); -// #endif -// // Handle error appropriately, possibly exit the program -// } else { -// curlInitialized.store(true, std::memory_order_release); -// } -// } -//} - -// Global cleanup function -//void cleanupCurl() { -// std::lock_guard lock(curlInitMutex); -// if (curlInitialized.load(std::memory_order_acquire)) { -// curl_global_cleanup(); -// curlInitialized.store(false, std::memory_order_release); -// } -//} - -//std::unique_ptr writeBuffer; - -/** - * @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 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; - } - - 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"; - -#if USING_FSTREAM_DIRECTIVE - // Use ofstream if !USING_FSTREAM_DIRECTIVE is not defined - std::ofstream file(tempFilePath, std::ios::binary); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error opening file: " + tempFilePath); - #endif - return false; - } -#else - // 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) { - //if (!writeBuffer) - 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); - } - - //setvbuf(file.get(), NULL, _IOFBF, DOWNLOAD_WRITE_BUFFER); -#endif - - // Ensure curl is initialized - //initializeCurl(); - - //if (!R_SUCCEEDED(socketInitializeDefault())) { - // #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 -#if USING_FSTREAM_DIRECTIVE - file.close(); -#else - file.reset(); - writeBuffer.reset(); -#endif - 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); -#if USING_FSTREAM_DIRECTIVE - curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &file); -#else - curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, file.get()); -#endif - - // 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, 10L); // 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()); - - // Detect if download was aborted - //const bool wasAborted = (result == CURLE_ABORTED_BY_CALLBACK || - // abortDownload.load(std::memory_order_acquire)); - - // Check HTTP response code BEFORE closing file/curl - long http_code = 0; - curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &http_code); - -#if USING_FSTREAM_DIRECTIVE - file.close(); -#else - file.reset(); - writeBuffer.reset(); -#endif - - curl.reset(); - - // Always cleanup global state - //curl_global_cleanup(); - // - //// Sleep to let cleanup finish - //for (int i = 0; i < 10; ++i) { - // svcSleepThread(50'000'000ULL); - //} - // - //// Explicitly reinitialize for next download - //curl_global_init(CURL_GLOBAL_DEFAULT); - - // CRITICAL: For aborted downloads, give curl time to clean up network/SSL state - // before destroying the handle. This prevents memory leaks in the global heap. - //if (wasAborted) { - // for (int i = 0; i < 10; ++i) { - // svcSleepThread(50'000'000ULL); // 50ms x 10 = 500ms total - // } - //} - - //cleanupCurl(); - - //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; - } - -#if USING_FSTREAM_DIRECTIVE - std::ifstream checkFile(tempFilePath); - if (!checkFile || checkFile.peek() == std::ifstream::traits_type::eof()) { - #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); - } - checkFile.close(); - return false; - } - checkFile.close(); -#else - // 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; - } -#endif - - // 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 - //static const size_t zipReadBufferSize = UNZIP_READ_BUFFER; - 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 - //u64 lastAbortCheck = armTicksToNs(armGetSystemTick()); - //u64 currentNanos; // Reused for all tick operations - 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 { - #if !USING_FSTREAM_DIRECTIVE - 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(); } - #else - std::ofstream file; - - OutputFileManager(size_t bufSize) { - // Constructor for consistency with FILE* version - } - - bool open(const std::string& path) { - close(); - file.open(path, std::ios::binary); - if (file.is_open()) { - file.rdbuf()->pubsetbuf(nullptr, UNZIP_WRITE_BUFFER); - } - return file.is_open(); - } - - void close() { - if (file.is_open()) { - file.close(); - } - } - - bool is_open() const { return file.is_open(); } - - size_t write(const void* data, size_t size) { - if (file.is_open()) { - file.write(static_cast(data), size); - return file.good() ? size : 0; - } - return 0; - } - #endif - }; - - 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) { - // Time-based abort check at start of each file (only if 2+ seconds have passed) - //currentNanos = armTicksToNs(armGetSystemTick()); - //if ((currentNanos - lastAbortCheck) >= 2000000000ULL) { - // if (abortUnzip.load(std::memory_order_relaxed)) { - // unzipPercentage.store(-1, std::memory_order_release); - // #if USING_LOGGING_DIRECTIVE - // logMessage("Extraction aborted during size calculation"); - // #endif - // abortUnzip.store(false, std::memory_order_release); - // return false; - // } - // lastAbortCheck = currentNanos; - //} - 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; - //fileName.reserve(512); - //extractedFilePath.reserve(1024); - //directoryPath.reserve(1024); - - // Single large buffer for extraction - reused for all files - const size_t bufferSize = UNZIP_WRITE_BUFFER; - //std::unique_ptr buffer = std::make_unique(bufferSize); - - 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.reserve(toDestination.size() + 1); - - destination = toDestination; - if (!destination.empty() && destination.back() != '/') { - destination += '/'; - } - - int newProgress;; - - // Extract files - result = unzGoToFirstFile(zipFile); - while (result == UNZ_OK && success) { - // Time-based abort check at start of each file (only if 2+ seconds have passed) - //currentNanos = armTicksToNs(armGetSystemTick()); - //if ((currentNanos - lastAbortCheck) >= 2000000000ULL) { - // if (abortUnzip.load(std::memory_order_relaxed)) { - // success = false; - // break; // RAII will handle cleanup - // } - // lastAbortCheck = currentNanos; - //} - - 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.clear(); - 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/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp deleted file mode 100644 index 2ff8159d..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp +++ /dev/null @@ -1,506 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#include "get_funcs.hpp" - - -namespace ult { - - /** - * @brief Reads the contents of a file and returns it as a string, normalizing line endings. - * - * @param filePath The path to the file to be read. - * @return The content of the file as a string with line endings normalized to '\n'. - */ - //std::string getFileContents(const std::string& filePath) { - // #if !USING_FSTREAM_DIRECTIVE - // FILE* file = fopen(filePath.c_str(), "rb"); - // if (!file) { - // #if USING_LOGGING_DIRECTIVE - // logMessage("Failed to open file: " + filePath); - // #endif - // return ""; - // } - // - // // Determine the file size - // fseek(file, 0, SEEK_END); - // long size = ftell(file); - // if (size <= 0) { - // fclose(file); - // return ""; - // } - // fseek(file, 0, SEEK_SET); - // - // // Read the entire file into a string - // std::string content(size, '\0'); - // if (fread(&content[0], 1, size, file) != static_cast(size)) { - // #if USING_LOGGING_DIRECTIVE - // logMessage("Failed to read file: " + filePath); - // #endif - // fclose(file); - // return ""; - // } - // - // fclose(file); - // - // #else - // std::ifstream file(filePath, std::ios::binary); - // if (!file) { - // #if USING_LOGGING_DIRECTIVE - // logMessage("Failed to open file: " + filePath); - // #endif - // return ""; - // } - // - // // Determine the file size - // file.seekg(0, std::ios::end); - // std::streamsize size = file.tellg(); - // if (size <= 0) { - // return ""; - // } - // file.seekg(0, std::ios::beg); - // - // // Read the entire file into a string - // std::string content(size, '\0'); - // if (!file.read(&content[0], size)) { - // #if USING_LOGGING_DIRECTIVE - // logMessage("Failed to read file: " + filePath); - // #endif - // return ""; - // } - // #endif - // - // // Erase any carriage return characters (normalize line endings) - // content.erase(std::remove(content.begin(), content.end(), '\r'), content.end()); - // return content; - //} - - - - - /** - * @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 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 (isDirectory(entry, fullPath)) { - subdirectories.emplace_back(entryName); - } - } - - return subdirectories; - } - - /** - * @brief Check if a directory entry is a directory (no caching). - * Fast path for known types, stat() only when necessary. - */ - inline bool isDirectory(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 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 (isDirectory(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; - //fullPath.reserve(512); - //result.reserve(512); - //currentPath.reserve(512); - - struct stat st; - - bool isDir; - //std::string pathRef; - size_t currentPartIndex; - - while (!stack.empty()) { - if (maxLines > 0 && results.size() >= maxLines) return; - - std::tie(currentPath, currentPartIndex) = stack.back(); - stack.pop_back(); - - // Copy once to avoid repeated access - //currentPath = pathRef; - - 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() != '/'; - - // Pre-calculate base path for efficiency - //const size_t basePathLen = currentPath.length(); - - 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/sys-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp deleted file mode 100644 index a4241624..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp +++ /dev/null @@ -1,188 +0,0 @@ -/******************************************************************************** - * 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-2025 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"; - - // 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 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 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 EXPANSION_PATH = BASE_CONFIG_PATH + "expansion/"; - 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; - - // 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 NX_OVLLOADER_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/latest/download/nx-ovlloader.zip"; - //const std::string NX_OVLLOADER_PLUS_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/latest/download/nx-ovlloader+.zip"; - const std::string OLD_NX_OVLLOADER_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/download/v1.0.8/nx-ovlloader.zip"; - //const std::string OLD_NX_OVLLOADER_PLUS_ZIP_URL = GITHUB_BASE_URL + "nx-ovlloader/releases/download/v1.0.8/nx-ovlloader+.zip"; - const std::string UPDATER_PAYLOAD_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/payloads/ultrahand_updater.bin"; - //const std::string SOUND_EFFECTS_URL = GITHUB_RAW_BASE_URL + "Ultrahand-Overlay/main/sounds/sounds.zip"; - - // 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 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"; - 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 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 = " "; - - 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/sys-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp deleted file mode 100644 index be00b524..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/haptics.cpp +++ /dev/null @@ -1,261 +0,0 @@ -/******************************************************************************** - * 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 ppkantorski - ********************************************************************************/ - -#include "haptics.hpp" - -namespace ult { - - // ===== Internal state (private to this file) ===== - //bool rumbleInitialized = false; - static HidVibrationDeviceHandle vibHandheld; - 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 clickDocked = { - // .amp_low = 0.20f, - // .freq_low = 100.0f, - // .amp_high = 0.80f, - // .freq_high = 300.0f - //}; - // - //static constexpr HidVibrationValue clickHandheld = { - // .amp_low = 0.20f, - // .freq_low = 100.0f, - // .amp_high = 0.80f, - // .freq_high = 300.0f - //}; - - 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(vibHandheld, 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); - - // Clear previous handles to avoid using stale handles if controllers were removed - vibHandheld = (HidVibrationDeviceHandle)0; - vibPlayer1Left = (HidVibrationDeviceHandle)0; - vibPlayer1Right = (HidVibrationDeviceHandle)0; - - // Handheld - if (handheldStyle) { - hidInitializeVibrationDevices(&vibHandheld, 1, - HidNpadIdType_Handheld, - (HidNpadStyleTag)handheldStyle); - } - - // Player 1 (left + right Joy-Con or Pro Controller) - if (player1Style) { - HidVibrationDeviceHandle tmp[2] = { (HidVibrationDeviceHandle)0, (HidVibrationDeviceHandle)0 }; - hidInitializeVibrationDevices(tmp, 2, - HidNpadIdType_No1, - (HidNpadStyleTag)player1Style); - - vibPlayer1Left = tmp[0]; - vibPlayer1Right = tmp[1]; - } - - // Ensure cache is valid immediately after initHaptics() - cachedHandheldStyle = handheldStyle; - cachedPlayer1Style = player1Style; - } - - //void deinitHaptics() { - // rumbleInitialized = false; - //} - - 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) - //const bool changed = - // (currentHandheldStyle != lastHandheldStyle) || (currentPlayer1Style != lastPlayer1Style); - - 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 - //const HidVibrationValue* pattern = cachedHandheldStyle ? &clickHandheld : &clickDocked; - sendVibration(&vibrationStop); - //if (cachedHandheldStyle) { - // sendVibration(&clickHandheld); - // sendVibration(&clickHandheld); - //} else { - // sendVibration(&clickDocked); - // sendVibration(&clickDocked); - //} - sendVibration2x(&hapticsPreset); - clickActive.store(true, std::memory_order_release); - rumbleStartTick = armGetSystemTick(); - - } - - void rumbleDoubleClick() { - //onst HidVibrationValue* pattern = cachedHandheldStyle ? &clickHandheld : &clickDocked; - sendVibration(&vibrationStop); - //if (cachedHandheldStyle) { - // sendVibration(&clickHandheld); - // sendVibration(&clickHandheld); - //} else { - // sendVibration(&clickDocked); - // sendVibration(&clickDocked); - //} - 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) { - // Use cached style here too - //if (cachedHandheldStyle) { - // sendVibration(&clickHandheld); - // sendVibration(&clickHandheld); - //} else { - // sendVibration(&clickDocked); - // sendVibration(&clickDocked); - //} - 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 - //const HidVibrationValue* pattern = cachedHandheldStyle ? &clickHandheld : &clickDocked; - sendVibration(&vibrationStop); - //if (cachedHandheldStyle) { - // sendVibration(&clickHandheld); - // sendVibration(&clickHandheld); - //} else { - // sendVibration(&clickDocked); - // sendVibration(&clickDocked); - //} - sendVibration2x(&hapticsPreset); - svcSleepThread(DOUBLE_CLICK_PULSE_DURATION_NS); - - sendVibration(&vibrationStop); - svcSleepThread(DOUBLE_CLICK_GAP_NS); - - //if (cachedHandheldStyle) { - // sendVibration(&clickHandheld); - // sendVibration(&clickHandheld); - //} else { - // sendVibration(&clickDocked); - // sendVibration(&clickDocked); - //} - sendVibration2x(&hapticsPreset); - svcSleepThread(DOUBLE_CLICK_PULSE_DURATION_NS); - - sendVibration(&vibrationStop); - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp deleted file mode 100644 index d5a1874e..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp +++ /dev/null @@ -1,1018 +0,0 @@ -/******************************************************************************** - * 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-2025 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.clear(); - 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. - */ - - - // Function to convert ASCII string to Hex string - std::string asciiToHex(const std::string& asciiStr) { - std::string hexStr; - //hexStr.reserve(asciiStr.length() * 2); // Reserve space for the hexadecimal string - - 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]; - //int value; - - // 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; - //throw std::invalid_argument("Invalid hexadecimal character"); - } - - // 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) { - //std::string hexadecimal = decimalToHex(decimalStr, byteGroupSize); - - // Reverse the hexadecimal string in groups of byteGroupSize - //std::string reversedHex; - //for (int i = hexadecimal.length() - byteGroupSize; i >= 0; i -= byteGroupSize) { - // reversedHex += hexadecimal.substr(i, 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; - - #if !USING_FSTREAM_DIRECTIVE - 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); - - #else - std::ifstream file(filePath, std::ios::binary); - if (!file.is_open()) { - return offsets; - } - - file.seekg(0, std::ios::end); - const size_t fileSize = file.tellg(); - file.seekg(0, std::ios::beg); - - if (hexData.length() % 2 != 0) { - file.close(); - 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()); - - 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]]; - } - for (; i < hexLen; i += 2) { - binaryData[i/2] = (hexTable[hexPtr[i]] << 4) | hexTable[hexPtr[i + 1]]; - } - - 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 (file.read(reinterpret_cast(buffer.get()), HEX_BUFFER_SIZE) || file.gcount() > 0) { - bytesRead = file.gcount(); - const unsigned char* bufPtr = buffer.get(); - - // Same optimized search as FILE* version - i = 0; - const size_t searchEnd = bytesRead; - - for (; i + 4 <= searchEnd; i += 4) { - 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)); - } - } - } - - 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; - } - - file.close(); - #endif - - 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); - - #if !USING_FSTREAM_DIRECTIVE - // 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); - #else - // Open the file for both reading and writing in binary mode - std::fstream file(filePath, std::ios::binary | std::ios::in | std::ios::out); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open the file."); - #endif - return; - } - - // Retrieve the file size - file.seekg(0, std::ios::end); - const std::streampos fileSize = file.tellg(); - - if (offset >= fileSize) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Offset exceeds file size."); - #endif - 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 - 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 - 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]]; - } - 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 - file.seekp(offset); - file.write(reinterpret_cast(binaryData.get()), dataLen); - if (!file) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to write data to the file."); - #endif - return; - } - - file.close(); - #endif - } - - - /** - * @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 - //int sum = hexSum + ult::stoi(offsetStr); - 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) { - //logMessage("offsetStr: "+offsetStr); - //logMessage("hexDataReplacement: "+hexDataReplacement); - hexEditByOffset(filePath, offsetStr, hexDataReplacement); - } - } else { - // Convert the occurrence string to an integer - if (occurrence > 0 && occurrence <= offsetStrs.size()) { - // Replace the specified occurrence/index - //std::string offsetStr = offsetStrs[occurrence - 1]; - //logMessage("offsetStr: "+offsetStr); - //logMessage("hexDataReplacement: "+hexDataReplacement); - hexEditByOffset(filePath, offsetStrs[occurrence - 1], hexDataReplacement); - } else { - // Invalid occurrence/index specified - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Invalid hex occurrence/index specified."); - #endif - } - } - //std::cout << "Hex data replaced successfully." << std::endl; - } - } - - /** - * @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); - - #if !USING_FSTREAM_DIRECTIVE - 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]; - } - - #else - std::ifstream file(filePath, std::ios::binary); - if (!file) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open the file."); - #endif - return ""; - } - - file.seekg(totalOffset); - if (!file) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error seeking to offset."); - #endif - return ""; - } - - // Use heap allocation for the buffer to avoid stack overflow with large buffer sizes - std::unique_ptr buffer(new unsigned char[length]); - file.read(reinterpret_cast(buffer.get()), length); - file.close(); - - if (file.gcount() != static_cast(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]; - } - #endif - - 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) { - #if !USING_FSTREAM_DIRECTIVE - // 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 - } - #else - // Step 1: Read the entire binary file into a vector - std::ifstream file(filePath, std::ios::binary | std::ios::ate); - if (!file.is_open()) { - return ""; // Return empty string if file cannot be opened - } - - const std::streamsize size = file.tellg(); - file.seekg(0, std::ios::beg); - - std::vector buffer(size); - if (!file.read(reinterpret_cast(buffer.data()), size)) { - return ""; // Return empty string if reading fails - } - #endif - - // 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/sys-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp deleted file mode 100644 index 33ad3876..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp +++ /dev/null @@ -1,2563 +0,0 @@ -/******************************************************************************** - * 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-2025 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; - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(filePath.c_str(), "r"); - if (!file) { - return packageHeader; - } - - char buffer[1024]; - std::string line; - #else - std::ifstream file(filePath); - if (!file) { - return packageHeader; - } - - std::string line; - #endif - - // 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; - - #if !USING_FSTREAM_DIRECTIVE - size_t len; - while (fgets(buffer, sizeof(buffer), 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(); - } - } - #else - while (getline(file, line) && fieldsFound < totalFields) { - // Remove carriage return if present - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - #endif - - // 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(); - } - - #if !USING_FSTREAM_DIRECTIVE - fclose(file); - #endif - - 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; - - //out.reserve(std::count(str.begin(), str.end(), delim) + 1); - - 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; - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(configIniPath.c_str(), "r"); - if (!file) { - return parsedData; - } - - char buffer[1024]; - std::string key, value; - key.reserve(64); - value.reserve(256); - - std::map* currentSectionMap = nullptr; - - while (fgets(buffer, sizeof(buffer), 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) { - currentSectionMap = &parsedData[std::string(start + 1, end - 1)]; - } - } else if (currentSectionMap) { - // 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) { - // Trim value - 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); - #else - std::ifstream configFile(configIniPath); - if (!configFile) { - return parsedData; - } - - std::string line; - line.reserve(256); - - std::map* currentSectionMap = nullptr; - - while (getline(configFile, line)) { - // Strip carriage return - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - if (line.empty()) continue; - - // Trim using pointers for speed - const char* start = line.c_str(); - const char* end = start + line.length(); - - 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) { - currentSectionMap = &parsedData[std::string(start + 1, end - 1)]; - } - } else if (currentSectionMap) { - // 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) { - // Trim value - 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) - ); - } - } - } - } - - configFile.close(); - #endif - - 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; - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(configIniPath.c_str(), "r"); - if (!file) { - return sectionData; - } - - char buffer[1024]; - 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, sizeof(buffer), 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); - #else - std::ifstream configFile(configIniPath); - if (!configFile) { - return sectionData; - } - - std::string line; - line.reserve(256); - - std::string key, value; - key.reserve(64); - value.reserve(128); - - bool inTargetSection = false; - size_t delimiterPos; - - while (getline(configFile, line)) { - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - trim(line); - - if (line.empty()) continue; - - // Skip comment lines - if (line[0] == '#' || line[0] == ';') continue; - - if (line[0] == '[' && line.back() == ']') { - 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); - } - } - } - #endif - - 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; - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(filePath.c_str(), "r"); - if (!file) { - return sections; - } - - char buffer[1024]; - std::string line; - //line.reserve(1024); // Add reservation for efficiency - - size_t len; - std::string sectionName; - while (fgets(buffer, sizeof(buffer), 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); - #else - std::ifstream file(filePath); - if (!file) { - return sections; - } - - std::string line; - //line.reserve(1024); // Add reservation for efficiency - - std::string sectionName; - while (std::getline(file, line)) { - // Remove carriage return if present - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - trim(line); - - // Check if the line contains a section header - if (!line.empty() && line.front() == '[' && line.back() == ']') { - sectionName.assign(line, 1, line.size() - 2); - sections.push_back(std::move(sectionName)); - } - // Clear strings to reuse capacity - line.clear(); - sectionName.clear(); - } - - file.close(); // Add explicit close - #endif - - 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; - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(filePath.c_str(), "r"); - if (!file) { - return value; - } - - char buffer[1024]; - bool inTargetSection = false; - - while (fgets(buffer, sizeof(buffer), 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); - #else - std::ifstream file(filePath); - if (!file) { - return value; - } - - std::string line; - line.reserve(256); - bool inTargetSection = false; - - while (std::getline(file, line)) { - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - if (line.empty()) continue; - - // Trim using pointers - const char* start = line.c_str(); - const char* end = start + line.length(); - - 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) { - size_t sectionLen = end - start - 2; - inTargetSection = (sectionLen == sectionName.length() && - std::memcmp(start + 1, sectionName.data(), sectionLen) == 0); - } - } 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) { - 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 - } - } - } - } - } - - file.close(); - #endif - - 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"; - - #if !USING_FSTREAM_DIRECTIVE - 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 - char line[1024]; - std::string lineStr; - //lineStr.reserve(1024); - - bool isNewSection = false; - bool isSection = false; - size_t len = 0; - - while (fgets(line, sizeof(line), 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); - #else - std::ifstream inputFile(filePath); - if (!inputFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open the input file: " + filePath); - #endif - return; - } - - std::ofstream outputFile(tempPath); - if (!outputFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to create the output file: " + tempPath); - #endif - return; - } - - // Declare all variables outside the loop - std::string line; - //line.reserve(1024); - - bool isNewSection = false; - bool isSection = false; - - while (std::getline(inputFile, line)) { - // Remove carriage return if present - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - trim(line); - - if (!line.empty()) { - isSection = (line[0] == '[' && line.back() == ']'); - - if (isSection) { - if (isNewSection) { - outputFile << '\n'; - } - isNewSection = true; - } - - outputFile << line << '\n'; - } - // Clear string to reuse capacity - line.clear(); - } - - inputFile.close(); - outputFile.close(); - #endif - - // 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)); - } - - #if !USING_FSTREAM_DIRECTIVE - 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 - char line[1024]; - 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, sizeof(line), 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); - } - #else - std::ifstream configFile(fileToEdit); - StringStream buffer(""); // Use StringStream to collect results - - if (!configFile) { - std::ofstream outFile(fileToEdit); - outFile << "[" << desiredSection << "]\n" << desiredKey << "=" << desiredValue << '\n'; - return; - } - - std::string line; - bool sectionFound = false; - bool keyFound = false; - bool firstSection = true; // Flag to control new line before first section - std::string currentSection; - - size_t delimiterPos; - std::string key; - - size_t start, end, key_start, key_end; - while (std::getline(configFile, line)) { - // Remove carriage return if present (getline already removes \n) - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - // Early exit for empty lines - if (line.empty()) continue; - - // Manual trim for better performance - start = 0; - end = line.length() - 1; - - // Find start of non-whitespace - while (start < line.length() && (line[start] == ' ' || line[start] == '\t')) { - ++start; - } - - // Early exit for whitespace-only lines - if (start >= line.length()) continue; - - // Find end of non-whitespace - while (end > start && (line[end] == ' ' || line[end] == '\t')) { - --end; - } - - // Create trimmed line if needed - if (start > 0 || end < line.length() - 1) { - line.assign(line, start, end - start + 1); - } - - if (line[0] == '[' && line.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(line, 1, line.size() - 2); - sectionFound = (currentSection == desiredSection); - buffer << line << '\n'; - firstSection = false; - - // Clear strings to reuse capacity - line.clear(); - currentSection.clear(); - continue; - } - - if (sectionFound && !keyFound) { - delimiterPos = line.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 && (line[key_start] == ' ' || line[key_start] == '\t')) { - ++key_start; - } - - // Find end of key (skip trailing whitespace) - while (key_end > key_start && (line[key_end] == ' ' || line[key_end] == '\t')) { - --key_end; - } - - if (key_end >= key_start) { - key.assign(line, key_start, key_end - key_start + 1); - - if (key == desiredKey) { - keyFound = true; - // Build the replacement line more efficiently - line.assign(desiredNewKey.empty() ? desiredKey : desiredNewKey); - line += '='; - line += desiredValue; - } - } - } - } - - buffer << line << '\n'; - - // Clear strings to reuse capacity - line.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'; - } - - configFile.close(); - - std::ofstream outFile(fileToEdit); - outFile << buffer.str(); - outFile.close(); - #endif - } - - - /** - * @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); - //cleanIniFormatting(fileToEdit); - } - - /** - * @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); - //cleanIniFormatting(fileToEdit); - } - - - - /** - * @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); - - #if !USING_FSTREAM_DIRECTIVE - 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 - char line[1024]; - bool sectionExists = false; - size_t len = 0; - //const char* start; - const char* end; - - size_t content_len; - - // First pass: check if section exists and copy all content - while (fgets(line, sizeof(line), 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); - - #else - std::ifstream inputFile(filePath); - if (!inputFile) { - // Create new file with just the section if file doesn't exist - std::ofstream newFile(filePath); - if (newFile) { - newFile << "[" << sectionName << "]\n"; - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Error: Failed to create new INI file."); - } - #endif - return; - } - - const std::string tempPath = filePath + ".tmp"; - std::ofstream tempFile(tempPath); - if (!tempFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Failed to create a temporary file."); - #endif - return; - } - - // Pre-calculate section comparison values - const size_t sectionNameLen = sectionName.length(); - const size_t fullSectionLen = sectionNameLen + 2; // [ + sectionName + ] - - // Declare variables outside the loop - std::string line; - bool sectionExists = false; - - size_t end_pos, content_len; - // Read entire file and check for section - while (std::getline(inputFile, line)) { - // Optimize section detection - if (line.length() >= fullSectionLen && line[0] == '[') { - // Find end of content (excluding carriage return) - end_pos = line.length() - 1; - if (line[end_pos] == '\r') --end_pos; - - // Check if this could be our section - if (end_pos < line.length() && line[end_pos] == ']') { - content_len = end_pos + 1; - if (content_len == fullSectionLen) { - // Direct comparison - much faster than string creation - if (line.compare(1, sectionNameLen, sectionName) == 0) { - sectionExists = true; - // Early optimization: write remaining file and exit loop - tempFile << line << '\n'; - - // Copy rest of file efficiently - while (std::getline(inputFile, line)) { - tempFile << line << '\n'; - line.clear(); // Clear to reuse capacity - } - break; - } - } - } - } - - tempFile << line << '\n'; - line.clear(); // Clear to reuse capacity - } - - // If the section does not exist, add it - if (!sectionExists) { - tempFile << "[" << sectionName << "]\n"; - } - - inputFile.close(); - tempFile.close(); - #endif - - // 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); - - #if !USING_FSTREAM_DIRECTIVE - 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; - } - - char line[1024]; - std::string sectionName; - std::string lineStr; - - while (fgets(line, sizeof(line), 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); - #else - std::ifstream configFile(filePath); - if (!configFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open the input file: " + filePath); - #endif - return; - } - - std::string tempPath = filePath + ".tmp"; - std::ofstream tempFile(tempPath); - if (!tempFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to create the temporary file: " + tempPath); - #endif - return; - } - - std::string line, sectionName; - while (getline(configFile, line)) { - trim(line); - if (!line.empty() && line.front() == '[' && line.back() == ']') { - sectionName = line.substr(1, line.length() - 2); - tempFile << "[" << (sectionName == currentSectionName ? newSectionName : sectionName) << "]\n"; - } else { - tempFile << line << '\n'; - } - } - - configFile.close(); - tempFile.close(); - #endif - - // 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); - - #if !USING_FSTREAM_DIRECTIVE - 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 + ] - - char line[1024]; - std::string currentSection; - bool inSectionToRemove = false; - - size_t len; - const char* start; - const char* end; - - size_t trimmed_len; - while (fgets(line, sizeof(line), 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); - #else - std::ifstream configFile(filePath); - if (!configFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open the input file: " + filePath); - #endif - return; - } - - std::string tempPath = filePath + ".tmp"; - std::ofstream tempFile(tempPath); - if (!tempFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to create the temporary file: " + tempPath); - #endif - return; - } - - // Pre-calculate section comparison values - const size_t sectionNameLen = sectionName.length(); - const size_t fullSectionLen = sectionNameLen + 2; // [ + sectionName + ] - - std::string line, currentSection; - bool inSectionToRemove = false; - - size_t start, end, trimmed_len; - while (getline(configFile, line)) { - // Early exit for empty lines - if (line.empty()) { - if (!inSectionToRemove) { - tempFile << line << '\n'; - } - continue; - } - - // Manual trim for better performance - start = 0; - end = line.length() - 1; - - // Find start of non-whitespace - while (start < line.length() && (line[start] == ' ' || line[start] == '\t')) { - ++start; - } - - // Find end of non-whitespace (excluding carriage return) - while (end > start && (line[end] == ' ' || line[end] == '\t' || line[end] == '\r')) { - --end; - } - - // Early exit for whitespace-only lines - if (start >= line.length() || end < start) { - if (!inSectionToRemove) { - tempFile << line << '\n'; - } - continue; - } - - // Calculate trimmed length - trimmed_len = end - start + 1; - - // Check if this is a section header - if (trimmed_len >= 3 && line[start] == '[' && line[end] == ']') { - // Optimize section detection with direct comparison - if (trimmed_len == fullSectionLen) { - // Direct string comparison - much faster than substr + comparison - if (line.compare(start + 1, sectionNameLen, sectionName) == 0) { - inSectionToRemove = true; - continue; // Skip writing this section header - } - } - - // Different section - not the one to remove - inSectionToRemove = false; - tempFile << line << '\n'; - } else if (!inSectionToRemove) { - tempFile << line << '\n'; - } - // If inSectionToRemove is true, skip writing this line - } - - configFile.close(); - tempFile.close(); - #endif - - // 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); - - #if !USING_FSTREAM_DIRECTIVE - 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 - char line[1024]; - std::string currentSection; - //currentSection.reserve(64); - - std::string lineStr; - //lineStr.reserve(1024); - - std::string trimmedLine; - //trimmedLine.reserve(1024); - - std::string lineKey; - //lineKey.reserve(128); - - bool inTargetSection = false; - size_t eqPos; - - while (fgets(line, sizeof(line), 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); - #else - std::ifstream configFile(filePath); - if (!configFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to open the input file: " + filePath); - #endif - return; - } - - std::string tempPath = filePath + ".tmp"; - std::ofstream tempFile(tempPath); - if (!tempFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to create the temporary file: " + tempPath); - #endif - return; - } - - // Declare all variables outside the loop for efficiency - std::string line; - //line.reserve(1024); - - std::string currentSection; - //currentSection.reserve(64); - - std::string trimmedLine; - //trimmedLine.reserve(1024); - - std::string lineKey; - //lineKey.reserve(128); - - bool inTargetSection = false; - size_t eqPos; - - while (getline(configFile, line)) { - trimmedLine = line; - // Remove carriage return if present - 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); - tempFile << line << '\n'; - } else if (inTargetSection) { - // Better key matching that handles spaces - eqPos = trimmedLine.find('='); - if (eqPos != std::string::npos) { - lineKey.assign(trimmedLine, 0, eqPos); - trim(lineKey); - if (lineKey == keyName) { - continue; // Skip this line - } - } - tempFile << line << '\n'; - } else { - tempFile << line << '\n'; - } - } - - configFile.close(); - tempFile.close(); - #endif - - // 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 - } - } - - //void saveIniFileData(const std::string& filePath, const std::map>& data) { - // std::ofstream file(filePath); - // if (!file.is_open()) { - // // Handle error: could not open file - // return; - // } - // - // for (const auto& section : data) { - // file << "[" << section.first << "]\n"; - // for (const auto& kv : section.second) { - // file << kv.first << "=" << kv.second << "\n"; - // } - // file << "\n"; // Separate sections with a newline - // } - // - // file.close(); - //} - - - 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; - - //commandParts.reserve(8); - - 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); - } - } - - 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); - - #if !USING_FSTREAM_DIRECTIVE - FILE* packageFile = fopen(packageIniPath.c_str(), "r"); - if (!packageFile) return {}; - - std::vector>>> options; - options.reserve(32); // Reserve reasonable capacity - - char buffer[1024]; - std::string currentSection; - std::vector> sectionCommands; - sectionCommands.reserve(16); - - while (fgets(buffer, sizeof(buffer), 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); - #else - std::ifstream packageFile(packageIniPath); - if (!packageFile) return {}; - - std::vector>>> options; - options.reserve(32); - - std::string line; - line.reserve(256); - std::string currentSection; - std::vector> sectionCommands; - sectionCommands.reserve(16); - - while (std::getline(packageFile, line)) { - // Remove carriage return if present - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - if (line.empty() || line[0] == '#') continue; - - if (line[0] == '[' && line.back() == ']') { - if (!currentSection.empty()) { - options.emplace_back(std::move(currentSection), std::move(sectionCommands)); - sectionCommands = std::vector>(); - sectionCommands.reserve(16); - } - currentSection.assign(line, 1, line.size() - 2); - } else if (!currentSection.empty()) { - sectionCommands.push_back(parseCommandLine(line)); - } - } - - if (!currentSection.empty()) { - options.emplace_back(std::move(currentSection), std::move(sectionCommands)); - } - - packageFile.close(); - #endif - - 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); - - #if !USING_FSTREAM_DIRECTIVE - FILE* packageFile = fopen(packageIniPath.c_str(), "r"); - if (!packageFile) return {}; - - std::vector> sectionCommands; - sectionCommands.reserve(16); - - char buffer[1024]; - bool inTargetSection = false; - - while (fgets(buffer, sizeof(buffer), 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); - #else - std::ifstream packageFile(packageIniPath); - if (!packageFile) return {}; - - std::string line; - line.reserve(256); - std::vector> sectionCommands; - sectionCommands.reserve(16); - bool inTargetSection = false; - - while (std::getline(packageFile, line)) { - // Remove carriage return if present - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - - if (line.empty() || line[0] == '#') continue; - - // Section header - if (line[0] == '[' && line.back() == ']') { - size_t sectionLen = line.size() - 2; - - if (sectionLen > 0) { - // Direct comparison without constructing substring - bool isTarget = (sectionLen == sectionName.length() && - std::memcmp(line.data() + 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(line)); - } - } - - packageFile.close(); - #endif - - 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); - - #if !USING_FSTREAM_DIRECTIVE - FILE* file = fopen(filePath.c_str(), "w"); - if (!file) { - return; - } - - // Use larger buffer for better write performance - char writeBuffer[4096]; - setvbuf(file, writeBuffer, _IOFBF, sizeof(writeBuffer)); - - 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); - #else - std::ofstream file(filePath); - if (!file.is_open()) { - return; - } - - // Set larger buffer for better performance - char writeBuffer[4096]; - file.rdbuf()->pubsetbuf(writeBuffer, sizeof(writeBuffer)); - - std::string buffer; - buffer.reserve(2048); - - 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'; - - // Write entire section at once - file.write(buffer.data(), buffer.size()); - } - - file.close(); - #endif - } - - - - 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(); - - #if !USING_FSTREAM_DIRECTIVE - 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); - #else - std::ifstream in(filePath); - if (!in) return; - std::ofstream out(tempPath); - if (!out) return; - - std::vector section; - std::string line; - bool inMatch = matchAll; - size_t patIdx = SIZE_MAX, tgtIdx = SIZE_MAX; - - while (std::getline(in, line)) { - if (!line.empty() && line.back() == '\r') line.pop_back(); - - std::string tl = line; - trim(tl); - - if (!tl.empty() && tl[0] == '[' && tl.back() == ']') { - // Flush previous 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) { - out << targetKey << "=" << value << '\n'; - } else { - out << section[i] << '\n'; - } - if (i + 1 == insertAt) { - out << targetKey << "=" << value << '\n'; - } - } - } else if (operation == KeyOp::REMOVE) { - for (size_t i = 0; i < section.size(); ++i) { - if (i != tgtIdx) out << section[i] << '\n'; - } - } - } else { - for (const auto& l : section) out << l << '\n'; - } - - section.clear(); - out << line << '\n'; - 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(line); - } - - // 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) { - out << targetKey << "=" << value << '\n'; - } else { - out << section[i] << '\n'; - } - if (i + 1 == insertAt) { - out << targetKey << "=" << value << '\n'; - } - } - } else if (operation == KeyOp::REMOVE) { - for (size_t i = 0; i < section.size(); ++i) { - if (i != tgtIdx) out << section[i] << '\n'; - } - } - } else { - for (const auto& l : section) out << l << '\n'; - } - - in.close(); - out.close(); - #endif - - 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/sys-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp deleted file mode 100644 index e96859e2..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp +++ /dev/null @@ -1,400 +0,0 @@ -/******************************************************************************** - * 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-2025 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); - #if !USING_FSTREAM_DIRECTIVE - 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'; - - #else - std::ifstream file(filePath, std::ios::binary | std::ios::ate); - if (!file.is_open()) { - return nullptr; - } - - // Get file size from current position (end) - const std::streampos fileSize = file.tellg(); - file.seekg(0, std::ios::beg); - - // Check for reasonable file size - if (fileSize <= 0 || fileSize > 6 * 1024 * 1024) { - return nullptr; - } - - // Use vector for better performance and explicit null termination - std::vector buffer; - buffer.resize(static_cast(fileSize) + 1); // +1 for null terminator - - file.read(buffer.data(), static_cast(fileSize)); - - // Check how much was actually read - std::streamsize actualRead = file.gcount(); - if (actualRead != fileSize) { - return nullptr; - } - - // Ensure null termination for cJSON - buffer[actualRead] = '\0'; - file.close(); - #endif - - // 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; - - // Trim whitespace first - std::string trimmedValue = value; - // Remove leading whitespace - trimmedValue.erase(0, trimmedValue.find_first_not_of(" \t\n\r")); - // Remove trailing whitespace - trimmedValue.erase(trimmedValue.find_last_not_of(" \t\n\r") + 1); - - if (trimmedValue.empty()) { - jsonValue = cJSON_CreateString(""); - } else if (trimmedValue == "true") { - jsonValue = cJSON_CreateBool(1); - } else if (trimmedValue == "false") { - jsonValue = cJSON_CreateBool(0); - } else if (trimmedValue == "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(trimmedValue.c_str(), &endPtr, 10); - if (endPtr == trimmedValue.c_str() + trimmedValue.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(trimmedValue.c_str(), &endPtr); - if (endPtr == trimmedValue.c_str() + trimmedValue.length() && errno == 0) { - // Successfully parsed as float - jsonValue = cJSON_CreateNumber(doubleValue); - } else { - // Treat as string - jsonValue = cJSON_CreateString(trimmedValue.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); - #if !USING_FSTREAM_DIRECTIVE - 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); - } - #else - std::ofstream file(filePath); // Use text mode for JSON - if (file.is_open()) { - file << jsonString; - success = !file.fail(); - file.close(); - } - #endif - } - - 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); - #if !USING_FSTREAM_DIRECTIVE - 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); - } - #else - std::ofstream file(filePath); // Use text mode - if (file.is_open()) { - file << jsonString; - success = !file.fail(); - file.close(); - } - #endif - } - - 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)); - //cJSON_AddNumberToObject(notif, "arrival_ns", static_cast(armTicksToNs(tick))); - - // 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/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp deleted file mode 100644 index fe7c5243..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp +++ /dev/null @@ -1,531 +0,0 @@ -/******************************************************************************** - * 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-2025 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; - - #if !USING_FSTREAM_DIRECTIVE - 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); - #else - std::ifstream file(filePath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + filePath); - #endif - return lines; - } - - std::string line; - while (std::getline(file, line)) { - // Check cap before adding - if (maxLines > 0 && lines.size() >= maxLines) { - break; - } - - if (preserveNewlines) { - // Add back the newline that getline removed - line += '\n'; - lines.emplace_back(std::move(line)); - } else { - // Remove carriage return if present (getline removes \n but not \r) - if (!line.empty() && line.back() == '\r') { - line.pop_back(); - } - lines.emplace_back(std::move(line)); - } - } - - file.close(); - #endif - - 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); - - #if !USING_FSTREAM_DIRECTIVE - 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); - - #else - std::ifstream file(listPath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + listPath); - #endif - return ""; - } - - std::string line; - - // Skip lines until reaching the desired index - for (size_t i = 0; i < listIndex; ++i) { - if (!std::getline(file, line)) { - return ""; // Index out of bounds - } - } - - // Read the target line - if (!std::getline(file, line)) { - return ""; // Index out of bounds - } - - file.close(); - return line; - #endif - } - - - /** - * @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; - - #if !USING_FSTREAM_DIRECTIVE - 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); - #else - std::ifstream file(filePath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + filePath); - #endif - return lines; - } - - std::string line; - while (std::getline(file, line)) { - if (!packagePath.empty()) { - preprocessPath(line, packagePath); - } - lines.insert(std::move(line)); - } - - file.close(); - #endif - - 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); - - #if !USING_FSTREAM_DIRECTIVE - 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); - #else - std::ofstream file(filePath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + filePath); - #endif - return; - } - - for (const auto& entry : fileSet) { - file << entry << '\n'; - } - - file.close(); - #endif - } - - // 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); - - #if !USING_FSTREAM_DIRECTIVE - 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); - - #else - std::ifstream streamFile(streamFilePath); - if (!streamFile.is_open()) return; - - std::ofstream outputFile(outputTxtFilePath); - if (!outputFile.is_open()) return; - - std::string line; - while (std::getline(streamFile, line)) { - if (compareSet.count(line)) { - outputFile << line << '\n'; - } - } - #endif - } - - // 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); - - #if !USING_FSTREAM_DIRECTIVE - 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); - - #else - std::ifstream file(filePath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage(UNABLE_TO_OPEN_FILE + filePath); - #endif - continue; - } - - std::string line; - while (std::getline(file, line) && !targetLines.empty()) { // Early exit! - auto it = targetLines.find(line); - if (it != targetLines.end()) { - duplicates.emplace(std::move(*it)); // Move instead of copy - targetLines.erase(it); - } - } - #endif - filePath = ""; // Clear after processing - reduces vector memory footprint - } - - writeSetToFile(duplicates, outputTxtFilePath); - } -} \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp deleted file mode 100644 index bf13342c..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp +++ /dev/null @@ -1,736 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#include - -namespace ult { - - //const std::string CHEAT_HEADER = "// auto generated by pchtxt2cheat\n\n"; - 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 - } - - //size_t len; - 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 - - #if !USING_FSTREAM_DIRECTIVE - 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); - #else - std::ifstream pchtxtFile(pchtxtPath); - if (!pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; - } - - std::string pchtxt((std::istreambuf_iterator(pchtxtFile)), std::istreambuf_iterator()); - #endif - - 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; - } - - #if !USING_FSTREAM_DIRECTIVE - 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); - } - #else - std::ifstream existingCheatFile(cheatFilePath); - bool cheatNameExists = false; - if (existingCheatFile) { - std::string line; - while (std::getline(existingCheatFile, line)) { - if (line == "[" + cheatName + "]") { - cheatNameExists = true; - break; - } - } - } - existingCheatFile.close(); - #endif - - // Open output cheat file - #if !USING_FSTREAM_DIRECTIVE - 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; - } - #else - std::ofstream outCheatFile(cheatFilePath, std::ios::app); - if (!outCheatFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create cheat file " + cheatFilePath); - #endif - return false; - } - #endif - - if (!cheatNameExists) { - #if !USING_FSTREAM_DIRECTIVE - fprintf(outCheatFile, "[%s]\n", cheatName.c_str()); - #else - outCheatFile << "[" << cheatName << "]\n"; - #endif - } - - 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); - - #if !USING_FSTREAM_DIRECTIVE - // 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 - } - #else - if (!cheatExists(cheatFilePath, cheatLine)) { - outCheatFile << cheatLine << "\n"; - validCheatsProcessed++; // ADDED: Increment counter for new cheats - } - #endif - } - - #if !USING_FSTREAM_DIRECTIVE - fclose(outCheatFile); - #else - outCheatFile.close(); - #endif - - // 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; - } - - - // Corrected helper function to convert values to big-endian format - //uint32_t toBigEndian(uint32_t value) { - // return ((value & 0x000000FF) << 24) | - // ((value & 0x0000FF00) << 8) | - // ((value & 0x00FF0000) >> 8) | - // ((value & 0xFF000000) >> 24); - //} - // - //uint16_t toBigEndian(uint16_t value) { - // return ((value & 0x00FF) << 8) | - // ((value & 0xFF00) >> 8); - //} - - // Helper function to convert a vector of bytes to a hex string for logging - - //std::string hexToString(const std::vector& bytes) { - // StringStream oss; // Use your custom StringStream - // oss.hex(); // Enable hex mode for the stream - // - // for (uint8_t byte : bytes) { - // if (byte < 0x10) { - // oss << "0"; // Append leading zero for single-digit hex values - // } - // oss << static_cast(byte); // Convert byte to int and then append it - // } - // - // return oss.str(); // Return the final hex string - //} - - - - - - /** - * @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) { - #if !USING_FSTREAM_DIRECTIVE - // 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); - - #else - // Use fstream for reading - std::ifstream pchtxtFile(pchtxtPath); - if (!pchtxtFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to open file " + pchtxtPath); - #endif - return false; - } - - std::vector>> patches; - std::string line; - uint32_t lineNum = 0; - std::string nsobid; - int offset = 0; // Default offset - - uint32_t address; - uint8_t byte; - std::vector valueBytes; - std::string offsetStr; - - while (std::getline(pchtxtFile, line)) { - ++lineNum; - if (line.empty() || line.front() == '@') { - 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("@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(); - } - - pchtxtFile.close(); - #endif - - // 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; - - #if !USING_FSTREAM_DIRECTIVE - // 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 - } - #else - // Use fstream for writing - std::ofstream ipsFile(ipsFilePath, std::ios::binary); - if (!ipsFile) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create IPS file " + ipsFilePath); - #endif - return false; - } - - ipsFile.write(IPS32_HEAD_MAGIC, std::strlen(IPS32_HEAD_MAGIC)); - - uint16_t valueLength; - uint32_t bigEndianAddress; - for (const auto& patch : patches) { - bigEndianAddress = toBigEndian(patch.first); // Convert address to big-endian - ipsFile.write(reinterpret_cast(&bigEndianAddress), sizeof(bigEndianAddress)); // Write address - - valueLength = toBigEndian(static_cast(patch.second.size())); // Convert length to big-endian - ipsFile.write(reinterpret_cast(&valueLength), sizeof(valueLength)); // Write length of value - - ipsFile.write(reinterpret_cast(patch.second.data()), patch.second.size()); // Write value - } - - ipsFile.write(IPS32_FOOT_MAGIC, std::strlen(IPS32_FOOT_MAGIC)); - ipsFile.close(); - - - std::ifstream _pchtxtFile(pchtxtPath); - 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 - } - - std::string pchtxt((std::istreambuf_iterator(_pchtxtFile)), std::istreambuf_iterator()); - - const std::string tid = findTitleID(pchtxt); - if (!tid.empty()) { - const std::string tidFilePath = outputFolder + tid; - std::ofstream tidFile(tidFilePath); - tidFile.close(); // Creates an empty file - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Warning: Could not find Title ID in " + pchtxtPath); - #endif - } - #endif - - return true; - } - -} diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp deleted file mode 100644 index b4e47670..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp +++ /dev/null @@ -1,1522 +0,0 @@ -/******************************************************************************** - * 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-2025 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 - } - } - - #if !USING_FSTREAM_DIRECTIVE - 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 - } - } - #else - void writeLog(std::ofstream& logFile, const std::string& line) { - if (logFile.is_open()) { - std::lock_guard lock(logMutex2); - logFile << line << std::endl; - logFile.flush(); // Ensure data is written immediately - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Failed to write to log file."); - #endif - } - } - #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)); - - #if !USING_FSTREAM_DIRECTIVE - 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 - } - #else - std::ofstream file(filePath); - if (file.is_open()) { - file << content; - file.close(); - } else { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Unable to create file " + filePath); - #endif - } - #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()) { - #if !USING_FSTREAM_DIRECTIVE - 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 - #else - createDirectory(getParentDirFromPath(logSource)); - std::ofstream logSourceFile(logSource, std::ios::app); - if (logSourceFile.is_open()) { - writeLog(logSourceFile, pathToDelete); - logSourceFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open source log file: " + logSource); - } - #endif - #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()) { - #if !USING_FSTREAM_DIRECTIVE - 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 - #else - createDirectory(getParentDirFromPath(logSource)); - std::ofstream logSourceFile(logSource, std::ios::app); - if (logSourceFile.is_open()) { - for (const auto& deletedPath : successfulDeletions) { - writeLog(logSourceFile, deletedPath); - } - logSourceFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open source log file: " + logSource); - } - #endif - #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; - } - - //bool hasContent = false; - 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; - } - - //hasContent = true; - - // 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 !USING_FSTREAM_DIRECTIVE - 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 - } - #else - if (!logSource.empty()) { - createDirectory(getParentDirFromPath(logSource)); - std::ofstream logSourceFile(logSource, std::ios::app); - if (logSourceFile.is_open()) { - writeLog(logSourceFile, sourcePath); - logSourceFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open source log file: " + logSource); - } - #endif - } - - if (!logDestination.empty()) { - createDirectory(getParentDirFromPath(logDestination)); - std::ofstream logDestFile(logDestination, std::ios::app); - if (logDestFile.is_open()) { - writeLog(logDestFile, finalDestPath); - logDestFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open destination log file: " + logDestination); - } - #endif - } - #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]); - - #if !USING_FSTREAM_DIRECTIVE - 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; - } - - #else - std::ifstream srcFile; - std::ofstream destFile; - - // Retry loop for file opening - for (size_t retryCount = 0; retryCount <= maxRetries; ++retryCount) { - srcFile.open(fromFile, std::ios::binary); - destFile.open(toFile, std::ios::binary); - - if (srcFile.is_open() && destFile.is_open()) { - break; - } - - srcFile.close(); - destFile.close(); - - if (retryCount == maxRetries) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error: Failed to open files after " + std::to_string(maxRetries) + " retries"); - #endif - return; - } - } - - // Main copy loop - char* bufferPtr = buffer.get(); - while (srcFile.read(bufferPtr, bufferSize) || srcFile.gcount() > 0) { - if (abortFileOp.load(std::memory_order_acquire)) { - srcFile.close(); - destFile.close(); - remove(toFile.c_str()); - copyPercentage.store(-1, std::memory_order_release); - return; - } - - std::streamsize bytesToWrite = srcFile.gcount(); - destFile.write(bufferPtr, bytesToWrite); - - if (!destFile.good()) { - #if USING_LOGGING_DIRECTIVE - if (!disableLogging) - logMessage("Error writing to destination file"); - #endif - srcFile.close(); - destFile.close(); - remove(toFile.c_str()); - copyPercentage.store(-1, std::memory_order_release); - return; - } - - totalBytesCopied += bytesToWrite; - if (totalSize > 0) { - copyPercentage.store(static_cast(100 * totalBytesCopied / totalSize), std::memory_order_release); - } - } - - srcFile.close(); - destFile.close(); - #endif - - // 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 !USING_FSTREAM_DIRECTIVE - 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 - } - #else - if (!logSource.empty()) { - createDirectory(getParentDirFromPath(logSource)); - std::ofstream logSourceFile(logSource, std::ios::app); - if (logSourceFile.is_open()) { - writeLog(logSourceFile, logFromPath); - logSourceFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open source log file: " + logSource); - } - #endif - } - - if (!logDestination.empty()) { - createDirectory(getParentDirFromPath(logDestination)); - std::ofstream logDestFile(logDestination, std::ios::app); - if (logDestFile.is_open()) { - writeLog(logDestFile, logToPath); - logDestFile.close(); - } - #if USING_LOGGING_DIRECTIVE - else { - if (!disableLogging) - logMessage("Failed to open destination log file: " + logDestination); - } - #endif - } - #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()); - //logMessage("mirror-delete: "+path+" "+updatedPath); - if (mode == "delete") - deleteFileOrDirectory(updatedPath); - else if (mode == "copy") { - if (path != updatedPath) - copyFileOrDirectory(path, updatedPath, &totalBytesCopied, totalSize); - } - path = ""; - } - //fileList.clear(); - 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. - * Uses FILE* if !USING_FSTREAM_DIRECTIVE is defined, otherwise uses std::ofstream. - * - * @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; - - #if !USING_FSTREAM_DIRECTIVE - FileGuard fp(std::fopen(outFile.c_str(), "wb")); - // File automatically closed by FileGuard destructor - #else - std::ofstream ofs(outFile, std::ios::binary | std::ios::trunc); - ofs.close(); - #endif - 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/sys-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp deleted file mode 100644 index 9738df36..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp +++ /dev/null @@ -1,641 +0,0 @@ -/******************************************************************************** - * 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-2025 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); - } - - - //bool canConvertToInt(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; - //} - - - // 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 Replaces multiple consecutive slashes with a single slash in a string. - * - * This function replaces sequences of two or more consecutive slashes with a single slash in the input string. - * - * @param input The input string to process. - * @return The string with multiple slashes replaced. - */ - //std::string replaceMultipleSlashes(const std::string& input) { - // std::string output; - // output.reserve(input.size()); // Reserve space for the output string - // - // bool previousSlash = false; - // for (char c : input) { - // if (c == '/') { - // if (!previousSlash) { - // output.push_back(c); - // } - // previousSlash = true; - // } else { - // output.push_back(c); - // previousSlash = false; - // } - // } - // - // return output; - //} - - - - /** - * @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); - } - - - - //std::string addQuotesIfNeeded(const std::string& str) { - // if (str.find(' ') != std::string::npos) { - // return "\"" + str + "\""; - // } - // return str; - //} - - - /** - * @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; - //std::transform(result.begin(), result.end(), result.begin(), - // [](unsigned char c) { return std::tolower(c); }); - //return result; - 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; - } - - //#if IS_LAUNCHER_DIRECTIVE - //std::string inputExists(const std::string& input) { - // std::string e; - // for (char c : input) { - // e += (c + 5); - // } - // return e; - //} - //#endif -} diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp deleted file mode 100644 index 9da62f8e..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp +++ /dev/null @@ -1,1882 +0,0 @@ -/******************************************************************************** - * 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-2025 ppkantorski - ********************************************************************************/ - -#include - -#include -extern "C" { // assertion override - void __assert_func(const char *_file, int _line, const char *_func, const char *_expr ) { - abort(); - } -} - -namespace ult { - - 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); - //std::mutex simulatedNextPageMutex; - - // Helper function to read file content into a string - bool readFileContent(const std::string& filePath, std::string& content) { - #if !USING_FSTREAM_DIRECTIVE - 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); - #else - std::ifstream file(filePath); - if (!file.is_open()) { - #if USING_LOGGING_DIRECTIVE - logMessage("Failed to open JSON file: " + filePath); - #endif - return false; - } - content.assign(std::istreambuf_iterator(file), std::istreambuf_iterator()); - file.close(); - #endif - - 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); - } - - - 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); - } - - //static bool pminfoInitialized = false; - //static u64 lastPid = 0; - //static u64 lastTid = 0; - // - //std::string getTitleIdAsString() { - // Result rc; - // u64 pid = 0; - // u64 tid = 0; - // - // // Get the current application PID - // rc = pmdmntGetApplicationProcessId(&pid); - // if (R_FAILED(rc) || pid == 0) { - // return NULL_STR; - // } - // - // // If it's the same PID as last time, return cached TID - // if (pid == lastPid && lastTid != 0) { - // char cachedTidStr[17]; - // snprintf(cachedTidStr, sizeof(cachedTidStr), "%016lX", lastTid); - // return std::string(cachedTidStr); - // } - // - // // Initialize pminfo if not already - // if (!pminfoInitialized) { - // rc = pminfoInitialize(); - // if (R_FAILED(rc)) { - // return NULL_STR; - // } - // pminfoInitialized = true; - // } - // - // // Retrieve the TID (Program ID) - // rc = pminfoGetProgramId(&tid, pid); - // if (R_FAILED(rc)) { - // return NULL_STR; - // } - // - // lastPid = pid; - // lastTid = tid; - // - // char titleIdStr[17]; - // snprintf(titleIdStr, sizeof(titleIdStr), "%016lX", tid); - // return std::string(titleIdStr); - //} - - //std::string getProcessIdAsString() { - // u64 pid = 0; - // if (R_FAILED(pmdmntGetApplicationProcessId(&pid))) - // return NULL_STR; - // - // char pidStr[21]; // Max u64 is 20 digits + null terminator - // snprintf(pidStr, sizeof(pidStr), "%llu", pid); - // return std::string(pidStr); - //} - - std::string getBuildIdAsString() { - u64 pid = 0; - if (R_FAILED(pmdmntGetApplicationProcessId(&pid))) - return NULL_STR; - - Service srv; - if (R_FAILED(smGetService(&srv, "dmnt:cht"))) - return NULL_STR; - - if (R_FAILED(serviceDispatch(&srv, 65003))) { - serviceClose(&srv); - return NULL_STR; - } - - struct { - u64 process_id; - u64 title_id; - struct { u64 base; u64 size; } main_nso_extents; - struct { u64 base; u64 size; } heap_extents; - struct { u64 base; u64 size; } alias_extents; - struct { u64 base; u64 size; } address_space_extents; - u8 main_nso_build_id[0x20]; - } metadata; - - Result rc = serviceDispatchOut(&srv, 65002, metadata); - serviceClose(&srv); - - if (R_FAILED(rc)) - return NULL_STR; - - u64 buildid; - std::memcpy(&buildid, metadata.main_nso_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 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 - - // Define the duration boundaries (for smooth scrolling) - //const std::chrono::milliseconds initialInterval = std::chrono::milliseconds(67); // Example initial interval - //const std::chrono::milliseconds shortInterval = std::chrono::milliseconds(10); // Short interval after long hold - //const std::chrono::milliseconds transitionPoint = std::chrono::milliseconds(2000); // Point at which the shortest interval is reached - - // Function to interpolate between two durations - //std::chrono::milliseconds interpolateDuration(std::chrono::milliseconds start, std::chrono::milliseconds end, float t) { - // using namespace std::chrono; - // auto interpolated = start.count() + static_cast((end.count() - start.count()) * t); - // return milliseconds(interpolated); - //} - - - - //#include // Comment out filesystem - - // CUSTOM SECTION START - //float backWidth, selectWidth, nextPageWidth; - 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}; - - bool firstBoot = true; // for detecting first boot - - //std::unordered_map hexSumCache; - - // 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 progressAnimation = false; - bool disableTransparency = false; - //bool useCustomWallpaper = false; - //bool useMemoryExpansion = 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; - - - //void convertComboToUnicode(std::string& combo); - - - 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" } - }}; - - 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}; - - #if IS_LAUNCHER_DIRECTIVE - std::string ENGLISH = "English"; - std::string SPANISH = "Spanish"; - std::string FRENCH = "French"; - std::string GERMAN = "German"; - std::string JAPANESE = "Japanese"; - std::string KOREAN = "Korean"; - std::string ITALIAN = "Italian"; - std::string DUTCH = "Dutch"; - std::string PORTUGUESE = "Portuguese"; - std::string RUSSIAN = "Russian"; - std::string UKRAINIAN = "Ukrainian"; - std::string POLISH = "Polish"; - std::string SIMPLIFIED_CHINESE = "Simplified Chinese"; - std::string TRADITIONAL_CHINESE = "Traditional Chinese"; - std::string OVERLAYS = "Overlays"; //defined in libTesla now - std::string OVERLAYS_ABBR = "Overlays"; - std::string OVERLAY = "Overlay"; - std::string HIDDEN_OVERLAYS = "Hidden Overlays"; - std::string PACKAGES = "Packages"; //defined in libTesla now - std::string PACKAGE = "Package"; - std::string HIDDEN_PACKAGES = "Hidden Packages"; - std::string HIDDEN = "Hidden"; - std::string HIDE_OVERLAY = "Hide Overlay"; - std::string HIDE_PACKAGE = "Hide Package"; - std::string LAUNCH_ARGUMENTS = "Launch Arguments"; - std::string FORCE_AMS110_SUPPORT = "Force AMS110+ Support"; - std::string QUICK_LAUNCH = "Quick Launch"; - std::string BOOT_COMMANDS = "Boot Commands"; - std::string EXIT_COMMANDS = "Exit Commands"; - std::string ERROR_LOGGING = "Error Logging"; - std::string COMMANDS = "Commands"; - std::string SETTINGS = "Settings"; - std::string FAVORITE = "Favorite"; - std::string MAIN_SETTINGS = "Main Settings"; - std::string UI_SETTINGS = "UI Settings"; - - std::string WIDGET = "Widget"; - std::string WIDGET_ITEMS = "Widget Items"; - std::string WIDGET_SETTINGS = "Widget Settings"; - std::string CLOCK = "Clock"; - std::string BATTERY = "Battery"; - std::string SOC_TEMPERATURE = "SOC Temperature"; - std::string PCB_TEMPERATURE = "PCB Temperature"; - std::string BACKDROP = "Backdrop"; - std::string DYNAMIC_COLORS = "Dynamic Colors"; - std::string CENTER_ALIGNMENT = "Center Alignment"; - std::string EXTENDED_BACKDROP = "Extended Backdrop"; - std::string MISCELLANEOUS = "Miscellaneous"; - //std::string MENU_ITEMS = "Menu Items"; - std::string MENU_SETTINGS = "Menu Settings"; - std::string USER_GUIDE = "User Guide"; - std::string SHOW_HIDDEN = "Show Hidden"; - std::string SHOW_DELETE = "Show Delete"; - std::string SHOW_UNSUPPORTED = "Show Unsupported"; - std::string PAGE_SWAP = "Page Swap"; - std::string RIGHT_SIDE_MODE = "Right-side Mode"; - std::string OVERLAY_VERSIONS = "Overlay Versions"; - std::string PACKAGE_VERSIONS = "Package Versions"; - std::string CLEAN_VERSIONS = "Clean Versions"; - //std::string VERSION_LABELS = "Version Labels"; - std::string KEY_COMBO = "Key Combo"; - std::string MODE = "Mode"; - std::string LAUNCH_MODES = "Launch Modes"; - std::string LANGUAGE = "Language"; - std::string OVERLAY_INFO = "Overlay Info"; - std::string SOFTWARE_UPDATE = "Software Update"; - std::string UPDATE_ULTRAHAND = "Update Ultrahand"; - std::string UPDATE_LANGUAGES = "Update Languages"; - std::string SYSTEM = "System"; - std::string DEVICE_INFO = "Device Info"; - std::string FIRMWARE = "Firmware"; - std::string BOOTLOADER = "Bootloader"; - std::string HARDWARE = "Hardware"; - std::string MEMORY = "Memory"; - std::string VENDOR = "Vendor"; - std::string MODEL = "Model"; - std::string STORAGE = "Storage"; - //std::string NOTICE = "Notice"; - //std::string UTILIZES = "Utilizes"; - - - std::string OVERLAY_MEMORY = "Overlay Memory"; - std::string NOT_ENOUGH_MEMORY = "Not enough memory."; - std::string WALLPAPER_SUPPORT_DISABLED = "Wallpaper support disabled."; - std::string SOUND_SUPPORT_DISABLED = "Sound support disabled."; - std::string WALLPAPER_SUPPORT_ENABLED = "Wallpaper support enabled."; - std::string SOUND_SUPPORT_ENABLED = "Sound support enabled."; - std::string EXIT_OVERLAY_SYSTEM = "Exit Overlay System"; - - //std::string MEMORY_EXPANSION = "Memory Expansion"; - //std::string REBOOT_REQUIRED = "*Reboot required."; - std::string LOCAL_IP = "Local IP"; - std::string WALLPAPER = "Wallpaper"; - std::string THEME = "Theme"; - std::string DEFAULT = "default"; - std::string ROOT_PACKAGE = "Root Package"; - std::string SORT_PRIORITY = "Sort Priority"; - std::string OPTIONS = "Options"; - std::string FAILED_TO_OPEN = "Failed to open file"; - std::string LAUNCH_COMBOS = "Launch Combos"; - std::string NOTIFICATIONS = "Notifications"; - std::string SOUND_EFFECTS = "Sound Effects"; - std::string HAPTIC_FEEDBACK = "Haptic Feedback"; - std::string OPAQUE_SCREENSHOTS = "Opaque Screenshots"; - - std::string PACKAGE_INFO = "Package Info"; - std::string _TITLE = "Title"; - std::string _VERSION= "Version"; - std::string _CREATOR = "Creator(s)"; - std::string _ABOUT = "About"; - std::string _CREDITS = "Credits"; - - std::string USERGUIDE_OFFSET = "177"; - std::string SETTINGS_MENU = "Settings Menu"; - std::string SCRIPT_OVERLAY = "Script Overlay"; - std::string STAR_FAVORITE = "Star/Favorite"; - std::string APP_SETTINGS = "App Settings"; - std::string ON_MAIN_MENU = "on Main Menu"; - std::string ON_A_COMMAND = "on a command"; - std::string ON_OVERLAY_PACKAGE = "on overlay/package"; - std::string FEATURES = "Features"; - std::string SWIPE_TO_OPEN = "Swipe to Open"; - - std::string THEME_SETTINGS = "Theme Settings"; - std::string DYNAMIC_LOGO = "Dynamic Logo"; - std::string SELECTION_BACKGROUND = "Selection Background"; - std::string SELECTION_TEXT = "Selection Text"; - std::string SELECTION_VALUE = "Selection Value"; - std::string LIBULTRAHAND_TITLES = "libultrahand Titles"; - std::string LIBULTRAHAND_VERSIONS = "libultrahand Versions"; - std::string PACKAGE_TITLES = "Package Titles"; - - std::string ULTRAHAND_HAS_STARTED = "Ultrahand has started."; - std::string NEW_UPDATE_IS_AVAILABLE = "New update is available!"; - //std::string REBOOT_IS_REQUIRED = "Reboot is required."; - //std::string HOLD_A_TO_DELETE = "Hold \uE0E0 to Delete"; - std::string DELETE_PACKAGE = "Delete Package"; - std::string DELETE_OVERLAY = "Delete Overlay"; - std::string SELECTION_IS_EMPTY = "Selection is empty!"; - std::string FORCED_SUPPORT_WARNING = "Forcing support can be dangerous."; - - std::string TASK_IS_COMPLETE = "Task is complete!"; - std::string TASK_HAS_FAILED = "Task has failed."; - - //std::string PACKAGE_VERSIONS = "Package Versions"; - - //std::string PROGRESS_ANIMATION = "Progress Animation"; - - std::string REBOOT_TO = "Reboot To"; - std::string REBOOT = "Reboot"; - std::string SHUTDOWN = "Shutdown"; - std::string BOOT_ENTRY = "Boot Entry"; - #endif - - std::string INCOMPATIBLE_WARNING = "Incompatible on AMS v1.10+"; - std::string SYSTEM_RAM = "System RAM"; - std::string FREE = "free"; - - std::string DEFAULT_CHAR_WIDTH = "0.33"; - std::string UNAVAILABLE_SELECTION = "Not available"; - - - std::string ON = "On"; - std::string OFF = "Off"; - - std::string OK = "OK"; - std::string BACK = "Back"; - std::string HIDE = "Hide"; - std::string CANCEL = "Cancel"; - - std::string GAP_1 = " "; - std::string GAP_2 = " "; - - std::atomic halfGap = 0.0f; - - - //std::string EMPTY = "Empty"; - - #if USING_WIDGET_DIRECTIVE - std::string SUNDAY = "Sunday"; - std::string MONDAY = "Monday"; - std::string TUESDAY = "Tuesday"; - std::string WEDNESDAY = "Wednesday"; - std::string THURSDAY = "Thursday"; - std::string FRIDAY = "Friday"; - std::string SATURDAY = "Saturday"; - - std::string JANUARY = "January"; - std::string FEBRUARY = "February"; - std::string MARCH = "March"; - std::string APRIL = "April"; - std::string MAY = "May"; - std::string JUNE = "June"; - std::string JULY = "July"; - std::string AUGUST = "August"; - std::string SEPTEMBER = "September"; - std::string OCTOBER = "October"; - std::string NOVEMBER = "November"; - std::string DECEMBER = "December"; - - std::string SUN = "Sun"; - std::string MON = "Mon"; - std::string TUE = "Tue"; - std::string WED = "Wed"; - std::string THU = "Thu"; - std::string FRI = "Fri"; - std::string SAT = "Sat"; - - std::string JAN = "Jan"; - std::string FEB = "Feb"; - std::string MAR = "Mar"; - std::string APR = "Apr"; - std::string MAY_ABBR = "May"; - std::string JUN = "Jun"; - std::string JUL = "Jul"; - std::string AUG = "Aug"; - std::string SEP = "Sep"; - std::string OCT = "Oct"; - std::string NOV = "Nov"; - std::string DEC = "Dec"; - #endif - - - #if IS_LAUNCHER_DIRECTIVE - // Constant string definitions (English) - void reinitializeLangVars() { - ENGLISH = "English"; - SPANISH = "Spanish"; - FRENCH = "French"; - GERMAN = "German"; - JAPANESE = "Japanese"; - KOREAN = "Korean"; - ITALIAN = "Italian"; - DUTCH = "Dutch"; - PORTUGUESE = "Portuguese"; - RUSSIAN = "Russian"; - UKRAINIAN = "Ukrainian"; - POLISH = "Polish"; - SIMPLIFIED_CHINESE = "Simplified Chinese"; - TRADITIONAL_CHINESE = "Traditional Chinese"; - DEFAULT_CHAR_WIDTH = "0.33"; - UNAVAILABLE_SELECTION = "Not available"; - OVERLAYS = "Overlays"; //defined in libTesla now - OVERLAYS_ABBR = "Overlays"; - OVERLAY = "Overlay"; - HIDDEN_OVERLAYS = "Hidden Overlays"; - PACKAGES = "Packages"; //defined in libTesla now - PACKAGE = "Package"; - HIDDEN_PACKAGES = "Hidden Packages"; - HIDDEN = "Hidden"; - HIDE_OVERLAY = "Hide Overlay"; - HIDE_PACKAGE = "Hide Package"; - LAUNCH_ARGUMENTS = "Launch Arguments"; - FORCE_AMS110_SUPPORT = "Force AMS110+ Support"; - QUICK_LAUNCH = "Quick Launch"; - BOOT_COMMANDS = "Boot Commands"; - EXIT_COMMANDS = "Exit Commands"; - ERROR_LOGGING = "Error Logging"; - COMMANDS = "Commands"; - SETTINGS = "Settings"; - FAVORITE = "Favorite"; - MAIN_SETTINGS = "Main Settings"; - UI_SETTINGS = "UI Settings"; - WIDGET = "Widget"; - WIDGET_ITEMS = "Widget Items"; - WIDGET_SETTINGS = "Widget Settings"; - CLOCK = "Clock"; - BATTERY = "Battery"; - SOC_TEMPERATURE = "SOC Temperature"; - PCB_TEMPERATURE = "PCB Temperature"; - BACKDROP = "Backdrop"; - DYNAMIC_COLORS = "Dynamic Colors"; - CENTER_ALIGNMENT = "Center Alignment"; - EXTENDED_BACKDROP = "Extended Backdrop"; - MISCELLANEOUS = "Miscellaneous"; - //MENU_ITEMS = "Menu Items"; - MENU_SETTINGS = "Menu Settings"; - USER_GUIDE = "User Guide"; - SHOW_HIDDEN = "Show Hidden"; - SHOW_DELETE = "Show Delete"; - SHOW_UNSUPPORTED = "Show Unsupported"; - PAGE_SWAP = "Page Swap"; - RIGHT_SIDE_MODE = "Right-side Mode"; - OVERLAY_VERSIONS = "Overlay Versions"; - PACKAGE_VERSIONS = "Package Versions"; - CLEAN_VERSIONS = "Clean Versions"; - //VERSION_LABELS = "Version Labels"; - KEY_COMBO = "Key Combo"; - MODE = "Mode"; - LAUNCH_MODES = "Launch Modes"; - LANGUAGE = "Language"; - OVERLAY_INFO = "Overlay Info"; - SOFTWARE_UPDATE = "Software Update"; - UPDATE_ULTRAHAND = "Update Ultrahand"; - UPDATE_LANGUAGES = "Update Languages"; - SYSTEM = "System"; - DEVICE_INFO = "Device Info"; - FIRMWARE = "Firmware"; - BOOTLOADER = "Bootloader"; - HARDWARE = "Hardware"; - MEMORY = "Memory"; - VENDOR = "Vendor"; - MODEL = "Model"; - STORAGE = "Storage"; - //NOTICE = "Notice"; - //UTILIZES = "Utilizes"; - SYSTEM_RAM = "System RAM"; - FREE = "free"; - - OVERLAY_MEMORY = "Overlay Memory"; - NOT_ENOUGH_MEMORY = "Not enough memory."; - WALLPAPER_SUPPORT_DISABLED = "Wallpaper support disabled."; - SOUND_SUPPORT_DISABLED = "Sound support disabled."; - WALLPAPER_SUPPORT_ENABLED = "Wallpaper support enabled."; - SOUND_SUPPORT_ENABLED = "Sound support enabled."; - EXIT_OVERLAY_SYSTEM = "Exit Overlay System"; - - //MEMORY_EXPANSION = "Memory Expansion"; - //REBOOT_REQUIRED = "*Reboot required."; - LOCAL_IP = "Local IP"; - WALLPAPER = "Wallpaper"; - THEME = "Theme"; - DEFAULT = "default"; - ROOT_PACKAGE = "Root Package"; - SORT_PRIORITY = "Sort Priority"; - OPTIONS = "Options"; - FAILED_TO_OPEN = "Failed to open file"; - - LAUNCH_COMBOS = "Launch Combos"; - NOTIFICATIONS = "Notifications"; - SOUND_EFFECTS = "Sound Effects"; - HAPTIC_FEEDBACK = "Haptic Feedback"; - OPAQUE_SCREENSHOTS = "Opaque Screenshots"; - ON = "On"; - OFF = "Off"; - PACKAGE_INFO = "Package Info"; - _TITLE = "Title"; - _VERSION= "Version"; - _CREATOR = "Creator(s)"; - _ABOUT = "About"; - _CREDITS = "Credits"; - OK = "OK"; - BACK = "Back"; - HIDE = "Hide"; - CANCEL = "Cancel"; - - REBOOT_TO = "Reboot To"; - REBOOT = "Reboot"; - SHUTDOWN = "Shutdown"; - BOOT_ENTRY = "Boot Entry"; - GAP_1 = " "; - GAP_2 = " "; - - USERGUIDE_OFFSET = "177"; - SETTINGS_MENU = "Settings Menu"; - SCRIPT_OVERLAY = "Script Overlay"; - STAR_FAVORITE = "Star/Favorite"; - APP_SETTINGS = "App Settings"; - ON_MAIN_MENU = "on Main Menu"; - ON_A_COMMAND = "on a command"; - ON_OVERLAY_PACKAGE = "on overlay/package"; - FEATURES = "Features"; - SWIPE_TO_OPEN = "Swipe to Open"; - //PROGRESS_ANIMATION = "Progress Animation"; - - THEME_SETTINGS = "Theme Settings"; - DYNAMIC_LOGO = "Dynamic Logo"; - SELECTION_BACKGROUND = "Selection Background"; - SELECTION_TEXT = "Selection Text"; - SELECTION_VALUE = "Selection Value"; - LIBULTRAHAND_TITLES = "libultrahand Titles"; - LIBULTRAHAND_VERSIONS = "libultrahand Versions"; - PACKAGE_TITLES = "Package Titles"; - //PACKAGE_VERSIONS = "Package Versions"; - - ULTRAHAND_HAS_STARTED = "Ultrahand has started."; - NEW_UPDATE_IS_AVAILABLE = "New update is available!"; - //REBOOT_IS_REQUIRED = "Reboot is required."; - //HOLD_A_TO_DELETE = "Hold  to Delete"; - DELETE_PACKAGE = "Delete Package"; - DELETE_OVERLAY = "Delete Overlay"; - SELECTION_IS_EMPTY = "Selection is empty!"; - FORCED_SUPPORT_WARNING = "Forcing support can be dangerous."; - INCOMPATIBLE_WARNING = "Incompatible on AMS v1.10+"; - TASK_IS_COMPLETE = "Task is complete!"; - TASK_HAS_FAILED = "Task has failed."; - - //EMPTY = "Empty"; - - SUNDAY = "Sunday"; - MONDAY = "Monday"; - TUESDAY = "Tuesday"; - WEDNESDAY = "Wednesday"; - THURSDAY = "Thursday"; - FRIDAY = "Friday"; - SATURDAY = "Saturday"; - - JANUARY = "January"; - FEBRUARY = "February"; - MARCH = "March"; - APRIL = "April"; - MAY = "May"; - 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_ABBR = "May"; - JUN = "Jun"; - JUL = "Jul"; - AUG = "Aug"; - SEP = "Sep"; - OCT = "Oct"; - NOV = "Nov"; - DEC = "Dec"; - } - #endif - - - - // Function to update a constant if the new value from JSON is not empty - void updateIfNotEmpty(std::string& constant, const std::string& newValue) { - if (!newValue.empty()) { - constant = newValue; - } - } - - void parseLanguage(const std::string& langFile) { - // Map to store parsed JSON data - std::unordered_map jsonMap; - if (!parseJsonToMap(langFile, jsonMap)) { - #if USING_LOGGING_DIRECTIVE - logMessage("Failed to parse language file: " + langFile); - #endif - return; - } - - - std::unordered_map configMap = { - #if IS_LAUNCHER_DIRECTIVE - {"ENGLISH", &ENGLISH}, - {"SPANISH", &SPANISH}, - {"FRENCH", &FRENCH}, - {"GERMAN", &GERMAN}, - {"JAPANESE", &JAPANESE}, - {"KOREAN", &KOREAN}, - {"ITALIAN", &ITALIAN}, - {"DUTCH", &DUTCH}, - {"PORTUGUESE", &PORTUGUESE}, - {"RUSSIAN", &RUSSIAN}, - {"UKRAINIAN", &UKRAINIAN}, - {"POLISH", &POLISH}, - {"SIMPLIFIED_CHINESE", &SIMPLIFIED_CHINESE}, - {"TRADITIONAL_CHINESE", &TRADITIONAL_CHINESE}, - {"OVERLAYS", &OVERLAYS}, - {"OVERLAYS_ABBR", &OVERLAYS_ABBR}, - {"OVERLAY", &OVERLAY}, - {"HIDDEN_OVERLAYS", &HIDDEN_OVERLAYS}, - {"PACKAGES", &PACKAGES}, - {"PACKAGE", &PACKAGE}, - {"HIDDEN_PACKAGES", &HIDDEN_PACKAGES}, - {"HIDDEN", &HIDDEN}, - {"HIDE_PACKAGE", &HIDE_PACKAGE}, - {"HIDE_OVERLAY", &HIDE_OVERLAY}, - {"LAUNCH_ARGUMENTS", &LAUNCH_ARGUMENTS}, - {"FORCE_AMS110_SUPPORT", &FORCE_AMS110_SUPPORT}, - {"QUICK_LAUNCH", &QUICK_LAUNCH}, - {"BOOT_COMMANDS", &BOOT_COMMANDS}, - {"EXIT_COMMANDS", &EXIT_COMMANDS}, - {"ERROR_LOGGING", &ERROR_LOGGING}, - {"COMMANDS", &COMMANDS}, - {"SETTINGS", &SETTINGS}, - {"FAVORITE", &FAVORITE}, - {"MAIN_SETTINGS", &MAIN_SETTINGS}, - {"UI_SETTINGS", &UI_SETTINGS}, - - {"WIDGET", &WIDGET}, - {"WIDGET_ITEMS", &WIDGET_ITEMS}, - {"WIDGET_SETTINGS", &WIDGET_SETTINGS}, - {"CLOCK", &CLOCK}, - {"BATTERY", &BATTERY}, - {"SOC_TEMPERATURE", &SOC_TEMPERATURE}, - {"PCB_TEMPERATURE", &PCB_TEMPERATURE}, - {"BACKDROP", &BACKDROP}, - {"DYNAMIC_COLORS", &DYNAMIC_COLORS}, - {"CENTER_ALIGNMENT", &CENTER_ALIGNMENT}, - {"EXTENDED_BACKDROP", &EXTENDED_BACKDROP}, - {"MISCELLANEOUS", &MISCELLANEOUS}, - //{"MENU_ITEMS", &MENU_ITEMS}, - {"MENU_SETTINGS", &MENU_SETTINGS}, - {"USER_GUIDE", &USER_GUIDE}, - {"SHOW_HIDDEN", &SHOW_HIDDEN}, - {"SHOW_DELETE", &SHOW_DELETE}, - {"SHOW_UNSUPPORTED", &SHOW_UNSUPPORTED}, - {"PAGE_SWAP", &PAGE_SWAP}, - {"RIGHT_SIDE_MODE", &RIGHT_SIDE_MODE}, - {"OVERLAY_VERSIONS", &OVERLAY_VERSIONS}, - {"PACKAGE_VERSIONS", &PACKAGE_VERSIONS}, - {"CLEAN_VERSIONS", &CLEAN_VERSIONS}, - //{"VERSION_LABELS", &VERSION_LABELS}, - {"KEY_COMBO", &KEY_COMBO}, - {"MODE", &MODE}, - {"LAUNCH_MODES", &LAUNCH_MODES}, - {"LANGUAGE", &LANGUAGE}, - {"OVERLAY_INFO", &OVERLAY_INFO}, - {"SOFTWARE_UPDATE", &SOFTWARE_UPDATE}, - {"UPDATE_ULTRAHAND", &UPDATE_ULTRAHAND}, - {"UPDATE_LANGUAGES", &UPDATE_LANGUAGES}, - {"SYSTEM", &SYSTEM}, - {"DEVICE_INFO", &DEVICE_INFO}, - {"FIRMWARE", &FIRMWARE}, - {"BOOTLOADER", &BOOTLOADER}, - {"HARDWARE", &HARDWARE}, - {"MEMORY", &MEMORY}, - {"VENDOR", &VENDOR}, - {"MODEL", &MODEL}, - {"STORAGE", &STORAGE}, - //{"NOTICE", &NOTICE}, - //{"UTILIZES", &UTILIZES}, - - {"OVERLAY_MEMORY", &OVERLAY_MEMORY}, - {"NOT_ENOUGH_MEMORY", &NOT_ENOUGH_MEMORY}, - {"WALLPAPER_SUPPORT_DISABLED", &WALLPAPER_SUPPORT_DISABLED}, - {"SOUND_SUPPORT_DISABLED", &SOUND_SUPPORT_DISABLED}, - {"WALLPAPER_SUPPORT_ENABLED", &WALLPAPER_SUPPORT_ENABLED}, - {"SOUND_SUPPORT_ENABLED", &SOUND_SUPPORT_ENABLED}, - {"EXIT_OVERLAY_SYSTEM", &EXIT_OVERLAY_SYSTEM}, - - //{"MEMORY_EXPANSION", &MEMORY_EXPANSION}, - //{"REBOOT_REQUIRED", &REBOOT_REQUIRED}, - {"LOCAL_IP", &LOCAL_IP}, - {"WALLPAPER", &WALLPAPER}, - {"THEME", &THEME}, - {"DEFAULT", &DEFAULT}, - {"ROOT_PACKAGE", &ROOT_PACKAGE}, - {"SORT_PRIORITY", &SORT_PRIORITY}, - {"OPTIONS", &OPTIONS}, - {"FAILED_TO_OPEN", &FAILED_TO_OPEN}, - - {"LAUNCH_COMBOS", &LAUNCH_COMBOS}, - {"NOTIFICATIONS", &NOTIFICATIONS}, - {"SOUND_EFFECTS", &SOUND_EFFECTS}, - {"HAPTIC_FEEDBACK", &HAPTIC_FEEDBACK}, - {"OPAQUE_SCREENSHOTS", &OPAQUE_SCREENSHOTS}, - - {"PACKAGE_INFO", &PACKAGE_INFO}, - {"TITLE", &_TITLE}, - {"VERSION", &_VERSION}, - {"CREATOR", &_CREATOR}, - {"ABOUT", &_ABOUT}, - {"CREDITS", &_CREDITS}, - - {"USERGUIDE_OFFSET", &USERGUIDE_OFFSET}, - {"SETTINGS_MENU", &SETTINGS_MENU}, - {"SCRIPT_OVERLAY", &SCRIPT_OVERLAY}, - {"STAR_FAVORITE", &STAR_FAVORITE}, - {"APP_SETTINGS", &APP_SETTINGS}, - {"ON_MAIN_MENU", &ON_MAIN_MENU}, - {"ON_A_COMMAND", &ON_A_COMMAND}, - {"ON_OVERLAY_PACKAGE", &ON_OVERLAY_PACKAGE}, - {"FEATURES", &FEATURES}, - {"SWIPE_TO_OPEN", &SWIPE_TO_OPEN}, - - {"THEME_SETTINGS", &THEME_SETTINGS}, - {"DYNAMIC_LOGO", &DYNAMIC_LOGO}, - {"SELECTION_BACKGROUND", &SELECTION_BACKGROUND}, - {"SELECTION_TEXT", &SELECTION_TEXT}, - {"SELECTION_VALUE", &SELECTION_VALUE}, - {"LIBULTRAHAND_TITLES", &LIBULTRAHAND_TITLES}, - {"LIBULTRAHAND_VERSIONS", &LIBULTRAHAND_VERSIONS}, - {"PACKAGE_TITLES", &PACKAGE_TITLES}, - - {"ULTRAHAND_HAS_STARTED", &ULTRAHAND_HAS_STARTED}, - {"NEW_UPDATE_IS_AVAILABLE", &NEW_UPDATE_IS_AVAILABLE}, - //{"REBOOT_IS_REQUIRED", &REBOOT_IS_REQUIRED}, - //{"HOLD_A_TO_DELETE", &HOLD_A_TO_DELETE}, - {"DELETE_PACKAGE", &DELETE_PACKAGE}, - {"DELETE_OVERLAY", &DELETE_OVERLAY}, - {"SELECTION_IS_EMPTY", &SELECTION_IS_EMPTY}, - {"FORCED_SUPPORT_WARNING", &FORCED_SUPPORT_WARNING}, - {"INCOMPATIBLE_WARNING", &INCOMPATIBLE_WARNING}, - {"TASK_IS_COMPLETE", &TASK_IS_COMPLETE}, - {"TASK_HAS_FAILED", &TASK_HAS_FAILED}, - - //{"PACKAGE_VERSIONS", &PACKAGE_VERSIONS}, - //{"PROGRESS_ANIMATION", &PROGRESS_ANIMATION}, - - {"REBOOT_TO", &REBOOT_TO}, - {"REBOOT", &REBOOT}, - {"SHUTDOWN", &SHUTDOWN}, - {"BOOT_ENTRY", &BOOT_ENTRY}, - #endif - - {"SYSTEM_RAM", &SYSTEM_RAM}, - {"FREE", &FREE}, - - {"DEFAULT_CHAR_WIDTH", &DEFAULT_CHAR_WIDTH}, - {"UNAVAILABLE_SELECTION", &UNAVAILABLE_SELECTION}, - - {"ON", &ON}, - {"OFF", &OFF}, - - {"OK", &OK}, - {"BACK", &BACK}, - {"HIDE", &HIDE}, - {"CANCEL", &CANCEL}, - - {"GAP_1", &GAP_1}, - {"GAP_2", &GAP_2}, - - //{"EMPTY", &EMPTY}, - - #if USING_WIDGET_DIRECTIVE - {"SUNDAY", &SUNDAY}, - {"MONDAY", &MONDAY}, - {"TUESDAY", &TUESDAY}, - {"WEDNESDAY", &WEDNESDAY}, - {"THURSDAY", &THURSDAY}, - {"FRIDAY", &FRIDAY}, - {"SATURDAY", &SATURDAY}, - {"JANUARY", &JANUARY}, - {"FEBRUARY", &FEBRUARY}, - {"MARCH", &MARCH}, - {"APRIL", &APRIL}, - {"MAY", &MAY}, - {"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_ABBR", &MAY_ABBR}, - {"JUN", &JUN}, - {"JUL", &JUL}, - {"AUG", &AUG}, - {"SEP", &SEP}, - {"OCT", &OCT}, - {"NOV", &NOV}, - {"DEC", &DEC} - #endif - }; - - // Iterate over the map to update global variables - for (auto& kv : configMap) { - auto it = jsonMap.find(kv.first); - if (it != jsonMap.end()) { - updateIfNotEmpty(*kv.second, it->second); - } - } - } - - - // Helper function to apply replacements - //void applyTimeStrReplacements(std::string& str, const std::unordered_map& mappings) { - // size_t pos; - // for (const auto& mapping : mappings) { - // pos = str.find(mapping.first); - // while (pos != std::string::npos) { - // str.replace(pos, mapping.first.length(), mapping.second); - // pos = str.find(mapping.first, pos + mapping.second.length()); - // } - // } - //} - - #if USING_WIDGET_DIRECTIVE - void localizeTimeStr(char* timeStr) { - // Define static unordered_map for day and month mappings - static std::unordered_map mappings = { - {"Sun", &SUN}, - {"Mon", &MON}, - {"Tue", &TUE}, - {"Wed", &WED}, - {"Thu", &THU}, - {"Fri", &FRI}, - {"Sat", &SAT}, - {"Sunday", &SUNDAY}, - {"Monday", &MONDAY}, - {"Tuesday", &TUESDAY}, - {"Wednesday", &WEDNESDAY}, - {"Thursday", &THURSDAY}, - {"Friday", &FRIDAY}, - {"Saturday", &SATURDAY}, - {"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}, - {"January", &JANUARY}, - {"February", &FEBRUARY}, - {"March", &MARCH}, - {"April", &APRIL}, - {"May", &MAY}, - {"June", &JUNE}, - {"July", &JULY}, - {"August", &AUGUST}, - {"September", &SEPTEMBER}, - {"October", &OCTOBER}, - {"November", &NOVEMBER}, - {"December", &DECEMBER} - }; - - std::string timeStrCopy = timeStr; // Convert the char array to a string for processing - - // Apply day and month replacements - size_t pos; - for (const auto& mapping : mappings) { - pos = timeStrCopy.find(mapping.first); - while (pos != std::string::npos) { - timeStrCopy.replace(pos, mapping.first.length(), *(mapping.second)); - pos = timeStrCopy.find(mapping.first, pos + mapping.second->length()); - } - } - - // Copy the modified string back to the character array - strcpy(timeStr, timeStrCopy.c_str()); - } - #endif - - // Unified function to apply replacements - void applyLangReplacements(std::string& text, bool isValue) { - if (isValue) { - // Direct comparison for value replacements - if (text.length() == 2) { - if (text[0] == 'O') { - if (text[1] == 'n') { - text = ON; - return; - } else if (text[1] == 'f' && text == "Off") { - text = OFF; - return; - } - } - } - } - #if IS_LAUNCHER_DIRECTIVE - else { - // Direct comparison for launcher replacements - 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 - } - - - - // Predefined hexMap - //const 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; - //}(); - - - // Prepare a map of default settings - std::map defaultThemeSettingsMap = { - {"default_overlay_color", whiteColor}, - {"default_package_color", whiteColor}, - {"default_script_color", "FF33FF"}, - {"clock_color", whiteColor}, - {"temperature_color", whiteColor}, - {"battery_color", "ffff45"}, - {"battery_charging_color", "00FF00"}, - {"battery_low_color", "FF0000"}, - {"widget_backdrop_alpha", "15"}, - {"widget_backdrop_color", blackColor}, - {"bg_alpha", "13"}, - {"bg_color", blackColor}, - {"separator_alpha", "15"}, - {"separator_color", "404040"}, - {"text_separator_color", "404040"}, - {"text_color", whiteColor}, - {"notification_text_color", whiteColor}, - {"header_text_color", whiteColor}, - {"header_separator_color", whiteColor}, - {"star_color", whiteColor}, - {"selection_star_color", whiteColor}, - {"bottom_button_color", whiteColor}, - {"bottom_text_color", whiteColor}, - {"bottom_separator_color", whiteColor}, - {"top_separator_color", "404040"}, - {"table_bg_color", "2C2C2C"}, - {"table_bg_alpha", "14"}, - {"table_section_text_color", whiteColor}, - //{"table_info_text_color", "00FFDD"}, - {"table_info_text_color", "9ed0ff"}, - {"warning_text_color", "FF7777"}, - {"healthy_ram_text_color", "00FF00"}, - {"neutral_ram_text_color", "FFAA00"}, - {"bad_ram_text_color", "FF0000"}, - {"trackbar_slider_color", "606060"}, - {"trackbar_slider_border_color", "505050"}, - {"trackbar_slider_malleable_color", "A0A0A0"}, - {"trackbar_full_color", "00FFDD"}, - {"trackbar_empty_color", "404040"}, - {"overlay_text_color", whiteColor}, - {"ult_overlay_text_color", "9ed0ff"}, - {"package_text_color", whiteColor}, - {"ult_package_text_color", "9ed0ff"}, - {"banner_version_text_color", greyColor}, - {"overlay_version_text_color", greyColor}, - {"ult_overlay_version_text_color", "00FFDD"}, - {"package_version_text_color", greyColor}, - {"ult_package_version_text_color", "00FFDD"}, - {"on_text_color", "00FFDD"}, - {"off_text_color", greyColor}, - {"invalid_text_color", "FF0000"}, - {"inprogress_text_color", "FFFF45"}, - {"selection_text_color", "9ed0ff"}, - {"selection_value_text_color", "FF7777"}, - {"selection_bg_color", blackColor}, - {"selection_bg_alpha", "11"}, - {"scrollbar_color", "555555"}, - {"scrollbar_wall_color", "AAAAAA"}, - {"highlight_color_1", "2288CC"}, - {"highlight_color_2", "88FFFF"}, - {"highlight_color_3", "FFFF45"}, - {"highlight_color_4", "F7253E"}, - {"click_text_color", whiteColor}, - {"click_alpha", "7"}, - {"click_color", "3E25F7"}, - {"progress_alpha", "7"}, - {"progress_color", "253EF7"}, - {"invert_bg_click_color", FALSE_STR}, - //{"disable_selection_bg", FALSE_STR}, - //{"disable_selection_value_color", FALSE_STR}, - //{"disable_colorful_logo", FALSE_STR}, - {"logo_color_1", whiteColor}, - {"logo_color_2", "FF0000"}, - {"dynamic_logo_color_1", "00E669"}, - {"dynamic_logo_color_2", "8080EA"} - }; - - bool isNumericCharacter(char c) { - return std::isdigit(c); - } - - bool isValidHexColor(const std::string& hexColor) { - // Check if the string is a valid hexadecimal color of the format "#RRGGBB" - if (hexColor.size() != 6) { - return false; // Must be exactly 6 characters long - } - - for (char c : hexColor) { - if (!isxdigit(c)) { - return false; // Must contain only hexadecimal digits (0-9, A-F, a-f) - } - } - - return true; - } - - - std::atomic refreshWallpaperNow(false); - std::atomic refreshWallpaper(false); - std::vector wallpaperData; - std::atomic inPlot(false); - - std::mutex wallpaperMutex; - std::condition_variable cv; - - - void loadWallpaperFile(const std::string& filePath, s32 width, s32 height) { - const size_t originalDataSize = width * height * 4; - const size_t compressedDataSize = originalDataSize / 2; - - wallpaperData.resize(compressedDataSize); - - if (!isFileOrDirectory(filePath)) { - wallpaperData.clear(); - return; - } - - FILE* file = fopen(filePath.c_str(), "rb"); - if (!file) { - wallpaperData.clear(); - return; - } - - setvbuf(file, nullptr, _IOFBF, 256 * 1024); - - constexpr size_t chunkBytes = 128 * 1024; - uint8_t chunkBuffer[chunkBytes]; - - size_t totalRead = 0; - uint8_t* dst = wallpaperData.data(); - const uint8x8_t mask = vdup_n_u8(0xF0); - - while (totalRead < originalDataSize) { - const size_t remaining = originalDataSize - totalRead; - const size_t toRead = remaining < chunkBytes ? remaining : chunkBytes; - - const size_t bytesRead = fread(chunkBuffer, 1, toRead, file); - if (bytesRead == 0) { - fclose(file); - wallpaperData.clear(); - return; - } - - const uint8_t* src = chunkBuffer; - size_t i = 0; - - // NEON: Process 16 bytes -> 8 bytes - 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; - } - - // Scalar fallback - for (; i + 1 < bytesRead; i += 2) { - *dst++ = (src[i] & 0xF0) | (src[i + 1] >> 4); - } - - totalRead += bytesRead; - } - - fclose(file); - } - - - 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() && isFileOrDirectory(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 (isFileOrDirectory(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(); - } - - - - // Global variables for FPS calculation - //double lastTimeCount = 0.0; - //int frameCount = 0; - //float fps = 0.0f; - //double elapsedTime = 0.0; - - 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); - //bool simulatedBackComplete = true; - std::atomic simulatedSelect(false); - //bool simulatedSelectComplete = true; - std::atomic simulatedNextPage(false); - //std::atomic simulatedNextPageComplete(true); - std::atomic simulatedMenu(false); - //bool simulatedMenuComplete = true; - 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; - //float powerConsumption; - bool powerCacheIsCharging; - PsmSession powerSession; - - // Define variables to store previous battery charge and time - //uint32_t prevBatteryCharge = 0; - //s64 timeOut = 0; - - - std::atomic batteryCharge{0}; - std::atomic isCharging{false}; - //bool validPower; - - - - 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 = armTicksToNs(armGetSystemTick()); - - // 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); - //prevBatteryCharge = charge; // if needed - } - } - } - } - - 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 - //std::string hideClock, hideBattery, hidePCBTemp, hideSOCTemp; - 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 - 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; - } - - 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 - //libultrahandTitles = getBoolValue("libultrahand_titles", false); // FALSE_STR default - //useLibultrahandVersions = getBoolValue("libultrahand_versions", true); // TRUE_STR default - //matchPackages = getBoolValue("match_packages", true); // TRUE_STR default - - //#ifdef APP_VERSION - //versionLabel = cleanVersionLabel(APP_VERSION) + " (" + loaderTitle + " " + cleanVersionLabel(loaderInfo) + ")"; - //#endif - //versionLabel = (cleanVersionLabels) ? std::string(APP_VERSION) : (std::string(APP_VERSION) + " (" + extractTitle(loaderInfo) + " v" + cleanVersionLabel(loaderInfo) + ")"); - } - #endif - - - // Number of renderer threads to use - const unsigned numThreads = 4;//expandedMemory ? 4 : 0; - std::vector renderThreads(numThreads); - - const s32 bmpChunkSize = ((720 + numThreads - 1) / numThreads); - std::atomic currentRow; - - //std::atomic barrierCounter{0}; - //std::mutex barrierMutex; - //std::condition_variable barrierCV; - // - //void barrierWait() { - // std::unique_lock lock(barrierMutex); - // if (++barrierCounter == numThreads) { - // barrierCounter = 0; // Reset for the next round - // barrierCV.notify_all(); - // } else { - // barrierCV.wait(lock, [] { return barrierCounter == 0; }); - // } - //} -} diff --git a/Source/sys-clk/overlay/lib/libultrahand/ultrahand.mk b/Source/sys-clk/overlay/lib/libultrahand/ultrahand.mk deleted file mode 100644 index 4e0cc197..00000000 --- a/Source/sys-clk/overlay/lib/libultrahand/ultrahand.mk +++ /dev/null @@ -1,30 +0,0 @@ -#--------------------------------------------------------------------------------- -# 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 - -INCLUDES += \ - $(ULTRA_DIR)/common \ - $(ULTRA_DIR)/libultra/include \ - $(ULTRA_DIR)/libtesla/include