From f3eae72b4713dbcd802f8bf867110e854da8a051 Mon Sep 17 00:00:00 2001 From: souldbminersmwc Date: Wed, 17 Sep 2025 19:56:06 -0400 Subject: [PATCH] rewrite everything --- .gitignore | 1 + .../loader/source/oc/customize.cpp | 526 +- .../loader/source/oc/customize.hpp | 100 +- .../loader/source/oc/mtc_timing_value.hpp | 294 +- .../stratosphere/loader/source/oc/pcv/pcv.cpp | 61 +- .../stratosphere/loader/source/oc/pcv/pcv.hpp | 677 +- .../loader/source/oc/pcv/pcv_common.hpp | 298 +- .../loader/source/oc/pcv/pcv_erista.cpp | 535 +- .../loader/source/oc/pcv/pcv_mariko.cpp | 169 +- .../stratosphere/loader/source/patch.py | 74 + Source/MemTesterNX/source/main.c | 5 +- Source/ReverseNX-RT.diff(deprecated) | 287 + Source/TinyMemBenchNX/source/main.c | 2 +- Source/clkrst_query.cpp | 2 +- Source/sys-clk-OC/README.md | 212 - Source/sys-clk/.gitignore | 5 + Source/sys-clk/.gitlab-ci.yml | 17 + Source/sys-clk/.gitmodules | 3 + Source/sys-clk/LICENSE | 7 + Source/sys-clk/README.md | 163 + Source/sys-clk/build.sh | 45 + Source/sys-clk/common/include/sysclk.h | 26 + Source/sys-clk/common/include/sysclk/apm.h | 22 + Source/sys-clk/common/include/sysclk/board.h | 126 + .../common/include/sysclk/client/ipc.h | 38 + .../common/include/sysclk/client/types.h | 29 + .../common/include/sysclk/clock_manager.h | 37 + Source/sys-clk/common/include/sysclk/config.h | 79 + Source/sys-clk/common/include/sysclk/errors.h | 21 + Source/sys-clk/common/include/sysclk/ipc.h | 54 + Source/sys-clk/common/src/apm_profile_table.c | 32 + Source/sys-clk/common/src/client/ipc.c | 133 + Source/sys-clk/config.ini.template | 19 + Source/sys-clk/overlay/.gitignore | 2 + Source/sys-clk/overlay/Makefile | 170 + Source/sys-clk/overlay/data/logo_rgba.bin | Bin 0 -> 17160 bytes Source/sys-clk/overlay/lang/de.json | 35 + Source/sys-clk/overlay/lang/en.json | 35 + Source/sys-clk/overlay/lang/es.json | 35 + Source/sys-clk/overlay/lang/fr.json | 35 + Source/sys-clk/overlay/lang/it.json | 35 + Source/sys-clk/overlay/lang/ja.json | 35 + Source/sys-clk/overlay/lang/ko.json | 35 + Source/sys-clk/overlay/lang/nl.json | 35 + Source/sys-clk/overlay/lang/pl.json | 35 + Source/sys-clk/overlay/lang/pt.json | 35 + Source/sys-clk/overlay/lang/ru.json | 35 + Source/sys-clk/overlay/lang/uk.json | 35 + Source/sys-clk/overlay/lang/zh-cn.json | 35 + Source/sys-clk/overlay/lang/zh-tw.json | 35 + .../lib/libultrahand/.github/FUNDING.yml | 2 + .../overlay/lib/libultrahand/.gitmodules | 0 .../lib/libultrahand/.pics/libultrahand.png | Bin 0 -> 390117 bytes .../overlay/lib/libultrahand/.pics/tmp | 1 + .../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 | 5265 ++++++ .../libultrahand/libtesla/include/tesla.hpp | 13617 ++++++++++++++++ .../overlay/lib/libultrahand/libultra/LICENSE | 339 + .../lib/libultrahand/libultra/README.md | 69 + .../lib/libultrahand/libultra/SUB_LICENSE | 395 + .../libultra/include/debug_funcs.hpp | 52 + .../libultra/include/download_funcs.hpp | 89 + .../libultra/include/get_funcs.hpp | 160 + .../libultra/include/global_vars.hpp | 171 + .../libultra/include/hex_funcs.hpp | 211 + .../libultra/include/ini_funcs.hpp | 344 + .../libultra/include/json_funcs.hpp | 107 + .../libultra/include/list_funcs.hpp | 110 + .../libultra/include/mod_funcs.hpp | 108 + .../libultra/include/path_funcs.hpp | 279 + .../libultra/include/string_funcs.hpp | 273 + .../libultra/include/tsl_utils.hpp | 719 + .../libultrahand/libultra/include/ultra.hpp | 47 + .../libultra/source/debug_funcs.cpp | 60 + .../libultra/source/download_funcs.cpp | 812 + .../libultra/source/get_funcs.cpp | 506 + .../libultra/source/global_vars.cpp | 178 + .../libultra/source/hex_funcs.cpp | 881 + .../libultra/source/ini_funcs.cpp | 2465 +++ .../libultra/source/json_funcs.cpp | 400 + .../libultra/source/list_funcs.cpp | 467 + .../libultra/source/mod_funcs.cpp | 736 + .../libultra/source/path_funcs.cpp | 1446 ++ .../libultra/source/string_funcs.cpp | 609 + .../libultra/source/tsl_utils.cpp | 1684 ++ .../overlay/lib/libultrahand/ultrahand.mk | 30 + Source/sys-clk/overlay/scripts/make_logo.sh | 16 + Source/sys-clk/overlay/src/ipc.h | 23 + Source/sys-clk/overlay/src/main.cpp | 81 + Source/sys-clk/overlay/src/pcv_types.h | 41 + Source/sys-clk/overlay/src/rgltr.h | 19 + Source/sys-clk/overlay/src/rgltr_services.cpp | 43 + Source/sys-clk/overlay/src/rgltr_services.h | 29 + .../overlay/src/ui/elements/base_frame.h | 31 + Source/sys-clk/overlay/src/ui/format.h | 28 + .../overlay/src/ui/gui/app_profile_gui.cpp | 127 + .../overlay/src/ui/gui/app_profile_gui.h | 34 + .../sys-clk/overlay/src/ui/gui/base_gui.cpp | 56 + Source/sys-clk/overlay/src/ui/gui/base_gui.h | 36 + .../overlay/src/ui/gui/base_menu_gui.cpp | 291 + .../overlay/src/ui/gui/base_menu_gui.h | 59 + .../sys-clk/overlay/src/ui/gui/fatal_gui.cpp | 67 + Source/sys-clk/overlay/src/ui/gui/fatal_gui.h | 29 + .../overlay/src/ui/gui/freq_choice_gui.cpp | 67 + .../overlay/src/ui/gui/freq_choice_gui.h | 35 + .../src/ui/gui/global_override_gui.cpp | 108 + .../overlay/src/ui/gui/global_override_gui.h | 31 + .../sys-clk/overlay/src/ui/gui/main_gui.cpp | 93 + Source/sys-clk/overlay/src/ui/gui/main_gui.h | 25 + .../sys-clk/overlay/src/ui/gui/misc_gui.cpp | 444 + Source/sys-clk/overlay/src/ui/gui/misc_gui.h | 30 + Source/sys-clk/overlay/src/ui/style.h | 20 + Source/sys-clk/sysmodule/.gitignore | 2 + Source/sys-clk/sysmodule/Makefile | 164 + .../sys-clk/sysmodule/lib/minIni/.gitignore | 13 + Source/sys-clk/sysmodule/lib/minIni/.gitrepo | 12 + Source/sys-clk/sysmodule/lib/minIni/LICENSE | 189 + Source/sys-clk/sysmodule/lib/minIni/Makefile | 133 + Source/sys-clk/sysmodule/lib/minIni/NOTICE | 12 + Source/sys-clk/sysmodule/lib/minIni/README.md | 170 + .../sysmodule/lib/minIni/dev/minGlue-FatFs.h | 37 + .../sysmodule/lib/minIni/dev/minGlue-ccs.h | 64 + .../sysmodule/lib/minIni/dev/minGlue-efsl.h | 63 + .../sysmodule/lib/minIni/dev/minGlue-ffs.h | 26 + .../sysmodule/lib/minIni/dev/minGlue-mdd.h | 58 + .../sysmodule/lib/minIni/dev/minGlue-stdio.h | 31 + .../sysmodule/lib/minIni/dev/minGlue.h | 35 + .../sys-clk/sysmodule/lib/minIni/dev/minIni.c | 1009 ++ .../sys-clk/sysmodule/lib/minIni/dev/minIni.h | 68 + .../sys-clk/sysmodule/lib/minIni/dev/test.c | 117 + .../sys-clk/sysmodule/lib/minIni/dev/test.ini | 8 + .../sys-clk/sysmodule/lib/minIni/dev/test2.cc | 80 + .../sysmodule/lib/minIni/dev/testplain.ini | 3 + .../sysmodule/lib/minIni/dev/wxMinIni.h | 101 + .../sysmodule/lib/minIni/doc/minIni.pdf | Bin 0 -> 153827 bytes .../sysmodule/lib/minIni/include/minIni.h | 21 + Source/sys-clk/sysmodule/lib/nxExt/.gitignore | 13 + Source/sys-clk/sysmodule/lib/nxExt/Makefile | 132 + .../sysmodule/lib/nxExt/include/nxExt.h | 19 + .../lib/nxExt/include/nxExt/apm_ext.h | 29 + .../nxExt/include/nxExt/cpp/lockable_mutex.h | 64 + .../sysmodule/lib/nxExt/include/nxExt/i2c.h | 24 + .../lib/nxExt/include/nxExt/ipc_server.h | 62 + .../lib/nxExt/include/nxExt/max17050.h | 27 + .../sysmodule/lib/nxExt/include/nxExt/t210.h | 28 + .../lib/nxExt/include/nxExt/tmp451.h | 27 + .../sys-clk/sysmodule/lib/nxExt/src/apm_ext.c | 66 + Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c | 28 + .../sysmodule/lib/nxExt/src/ipc_server.c | 204 + .../sysmodule/lib/nxExt/src/max17050.c | 124 + Source/sys-clk/sysmodule/lib/nxExt/src/t210.c | 289 + .../sys-clk/sysmodule/lib/nxExt/src/tmp451.c | 102 + Source/sys-clk/sysmodule/perms.json | 129 + Source/sys-clk/sysmodule/src/board.cpp | 377 + Source/sys-clk/sysmodule/src/board.h | 40 + .../sys-clk/sysmodule/src/clock_manager.cpp | 316 + Source/sys-clk/sysmodule/src/clock_manager.h | 54 + Source/sys-clk/sysmodule/src/config.cpp | 473 + Source/sys-clk/sysmodule/src/config.h | 70 + Source/sys-clk/sysmodule/src/errors.cpp | 37 + Source/sys-clk/sysmodule/src/errors.h | 35 + Source/sys-clk/sysmodule/src/file_utils.cpp | 199 + Source/sys-clk/sysmodule/src/file_utils.h | 38 + Source/sys-clk/sysmodule/src/ipc_service.cpp | 326 + Source/sys-clk/sysmodule/src/ipc_service.h | 47 + Source/sys-clk/sysmodule/src/main.cpp | 125 + .../sysmodule/src/process_management.cpp | 67 + .../sysmodule/src/process_management.h | 24 + build.sh | 21 + 177 files changed, 49152 insertions(+), 1258 deletions(-) create mode 100644 Source/Atmosphere/stratosphere/loader/source/patch.py create mode 100644 Source/ReverseNX-RT.diff(deprecated) delete mode 100644 Source/sys-clk-OC/README.md create mode 100644 Source/sys-clk/.gitignore create mode 100644 Source/sys-clk/.gitlab-ci.yml create mode 100644 Source/sys-clk/.gitmodules create mode 100644 Source/sys-clk/LICENSE create mode 100644 Source/sys-clk/README.md create mode 100644 Source/sys-clk/build.sh create mode 100644 Source/sys-clk/common/include/sysclk.h create mode 100644 Source/sys-clk/common/include/sysclk/apm.h create mode 100644 Source/sys-clk/common/include/sysclk/board.h create mode 100644 Source/sys-clk/common/include/sysclk/client/ipc.h create mode 100644 Source/sys-clk/common/include/sysclk/client/types.h create mode 100644 Source/sys-clk/common/include/sysclk/clock_manager.h create mode 100644 Source/sys-clk/common/include/sysclk/config.h create mode 100644 Source/sys-clk/common/include/sysclk/errors.h create mode 100644 Source/sys-clk/common/include/sysclk/ipc.h create mode 100644 Source/sys-clk/common/src/apm_profile_table.c create mode 100644 Source/sys-clk/common/src/client/ipc.c create mode 100644 Source/sys-clk/config.ini.template create mode 100644 Source/sys-clk/overlay/.gitignore create mode 100644 Source/sys-clk/overlay/Makefile create mode 100644 Source/sys-clk/overlay/data/logo_rgba.bin create mode 100644 Source/sys-clk/overlay/lang/de.json create mode 100644 Source/sys-clk/overlay/lang/en.json create mode 100644 Source/sys-clk/overlay/lang/es.json create mode 100644 Source/sys-clk/overlay/lang/fr.json create mode 100644 Source/sys-clk/overlay/lang/it.json create mode 100644 Source/sys-clk/overlay/lang/ja.json create mode 100644 Source/sys-clk/overlay/lang/ko.json create mode 100644 Source/sys-clk/overlay/lang/nl.json create mode 100644 Source/sys-clk/overlay/lang/pl.json create mode 100644 Source/sys-clk/overlay/lang/pt.json create mode 100644 Source/sys-clk/overlay/lang/ru.json create mode 100644 Source/sys-clk/overlay/lang/uk.json create mode 100644 Source/sys-clk/overlay/lang/zh-cn.json create mode 100644 Source/sys-clk/overlay/lang/zh-tw.json create mode 100644 Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml create mode 100644 Source/sys-clk/overlay/lib/libultrahand/.gitmodules create mode 100644 Source/sys-clk/overlay/lib/libultrahand/.pics/libultrahand.png create mode 100644 Source/sys-clk/overlay/lib/libultrahand/.pics/tmp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/LICENSE create mode 100644 Source/sys-clk/overlay/lib/libultrahand/README.md create mode 100644 Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE create mode 100644 Source/sys-clk/overlay/lib/libultrahand/common/cJSON.c create mode 100644 Source/sys-clk/overlay/lib/libultrahand/common/cJSON.h create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/README.md create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/README.md create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp create mode 100644 Source/sys-clk/overlay/lib/libultrahand/ultrahand.mk create mode 100644 Source/sys-clk/overlay/scripts/make_logo.sh create mode 100644 Source/sys-clk/overlay/src/ipc.h create mode 100644 Source/sys-clk/overlay/src/main.cpp create mode 100644 Source/sys-clk/overlay/src/pcv_types.h create mode 100644 Source/sys-clk/overlay/src/rgltr.h create mode 100644 Source/sys-clk/overlay/src/rgltr_services.cpp create mode 100644 Source/sys-clk/overlay/src/rgltr_services.h create mode 100644 Source/sys-clk/overlay/src/ui/elements/base_frame.h create mode 100644 Source/sys-clk/overlay/src/ui/format.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/app_profile_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/app_profile_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/base_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/base_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/base_menu_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/base_menu_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/fatal_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/fatal_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/global_override_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/global_override_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/main_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/main_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp create mode 100644 Source/sys-clk/overlay/src/ui/gui/misc_gui.h create mode 100644 Source/sys-clk/overlay/src/ui/style.h create mode 100644 Source/sys-clk/sysmodule/.gitignore create mode 100644 Source/sys-clk/sysmodule/Makefile create mode 100644 Source/sys-clk/sysmodule/lib/minIni/.gitignore create mode 100644 Source/sys-clk/sysmodule/lib/minIni/.gitrepo create mode 100644 Source/sys-clk/sysmodule/lib/minIni/LICENSE create mode 100644 Source/sys-clk/sysmodule/lib/minIni/Makefile create mode 100644 Source/sys-clk/sysmodule/lib/minIni/NOTICE create mode 100644 Source/sys-clk/sysmodule/lib/minIni/README.md create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-FatFs.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ccs.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-efsl.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ffs.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-mdd.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-stdio.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minGlue.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minIni.c create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/minIni.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/test.c create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/test.ini create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/test2.cc create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/testplain.ini create mode 100644 Source/sys-clk/sysmodule/lib/minIni/dev/wxMinIni.h create mode 100644 Source/sys-clk/sysmodule/lib/minIni/doc/minIni.pdf create mode 100644 Source/sys-clk/sysmodule/lib/minIni/include/minIni.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/.gitignore create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/Makefile create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/apm_ext.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/cpp/lockable_mutex.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/i2c.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/ipc_server.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/max17050.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/t210.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/tmp451.h create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/src/apm_ext.c create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/src/ipc_server.c create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/src/max17050.c create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/src/t210.c create mode 100644 Source/sys-clk/sysmodule/lib/nxExt/src/tmp451.c create mode 100644 Source/sys-clk/sysmodule/perms.json create mode 100644 Source/sys-clk/sysmodule/src/board.cpp create mode 100644 Source/sys-clk/sysmodule/src/board.h create mode 100644 Source/sys-clk/sysmodule/src/clock_manager.cpp create mode 100644 Source/sys-clk/sysmodule/src/clock_manager.h create mode 100644 Source/sys-clk/sysmodule/src/config.cpp create mode 100644 Source/sys-clk/sysmodule/src/config.h create mode 100644 Source/sys-clk/sysmodule/src/errors.cpp create mode 100644 Source/sys-clk/sysmodule/src/errors.h create mode 100644 Source/sys-clk/sysmodule/src/file_utils.cpp create mode 100644 Source/sys-clk/sysmodule/src/file_utils.h create mode 100644 Source/sys-clk/sysmodule/src/ipc_service.cpp create mode 100644 Source/sys-clk/sysmodule/src/ipc_service.h create mode 100644 Source/sys-clk/sysmodule/src/main.cpp create mode 100644 Source/sys-clk/sysmodule/src/process_management.cpp create mode 100644 Source/sys-clk/sysmodule/src/process_management.h create mode 100644 build.sh diff --git a/.gitignore b/.gitignore index 2276a02d..d8998056 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ *.DS_Store .vscode/ +build/ \ No newline at end of file diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/customize.cpp b/Source/Atmosphere/stratosphere/loader/source/oc/customize.cpp index 2ff48a89..7630b07f 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/customize.cpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/customize.cpp @@ -1,6 +1,8 @@ /* - * Copyright (C) hanai3bi (meha) + * Copyright (C) Switch-OC-Suite * + * Copyright (c) 2023 hanai3Bi + * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. @@ -15,71 +17,159 @@ */ #include "customize.hpp" - +#define ENABLED 1 +#define DISABLED 0 namespace ams::ldr::oc { //volatile EristaMtcTable EristaMtcTablePlaceholder = { .rev = ERISTA_MTC_MAGIC, }; //volatile MarikoMtcTable MarikoMtcTablePlaceholder = { .rev = MARIKO_MTC_MAGIC, }; volatile CustomizeTable C = { -// --- u32 fields --- +/* DRAM Timing: + * AUTO_ADJ_ALL: Auto adjust timings for Mariko LPDDR4X ≤3733 Mbps specs, 8Gb density. (Default) + * CUSTOM_ADJ_ALL: Basically same as NO_ADJ_ALL, with core timing adjustments + * NO_ADJ_ALL: No timing adjustment for both Erista and Mariko. + * CUSTOMIZED_ALL: Replace with values in customized table for both Erista and Mariko. + */ .mtcConf = AUTO_ADJ_ALL, + +/* Common: + * - Boost Clock in kHz: + * Default: 1785000 + * Boost clock will be applied when applications request higher CPU frequency for quicker loading. + * This will be set regardless of whether sys-clk is enabled. + */ .commonCpuBoostClock = 1785000, -.commonEmcMemVolt = 1175000, +/* - EMC Vddq (Erista Only) and RAM Vdd2 Voltage in uV + * Range: 1100'000 to 1250'000 uV + * Erista Default(HOS): 1125'000 (bootloader: 1100'000) + * Mariko Default: 1100'000 (It will not work without sys-clk-OC.) + * Value should be divided evenly by 12'500. + * Not enabled by default. + */ +.commonEmcMemVolt = 0, + +/* Erista CPU: + * - Max Voltage in mV + * - CpuVoltL4T: 1235 + */ .eristaCpuMaxVolt = 1235, + +/* Erista EMC(RAM): + * - RAM Clock in kHz + * [WARNING] + * RAM overclock could be UNSTABLE if timing parameters are not suitable for your DRAM: + * - Graphical glitches + * - System instabilities + * - NAND corruption + */ .eristaEmcMaxClock = 1862400, -.marikoCpuMaxVolt = 1120, + +/* Mariko CPU: + * - Max Voltage in mV: + * Default voltage: 1120 + */ +.marikoCpuMaxVolt = 1235, + +/* Mariko EMC(RAM): + * - RAM Clock in kHz: + * Values should be ≥ 1600000, and divided evenly by 9600. + * [WARNING] + * RAM overclock could be UNSTABLE if timing parameters are not suitable for your DRAM: + * - Graphical glitches + * - System instabilities + * - NAND corruption + */ .marikoEmcMaxClock = 1996800, -.marikoEmcVddqVolt = 600000, +/* - EMC Vddq (Mariko Only) Voltage in uV + * Range: 550'000 to 650'000 uV + * Value should be divided evenly by 5'000 + * Default: 600'000 + * Not enabled by default. + * This will not work without sys-clk-OC. + */ +.marikoEmcVddqVolt = 0, + .marikoCpuUV = 0, + .marikoGpuUV = 0, + +.eristaCpuUV = 0, + +.eristaGpuUV = 1, + +.enableMarikoGpuUnsafeFreqs = DISABLED, + +.enableEristaGpuUnsafeFreqs = DISABLED, + +.enableMarikoCpuUnsafeFreqs = DISABLED, + +.enableEristaCpuUnsafeFreqs = DISABLED, + .commonGpuVoltOffset = 0, -.marikoCpuHighVoltOffset = 0, -.marikoCpuHighUV = 0, -.cpuMaxFreq = 1785000, -.gpuMaxFreq = 921600, -.gpuVmax = 800, -.gpuVmin = 600, + .marikoEmcDvbShift = 0, -.latency = 0, -.BL = 16, -.WL = 32, -.RL = 14, -.tRFCpb = 140, -.tRFCab = 280, -.tRAS = 42, -.tRPpb = 18, -.tRPab = 21, -.tRC = 60, -.tWTR = 10, -.tWR = 18, -.tRCD = 18, -.tREFpb = 488, -.tMRWCKEL = 14, -.tSR = 15, -.tFAW = 40, -// --- double fields --- -.tR2REF = 25.5, -.tDQSCK_min = 1.5, -.tDQSCK_max = 3.5, -.tWPRE = 1.8, -.tRPST = 0.4, -.tDQSS_max = 1.25, -.tDQS2DQ_max = 0.8, -.tDQSQ = 0.18, -.tRTP = 7.5, -.tRRD = 10.0, -.tXP = 10.0, -.tCMDCKE = 1.75, -.tCKELCS = 5.0, -.tCSCKEH = 1.75, -.tXSR = 287.5, -.tCKE = 7.5, -.tCKCKEH = 1.75, +.ramTimingPresetOne = 0, -.marikoGpuVoltArray = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, +.ramTimingPresetTwo = 0, +.ramTimingPresetThree = 0, + +.ramTimingPresetFour = 0, + +.ramTimingPresetFive = 0, + +.ramTimingPresetSix = 0, + +.ramTimingPresetSeven = 0, // Sets the BL of the ram. Change to 2 to get 1866BL and set to 0 to keep the default 1600BL + +// NOTE: These tables should NOT BE USED and are only here as placeholders. Always try and find your own optimal tables. + +.marikoGpuVoltArray = { + 610 /* 76 */, + 610 /* 153 */, + 610 /* 230 */, + 610 /* 307 */, + 610 /* 384 */, + 610 /* 460 */, + 610 /* 537 */, + 610 /* 614 */, + 610 /* 691 */, + 610 /* 768 */, + 620 /* 844 */, + 640 /* 921 */, + 675 /* 998 */, + 710 /* 1075 */, + 735 /* 1152 */, + 785 /* 1228 */, + 0 /* 1305 (Disabled by default) */, + 0 /* 1344 (Disabled by default) */, + 0 /* 1382 (Disabled by default) */, + 0 /* 1420 (Disabled by default) */, + 0 /* 1459 (Disabled by default) */, + 0 /* 1497 (Disabled by default) */, + 0 /* 1536 (Disabled by default) */, + +}, + +.eristaGpuVoltArray = { + 750 /* 76 */, + 750 /* 153 */, + 750 /* 230 */, + 750 /* 307 */, + 775 /* 384 */, + 800 /* 460 */, + 825 /* 537 */, + 850 /* 614 */, + 875 /* 691 */, + 900 /* 768 */, + 950 /* 844 */, + 975 /* 921 */, + 0 /* 998 (Disabled by default) */, + 0 /* 1075 (Disabled by default) */, + 0 /* 1152 (Disabled by default) */, +}, /* Advanced Settings: * - Erista CPU DVFS Table: @@ -107,20 +197,23 @@ volatile CustomizeTable C = { { 2091000, { 1235000 }, { 5100873, -279186, 4747 } }, { 2193000, { 1235000 }, { 5100873, -279186, 4747 } }, { 2295000, { 1235000 }, { 5100873, -279186, 4747 } }, + { 2397000, { 1235000 }, { 5100873, -279186, 4747 } }, + { 2499000, { 1235000 }, { 5100873, -279186, 4747 } }, + { 2602000, { 1235000 }, { 5100873, -279186, 4747 } }, }, /* - Mariko CPU DVFS Table: * 2397000 might not work for some SoCs. */ .marikoCpuDvfsTable = { - { 204000, { 721589, -12695, 27 }, { 1120000 } }, - { 306000, { 747134, -14195, 27 }, { 1120000 } }, - { 408000, { 776324, -15705, 27 }, { 1120000 } }, - { 510000, { 809160, -17205, 27 }, { 1120000 } }, - { 612000, { 845641, -18715, 27 }, { 1120000 } }, - { 714000, { 885768, -20215, 27 }, { 1120000 } }, - { 816000, { 929540, -21725, 27 }, { 1120000 } }, - { 918000, { 976958, -23225, 27 }, { 1120000 } }, + { 204000, { 721589, -12695, 27 }, {} }, + { 306000, { 747134, -14195, 27 }, {} }, + { 408000, { 776324, -15705, 27 }, {} }, + { 510000, { 809160, -17205, 27 }, {} }, + { 612000, { 845641, -18715, 27 }, {} }, + { 714000, { 885768, -20215, 27 }, {} }, + { 816000, { 929540, -21725, 27 }, {} }, + { 918000, { 976958, -23225, 27 }, {} }, { 1020000, { 1028021, -24725, 27 }, { 1120000 } }, { 1122000, { 1082730, -26235, 27 }, { 1120000 } }, { 1224000, { 1141084, -27735, 27 }, { 1120000 } }, @@ -135,10 +228,205 @@ volatile CustomizeTable C = { { 2091000, { 1716501, -39395, 27 }, { 1235000 } }, { 2193000, { 1775132, -40505, 27 }, { 1235000 } }, { 2295000, { 1866287, -42005, 27 }, { 1235000 } }, - { 2397000, { 1961107, -43506, 27 }, { 1235000 } }, + //{ 2397000, { 1961107, -43506, 27 }, { 1235000 } }, }, .marikoCpuDvfsTableSLT = { + { 204000, { 732856, -17335, 113 }, {} }, + { 306000, { 760024, -18195, 113 }, {} }, + { 408000, { 789258, -19055, 113 }, {} }, + { 510000, { 789258, -19055, 113 }, {} }, + { 612000, { 853926, -20775, 113 }, {} }, + { 714000, { 889361, -21625, 113 }, {} }, + { 816000, { 926862, -22485, 113 }, {} }, + { 918000, { 966431, -23345, 113 }, {} }, + { 1020000, { 1008066, -24205, 113 }, { 1120000 } }, + { 1122000, { 1051768, -25065, 113 }, { 1120000 } }, + { 1224000, { 1097537, -25925, 113 }, { 1120000 } }, + { 1326000, { 1145373, -26785, 113 }, { 1120000 } }, + { 1428000, { 1195276, -27645, 113 }, { 1120000 } }, + { 1581000, { 1274006, -28935, 113 }, { 1120000 } }, + { 1683000, { 1329076, -29795, 113 }, { 1120000 } }, + { 1785000, { 1386213, -30655, 113 }, { 1120000 } }, + { 1887000, { 1445416, -31515, 113 }, { 1120000 } }, + { 1963500, { 1490873, -32155, 113 }, { 1120000 } }, + // Appending table + { 2091000, { 1580725, -33235, 113 }, { 1120000 } }, + { 2193000, { 1580725, -33235, 113 }, { 1235000 } }, + { 2295000, { 1635431, -34095, 113 }, { 1235000 } }, + { 2397000, { 1702903, -34955, 113 }, { 1235000 } }, +}, + +/* - Erista GPU DVFS Table: + */ +.eristaGpuDvfsTable = { + { 76800, { }, { 814294, 8144, -940, 808, -21583, 226 } }, + { 153600, { }, { 856185, 8144, -940, 808, -21583, 226 } }, + { 230400, { }, { 898077, 8144, -940, 808, -21583, 226 } }, + { 307200, { }, { 939968, 8144, -940, 808, -21583, 226 } }, + { 384000, { }, { 981860, 8144, -940, 808, -21583, 226 } }, + { 460800, { }, { 1023751, 8144, -940, 808, -21583, 226 } }, + { 537600, { }, { 1065642, 8144, -940, 808, -21583, 226 } }, + { 614400, { }, { 1107534, 8144, -940, 808, -21583, 226 } }, + { 691200, { }, { 1149425, 8144, -940, 808, -21583, 226 } }, + { 768000, { }, { 1191317, 8144, -940, 808, -21583, 226 } }, + { 844800, { }, { 1233208, 8144, -940, 808, -21583, 226 } }, + { 921600, { }, { 1275100, 8144, -940, 808, -21583, 226 } }, +// { 998400, { }, { 1316991, 8144, -940, 808, -21583, 226 } }, +// { 1075200, { }, { 1358882, 8144, -940, 808, -21583, 226 } }, + +}, + +.eristaGpuDvfsTableSLT = { + { 76800, { }, { 772403, 8144, -940, 808, -21583, 226 } }, + { 153600, { }, { 814294, 8144, -940, 808, -21583, 226 } }, + { 230400, { }, { 856186, 8144, -940, 808, -21583, 226 } }, + { 307200, { }, { 898077, 8144, -940, 808, -21583, 226 } }, + { 384000, { }, { 939969, 8144, -940, 808, -21583, 226 } }, + { 460800, { }, { 981860, 8144, -940, 808, -21583, 226 } }, + { 537600, { }, { 1023751, 8144, -940, 808, -21583, 226 } }, + { 614400, { }, { 1065643, 8144, -940, 808, -21583, 226 } }, + { 691200, { }, { 1107534, 8144, -940, 808, -21583, 226 } }, + { 768000, { }, { 1149426, 8144, -940, 808, -21583, 226 } }, + { 844800, { }, { 1191317, 8144, -940, 808, -21583, 226 } }, + { 921600, { }, { 1233209, 8144, -940, 808, -21583, 226 } }, +// { 998400, { }, { 1275100, 8144, -940, 808, -21583, 226 } }, +// { 1075200, { }, { 1316991, 8144, -940, 808, -21583, 226 } }, +}, + +.eristaGpuDvfsTableHigh = { + { 76800, { }, { 730512, 8144, -940, 808, -21583, 226 } }, + { 153600, { }, { 772403, 8144, -940, 808, -21583, 226 } }, + { 230400, { }, { 814295, 8144, -940, 808, -21583, 226 } }, + { 307200, { }, { 856186, 8144, -940, 808, -21583, 226 } }, + { 384000, { }, { 898078, 8144, -940, 808, -21583, 226 } }, + { 460800, { }, { 939969, 8144, -940, 808, -21583, 226 } }, + { 537600, { }, { 981860, 8144, -940, 808, -21583, 226 } }, + { 614400, { }, { 1023752, 8144, -940, 808, -21583, 226 } }, + { 691200, { }, { 1065643, 8144, -940, 808, -21583, 226 } }, + { 768000, { }, { 1107535, 8144, -940, 808, -21583, 226 } }, + { 844800, { }, { 1149426, 8144, -940, 808, -21583, 226 } }, + { 921600, { }, { 1191318, 8144, -940, 808, -21583, 226 } }, +// { 998400, { }, { 1233209, 8144, -940, 808, -21583, 226 } }, +// { 1075200, { }, { 1275100, 8144, -940, 808, -21583, 226 } }, +}, + +/* - Mariko GPU DVFS Table: + * 1305600 might not work for some SoCs. + */ +.marikoGpuDvfsTable = { + { 76800, {}, { 610000, } }, + { 153600, {}, { 610000, } }, + { 230400, {}, { 610000, } }, + { 307200, {}, { 610000, } }, + { 384000, {}, { 610000, } }, + { 460800, {}, { 610000, } }, + { 537600, {}, { 801688, -10900, -163, 298, -10599, 162 } }, + { 614400, {}, { 824214, -5743, -452, 238, -6325, 81 } }, + { 691200, {}, { 848830, -3903, -552, 119, -4030, -2 } }, + { 768000, {}, { 891575, -4409, -584, 0, -2849, 39 } }, + { 844800, {}, { 940071, -5367, -602, -60, -63, -93 } }, + { 921600, {}, { 986765, -6637, -614, -179, 1905, -13 } }, + { 998400, {}, { 1098475, -13529, -497, -179, 3626, 9 } }, + { 1075200, {}, { 1163644, -12688, -648, 0, 1077, 40 } }, + { 1152000, {}, { 1204812, -9908, -830, 0, 1469, 110 } }, + { 1228800, {}, { 1277303, -11675, -859, 0, 3722, 313 } }, + { 1267200, {}, { 1335531, -12567, -867, 0, 3681, 559 } }, + // Appending table + //{ 1305600, {}, { 1374130, -13725, -859, 0, 4442, 576 } }, +}, + +.marikoGpuDvfsTableSLT = { + { 76800, {}, { 590000, } }, + { 153600, {}, { 590000, } }, + { 230400, {}, { 590000, } }, + { 307200, {}, { 590000, } }, + { 384000, {}, { 590000, } }, + { 460800, {}, { 795089, -11096, -163, 298, -10421, 162 } }, + { 537600, {}, { 795089, -11096, -163, 298, -10421, 162 } }, + { 614400, {}, { 820606, -6285, -452, 238, -6182, 81 } }, + { 691200, {}, { 846289, -4565, -552, 119, -3958, -2 } }, + { 768000, {}, { 888720, -5110, -584, 0, -2849, 39 } }, + { 844800, {}, { 936634, -6089, -602, -60, -99, -93 } }, + { 921600, {}, { 982562, -7373, -614, -179, 1797, -13 } }, + { 998400, {}, { 1090179, -14125, -497, -179, 3518, 9 } }, + { 1075200, {}, { 1155798, -13465, -648, 0, 1077, 40 } }, + { 1152000, {}, { 1198568, -10904, -830, 0, 1469, 110 } }, + { 1228800, {}, { 1269988, -12707, -859, 0, 3722, 313 } }, + { 1267200, {}, { 1308155, -13694, -867, 0, 3681, 559 } }, +}, +.marikoGpuDvfsTableHiOPT = { + { 76800, {}, { 590000, } }, + { 153600, {}, { 590000, } }, + { 230400, {}, { 590000, } }, + { 307200, {}, { 590000, } }, + { 384000, {}, { 590000, } }, + { 460800, {}, { 590000, } }, + { 537600, {}, { 590000, } }, + { 614400, {}, { 590000, } }, + { 691200, {}, { 838712, -7304, -552, 119, -3750, -2 } }, + { 768000, {}, { 880210, -7955, -584, 0, -2849, 39 } }, + { 844800, {}, { 926398, -8892, -602, -60, -384, -93 } }, + { 921600, {}, { 970060, -10108, -614, -179, 1508, -13 } }, + { 998400, {}, { 1065665, -16075, -497, -179, 3213, 9 } }, + { 1075200, {}, { 1132576, -16093, -648, 0, 1077, 40 } }, + { 1152000, {}, { 1180029, -14534, -830, 0, 1469, 110 } }, + { 1228800, {}, { 1248293, -16383, -859, 0, 3722, 313 } }, + { 1267200, {}, { 1286399, -17475, -867, 0, 3681, 559 } }, +}, + +//.eristaMtcTable = const_cast(&EristaMtcTablePlaceholder), +//.marikoMtcTable = const_cast(&MarikoMtcTablePlaceholder), + +// UV3 tables + +.eristaGpuDvfsTableUv3UnsafeFreqs = { + { 76800, { }, { 814294, 8144, -940, 808, -21583, 226 } }, + { 153600, { }, { 856185, 8144, -940, 808, -21583, 226 } }, + { 230400, { }, { 898077, 8144, -940, 808, -21583, 226 } }, + { 307200, { }, { 939968, 8144, -940, 808, -21583, 226 } }, + { 384000, { }, { 981860, 8144, -940, 808, -21583, 226 } }, + { 460800, { }, { 1023751, 8144, -940, 808, -21583, 226 } }, + { 537600, { }, { 1065642, 8144, -940, 808, -21583, 226 } }, + { 614400, { }, { 1107534, 8144, -940, 808, -21583, 226 } }, + { 691200, { }, { 1149425, 8144, -940, 808, -21583, 226 } }, + { 768000, { }, { 1191317, 8144, -940, 808, -21583, 226 } }, + { 844800, { }, { 1233208, 8144, -940, 808, -21583, 226 } }, + { 921600, { }, { 1275100, 8144, -940, 808, -21583, 226 } }, + { 998400, { }, { 1316991, 8144, -940, 808, -21583, 226 } }, // UNSAFE + { 1075200, { }, { 1358882, 8144, -940, 808, -21583, 226 } }, // UNSAFE + { 1152000, { }, { 1400773, 8144, -940, 808, -21583, 226 } }, // DANGEROUS +}, + +.marikoGpuDvfsTableUv3UnsafeFreqs = { + { 76800, {}, { 590000, } }, + { 153600, {}, { 590000, } }, + { 230400, {}, { 590000, } }, + { 307200, {}, { 590000, } }, + { 384000, {}, { 590000, } }, + { 460800, {}, { 590000, } }, + { 537600, {}, { 590000, } }, + { 614400, {}, { 590000, } }, + { 691200, {}, { 838712, -7304, -552, 119, -3750, -2 } }, + { 768000, {}, { 880210, -7955, -584, 0, -2849, 39 } }, + { 844800, {}, { 926398, -8892, -602, -60, -384, -93 } }, + { 921600, {}, { 970060, -10108, -614, -179, 1508, -13 } }, + { 998400, {}, { 1065665, -16075, -497, -179, 3213, 9 } }, + { 1075200, {}, { 1132576, -16093, -648, 0, 1077, 40 } }, + { 1152000, {}, { 1180029, -14534, -830, 0, 1469, 110 } }, + { 1228800, {}, { 1248293, -16383, -859, 0, 3722, 313 } }, + { 1267200, {}, { 1286399, -17475, -867, 0, 3681, 559 } }, + { 1305600, {}, { 1286399, -17475, -867, 0, 3681, 559 } }, + { 1305600, {}, { 1324505, -17475, -867, 0, 3681, 559 } }, + { 1344000, {}, { 1362611, -17475, -867, 0, 3681, 559 } }, + { 1382400, {}, { 1400717, -17475, -867, 0, 3681, 559 } }, + { 1420800, {}, { 1438823, -17475, -867, 0, 3681, 559 } }, + { 1459200, {}, { 1476929, -17475, -867, 0, 3681, 559 } }, + { 1497600, {}, { 1515035, -17475, -867, 0, 3681, 559 } }, + { 1536000, {}, { 1553141, -17475, -867, 0, 3681, 559 } }, +}, + +.marikoCpuDvfsTableUnsafeFreqs = { { 204000, { 732856, -17335, 113 }, { 1120000 } }, { 306000, { 760024, -18195, 113 }, { 1120000 } }, { 408000, { 789258, -19055, 113 }, { 1120000 } }, @@ -170,128 +458,6 @@ volatile CustomizeTable C = { }, -/* - Erista GPU DVFS Table: - */ -.eristaGpuDvfsTable = { - { 76800, { }, { 814294, 8144, -940, 808, -21583, 226 } }, - { 153600, { }, { 856185, 8144, -940, 808, -21583, 226 } }, - { 230400, { }, { 898077, 8144, -940, 808, -21583, 226 } }, - { 307200, { }, { 939968, 8144, -940, 808, -21583, 226 } }, - { 384000, { }, { 981860, 8144, -940, 808, -21583, 226 } }, - { 460800, { }, { 1023751, 8144, -940, 808, -21583, 226 } }, - { 537600, { }, { 1065642, 8144, -940, 808, -21583, 226 } }, - { 614400, { }, { 1107534, 8144, -940, 808, -21583, 226 } }, - { 691200, { }, { 1149425, 8144, -940, 808, -21583, 226 } }, - { 768000, { }, { 1191317, 8144, -940, 808, -21583, 226 } }, - { 844800, { }, { 1233208, 8144, -940, 808, -21583, 226 } }, - { 921600, { }, { 1275100, 8144, -940, 808, -21583, 226 } }, - { 998400, { }, { 1316991, 8144, -940, 808, -21583, 226 } }, -}, - -/* - Mariko GPU DVFS Table: - * 1305600 might not work for some SoCs. - */ -.marikoGpuDvfsTable = { - { 76800, {}, { 590000, } }, - { 153600, {}, { 590000, } }, - { 230400, {}, { 590000, } }, - { 307200, {}, { 590000, } }, - { 384000, {}, { 590000, } }, - { 460800, {}, { 590000, } }, - { 537600, {}, { 590000, } }, - { 614400, {}, { 590000, } }, - { 691200, {}, { 838712, -7304, -552, 119, -3750, -2 } }, - { 768000, {}, { 880210, -7955, -584, 0, -2849, 39 } }, - { 844800, {}, { 926398, -8892, -602, -60, -384, -93 } }, - { 921600, {}, { 970060, -10108, -614, -179, 1508, -13 } }, - { 998400, {}, { 1065665, -16075, -497, -179, 3213, 9 } }, - { 1075200, {}, { 1132576, -16093, -648, 0, 1077, 40 } }, - { 1152000, {}, { 1180029, -14534, -830, 0, 1469, 110 } }, - { 1228800, {}, { 1248293, -16383, -859, 0, 3722, 313 } }, - { 1267200, {}, { 1286399, -17475, -867, 0, 3681, 559 } }, - // Appending table - { 1305600, {}, { 1304130, -13725, -859, 0, 4442, 576 } }, -}, - -.marikoGpuDvfsTableSLT = { - { 76800, {}, { 635000, } }, - { 153600, {}, { 635000, } }, - { 230400, {}, { 635000, } }, - { 307200, {}, { 635000, } }, - { 384000, {}, { 635000, } }, - { 460800, {}, { 635000, } }, - { 537600, {}, { 635000, } }, - { 614400, {}, { 635000, } }, - { 691200, {}, { 635000, } }, - { 768000, {}, { 635000, } }, - { 844800, {}, { 635000, } }, - { 921600, {}, { 635000, } }, - { 998400, {}, { 901575, -4409, -584, 0, -2849, 39 } }, - { 1075200, {}, { 940071, -5367, -602, -60, -63, -93 } }, - { 1152000, {}, { 996765, -6637, -614, -179, 1905, -13 } }, - { 1228800, {}, { 1098475, -13529, -497, -179, 3626, 9 } }, - { 1267200, {}, { 1131060, -13109, -573, -90, 2352, 25 } }, - { 1305600, {}, { 1163644, -12688, -648, 0, 1077, 40 } }, -}, -.marikoGpuDvfsTableHiOPT = { - { 76800, {}, { 550000, } }, - { 153600, {}, { 550000, } }, - { 230400, {}, { 550000, } }, - { 307200, {}, { 550000, } }, - { 384000, {}, { 550000, } }, - { 460800, {}, { 550000, } }, - { 537600, {}, { 550000, } }, - { 614400, {}, { 550000, } }, - { 691200, {}, { 550000, } }, - { 768000, {}, { 801688, -10900, -163, 298, -10599, 162 } }, - { 844800, {}, { 824214, -5743, -452, 238, -6325, 81 } }, - { 921600, {}, { 848830, -3903, -552, 119, -4030, -2 } }, - { 998400, {}, { 901575, -4409, -584, 0, -2849, 39 } }, - { 1075200, {}, { 940071, -5367, -602, -60, -63, -93 } }, - { 1152000, {}, { 996765, -6637, -614, -179, 1905, -13 } }, - { 1228800, {}, { 1098475, -13529, -497, -179, 3626, 9 } }, - { 1267200, {}, { 1131060, -13109, -573, -90, 2352, 25 } }, - { 1305600, {}, { 1163644, -12688, -648, 0, 1077, 40 } }, -}, - -.marikoGpuDvfsTableUv3 = { // This is for manually defined voltages, ignore the 0v, that means freq not enabled - { 76800, {}, { 0, } }, - { 153600, {}, { 0, } }, - { 230400, {}, { 0, } }, - { 307200, {}, { 0, } }, - { 384000, {}, { 0, } }, - { 460800, {}, { 0, } }, - { 537600, {}, { 0, } }, - { 614400, {}, { 0, } }, - { 691200, {}, { 0, } }, - { 768000, {}, { 0, } }, - { 844800, {}, { 0, } }, - { 921600, {}, { 0, } }, - { 998400, {}, { 0, } }, - { 1075200, {}, { 0, } }, - { 1152000, {}, { 0, } }, - { 1228800, {}, { 0, } }, - { 1267200, {}, { 0, } }, - { 1305600, {}, { 0, } }, - { 1344000, {}, { 0, } }, - { 1382400, {}, { 0, } }, - { 1420800, {}, { 0, } }, - { 1459200, {}, { 0, } }, - { 1497600, {}, { 0, } }, - { 1536000, {}, { 0, } }, -}, -//.eristaMtcTable = const_cast(&EristaMtcTablePlaceholder), -//.marikoMtcTable = const_cast(&MarikoMtcTablePlaceholder), -.eristaCPUvMax = 1300, - -.marikoCPUvMax = 1235, - -.MemVltMax = 1350000, - -.marikoVDDQMax = 650000, - -.marikoB3 = 179, - }; -} +} \ No newline at end of file diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/customize.hpp b/Source/Atmosphere/stratosphere/loader/source/oc/customize.hpp index 8de6b909..da7f2834 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/customize.hpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/customize.hpp @@ -1,6 +1,8 @@ /* - * Copyright (C) hanai3bi (meha) + * Copyright (C) Switch-OC-Suite * + * Copyright (c) 2023 hanai3Bi + * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. @@ -16,7 +18,7 @@ #pragma once -#define CUST_REV 2 +#define CUST_REV 11 #include "oc_common.hpp" #include "pcv/pcv_common.hpp" @@ -43,90 +45,58 @@ constexpr uint32_t MARIKO_MTC_MAGIC = 0x43544D4D; // MMTC typedef struct CustomizeTable { u8 cust[4] = {'C', 'U', 'S', 'T'}; - u32 custRev; + u32 custRev = CUST_REV; u32 mtcConf; u32 commonCpuBoostClock; u32 commonEmcMemVolt; - - // Erista CPU/EMC u32 eristaCpuMaxVolt; u32 eristaEmcMaxClock; - - // Mariko CPU/EMC u32 marikoCpuMaxVolt; u32 marikoEmcMaxClock; u32 marikoEmcVddqVolt; u32 marikoCpuUV; u32 marikoGpuUV; + + u32 eristaCpuUV; + u32 eristaGpuUV; + + u32 enableMarikoGpuUnsafeFreqs; + u32 enableEristaGpuUnsafeFreqs; + + u32 enableMarikoCpuUnsafeFreqs; + u32 enableEristaCpuUnsafeFreqs; + u32 commonGpuVoltOffset; - u32 marikoCpuHighVoltOffset; - u32 marikoCpuHighUV; - - u32 cpuMaxFreq; - u32 gpuMaxFreq; - u32 gpuVmax; - u32 gpuVmin; - + // advanced config u32 marikoEmcDvbShift; + u32 ramTimingPresetOne; + u32 ramTimingPresetTwo; + u32 ramTimingPresetThree; + u32 ramTimingPresetFour; + u32 ramTimingPresetFive; + u32 ramTimingPresetSix; + u32 ramTimingPresetSeven; + // + u32 marikoGpuVoltArray[23]; + u32 eristaGpuVoltArray[15]; - // RAM timings (u32) - u32 latency; - u32 BL; - u32 WL; - u32 RL; - u32 tRFCpb; - u32 tRFCab; - u32 tRAS; - u32 tRPpb; - u32 tRPab; - u32 tRC; - u32 tWTR; - u32 tWR; - u32 tRCD; - u32 tREFpb; - u32 tMRWCKEL; - u32 tSR; - u32 tFAW; - - // RAM timings (double) - double tR2REF; - double tDQSCK_min; - double tDQSCK_max; - double tWPRE; - double tRPST; - double tDQSS_max; - double tDQS2DQ_max; - double tDQSQ; - double tRTP; - double tRRD; - double tXP; - double tCMDCKE; - double tCKELCS; - double tCSCKEH; - double tXSR; - double tCKE; - double tCKCKEH; - - // Mariko GPU voltages - u32 marikoGpuVoltArray[24]; - - CustomizeCpuDvfsTable eristaCpuDvfsTable; CustomizeCpuDvfsTable marikoCpuDvfsTable; CustomizeCpuDvfsTable marikoCpuDvfsTableSLT; + CustomizeGpuDvfsTable eristaGpuDvfsTable; + CustomizeGpuDvfsTable eristaGpuDvfsTableSLT; + CustomizeGpuDvfsTable eristaGpuDvfsTableHigh; + + CustomizeGpuDvfsTable marikoGpuDvfsTable; CustomizeGpuDvfsTable marikoGpuDvfsTableSLT; CustomizeGpuDvfsTable marikoGpuDvfsTableHiOPT; - CustomizeGpuDvfsTable marikoGpuDvfsTableUv3; //EristaMtcTable* eristaMtcTable; //MarikoMtcTable* marikoMtcTable; - u32 eristaCPUvMax; - u32 marikoCPUvMax; - u32 MemVltMax; - u32 marikoVDDQMax; - u8 marikoB3; - + CustomizeGpuDvfsTable eristaGpuDvfsTableUv3UnsafeFreqs; + CustomizeGpuDvfsTable marikoGpuDvfsTableUv3UnsafeFreqs; + CustomizeCpuDvfsTable marikoCpuDvfsTableUnsafeFreqs; } CustomizeTable; //static_assert(sizeof(CustomizeTable) == sizeof(u8) * 4 + sizeof(u32) * 10 + sizeof(CustomizeCpuDvfsTable) * 5 + sizeof(void*) * 2); //static_assert(sizeof(CustomizeTable) == 7000); @@ -136,4 +106,4 @@ extern volatile CustomizeTable C; //extern volatile EristaMtcTable EristaMtcTablePlaceholder; //extern volatile MarikoMtcTable MarikoMtcTablePlaceholder; -} +} \ No newline at end of file diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/mtc_timing_value.hpp b/Source/Atmosphere/stratosphere/loader/source/oc/mtc_timing_value.hpp index e12af6d1..d314e9a6 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/mtc_timing_value.hpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/mtc_timing_value.hpp @@ -16,84 +16,220 @@ * from GCC preprocessor output */ - #pragma once +#pragma once - #include "oc_common.hpp" - namespace ams::ldr::oc { - #define MAX(A, B) std::max(A, B) - #define MIN(A, B) std::min(A, B) - #define CEIL(A) std::ceil(A) - #define FLOOR(A) std::floor(A) - namespace pcv::erista { - // tCK_avg (average clock period) in ns - const double tCK_avg = 1000'000. / C.eristaEmcMaxClock; +#include "oc_common.hpp" - // minimum number of cycles from any read command to any write command, irrespective of bank - const u32 R2W = CEIL (C.RL + CEIL(C.tDQSCK_max/tCK_avg) + C.BL/2 - C.WL + C.tWPRE + FLOOR(C.tRPST)) + 6; - - // Delay Time From WRITE-to-READ - const u32 W2R = C.WL + C.BL/2 + 1 + CEIL(C.tWTR/tCK_avg) - 6; - - // write-to-precharge time for commands to the same bank in cycles - const u32 WTP = C.WL + C.BL/2 + 1 + CEIL(C.tWR/tCK_avg) - 8; - - // #_of_rows per die for 8Gb density - const u32 numOfRows = 65536; - // {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%] - // emc_clk_period = dram_clk / 2; - // 1600 MHz: 5894, but N' set to 6176 (~4.8% margin) - const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(C.tREFpb) * C.eristaEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4); - const u32 REFBW = MIN((u32)65536, REFRESH+64); - - // Write With Auto Precharge to to Power-Down Entry - const u32 WTPDEN = WTP + 1 + CEIL(C.tDQSS_max/tCK_avg) + CEIL(C.tDQS2DQ_max/tCK_avg) + 6; - - // Additional time after t XP hasexpired until the MRR commandmay be issued - const double tMRRI = C.tRCD + 3 * tCK_avg; - - // tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns - const double tPDEX2MRR = C.tXP + tMRRI; - } - namespace pcv::mariko { - // tCK_avg (average clock period) in ns - const double tCK_avg = 1000'000. / C.marikoEmcMaxClock; - // minimum number of cycles from any read command to any write command, irrespective of bank - const u32 R2W = CEIL (C.RL + CEIL(C.tDQSCK_max/tCK_avg) + C.BL/2 - C.WL + C.tWPRE + FLOOR(C.tRPST)); - - // Delay Time From WRITE-to-READ - const u32 W2R = C.WL + C.BL/2 + 1 + CEIL(C.tWTR/tCK_avg); - - // write-to-precharge time for commands to the same bank in cycles - const u32 WTP = C.WL + C.BL/2 + 1 + CEIL(C.tWR/tCK_avg); - - // Read-To-MRW delay - const u32 RTM = C.RL + C.BL/2 + CEIL(C.tDQSCK_max/tCK_avg) + FLOOR(C.tRPST) + CEIL(7.5/tCK_avg); - - // Write-To-MRW/MRR delay - const u32 WTM = C.WL + 1 + C.BL/2 + CEIL(7.5/tCK_avg); - - // Read With AP-To-MRW/MRR delay - const u32 RATM = RTM + CEIL(C.tRTP/tCK_avg) - 8; - - // Write With AP-To-MRW/MRR delay - const u32 WATM = WTM + CEIL(C.tWR/tCK_avg); - - // #_of_rows per die for 8Gb density - const u32 numOfRows = 65536; - // {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%] - // emc_clk_period = dram_clk / 2; - // 1600 MHz: 5894, but N' set to 6176 (~4.8% margin) - const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(C.tREFpb) * C.marikoEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4); - const u32 REFBW = MIN((u32)65536, REFRESH+64); - - // Write With Auto Precharge to to Power-Down Entry - const u32 WTPDEN = WTP + 1 + CEIL(C.tDQSS_max/tCK_avg) + CEIL(C.tDQS2DQ_max/tCK_avg) + 6; - - // Additional time after t XP hasexpired until the MRR commandmay be issued - const double tMRRI = C.tRCD + 3 * tCK_avg; - - // tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns - const double tPDEX2MRR = C.tXP + tMRRI; - } - } - \ No newline at end of file +namespace ams::ldr::oc { + #define MAX(A, B) std::max(A, B) + #define MIN(A, B) std::min(A, B) + #define CEIL(A) std::ceil(A) + #define FLOOR(A) std::floor(A) + + //Preset One + const std::array tRCD_values = {18, 17, 16, 15, 14, 13}; + const std::array tRP_values = {18, 17, 16, 15, 14, 13}; + const std::array tRAS_values = {42, 39, 36, 34, 32, 30}; + + // Preset Two + const std::array tRRD_values = {10, 7.5, 6, 4, 3}; + const std::array tFAW_values = {40, 30, 24, 16, 12}; + + // Preset Three + const std::array tWR_values = {18, 15, 15, 12, 12, 8}; + const std::array tRTP_values = {7.5, 7.5, 6, 6, 4, 4}; + + // Preset Four + const std::array tRFC_values = {140, 120, 100, 80, 70, 60}; + + // Preset Five + const std::array tWTR_values = {10, 8, 6, 4, 2, 1}; + + // Preset Six + const std::array tREFpb_values = {488, 976, 1952, 3256, 9999}; + + const u32 TIMING_PRESET_ONE = C.ramTimingPresetOne; + const u32 TIMING_PRESET_TWO = C.ramTimingPresetTwo; + const u32 TIMING_PRESET_THREE = C.ramTimingPresetThree; + const u32 TIMING_PRESET_FOUR = C.ramTimingPresetFour; + const u32 TIMING_PRESET_FIVE = C.ramTimingPresetFive; + const u32 TIMING_PRESET_SIX = C.ramTimingPresetSix; + const u32 TIMING_PRESET_SEVEN = C.ramTimingPresetSeven; + + // Burst Length + const u32 BL = 16; + + // tRFCpb (refresh cycle time per bank) in ns for 8Gb density + const u32 tRFCpb = !TIMING_PRESET_FOUR ? 140 : tRFC_values[TIMING_PRESET_FOUR-1]; + + // tRFCab (refresh cycle time all banks) in ns for 8Gb density + const u32 tRFCab = !TIMING_PRESET_FOUR ? 280 : 2*tRFCpb; + + // tRAS (row active time) in ns + const u32 tRAS = !TIMING_PRESET_ONE ? 42 : tRAS_values[TIMING_PRESET_ONE-1]; + + // tRPpb (row precharge time per bank) in ns + const u32 tRPpb = !TIMING_PRESET_ONE ? 18 : tRP_values[TIMING_PRESET_ONE-1]; + + // tRPab (row precharge time all banks) in ns + const u32 tRPab = !TIMING_PRESET_ONE ? 21 : tRPpb + 3; + + // tRC (ACTIVATE-ACTIVATE command period same bank) in ns + const u32 tRC = tRPpb + tRAS; + + // DQS output access time from CK_t/CK_c + const double tDQSCK_min = 1.5; + // DQS output access time from CK_t/CK_c + const double tDQSCK_max = 3.5; + // Write preamble (tCK) + const double tWPRE = 1.8; + // Read postamble (tCK) + const double tRPST = 0.4; + // WRITE command to first DQS transition(max) (tCK) + const double tDQSS_max = 1.25; + // DQ-to-DQS offset(max) (ns) + const double tDQS2DQ_max = 0.8; + // DQS_t, DQS_c to DQ skew total, per group, per access (DBI Disabled) + const double tDQSQ = 0.18; + + // Write-to-Read delay + const u32 tWTR = !TIMING_PRESET_FIVE ? 10 : tWTR_values[TIMING_PRESET_FIVE-1]; + + // Internal READ-to-PRE-CHARGE command delay in ns + const double tRTP = !TIMING_PRESET_THREE ? 7.5 : tRTP_values[TIMING_PRESET_THREE-1]; + + // write recovery time + const u32 tWR = !TIMING_PRESET_THREE ? 18 : tWR_values[TIMING_PRESET_THREE-1]; + + // Read to refresh delay + const u32 tR2REF = tRTP + tRPpb; + + // tRCD (RAS-CAS delay) in ns + const u32 tRCD = !TIMING_PRESET_ONE ? 18 : tRCD_values[TIMING_PRESET_ONE-1]; + + // tRRD (Active bank-A to Active bank-B) in ns + const double tRRD = !TIMING_PRESET_TWO ? 10. : tRRD_values[TIMING_PRESET_TWO-1]; + + // tREFpb (average refresh interval per bank) in ns for 8Gb density + const u32 tREFpb = !TIMING_PRESET_SIX ? 488 : tREFpb_values[TIMING_PRESET_SIX-1]; + // tREFab (average refresh interval all 8 banks) in ns for 8Gb density + // const u32 tREFab = tREFpb * 8; + + // tPDEX2WR, tPDEX2RD (timing delay from exiting powerdown mode to a write/read command) in ns + // const u32 tPDEX2 = 10; + // Exit power-down to next valid command delay + const double tXP = 10; + + // Delay from valid command to CKE input LOW in ns + const double tCMDCKE = 1.75; + + // tACT2PDEN (timing delay from an activate, MRS or EMRS command to power-down entry) in ns + // Valid clock and CS requirement after CKE input LOW after MRW command + const u32 tMRWCKEL = 14; + + // Valid CS requirement after CKE input LOW + const double tCKELCS = 5; + + // Valid CS requirement before CKE input HIGH + const double tCSCKEH = 1.75; + + // tXSR (SELF REFRESH exit to next valid command delay) in ns + const double tXSR = tRFCab + 7.5; + + // tCKE (minimum pulse width(HIGH and LOW pulse width)) in ns + const double tCKE = 7.5; + + // Minimum self refresh time (entry to exit) + const u32 tSR = 15; + + // tFAW (Four-bank Activate Window) in ns + const u32 tFAW = !TIMING_PRESET_TWO ? 40 : tFAW_values[TIMING_PRESET_TWO-1]; + + // Valid Clock requirement before CKE Input HIGH in ns + const double tCKCKEH = 1.75; + + // p78 The first valid data is available RL × t CK + t DQSCK + t DQSQ + //const u32 QUSE = RL + CEIL(tDQSCK_min/tCK_avg + tDQSQ); + + namespace pcv::erista { + // tCK_avg (average clock period) in ns + const double tCK_avg = 1000'000. / C.eristaEmcMaxClock; + + // Write Latency + const u32 WL = 14 + TIMING_PRESET_SEVEN; + // Read Latency + const u32 RL = 32 + TIMING_PRESET_SEVEN; + + // minimum number of cycles from any read command to any write command, irrespective of bank + const u32 R2W = CEIL (RL + CEIL(tDQSCK_max/tCK_avg) + BL/2 - WL + tWPRE + FLOOR(tRPST)) + 6; + + // Delay Time From WRITE-to-READ + const u32 W2R = WL + BL/2 + 1 + CEIL(tWTR/tCK_avg) - 6; + + // write-to-precharge time for commands to the same bank in cycles + const u32 WTP = WL + BL/2 + 1 + CEIL(tWR/tCK_avg) - 8; + + // #_of_rows per die for 8Gb density + const u32 numOfRows = 65536; + // {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%] + // emc_clk_period = dram_clk / 2; + // 1600 MHz: 5894, but N' set to 6176 (~4.8% margin) + const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(tREFpb) * C.eristaEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4); + const u32 REFBW = MIN((u32)65536, REFRESH+64); + + // Write With Auto Precharge to to Power-Down Entry + const u32 WTPDEN = WTP + 1 + CEIL(tDQSS_max/tCK_avg) + CEIL(tDQS2DQ_max/tCK_avg) + 6; + + // Additional time after t XP hasexpired until the MRR commandmay be issued + const double tMRRI = tRCD + 3 * tCK_avg; + + // tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns + const double tPDEX2MRR = tXP + tMRRI; + } + namespace pcv::mariko { + // tCK_avg (average clock period) in ns + const double tCK_avg = 1000'000. / C.marikoEmcMaxClock; + // Write Latency + const u32 WL = 14 + TIMING_PRESET_SEVEN; + // Read Latency + const u32 RL = 32 + TIMING_PRESET_SEVEN; + + // minimum number of cycles from any read command to any write command, irrespective of bank + const u32 R2W = CEIL (RL + CEIL(tDQSCK_max/tCK_avg) + BL/2 - WL + tWPRE + FLOOR(tRPST)); + + // Delay Time From WRITE-to-READ + const u32 W2R = WL + BL/2 + 1 + CEIL(tWTR/tCK_avg); + + // write-to-precharge time for commands to the same bank in cycles + const u32 WTP = WL + BL/2 + 1 + CEIL(tWR/tCK_avg); + + // Read-To-MRW delay + const u32 RTM = RL + BL/2 + CEIL(tDQSCK_max/tCK_avg) + FLOOR(tRPST) + CEIL(7.5/tCK_avg); + + // Write-To-MRW/MRR delay + const u32 WTM = WL + 1 + BL/2 + CEIL(7.5/tCK_avg); + + // Read With AP-To-MRW/MRR delay + const u32 RATM = RTM + CEIL(tRTP/tCK_avg) - 8; + + // Write With AP-To-MRW/MRR delay + const u32 WATM = WTM + CEIL(tWR/tCK_avg); + + // #_of_rows per die for 8Gb density + const u32 numOfRows = 65536; + // {REFRESH, REFRESH_LO} = max[(tREF/#_of_rows) / (emc_clk_period) - 64, (tREF/#_of_rows) / (emc_clk_period) * 97%] + // emc_clk_period = dram_clk / 2; + // 1600 MHz: 5894, but N' set to 6176 (~4.8% margin) + const u32 REFRESH = MIN((u32)65472, u32(std::ceil((double(tREFpb) * C.marikoEmcMaxClock / numOfRows * 1.048 / 2 - 64))) / 4 * 4); + const u32 REFBW = MIN((u32)65536, REFRESH+64); + + // Write With Auto Precharge to to Power-Down Entry + const u32 WTPDEN = WTP + 1 + CEIL(tDQSS_max/tCK_avg) + CEIL(tDQS2DQ_max/tCK_avg) + 6; + + // Additional time after t XP hasexpired until the MRR commandmay be issued + const double tMRRI = tRCD + 3 * tCK_avg; + + // tPDEX2MRR (timing delay from exiting powerdown mode to MRR command) in ns + const double tPDEX2MRR = tXP + tMRRI; + } +} diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.cpp b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.cpp index ab500af7..1452a0d8 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.cpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.cpp @@ -1,6 +1,8 @@ /* - * Copyright (C) hanai3bi (meha) + * Copyright (C) Switch-OC-Suite * + * Copyright (c) 2023 hanai3Bi + * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. @@ -93,9 +95,34 @@ void SafetyCheck() { u32 eristaCpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaCpuDvfsTable)->freq); u32 marikoCpuDvfsMaxFreq = static_cast(C.marikoCpuUV ? GetDvfsTableLastEntry(C.marikoCpuDvfsTableSLT)->freq : GetDvfsTableLastEntry(C.marikoCpuDvfsTable)->freq); - u32 eristaGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq); + u32 eristaGpuDvfsMaxFreq; + switch (C.eristaGpuUV) + { + case 0: + eristaGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq); + break; + case 1: + eristaGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaGpuDvfsTableSLT)->freq); + break; + case 2: + eristaGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaGpuDvfsTableHigh)->freq); + break; + case 3: + if(C.enableEristaGpuUnsafeFreqs) + { + eristaGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaGpuDvfsTableUv3UnsafeFreqs)->freq); + } + else + { + eristaGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq); + } + break; + default: + eristaGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq); + break; + } + u32 marikoGpuDvfsMaxFreq; - u32 temporaryMaxFreqForCalculation = C.gpuMaxFreq; switch (C.marikoGpuUV) { case 0: marikoGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.marikoGpuDvfsTable)->freq); @@ -106,27 +133,23 @@ void SafetyCheck() { case 2: marikoGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.marikoGpuDvfsTableHiOPT)->freq); break; - case 3: - marikoGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.marikoGpuDvfsTableUv3)->freq); - temporaryMaxFreqForCalculation = 1536'000; - break; default: marikoGpuDvfsMaxFreq = static_cast(GetDvfsTableLastEntry(C.marikoGpuDvfsTable)->freq); break; } sValidator validators[] = { - { C.commonCpuBoostClock, 1020'000, C.cpuMaxFreq + 1, true }, - { C.commonEmcMemVolt, 1000'000, C.MemVltMax + 1 }, - { C.eristaCpuMaxVolt, 1100, C.eristaCPUvMax + 1 }, - { C.eristaEmcMaxClock, 1600'000, 2428'800 }, - { C.marikoCpuMaxVolt, 800, C.marikoCPUvMax + 1 }, - { C.marikoEmcMaxClock, 1600'000, 3504'000 }, - { C.marikoEmcVddqVolt, 550'000, C.marikoVDDQMax + 1 }, - { eristaCpuDvfsMaxFreq, 1785'000, C.cpuMaxFreq + 1 }, - { marikoCpuDvfsMaxFreq, 1785'000, C.cpuMaxFreq + 1 }, - { eristaGpuDvfsMaxFreq, 76'800, C.gpuMaxFreq + 1 }, - { marikoGpuDvfsMaxFreq, 76'800, temporaryMaxFreqForCalculation + 1 }, + { C.commonCpuBoostClock, 1020'000, 3000'000, true }, + { C.commonEmcMemVolt, 1100'000, 1500'000 }, // Official burst vmax for the RAMs + { C.eristaCpuMaxVolt, 1100, 1300 }, + { C.eristaEmcMaxClock, 1600'000, 2600'200 }, + { C.marikoCpuMaxVolt, 1100, 1300 }, + { C.marikoEmcMaxClock, 1600'000, 3500'000 }, + { C.marikoEmcVddqVolt, 550'000, 650'000 }, + { eristaCpuDvfsMaxFreq, 1785'000, 3000'000 }, + { marikoCpuDvfsMaxFreq, 1785'000, 3000'000 }, + { eristaGpuDvfsMaxFreq, 768'000, 1536'000 }, + { marikoGpuDvfsMaxFreq, 768'000, 1536'000 }, }; for (auto& i : validators) { @@ -146,4 +169,4 @@ void Patch(uintptr_t mapped_nso, size_t nso_size) { #endif } -} +} \ No newline at end of file diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.hpp b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.hpp index 2411a1a7..762a65c8 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.hpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv.hpp @@ -2,7 +2,7 @@ * Copyright (C) Switch-OC-Suite * * Copyright (c) 2023 hanai3Bi - * + * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. @@ -21,234 +21,302 @@ #include "../oc_common.hpp" #include "pcv_common.hpp" -namespace ams::ldr::oc::pcv { +namespace ams::ldr::oc::pcv +{ -namespace mariko { - constexpr cvb_entry_t CpuCvbTableDefault[] = { - // CPUB01_CVB_TABLE - { 204000, { 721589, -12695, 27 }, {} }, - { 306000, { 747134, -14195, 27 }, {} }, - { 408000, { 776324, -15705, 27 }, {} }, - { 510000, { 809160, -17205, 27 }, {} }, - { 612000, { 845641, -18715, 27 }, {} }, - { 714000, { 885768, -20215, 27 }, {} }, - { 816000, { 929540, -21725, 27 }, {} }, - { 918000, { 976958, -23225, 27 }, {} }, - { 1020000, { 1028021, -24725, 27 }, { 1120000 } }, - { 1122000, { 1082730, -26235, 27 }, { 1120000 } }, - { 1224000, { 1141084, -27735, 27 }, { 1120000 } }, - { 1326000, { 1203084, -29245, 27 }, { 1120000 } }, - { 1428000, { 1268729, -30745, 27 }, { 1120000 } }, - { 1581000, { 1374032, -33005, 27 }, { 1120000 } }, - { 1683000, { 1448791, -34505, 27 }, { 1120000 } }, - { 1785000, { 1527196, -36015, 27 }, { 1120000 } }, - { 1887000, { 1609246, -37515, 27 }, { 1120000 } }, - { 1963500, { 1675751, -38635, 27 }, { 1120000 } }, - { }, - }; + namespace mariko + { + constexpr cvb_entry_t CpuCvbTableDefault[] = { + // CPUB01_CVB_TABLE + {204000, {721589, -12695, 27}, {}}, + {306000, {747134, -14195, 27}, {}}, + {408000, {776324, -15705, 27}, {}}, + {510000, {809160, -17205, 27}, {}}, + {612000, {845641, -18715, 27}, {}}, + {714000, {885768, -20215, 27}, {}}, + {816000, {929540, -21725, 27}, {}}, + {918000, {976958, -23225, 27}, {}}, + {1020000, {1028021, -24725, 27}, {1120000}}, + {1122000, {1082730, -26235, 27}, {1120000}}, + {1224000, {1141084, -27735, 27}, {1120000}}, + {1326000, {1203084, -29245, 27}, {1120000}}, + {1428000, {1268729, -30745, 27}, {1120000}}, + {1581000, {1374032, -33005, 27}, {1120000}}, + {1683000, {1448791, -34505, 27}, {1120000}}, + {1785000, {1527196, -36015, 27}, {1120000}}, + {1887000, {1609246, -37515, 27}, {1120000}}, + {1963500, {1675751, -38635, 27}, {1120000}}, + {}, + }; - constexpr u16 CpuMinVolts[] = { 800, 637, 620, 610 }; + constexpr u16 CpuMinVolts[] = {800, 637, 620, 610}; - constexpr u32 CpuClkOfficial = 1963'500; - constexpr u32 CpuVoltOfficial = 1120; + constexpr u32 CpuClkOfficial = 1963'500; + constexpr u32 CpuVoltOfficial = 1120; - constexpr cvb_entry_t GpuCvbTableDefault[] = { - // GPUB01_NA_CVB_TABLE - { 76800, {}, { 610000, } }, - { 153600, {}, { 610000, } }, - { 230400, {}, { 610000, } }, - { 307200, {}, { 610000, } }, - { 384000, {}, { 610000, } }, - { 460800, {}, { 610000, } }, - { 537600, {}, { 801688, -10900, -163, 298, -10599, 162 } }, - { 614400, {}, { 824214, -5743, -452, 238, -6325, 81 } }, - { 691200, {}, { 848830, -3903, -552, 119, -4030, -2 } }, - { 768000, {}, { 891575, -4409, -584, 0, -2849, 39 } }, - { 844800, {}, { 940071, -5367, -602, -60, -63, -93 } }, - { 921600, {}, { 986765, -6637, -614, -179, 1905, -13 } }, - { 998400, {}, { 1098475, -13529, -497, -179, 3626, 9 } }, - { 1075200, {}, { 1163644, -12688, -648, 0, 1077, 40 } }, - { 1152000, {}, { 1204812, -9908, -830, 0, 1469, 110 } }, - { 1228800, {}, { 1277303, -11675, -859, 0, 3722, 313 } }, - { 1267200, {}, { 1335531, -12567, -867, 0, 3681, 559 } }, - { }, - }; + constexpr cvb_entry_t GpuCvbTableDefault[] = { + // GPUB01_NA_CVB_TABLE + {76800, {}, { + 610000, + }}, + {153600, {}, { + 610000, + }}, + {230400, {}, { + 610000, + }}, + {307200, {}, { + 610000, + }}, + {384000, {}, { + 610000, + }}, + {460800, {}, { + 610000, + }}, + {537600, {}, {801688, -10900, -163, 298, -10599, 162}}, + {614400, {}, {824214, -5743, -452, 238, -6325, 81}}, + {691200, {}, {848830, -3903, -552, 119, -4030, -2}}, + {768000, {}, {891575, -4409, -584, 0, -2849, 39}}, + {844800, {}, {940071, -5367, -602, -60, -63, -93}}, + {921600, {}, {986765, -6637, -614, -179, 1905, -13}}, + {998400, {}, {1098475, -13529, -497, -179, 3626, 9}}, + {1075200, {}, {1163644, -12688, -648, 0, 1077, 40}}, + {1152000, {}, {1204812, -9908, -830, 0, 1469, 110}}, + {1228800, {}, {1277303, -11675, -859, 0, 3722, 313}}, + {1267200, {}, {1335531, -12567, -867, 0, 3681, 559}}, + {}, + }; - constexpr u32 GpuClkPllLimit = 1300'000'000; + constexpr u32 GpuClkPllLimit = 1300'000'000; - /* GPU Max Clock asm Pattern: - * - * MOV W11, #0x1000 MOV (wide immediate) 0x1000 0xB (11) - * sf | opc | | hw | imm16 | Rd - * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 - * 0 | 1 0 | 1 0 0 1 0 1| 0 0| 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 |0 1 0 1 1 - * - * MOVK W11, #0xE, LSL#16 16 0xE 0xB (11) - * sf | opc | | hw | imm16 | Rd - * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 - * 0 | 1 1 | 1 0 0 1 0 1| 0 1| 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 |0 1 0 1 1 - */ - inline constexpr u32 asm_pattern[] = { 0x52820000, 0x72A001C0 }; - inline auto asm_compare_no_rd = [](u32 ins1, u32 ins2) { return ((ins1 ^ ins2) >> 5) == 0; }; - inline auto asm_get_rd = [](u32 ins) { return ins & ((1 << 5) - 1); }; - inline auto asm_set_rd = [](u32 ins, u8 rd) { return (ins & 0xFFFFFFE0) | (rd & 0x1F); }; - inline auto asm_set_imm16 = [](u32 ins, u16 imm) { return (ins & 0xFFE0001F) | ((imm & 0xFFFF) << 5); }; + /* GPU Max Clock asm Pattern: + * + * MOV W11, #0x1000 MOV (wide immediate) 0x1000 0xB (11) + * sf | opc | | hw | imm16 | Rd + * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 + * 0 | 1 0 | 1 0 0 1 0 1| 0 0| 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 |0 1 0 1 1 + * + * MOVK W11, #0xE, LSL#16 16 0xE 0xB (11) + * sf | opc | | hw | imm16 | Rd + * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 + * 0 | 1 1 | 1 0 0 1 0 1| 0 1| 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 |0 1 0 1 1 + */ + inline constexpr u32 asm_pattern[] = {0x52820000, 0x72A001C0}; + inline auto asm_compare_no_rd = [](u32 ins1, u32 ins2) + { return ((ins1 ^ ins2) >> 5) == 0; }; + inline auto asm_get_rd = [](u32 ins) + { return ins & ((1 << 5) - 1); }; + inline auto asm_set_rd = [](u32 ins, u8 rd) + { return (ins & 0xFFFFFFE0) | (rd & 0x1F); }; + inline auto asm_set_imm16 = [](u32 ins, u16 imm) + { return (ins & 0xFFE0001F) | ((imm & 0xFFFF) << 5); }; - inline bool GpuMaxClockPatternFn(u32* ptr32) { - return asm_compare_no_rd(*ptr32, asm_pattern[0]); - } - - constexpr emc_dvb_dvfs_table_t EmcDvbTableDefault[] = { - { 204000, { 637, 637, 637, } }, - { 408000, { 637, 637, 637, } }, - { 800000, { 637, 637, 637, } }, - { 1065600, { 637, 637, 637, } }, - { 1331200, { 650, 637, 637, } }, - { 1600000, { 675, 650, 637, } }, - }; - - constexpr u32 EmcClkOSAlt = 1331'200; - constexpr u32 EmcClkPllmLimit = 2133'000'000; - constexpr u32 EmcVddqDefault = 600'000; - constexpr u32 MemVdd2Default = 1100'000; - - constexpr u32 MTC_TABLE_REV = 3; - - void Patch(uintptr_t mapped_nso, size_t nso_size); - -} - -namespace erista { - constexpr cvb_entry_t CpuCvbTableDefault[] = { - // CPU_PLL_CVB_TABLE_ODN - { 204000, { 721094 }, {} }, - { 306000, { 754040 }, {} }, - { 408000, { 786986 }, {} }, - { 510000, { 819932 }, {} }, - { 612000, { 852878 }, {} }, - { 714000, { 885824 }, {} }, - { 816000, { 918770 }, {} }, - { 918000, { 951716 }, {} }, - { 1020000, { 984662 }, { -2875621, 358099, -8585 } }, - { 1122000, { 1017608 }, { -52225, 104159, -2816 } }, - { 1224000, { 1050554 }, { 1076868, 8356, -727 } }, - { 1326000, { 1083500 }, { 2208191, -84659, 1240 } }, - { 1428000, { 1116446 }, { 2519460, -105063, 1611 } }, - { 1581000, { 1130000 }, { 2889664, -122173, 1834 } }, - { 1683000, { 1168000 }, { 5100873, -279186, 4747 } }, - { 1785000, { 1227500 }, { 5100873, -279186, 4747 } }, - { }, - }; - - constexpr u32 CpuVoltL4T = 1235'000; - - constexpr u16 CpuMinVolts[] = { 950, 850, 825, 810 }; - - inline bool CpuMaxVoltPatternFn(u32* ptr32) { - u32 val = *ptr32; - return (val == 1132 || val == 1170 || val == 1227); - } - - constexpr u32 GpuClkPllLimit = 921'600'000; - - /* GPU Max Clock asm Pattern: - * - * MOV W11, #0x1000 MOV (wide immediate) 0x1000 0xB (11) - * sf | opc | | hw | imm16 | Rd - * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 - * 0 | 1 0 | 1 0 0 1 0 1| 0 0| 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 |0 1 0 1 1 - * - * MOVK W11, #0xE, LSL#16 16 0xE 0xB (11) - * sf | opc | | hw | imm16 | Rd - * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 - * 0 | 1 1 | 1 0 0 1 0 1| 0 1| 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 |0 1 0 1 1 - */ - inline constexpr u32 asm_pattern[] = { 0x52820000, 0x72A001C0 }; - inline auto asm_compare_no_rd = [](u32 ins1, u32 ins2) { return ((ins1 ^ ins2) >> 5) == 0; }; - inline auto asm_get_rd = [](u32 ins) { return ins & ((1 << 5) - 1); }; - inline auto asm_set_rd = [](u32 ins, u8 rd) { return (ins & 0xFFFFFFE0) | (rd & 0x1F); }; - inline auto asm_set_imm16 = [](u32 ins, u16 imm) { return (ins & 0xFFE0001F) | ((imm & 0xFFFF) << 5); }; - - inline bool GpuMaxClockPatternFn(u32* ptr32) { - return asm_compare_no_rd(*ptr32, asm_pattern[0]); - } - - constexpr cvb_entry_t GpuCvbTableDefault[] = { - // NA_FREQ_CVB_TABLE - { 76800, { }, { 814294, 8144, -940, 808, -21583, 226 } }, - { 153600, { }, { 856185, 8144, -940, 808, -21583, 226 } }, - { 230400, { }, { 898077, 8144, -940, 808, -21583, 226 } }, - { 307200, { }, { 939968, 8144, -940, 808, -21583, 226 } }, - { 384000, { }, { 981860, 8144, -940, 808, -21583, 226 } }, - { 460800, { }, { 1023751, 8144, -940, 808, -21583, 226 } }, - { 537600, { }, { 1065642, 8144, -940, 808, -21583, 226 } }, - { 614400, { }, { 1107534, 8144, -940, 808, -21583, 226 } }, - { 691200, { }, { 1149425, 8144, -940, 808, -21583, 226 } }, - { 768000, { }, { 1191317, 8144, -940, 808, -21583, 226 } }, - { 844800, { }, { 1233208, 8144, -940, 808, -21583, 226 } }, - { 921600, { }, { 1275100, 8144, -940, 808, -21583, 226 } }, - { }, - }; - - constexpr u32 MemVoltHOS = 1125'000; - constexpr u32 EmcClkPllmLimit = 1866'000'000; - - constexpr u32 MTC_TABLE_REV = 7; - - void Patch(uintptr_t mapped_nso, size_t nso_size); -} - -template -Result CpuFreqCvbTable(u32* ptr) { - cvb_entry_t* default_table = isMariko ? (cvb_entry_t *)(&mariko::CpuCvbTableDefault) : (cvb_entry_t *)(&erista::CpuCvbTableDefault); - cvb_entry_t* customize_table = const_cast(isMariko ? (C.marikoCpuUV ? C.marikoCpuDvfsTableSLT : C.marikoCpuDvfsTable) : C.eristaCpuDvfsTable); - - u32 cpu_max_volt = isMariko ? C.marikoCpuMaxVolt : C.eristaCpuMaxVolt; - u32 cpu_freq_threshold = 1020'000; - if (isMariko) { - cpu_freq_threshold = C.marikoCpuUV ? 2193'000 : 2091'000; - } else { - cpu_freq_threshold = cpu_max_volt >= 1235 ? 1887'000 : 1428'000; - } - - size_t default_entry_count = GetDvfsTableEntryCount(default_table); - size_t default_table_size = default_entry_count * sizeof(cvb_entry_t); - size_t customize_entry_count = GetDvfsTableEntryCount(customize_table); - size_t customize_table_size = customize_entry_count * sizeof(cvb_entry_t); - - // Validate existing table - cvb_entry_t* table_free = reinterpret_cast(ptr) + 1; - void* cpu_cvb_table_head = reinterpret_cast(table_free) - default_table_size; - bool validated = std::memcmp(cpu_cvb_table_head, default_table, default_table_size) == 0; - R_UNLESS(validated, ldr::ResultInvalidCpuDvfs()); - - std::memcpy(cpu_cvb_table_head, static_cast(customize_table), customize_table_size); - - // Patch CPU max volt - if (cpu_max_volt) { - cvb_entry_t* entry = static_cast(cpu_cvb_table_head); - for (size_t i = 0; i < customize_entry_count; i++) { - if (entry->freq >= cpu_freq_threshold) { - if (isMariko) { - PATCH_OFFSET(&(entry->cvb_pll_param.c0), cpu_max_volt * 1000); - } else { - PATCH_OFFSET(&(entry->cvb_dfll_param.c0), cpu_max_volt * 1000); - } - } - entry++; + inline bool GpuMaxClockPatternFn(u32 *ptr32) + { + return asm_compare_no_rd(*ptr32, asm_pattern[0]); } + + constexpr emc_dvb_dvfs_table_t EmcDvbTableDefault[] = { + {204000, { + 637, + 637, + 637, + }}, + {408000, { + 637, + 637, + 637, + }}, + {800000, { + 637, + 637, + 637, + }}, + {1065600, { + 637, + 637, + 637, + }}, + {1331200, { + 650, + 637, + 637, + }}, + {1600000, { + 675, + 650, + 637, + }}, + }; + + constexpr u32 EmcClkOSAlt = 1331'200; + constexpr u32 EmcClkPllmLimit = 2133'000'000; + constexpr u32 EmcVddqDefault = 600'000; + constexpr u32 MemVdd2Default = 1100'000; + + constexpr u32 MTC_TABLE_REV = 3; + + void Patch(uintptr_t mapped_nso, size_t nso_size); + } - R_SUCCEED(); -} + namespace erista + { + constexpr cvb_entry_t CpuCvbTableDefault[] = { + // CPU_PLL_CVB_TABLE_ODN + {204000, {721094}, {}}, + {306000, {754040}, {}}, + {408000, {786986}, {}}, + {510000, {819932}, {}}, + {612000, {852878}, {}}, + {714000, {885824}, {}}, + {816000, {918770}, {}}, + {918000, {951716}, {}}, + {1020000, {984662}, {-2875621, 358099, -8585}}, + {1122000, {1017608}, {-52225, 104159, -2816}}, + {1224000, {1050554}, {1076868, 8356, -727}}, + {1326000, {1083500}, {2208191, -84659, 1240}}, + {1428000, {1116446}, {2519460, -105063, 1611}}, + {1581000, {1130000}, {2889664, -122173, 1834}}, + {1683000, {1168000}, {5100873, -279186, 4747}}, + {1785000, {1227500}, {5100873, -279186, 4747}}, + {}, + }; -template -Result GpuFreqCvbTable(u32* ptr) { - cvb_entry_t* default_table = isMariko ? (cvb_entry_t *)(&mariko::GpuCvbTableDefault) : (cvb_entry_t *)(&erista::GpuCvbTableDefault); - cvb_entry_t* customize_table; - if (isMariko) { - switch (C.marikoGpuUV) { - case 0: + constexpr u32 CpuVoltL4T = 1235'000; + + constexpr u16 CpuMinVolts[] = {950, 850, 825, 810}; + + inline bool CpuMaxVoltPatternFn(u32 *ptr32) + { + u32 val = *ptr32; + return (val == 1132 || val == 1170 || val == 1227); + } + + constexpr u32 GpuClkPllLimit = 921'600'000; + + /* GPU Max Clock asm Pattern: + * + * MOV W11, #0x1000 MOV (wide immediate) 0x1000 0xB (11) + * sf | opc | | hw | imm16 | Rd + * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 + * 0 | 1 0 | 1 0 0 1 0 1| 0 0| 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 |0 1 0 1 1 + * + * MOVK W11, #0xE, LSL#16 16 0xE 0xB (11) + * sf | opc | | hw | imm16 | Rd + * #31 |30 29|28 27 26 25 24 23|22 21|20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 |4 3 2 1 0 + * 0 | 1 1 | 1 0 0 1 0 1| 0 1| 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 |0 1 0 1 1 + */ + inline constexpr u32 asm_pattern[] = {0x52820000, 0x72A001C0}; + inline auto asm_compare_no_rd = [](u32 ins1, u32 ins2) + { return ((ins1 ^ ins2) >> 5) == 0; }; + inline auto asm_get_rd = [](u32 ins) + { return ins & ((1 << 5) - 1); }; + inline auto asm_set_rd = [](u32 ins, u8 rd) + { return (ins & 0xFFFFFFE0) | (rd & 0x1F); }; + inline auto asm_set_imm16 = [](u32 ins, u16 imm) + { return (ins & 0xFFE0001F) | ((imm & 0xFFFF) << 5); }; + + inline bool GpuMaxClockPatternFn(u32 *ptr32) + { + return asm_compare_no_rd(*ptr32, asm_pattern[0]); + } + + constexpr cvb_entry_t GpuCvbTableDefault[] = { + // NA_FREQ_CVB_TABLE + {76800, {}, {814294, 8144, -940, 808, -21583, 226}}, + {153600, {}, {856185, 8144, -940, 808, -21583, 226}}, + {230400, {}, {898077, 8144, -940, 808, -21583, 226}}, + {307200, {}, {939968, 8144, -940, 808, -21583, 226}}, + {384000, {}, {981860, 8144, -940, 808, -21583, 226}}, + {460800, {}, {1023751, 8144, -940, 808, -21583, 226}}, + {537600, {}, {1065642, 8144, -940, 808, -21583, 226}}, + {614400, {}, {1107534, 8144, -940, 808, -21583, 226}}, + {691200, {}, {1149425, 8144, -940, 808, -21583, 226}}, + {768000, {}, {1191317, 8144, -940, 808, -21583, 226}}, + {844800, {}, {1233208, 8144, -940, 808, -21583, 226}}, + {921600, {}, {1275100, 8144, -940, 808, -21583, 226}}, + {}, + }; + + constexpr u32 MemVoltHOS = 1125'000; + constexpr u32 EmcClkPllmLimit = 1866'000'000; + + constexpr u32 MTC_TABLE_REV = 7; + + void Patch(uintptr_t mapped_nso, size_t nso_size); + } + + template + Result CpuFreqCvbTable(u32 *ptr) + { + cvb_entry_t *default_table = isMariko ? (cvb_entry_t *)(&mariko::CpuCvbTableDefault) : (cvb_entry_t *)(&erista::CpuCvbTableDefault); + cvb_entry_t *customize_table = const_cast( + isMariko + ? (C.enableMarikoCpuUnsafeFreqs + ? C.marikoCpuDvfsTableUnsafeFreqs + : (C.marikoCpuUV ? C.marikoCpuDvfsTableSLT : C.marikoCpuDvfsTable)) + : C.eristaCpuDvfsTable + ); + u32 cpu_max_volt = isMariko ? C.marikoCpuMaxVolt : C.eristaCpuMaxVolt; + u32 cpu_freq_threshold = 1020'000; + if (isMariko) + { + cpu_freq_threshold = C.marikoCpuUV ? 2193'000 : 2091'000; + } + else + { + cpu_freq_threshold = cpu_max_volt >= 1300 ? 1887'000 : 1428'000; + } + + size_t default_entry_count = GetDvfsTableEntryCount(default_table); + size_t default_table_size = default_entry_count * sizeof(cvb_entry_t); + size_t customize_entry_count = GetDvfsTableEntryCount(customize_table); + size_t customize_table_size = customize_entry_count * sizeof(cvb_entry_t); + + // Validate existing table + cvb_entry_t *table_free = reinterpret_cast(ptr) + 1; + void *cpu_cvb_table_head = reinterpret_cast(table_free) - default_table_size; + bool validated = std::memcmp(cpu_cvb_table_head, default_table, default_table_size) == 0; + R_UNLESS(validated, ldr::ResultInvalidCpuDvfs()); + + std::memcpy(cpu_cvb_table_head, static_cast(customize_table), customize_table_size); + + // Patch CPU max volt + if (cpu_max_volt) + { + cvb_entry_t *entry = static_cast(cpu_cvb_table_head); + for (size_t i = 0; i < customize_entry_count; i++) + { + if (entry->freq >= cpu_freq_threshold) + { + if (isMariko) + { + PATCH_OFFSET(&(entry->cvb_pll_param.c0), cpu_max_volt * 1000); + } + else + { + PATCH_OFFSET(&(entry->cvb_dfll_param.c0), cpu_max_volt * 1000); + } + } + entry++; + } + } + + R_SUCCEED(); + } + + template + Result GpuFreqCvbTable(u32 *ptr) + { + cvb_entry_t *default_table = isMariko ? (cvb_entry_t *)(&mariko::GpuCvbTableDefault) : (cvb_entry_t *)(&erista::GpuCvbTableDefault); + cvb_entry_t *customize_table; + if (isMariko) + { + switch (C.marikoGpuUV) + { + case 0: customize_table = const_cast(C.marikoGpuDvfsTable); break; case 1: @@ -257,84 +325,133 @@ Result GpuFreqCvbTable(u32* ptr) { case 2: customize_table = const_cast(C.marikoGpuDvfsTableHiOPT); break; + case 3: + if(C.enableMarikoGpuUnsafeFreqs) + { + customize_table = const_cast(C.marikoGpuDvfsTableUv3UnsafeFreqs); + } + else + { + customize_table = const_cast(C.marikoGpuDvfsTable); + } + break; default: customize_table = const_cast(C.marikoGpuDvfsTable); break; + } } - } else { - customize_table = const_cast(C.eristaGpuDvfsTable); - } - - size_t default_entry_count = GetDvfsTableEntryCount(default_table); - size_t default_table_size = default_entry_count * sizeof(cvb_entry_t); - size_t customize_entry_count = GetDvfsTableEntryCount(customize_table); - size_t customize_table_size = customize_entry_count * sizeof(cvb_entry_t); - - // Validate existing table - cvb_entry_t* table_free = reinterpret_cast(ptr) + 1; - void* gpu_cvb_table_head = reinterpret_cast(table_free) - default_table_size; - bool validated = std::memcmp(gpu_cvb_table_head, default_table, default_table_size) == 0; - R_UNLESS(validated, ldr::ResultInvalidGpuDvfs()); - - std::memcpy(gpu_cvb_table_head, (void*)customize_table, customize_table_size); - - // Patch GPU volt - if (isMariko && C.marikoGpuUV == 3) { - cvb_entry_t* entry = static_cast(gpu_cvb_table_head); - for (size_t i = 0; i < customize_entry_count; i++) { - u32 patched_voltage = C.marikoGpuVoltArray[i]; - if (C.marikoGpuVoltArray[i] < C.gpuVmin) + else + { + switch (C.eristaGpuUV) { - patched_voltage = C.gpuVmin; + case 0: + customize_table = const_cast(C.eristaGpuDvfsTable); + break; + case 1: + customize_table = const_cast(C.eristaGpuDvfsTableSLT); + break; + case 2: + customize_table = const_cast(C.eristaGpuDvfsTableHigh); + break; + case 3: + if(C.enableEristaGpuUnsafeFreqs) + { + customize_table = const_cast(C.eristaGpuDvfsTableUv3UnsafeFreqs); + } + else + { + customize_table = const_cast(C.eristaGpuDvfsTable); + } + break; + default: + customize_table = const_cast(C.eristaGpuDvfsTable); + break; } - if(C.marikoGpuVoltArray[i] > C.gpuVmax) { - patched_voltage = C.gpuVmax; + } + + size_t default_entry_count = GetDvfsTableEntryCount(default_table); + size_t default_table_size = default_entry_count * sizeof(cvb_entry_t); + size_t customize_entry_count = GetDvfsTableEntryCount(customize_table); + size_t customize_table_size = customize_entry_count * sizeof(cvb_entry_t); + + // Validate existing table + cvb_entry_t *table_free = reinterpret_cast(ptr) + 1; + void *gpu_cvb_table_head = reinterpret_cast(table_free) - default_table_size; + bool validated = std::memcmp(gpu_cvb_table_head, default_table, default_table_size) == 0; + R_UNLESS(validated, ldr::ResultInvalidGpuDvfs()); + + std::memcpy(gpu_cvb_table_head, (void *)customize_table, customize_table_size); + + // Patch GPU volt + if (C.marikoGpuUV == 3 || C.eristaGpuUV == 1) + { + cvb_entry_t *entry = static_cast(gpu_cvb_table_head); + for (size_t i = 0; i < customize_entry_count; i++) + { + if (isMariko) + { + if (C.marikoGpuVoltArray[i] == 0) + { + continue; + } + PATCH_OFFSET(&(entry->cvb_pll_param.c0), C.marikoGpuVoltArray[i] * 1000); + } + else + { + if (C.eristaGpuVoltArray[i] == 0) + { + continue; + } + PATCH_OFFSET(&(entry->cvb_pll_param.c0), C.eristaGpuVoltArray[i] * 1000); + } + PATCH_OFFSET(&(entry->cvb_pll_param.c1), 0); + PATCH_OFFSET(&(entry->cvb_pll_param.c2), 0); + PATCH_OFFSET(&(entry->cvb_pll_param.c3), 0); + PATCH_OFFSET(&(entry->cvb_pll_param.c4), 0); + PATCH_OFFSET(&(entry->cvb_pll_param.c5), 0); + entry++; } - - PATCH_OFFSET(&(entry->cvb_pll_param.c0), patched_voltage * 1000); - PATCH_OFFSET(&(entry->cvb_pll_param.c1), 0); - PATCH_OFFSET(&(entry->cvb_pll_param.c2), 0); - PATCH_OFFSET(&(entry->cvb_pll_param.c3), 0); - PATCH_OFFSET(&(entry->cvb_pll_param.c4), 0); - PATCH_OFFSET(&(entry->cvb_pll_param.c5), 0); - entry++; } - } - else if (C.commonGpuVoltOffset) { - cvb_entry_t* entry = static_cast(gpu_cvb_table_head); - for (size_t i = 0; i < customize_entry_count; i++) { - PATCH_OFFSET(&(entry->cvb_pll_param.c0), (entry->cvb_pll_param.c0 - C.commonGpuVoltOffset*1000)); - entry++; + else if (C.commonGpuVoltOffset) + { + cvb_entry_t *entry = static_cast(gpu_cvb_table_head); + for (size_t i = 0; i < customize_entry_count; i++) + { + PATCH_OFFSET(&(entry->cvb_pll_param.c0), (entry->cvb_pll_param.c0 - C.commonGpuVoltOffset * 1000)); + entry++; + } } - } - R_SUCCEED(); -}; + R_SUCCEED(); + }; -Result MemFreqPllmLimit(u32* ptr); -Result MemVoltHandler(u32* ptr); // Used for Erista MEM Vdd2 + EMC Vddq or Mariko MEM Vdd2 + Result MemFreqPllmLimit(u32 *ptr); + Result MemVoltHandler(u32 *ptr); // Used for Erista MEM Vdd2 + EMC Vddq or Mariko MEM Vdd2 -template -Result MemMtcCustomizeTable(T* dst, T* src) { - constexpr u32 mtc_magic = std::is_same_v ? MARIKO_MTC_MAGIC : ERISTA_MTC_MAGIC; - R_UNLESS(src->rev == mtc_magic, ldr::ResultInvalidMtcMagic()); + template + Result MemMtcCustomizeTable(T *dst, T *src) + { + constexpr u32 mtc_magic = std::is_same_v ? MARIKO_MTC_MAGIC : ERISTA_MTC_MAGIC; + R_UNLESS(src->rev == mtc_magic, ldr::ResultInvalidMtcMagic()); - constexpr u32 ZERO_VAL = UINT32_MAX; - // Skip params from dvfs_ver to clock_src; - for (size_t offset = offsetof(T, clk_src_emc); offset < sizeof(T); offset += sizeof(u32)) { - u32* src_ent = reinterpret_cast(reinterpret_cast(src) + offset); - u32* dst_ent = reinterpret_cast(reinterpret_cast(dst) + offset); - u32 src_val = *src_ent; + constexpr u32 ZERO_VAL = UINT32_MAX; + // Skip params from dvfs_ver to clock_src; + for (size_t offset = offsetof(T, clk_src_emc); offset < sizeof(T); offset += sizeof(u32)) + { + u32 *src_ent = reinterpret_cast(reinterpret_cast(src) + offset); + u32 *dst_ent = reinterpret_cast(reinterpret_cast(dst) + offset); + u32 src_val = *src_ent; - if (src_val) { - PATCH_OFFSET(dst_ent, src_val == ZERO_VAL ? 0 : src_val); + if (src_val) + { + PATCH_OFFSET(dst_ent, src_val == ZERO_VAL ? 0 : src_val); + } } - } - R_SUCCEED(); -}; + R_SUCCEED(); + }; -void SafetyCheck(); -void Patch(uintptr_t mapped_nso, size_t nso_size); + void SafetyCheck(); + void Patch(uintptr_t mapped_nso, size_t nso_size); } diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_common.hpp b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_common.hpp index c225b136..d0eb52c3 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_common.hpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_common.hpp @@ -14,153 +14,153 @@ * along with this program. If not, see . */ -#pragma once + #pragma once -namespace ams::ldr::oc::pcv { - -typedef struct cvb_coefficients { - s32 c0 = 0; - s32 c1 = 0; - s32 c2 = 0; - s32 c3 = 0; - s32 c4 = 0; - s32 c5 = 0; -} cvb_coefficients; - -typedef struct cvb_entry_t { - u64 freq; - cvb_coefficients cvb_dfll_param; - cvb_coefficients cvb_pll_param; -} cvb_entry_t; -static_assert(sizeof(cvb_entry_t) == 0x38); - -typedef struct cvb_cpu_dfll_data { - u32 tune0_low; - u32 tune0_high; - u32 tune1_low; - u32 tune1_high; - unsigned int tune_high_min_millivolts; - unsigned int tune_high_margin_millivolts; - unsigned long dvco_calibration_max; -} cvb_cpu_dfll_data; - -typedef struct emc_dvb_dvfs_table_t { - u64 freq; - s32 volt[4] = {0}; -} emc_dvb_dvfs_table_t; - -typedef struct __attribute__((packed)) div_nmp { - u8 divn_shift; - u8 divn_width; - u8 divm_shift; - u8 divm_width; - u8 divp_shift; - u8 divp_width; - u8 override_divn_shift; - u8 override_divm_shift; - u8 override_divp_shift; -} div_nmp; - -typedef struct __attribute__((packed)) clk_pll_param { - u32 freq; - u32 input_min; - u32 input_max; - u32 cf_min; - u32 cf_max; - u32 vco_min; - u32 vco_max; - s32 lock_delay; - u32 fixed_rate; - u32 unk_0; - struct div_nmp *div_nmp; - u32 unk_1[4]; - void (*unk_fn)(u64* unk_struct); // set_defaults? -} clk_pll_param; - -typedef struct __attribute__((packed)) dvfs_rail { - u32 id; - u32 unk_0[5]; - u32 freq; - u32 unk_1[8]; - u32 unk_flag; - u32 min_mv; - u32 step_mv; - u32 max_mv; - u32 unk_2[11]; -} dvfs_rail; - -typedef struct __attribute__((packed)) regulator { - u64 id; - const char* name; - u32 type; - union { - struct { - u32 volt_reg; - u32 step_uv; - u32 min_uv; - u32 default_uv; - u32 max_uv; - u32 unk_0[2]; - } type_1; - struct { - u32 unk_0; - u32 step_uv; - u32 unk_1; - u32 min_uv; - u32 max_uv; - u32 unk_2; - u32 default_uv; - } type_2_3; - }; - u32 unk_x[60]; -} regulator; -static_assert(sizeof(regulator) == 0x120); - -constexpr u32 CpuClkOSLimit = 1785'000; - -constexpr u32 EmcClkOSLimit = 1600'000; - -#define R_SKIP() R_SUCCEED() - -// Count 32 / Index 31 is reserved to be empty -constexpr size_t DvfsTableEntryCount = 32; -constexpr size_t DvfsTableEntryLimit = DvfsTableEntryCount - 1; - -template -size_t GetDvfsTableEntryCount(T* table_head) { - using NT = std::remove_const_t>; - - auto is_empty = [](NT* entry) { - uint8_t* m = reinterpret_cast(entry); - for (size_t i = 0; i < sizeof(NT); i++) { - if (*(m + i)) - return false; - } - return true; - }; - - NT* table = const_cast(table_head); - size_t count = 0; - while (count < DvfsTableEntryLimit) { - if (is_empty(table++)) { - return count; - } - count++; - } - return DvfsTableEntryLimit; -} - -template -T* GetDvfsTableLastEntry(T* table_head) { - using NT = std::remove_const_t>; - - NT* table = const_cast(table_head); - size_t count = GetDvfsTableEntryCount(table_head); - if (!count) { - return nullptr; - } - size_t index = count - 1; - return table + index; -} - -} \ No newline at end of file + namespace ams::ldr::oc::pcv { + + typedef struct cvb_coefficients { + s32 c0 = 0; + s32 c1 = 0; + s32 c2 = 0; + s32 c3 = 0; + s32 c4 = 0; + s32 c5 = 0; + } cvb_coefficients; + + typedef struct cvb_entry_t { + u64 freq; + cvb_coefficients cvb_dfll_param; + cvb_coefficients cvb_pll_param; + } cvb_entry_t; + static_assert(sizeof(cvb_entry_t) == 0x38); + + typedef struct cvb_cpu_dfll_data { + u32 tune0_low; + u32 tune0_high; + u32 tune1_low; + u32 tune1_high; + unsigned int tune_high_min_millivolts; + unsigned int tune_high_margin_millivolts; + unsigned long dvco_calibration_max; + } cvb_cpu_dfll_data; + + typedef struct emc_dvb_dvfs_table_t { + u64 freq; + s32 volt[4] = {0}; + } emc_dvb_dvfs_table_t; + + typedef struct __attribute__((packed)) div_nmp { + u8 divn_shift; + u8 divn_width; + u8 divm_shift; + u8 divm_width; + u8 divp_shift; + u8 divp_width; + u8 override_divn_shift; + u8 override_divm_shift; + u8 override_divp_shift; + } div_nmp; + + typedef struct __attribute__((packed)) clk_pll_param { + u32 freq; + u32 input_min; + u32 input_max; + u32 cf_min; + u32 cf_max; + u32 vco_min; + u32 vco_max; + s32 lock_delay; + u32 fixed_rate; + u32 unk_0; + struct div_nmp *div_nmp; + u32 unk_1[4]; + void (*unk_fn)(u64* unk_struct); // set_defaults? + } clk_pll_param; + + typedef struct __attribute__((packed)) dvfs_rail { + u32 id; + u32 unk_0[5]; + u32 freq; + u32 unk_1[8]; + u32 unk_flag; + u32 min_mv; + u32 step_mv; + u32 max_mv; + u32 unk_2[11]; + } dvfs_rail; + + typedef struct __attribute__((packed)) regulator { + u64 id; + const char* name; + u32 type; + union { + struct { + u32 volt_reg; + u32 step_uv; + u32 min_uv; + u32 default_uv; + u32 max_uv; + u32 unk_0[2]; + } type_1; + struct { + u32 unk_0; + u32 step_uv; + u32 unk_1; + u32 min_uv; + u32 max_uv; + u32 unk_2; + u32 default_uv; + } type_2_3; + }; + u32 unk_x[60]; + } regulator; + static_assert(sizeof(regulator) == 0x120); + + constexpr u32 CpuClkOSLimit = 1785'000; + + constexpr u32 EmcClkOSLimit = 1600'000; + + #define R_SKIP() R_SUCCEED() + + // Count 32 / Index 31 is reserved to be empty + constexpr size_t DvfsTableEntryCount = 32; + constexpr size_t DvfsTableEntryLimit = DvfsTableEntryCount - 1; + + template + size_t GetDvfsTableEntryCount(T* table_head) { + using NT = std::remove_const_t>; + + auto is_empty = [](NT* entry) { + uint8_t* m = reinterpret_cast(entry); + for (size_t i = 0; i < sizeof(NT); i++) { + if (*(m + i)) + return false; + } + return true; + }; + + NT* table = const_cast(table_head); + size_t count = 0; + while (count < DvfsTableEntryLimit) { + if (is_empty(table++)) { + return count; + } + count++; + } + return DvfsTableEntryLimit; + } + + template + T* GetDvfsTableLastEntry(T* table_head) { + using NT = std::remove_const_t>; + + NT* table = const_cast(table_head); + size_t count = GetDvfsTableEntryCount(table_head); + if (!count) { + return nullptr; + } + size_t index = count - 1; + return table + index; + } + + } \ No newline at end of file diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_erista.cpp b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_erista.cpp index 6cf6004f..02b22b12 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_erista.cpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_erista.cpp @@ -2,7 +2,7 @@ * Copyright (C) Switch-OC-Suite * * Copyright (c) 2023 hanai3Bi - * + * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. @@ -18,233 +18,328 @@ #include "pcv.hpp" #include "../mtc_timing_value.hpp" -#include "../customize.hpp" -namespace ams::ldr::oc::pcv::erista { -Result CpuVoltRange(u32* ptr) { - u32 min_volt_got = *(ptr - 1); - for (const auto& mv : CpuMinVolts) { - if (min_volt_got != mv) - continue; +namespace ams::ldr::oc::pcv::erista +{ - if (!C.eristaCpuMaxVolt) - R_SKIP(); + Result CpuVoltRange(u32 *ptr) + { + u32 min_volt_got = *(ptr - 1); + for (const auto &mv : CpuMinVolts) + { + if (min_volt_got != mv) + continue; + + if (!C.eristaCpuMaxVolt) + R_SKIP(); + + PATCH_OFFSET(ptr, C.eristaCpuMaxVolt); + R_SUCCEED(); + } + R_THROW(ldr::ResultInvalidCpuMinVolt()); + } + + Result GpuFreqMaxAsm(u32 *ptr32) + { + // Check if both two instructions match the pattern + u32 ins1 = *ptr32, ins2 = *(ptr32 + 1); + if (!(asm_compare_no_rd(ins1, asm_pattern[0]) && asm_compare_no_rd(ins2, asm_pattern[1]))) + R_THROW(ldr::ResultInvalidGpuFreqMaxPattern()); + + // Both instructions should operate on the same register + u8 rd = asm_get_rd(ins1); + if (rd != asm_get_rd(ins2)) + R_THROW(ldr::ResultInvalidGpuFreqMaxPattern()); + + u32 max_clock; + switch (C.eristaGpuUV) + { + case 0: + max_clock = GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq; + break; + case 1: + max_clock = GetDvfsTableLastEntry(C.eristaGpuDvfsTableSLT)->freq; + break; + case 2: + max_clock = GetDvfsTableLastEntry(C.eristaGpuDvfsTableHigh)->freq; + break; + case 3: + if(C.enableEristaGpuUnsafeFreqs) + { + max_clock = GetDvfsTableLastEntry(C.eristaGpuDvfsTableUv3UnsafeFreqs)->freq; + } + else + { + max_clock = GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq; + } + break; + default: + max_clock = GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq; + break; + } + u32 asm_patch[2] = { + asm_set_rd(asm_set_imm16(asm_pattern[0], max_clock), rd), + asm_set_rd(asm_set_imm16(asm_pattern[1], max_clock >> 16), rd)}; + PATCH_OFFSET(ptr32, asm_patch[0]); + PATCH_OFFSET(ptr32 + 1, asm_patch[1]); - PATCH_OFFSET(ptr, C.eristaCpuMaxVolt); R_SUCCEED(); } - R_THROW(ldr::ResultInvalidCpuMinVolt()); -} -Result GpuFreqMaxAsm(u32* ptr32) { - // Check if both two instructions match the pattern - u32 ins1 = *ptr32, ins2 = *(ptr32 + 1); - if (!(asm_compare_no_rd(ins1, asm_pattern[0]) && asm_compare_no_rd(ins2, asm_pattern[1]))) - R_THROW(ldr::ResultInvalidGpuFreqMaxPattern()); - - // Both instructions should operate on the same register - u8 rd = asm_get_rd(ins1); - if (rd != asm_get_rd(ins2)) - R_THROW(ldr::ResultInvalidGpuFreqMaxPattern()); - - u32 max_clock = GetDvfsTableLastEntry(C.eristaGpuDvfsTable)->freq; - - u32 asm_patch[2] = { - asm_set_rd(asm_set_imm16(asm_pattern[0], max_clock), rd), - asm_set_rd(asm_set_imm16(asm_pattern[1], max_clock >> 16), rd) - }; - PATCH_OFFSET(ptr32, asm_patch[0]); - PATCH_OFFSET(ptr32 + 1, asm_patch[1]); - - R_SUCCEED(); -} - -Result GpuFreqPllLimit(u32* ptr) { - clk_pll_param* entry = reinterpret_cast(ptr); - - // All zero except for freq - for (size_t i = 1; i < sizeof(clk_pll_param) / sizeof(u32); i++) { - R_UNLESS(*(ptr + i) == 0, ldr::ResultInvalidGpuPllEntry()); - } - - // Double the max clk simply - u32 max_clk = entry->freq * 2; - entry->freq = max_clk; - R_SUCCEED(); -} - -void MemMtcTableAutoAdjust(EristaMtcTable* table) { - if (C.mtcConf != AUTO_ADJ_ALL) - return; - - #define WRITE_PARAM_ALL_REG(TABLE, PARAM, VALUE) \ - TABLE->burst_regs.PARAM = VALUE; \ - TABLE->shadow_regs_ca_train.PARAM = VALUE; \ - TABLE->shadow_regs_quse_train.PARAM = VALUE; \ - TABLE->shadow_regs_rdwr_train.PARAM = VALUE; - - #define GET_CYCLE_CEIL(PARAM) u32(CEIL(double(PARAM) / tCK_avg)) - - WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(C.tRC)); - WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(C.tRFCab)); - WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(C.tRFCpb)); - WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS)); - WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb)); - WRITE_PARAM_ALL_REG(table, emc_r2w, R2W); - WRITE_PARAM_ALL_REG(table, emc_w2r, W2R); - WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(C.tRTP)); - WRITE_PARAM_ALL_REG(table, emc_w2p, WTP); - WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(C.tRRD)); - WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH); - WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4); - WRITE_PARAM_ALL_REG(table, emc_pdex2wr, GET_CYCLE_CEIL(C.tXP)); - WRITE_PARAM_ALL_REG(table, emc_pdex2rd, GET_CYCLE_CEIL(C.tXP)); - WRITE_PARAM_ALL_REG(table, emc_pchg2pden, GET_CYCLE_CEIL(C.tCMDCKE)); - WRITE_PARAM_ALL_REG(table, emc_act2pden, GET_CYCLE_CEIL(C.tMRWCKEL)); - WRITE_PARAM_ALL_REG(table, emc_ar2pden, GET_CYCLE_CEIL(C.tCMDCKE)); - WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN); - WRITE_PARAM_ALL_REG(table, emc_cke2pden, GET_CYCLE_CEIL(C.tCKELCS)); - WRITE_PARAM_ALL_REG(table, emc_pdex2cke, GET_CYCLE_CEIL(C.tCSCKEH)); - WRITE_PARAM_ALL_REG(table, emc_pdex2mrr, GET_CYCLE_CEIL(tPDEX2MRR)); - WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(C.tXSR), (u32)0x3fe)); - WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(C.tXSR), (u32)0x3fe)); - WRITE_PARAM_ALL_REG(table, emc_tcke, GET_CYCLE_CEIL(C.tCKE)); - WRITE_PARAM_ALL_REG(table, emc_tckesr, GET_CYCLE_CEIL(C.tSR)); - WRITE_PARAM_ALL_REG(table, emc_tpd, GET_CYCLE_CEIL(C.tCKE)); - WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(C.tFAW)); - WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(C.tRPab)); - WRITE_PARAM_ALL_REG(table, emc_tclkstable, GET_CYCLE_CEIL(C.tCKCKEH)); - WRITE_PARAM_ALL_REG(table, emc_tclkstop, GET_CYCLE_CEIL(C.tCKE)+8); - WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW); - - #define WRITE_PARAM_BURST_MC_REG(TABLE, PARAM, VALUE) TABLE->burst_mc_regs.PARAM = VALUE; - - constexpr u32 MC_ARB_DIV = 4; - constexpr u32 MC_ARB_SFA = 2; - table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV) - 2; - table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA; - table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(C.tRC) / MC_ARB_DIV) - 1; - table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV) - 2; - table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(C.tFAW) / MC_ARB_DIV) - 1; - table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(C.tRRD) / MC_ARB_DIV) - 1; - table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(C.tRTP) / MC_ARB_DIV); - table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV); - //table->burst_mc_regs.mc_emem_arb_timing_r2r = CEIL(table->burst_regs.emc_rext / MC_ARB_DIV) - 1 + MC_ARB_SFA; - //table->burst_mc_regs.mc_emem_arb_timing_w2w = CEIL(table->burst_regs.emc_wext / MC_ARB_DIV) - 1 + MC_ARB_SFA; - table->burst_mc_regs.mc_emem_arb_timing_r2w = CEIL(R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA; - table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA; - table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(C.tRFCpb) / MC_ARB_DIV); - //table->burst_mc_regs.mc_emem_arb_timing_ccdmw = CEIL(tCCDMW / MC_ARB_DIV) -1 + MC_ARB_SFA; -} - -void MemMtcTableCustomAdjust(EristaMtcTable* table) { - if (C.mtcConf != CUSTOM_ADJ_ALL) - return; - - constexpr u32 MC_ARB_DIV = 4; - constexpr u32 MC_ARB_SFA = 2; - - WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(C.tRC)); - WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS)); - WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb)); - WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(C.tRPab)); - WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_pdex2mrr, GET_CYCLE_CEIL(tPDEX2MRR)); - - table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV - 2); - table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(C.tRC) / MC_ARB_DIV - 1); - table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV - 1 + MC_ARB_SFA); - table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV - 2); - - u32 DA_TURNS = 0; - DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_r2w / 2) << 16; //R2W TURN - DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_w2r / 2) << 24; //W2R TURN - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_da_turns, DA_TURNS); - u32 DA_COVERS = 0; - u8 R_COVER = (table->burst_mc_regs.mc_emem_arb_timing_rap2pre + table->burst_mc_regs.mc_emem_arb_timing_rp + table->burst_mc_regs.mc_emem_arb_timing_rcd) / 2; - u8 W_COVER = (table->burst_mc_regs.mc_emem_arb_timing_wap2pre + table->burst_mc_regs.mc_emem_arb_timing_rp + table->burst_mc_regs.mc_emem_arb_timing_rcd) / 2; - DA_COVERS |= (u8)(table->burst_mc_regs.mc_emem_arb_timing_rc / 2); //RC COVER - DA_COVERS |= (R_COVER << 8); //RCD_R COVER - DA_COVERS |= (W_COVER << 16); //RCD_W COVER - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_da_covers, DA_COVERS); -} - -Result MemFreqMtcTable(u32* ptr) { - u32 khz_list[] = { 1600000, 1331200, 1065600, 800000, 665600, 408000, 204000, 102000, 68000, 40800 }; - u32 khz_list_size = sizeof(khz_list) / sizeof(u32); - - // Generate list for mtc table pointers - EristaMtcTable* table_list[khz_list_size]; - for (u32 i = 0; i < khz_list_size; i++) { - u8* table = reinterpret_cast(ptr) - offsetof(EristaMtcTable, rate_khz) - i * sizeof(EristaMtcTable); - table_list[i] = reinterpret_cast(table); - R_UNLESS(table_list[i]->rate_khz == khz_list[i], ldr::ResultInvalidMtcTable()); - R_UNLESS(table_list[i]->rev == MTC_TABLE_REV, ldr::ResultInvalidMtcTable()); - } - - if (C.eristaEmcMaxClock <= EmcClkOSLimit) - R_SKIP(); - - // Make room for new mtc table, discarding useless 40.8 MHz table - // 40800 overwritten by 68000, ..., 1331200 overwritten by 1600000, leaving table_list[0] not overwritten - for (u32 i = khz_list_size - 1; i > 0; i--) - std::memcpy(static_cast(table_list[i]), static_cast(table_list[i - 1]), sizeof(EristaMtcTable)); - - MemMtcTableAutoAdjust(table_list[0]); - PATCH_OFFSET(ptr, C.eristaEmcMaxClock); - - // Handle customize table replacement - //if (C.mtcConf == CUSTOMIZED_ALL) { - // MemMtcCustomizeTable(table_list[0], const_cast(C.eristaMtcTable)); - //} - - R_SUCCEED(); -} - -Result MemFreqMax(u32* ptr) { - if (C.eristaEmcMaxClock <= EmcClkOSLimit) - R_SKIP(); - - PATCH_OFFSET(ptr, C.eristaEmcMaxClock); - - R_SUCCEED(); -} - -void Patch(uintptr_t mapped_nso, size_t nso_size) { - u32 CpuCvbDefaultMaxFreq = static_cast(GetDvfsTableLastEntry(CpuCvbTableDefault)->freq); - u32 GpuCvbDefaultMaxFreq = static_cast(GetDvfsTableLastEntry(GpuCvbTableDefault)->freq); - - PatcherEntry patches[] = { - { "CPU Freq Table", CpuFreqCvbTable, 1, nullptr, CpuCvbDefaultMaxFreq }, - { "CPU Volt Limit", &CpuVoltRange, 0, &CpuMaxVoltPatternFn }, - { "GPU Freq Table", GpuFreqCvbTable, 1, nullptr, GpuCvbDefaultMaxFreq }, - { "GPU Freq Asm", &GpuFreqMaxAsm, 2, &GpuMaxClockPatternFn }, - { "GPU Freq PLL", &GpuFreqPllLimit, 1, nullptr, GpuClkPllLimit }, - { "MEM Freq Mtc", &MemFreqMtcTable, 0, nullptr, EmcClkOSLimit }, - { "MEM Freq Max", &MemFreqMax, 0, nullptr, EmcClkOSLimit }, - { "MEM Freq PLLM", &MemFreqPllmLimit, 2, nullptr, EmcClkPllmLimit }, - { "MEM Volt", &MemVoltHandler, 2, nullptr, MemVoltHOS }, - }; - - for (uintptr_t ptr = mapped_nso; - ptr <= mapped_nso + nso_size - sizeof(EristaMtcTable); - ptr += sizeof(u32)) + Result GpuFreqPllLimit(u32 *ptr) { - u32* ptr32 = reinterpret_cast(ptr); - for (auto& entry : patches) { - if (R_SUCCEEDED(entry.SearchAndApply(ptr32))) - break; + clk_pll_param *entry = reinterpret_cast(ptr); + + // All zero except for freq + for (size_t i = 1; i < sizeof(clk_pll_param) / sizeof(u32); i++) + { + R_UNLESS(*(ptr + i) == 0, ldr::ResultInvalidGpuPllEntry()); + } + + // Double the max clk simply + u32 max_clk = entry->freq * 2; + entry->freq = max_clk; + R_SUCCEED(); + } + + void MemMtcTableAutoAdjust(EristaMtcTable *table) + { + if (C.mtcConf != AUTO_ADJ_ALL) + return; + +#define WRITE_PARAM_ALL_REG(TABLE, PARAM, VALUE) \ + TABLE->burst_regs.PARAM = VALUE; \ + TABLE->shadow_regs_ca_train.PARAM = VALUE; \ + TABLE->shadow_regs_quse_train.PARAM = VALUE; \ + TABLE->shadow_regs_rdwr_train.PARAM = VALUE; + +#define GET_CYCLE_CEIL(PARAM) u32(CEIL(double(PARAM) / tCK_avg)) + + WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC)); + WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab)); + WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb)); + WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS)); + WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb)); + WRITE_PARAM_ALL_REG(table, emc_r2w, R2W); + WRITE_PARAM_ALL_REG(table, emc_w2r, W2R); + WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP)); + WRITE_PARAM_ALL_REG(table, emc_w2p, WTP); + WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD)); + WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH); + WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4); + WRITE_PARAM_ALL_REG(table, emc_pdex2wr, GET_CYCLE_CEIL(tXP)); + WRITE_PARAM_ALL_REG(table, emc_pdex2rd, GET_CYCLE_CEIL(tXP)); + WRITE_PARAM_ALL_REG(table, emc_pchg2pden, GET_CYCLE_CEIL(tCMDCKE)); + WRITE_PARAM_ALL_REG(table, emc_act2pden, GET_CYCLE_CEIL(tMRWCKEL)); + WRITE_PARAM_ALL_REG(table, emc_ar2pden, GET_CYCLE_CEIL(tCMDCKE)); + WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN); + WRITE_PARAM_ALL_REG(table, emc_cke2pden, GET_CYCLE_CEIL(tCKELCS)); + WRITE_PARAM_ALL_REG(table, emc_pdex2cke, GET_CYCLE_CEIL(tCSCKEH)); + WRITE_PARAM_ALL_REG(table, emc_pdex2mrr, GET_CYCLE_CEIL(tPDEX2MRR)); + WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + WRITE_PARAM_ALL_REG(table, emc_tcke, GET_CYCLE_CEIL(tCKE)); + WRITE_PARAM_ALL_REG(table, emc_tckesr, GET_CYCLE_CEIL(tSR)); + WRITE_PARAM_ALL_REG(table, emc_tpd, GET_CYCLE_CEIL(tCKE)); + WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW)); + WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab)); + WRITE_PARAM_ALL_REG(table, emc_tclkstable, GET_CYCLE_CEIL(tCKCKEH)); + WRITE_PARAM_ALL_REG(table, emc_tclkstop, GET_CYCLE_CEIL(tCKE) + 8); + WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW); + +#define WRITE_PARAM_BURST_MC_REG(TABLE, PARAM, VALUE) TABLE->burst_mc_regs.PARAM = VALUE; + + constexpr u32 MC_ARB_DIV = 4; + constexpr u32 MC_ARB_SFA = 2; + table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV) - 2; + table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA; + table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV) - 1; + table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV) - 2; + table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1; + table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1; + table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV); + table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV); + // table->burst_mc_regs.mc_emem_arb_timing_r2r = CEIL(table->burst_regs.emc_rext / MC_ARB_DIV) - 1 + MC_ARB_SFA; + // table->burst_mc_regs.mc_emem_arb_timing_w2w = CEIL(table->burst_regs.emc_wext / MC_ARB_DIV) - 1 + MC_ARB_SFA; + table->burst_mc_regs.mc_emem_arb_timing_r2w = CEIL(R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA; + table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA; + table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV); + // table->burst_mc_regs.mc_emem_arb_timing_ccdmw = CEIL(tCCDMW / MC_ARB_DIV) -1 + MC_ARB_SFA; + } + + void MemMtcTableCustomAdjust(EristaMtcTable *table) + { + if (C.mtcConf != CUSTOM_ADJ_ALL) + return; + + constexpr u32 MC_ARB_DIV = 4; + constexpr u32 MC_ARB_SFA = 2; + + if (TIMING_PRESET_ONE) + { + WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC)); + WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS)); + WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb)); + WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab)); + WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_pdex2mrr, GET_CYCLE_CEIL(tPDEX2MRR)); + + table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV - 2); + table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV - 1); + table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV - 1 + MC_ARB_SFA); + table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV - 2); + } + + if (TIMING_PRESET_TWO) + { + WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW)); + WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD)); + + table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1; + table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1; + } + + if (TIMING_PRESET_THREE) + { + WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP)); + WRITE_PARAM_ALL_REG(table, emc_w2p, WTP); + WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN); + + table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV); + table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV); + } + + if (TIMING_PRESET_FOUR) + { + WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab)); + WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb)); + WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + + table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV); + } + + if (TIMING_PRESET_FIVE) + { + WRITE_PARAM_ALL_REG(table, emc_w2r, W2R); + + table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA; + } + + if (TIMING_PRESET_SIX) + { + WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH); + WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4); + WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW); + } + + if (TIMING_PRESET_SEVEN) + { + WRITE_PARAM_ALL_REG(table, emc_r2w, R2W); + WRITE_PARAM_ALL_REG(table, emc_w2r, W2R); + WRITE_PARAM_ALL_REG(table, emc_w2p, WTP); + WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN); + + table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV); + table->burst_mc_regs.mc_emem_arb_timing_r2w = CEIL(R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA; + table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA; + } + + u32 DA_TURNS = 0; + DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_r2w / 2) << 16; // R2W TURN + DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_w2r / 2) << 24; // W2R TURN + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_da_turns, DA_TURNS); + u32 DA_COVERS = 0; + u8 R_COVER = (table->burst_mc_regs.mc_emem_arb_timing_rap2pre + table->burst_mc_regs.mc_emem_arb_timing_rp + table->burst_mc_regs.mc_emem_arb_timing_rcd) / 2; + u8 W_COVER = (table->burst_mc_regs.mc_emem_arb_timing_wap2pre + table->burst_mc_regs.mc_emem_arb_timing_rp + table->burst_mc_regs.mc_emem_arb_timing_rcd) / 2; + DA_COVERS |= (u8)(table->burst_mc_regs.mc_emem_arb_timing_rc / 2); // RC COVER + DA_COVERS |= (R_COVER << 8); // RCD_R COVER + DA_COVERS |= (W_COVER << 16); // RCD_W COVER + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_da_covers, DA_COVERS); + } + + Result MemFreqMtcTable(u32 *ptr) + { + u32 khz_list[] = {1600000, 1331200, 1065600, 800000, 665600, 408000, 204000, 102000, 68000, 40800}; + u32 khz_list_size = sizeof(khz_list) / sizeof(u32); + + // Generate list for mtc table pointers + EristaMtcTable *table_list[khz_list_size]; + for (u32 i = 0; i < khz_list_size; i++) + { + u8 *table = reinterpret_cast(ptr) - offsetof(EristaMtcTable, rate_khz) - i * sizeof(EristaMtcTable); + table_list[i] = reinterpret_cast(table); + R_UNLESS(table_list[i]->rate_khz == khz_list[i], ldr::ResultInvalidMtcTable()); + R_UNLESS(table_list[i]->rev == MTC_TABLE_REV, ldr::ResultInvalidMtcTable()); + } + + if (C.eristaEmcMaxClock <= EmcClkOSLimit) + R_SKIP(); + + // Make room for new mtc table, discarding useless 40.8 MHz table + // 40800 overwritten by 68000, ..., 1331200 overwritten by 1600000, leaving table_list[0] not overwritten + for (u32 i = khz_list_size - 1; i > 0; i--) + std::memcpy(static_cast(table_list[i]), static_cast(table_list[i - 1]), sizeof(EristaMtcTable)); + + MemMtcTableAutoAdjust(table_list[0]); + PATCH_OFFSET(ptr, C.eristaEmcMaxClock); + + // Handle customize table replacement + // if (C.mtcConf == CUSTOMIZED_ALL) { + // MemMtcCustomizeTable(table_list[0], const_cast(C.eristaMtcTable)); + //} + + R_SUCCEED(); + } + + Result MemFreqMax(u32 *ptr) + { + if (C.eristaEmcMaxClock <= EmcClkOSLimit) + R_SKIP(); + + PATCH_OFFSET(ptr, C.eristaEmcMaxClock); + + R_SUCCEED(); + } + + void Patch(uintptr_t mapped_nso, size_t nso_size) + { + u32 CpuCvbDefaultMaxFreq = static_cast(GetDvfsTableLastEntry(CpuCvbTableDefault)->freq); + u32 GpuCvbDefaultMaxFreq = static_cast(GetDvfsTableLastEntry(GpuCvbTableDefault)->freq); + + PatcherEntry patches[] = { + {"CPU Freq Table", CpuFreqCvbTable, 1, nullptr, CpuCvbDefaultMaxFreq}, + {"CPU Volt Limit", &CpuVoltRange, 0, &CpuMaxVoltPatternFn}, + {"GPU Freq Table", GpuFreqCvbTable, 1, nullptr, GpuCvbDefaultMaxFreq}, + {"GPU Freq Asm", &GpuFreqMaxAsm, 2, &GpuMaxClockPatternFn}, + {"GPU Freq PLL", &GpuFreqPllLimit, 1, nullptr, GpuClkPllLimit}, + {"MEM Freq Mtc", &MemFreqMtcTable, 0, nullptr, EmcClkOSLimit}, + {"MEM Freq Max", &MemFreqMax, 0, nullptr, EmcClkOSLimit}, + {"MEM Freq PLLM", &MemFreqPllmLimit, 2, nullptr, EmcClkPllmLimit}, + {"MEM Volt", &MemVoltHandler, 2, nullptr, MemVoltHOS}, + }; + + for (uintptr_t ptr = mapped_nso; + ptr <= mapped_nso + nso_size - sizeof(EristaMtcTable); + ptr += sizeof(u32)) + { + u32 *ptr32 = reinterpret_cast(ptr); + for (auto &entry : patches) + { + if (R_SUCCEEDED(entry.SearchAndApply(ptr32))) + break; + } + } + + for (auto &entry : patches) + { + LOGGING("%s Count: %zu", entry.description, entry.patched_count); + if (R_FAILED(entry.CheckResult())) + CRASH(entry.description); } } - for (auto& entry : patches) { - LOGGING("%s Count: %zu", entry.description, entry.patched_count); - if (R_FAILED(entry.CheckResult())) - CRASH(entry.description); - } -} - } \ No newline at end of file diff --git a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_mariko.cpp b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_mariko.cpp index 47630a5c..226f6755 100644 --- a/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_mariko.cpp +++ b/Source/Atmosphere/stratosphere/loader/source/oc/pcv/pcv_mariko.cpp @@ -18,7 +18,6 @@ #include "pcv.hpp" #include "../mtc_timing_value.hpp" -#include "../customize.hpp" namespace ams::ldr::oc::pcv::mariko { @@ -31,7 +30,11 @@ Result CpuFreqVdd(u32* ptr) { R_UNLESS(entry->max_mv == 1525'000, ldr::ResultInvalidCpuFreqVddEntry()); if (C.marikoCpuUV) { - PATCH_OFFSET(ptr, GetDvfsTableLastEntry(C.marikoCpuDvfsTableSLT)->freq); + if(!C.enableMarikoCpuUnsafeFreqs) { + PATCH_OFFSET(ptr, GetDvfsTableLastEntry(C.marikoCpuDvfsTableSLT)->freq); + } else { + PATCH_OFFSET(ptr, GetDvfsTableLastEntry(C.marikoCpuDvfsTableUnsafeFreqs)->freq); + } } else { PATCH_OFFSET(ptr, GetDvfsTableLastEntry(C.marikoCpuDvfsTable)->freq); } @@ -108,6 +111,16 @@ Result GpuFreqMaxAsm(u32* ptr32) { case 2: max_clock = GetDvfsTableLastEntry(C.marikoGpuDvfsTableHiOPT)->freq; break; + case 3: + if(C.enableMarikoGpuUnsafeFreqs) + { + max_clock = GetDvfsTableLastEntry(C.marikoGpuDvfsTableUv3UnsafeFreqs)->freq; + } + else + { + max_clock = GetDvfsTableLastEntry(C.marikoGpuDvfsTable)->freq; + } + break; default: max_clock = GetDvfsTableLastEntry(C.marikoGpuDvfsTable)->freq; break; @@ -183,44 +196,44 @@ void MemMtcTableAutoAdjust(MarikoMtcTable* table, const MarikoMtcTable* ref) { #define GET_CYCLE_CEIL(PARAM) u32(CEIL(double(PARAM) / tCK_avg)) - WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(C.tRC)); - WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(C.tRFCab)); - WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(C.tRFCpb)); - WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS)); - WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb)); + WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC)); + WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab)); + WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb)); + WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS)); + WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb)); WRITE_PARAM_ALL_REG(table, emc_r2w, R2W); WRITE_PARAM_ALL_REG(table, emc_w2r, W2R); - WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(C.tRTP)); + WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP)); WRITE_PARAM_ALL_REG(table, emc_w2p, WTP); WRITE_PARAM_ALL_REG(table, emc_trtm, RTM); WRITE_PARAM_ALL_REG(table, emc_twtm, WTM); WRITE_PARAM_ALL_REG(table, emc_tratm, RATM); WRITE_PARAM_ALL_REG(table, emc_twatm, WATM); - //WRITE_PARAM_ALL_REG(table, emc_tr2ref, GET_CYCLE_CEIL(C.tR2REF)); - WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(C.tRRD)); + //WRITE_PARAM_ALL_REG(table, emc_tr2ref, GET_CYCLE_CEIL(tR2REF)); + WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD)); WRITE_PARAM_ALL_REG(table, emc_rext, 26); WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH); WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4); - WRITE_PARAM_ALL_REG(table, emc_pdex2wr, GET_CYCLE_CEIL(C.tXP)); - WRITE_PARAM_ALL_REG(table, emc_pdex2rd, GET_CYCLE_CEIL(C.tXP)); - WRITE_PARAM_ALL_REG(table, emc_pchg2pden, GET_CYCLE_CEIL(C.tCMDCKE)); - WRITE_PARAM_ALL_REG(table, emc_act2pden, GET_CYCLE_CEIL(C.tMRWCKEL)); - WRITE_PARAM_ALL_REG(table, emc_ar2pden, GET_CYCLE_CEIL(C.tCMDCKE)); + WRITE_PARAM_ALL_REG(table, emc_pdex2wr, GET_CYCLE_CEIL(tXP)); + WRITE_PARAM_ALL_REG(table, emc_pdex2rd, GET_CYCLE_CEIL(tXP)); + WRITE_PARAM_ALL_REG(table, emc_pchg2pden, GET_CYCLE_CEIL(tCMDCKE)); + WRITE_PARAM_ALL_REG(table, emc_act2pden, GET_CYCLE_CEIL(tMRWCKEL)); + WRITE_PARAM_ALL_REG(table, emc_ar2pden, GET_CYCLE_CEIL(tCMDCKE)); WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN); - WRITE_PARAM_ALL_REG(table, emc_cke2pden, GET_CYCLE_CEIL(C.tCKELCS)); - //WRITE_PARAM_ALL_REG(table, emc_pdex2cke, GET_CYCLE_CEIL(C.tCSCKEH)); + WRITE_PARAM_ALL_REG(table, emc_cke2pden, GET_CYCLE_CEIL(tCKELCS)); + //WRITE_PARAM_ALL_REG(table, emc_pdex2cke, GET_CYCLE_CEIL(tCSCKEH)); WRITE_PARAM_ALL_REG(table, emc_pdex2mrr, GET_CYCLE_CEIL(tPDEX2MRR)); - WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(C.tXSR), (u32)0x3fe)); - WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(C.tXSR), (u32)0x3fe)); - WRITE_PARAM_ALL_REG(table, emc_tcke, GET_CYCLE_CEIL(C.tCKE) + 1); - WRITE_PARAM_ALL_REG(table, emc_tckesr, GET_CYCLE_CEIL(C.tSR)); - WRITE_PARAM_ALL_REG(table, emc_tpd, GET_CYCLE_CEIL(C.tCKE)); - WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(C.tFAW)); - WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(C.tRPab)); - //WRITE_PARAM_ALL_REG(table, emc_tclkstable, GET_CYCLE_CEIL(C.tCKCKEH)); - WRITE_PARAM_ALL_REG(table, emc_tclkstop, GET_CYCLE_CEIL(C.tCKE) + 8); + WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + WRITE_PARAM_ALL_REG(table, emc_tcke, GET_CYCLE_CEIL(tCKE) + 1); + WRITE_PARAM_ALL_REG(table, emc_tckesr, GET_CYCLE_CEIL(tSR)); + WRITE_PARAM_ALL_REG(table, emc_tpd, GET_CYCLE_CEIL(tCKE)); + WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW)); + WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab)); + //WRITE_PARAM_ALL_REG(table, emc_tclkstable, GET_CYCLE_CEIL(tCKCKEH)); + WRITE_PARAM_ALL_REG(table, emc_tclkstop, GET_CYCLE_CEIL(tCKE) + 8); WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW); ADJUST_PARAM_ALL_REG(table, emc_dyn_self_ref_control, ref); @@ -239,18 +252,18 @@ void MemMtcTableAutoAdjust(MarikoMtcTable* table, const MarikoMtcTable* ref) { constexpr u32 MC_ARB_SFA = 2; WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_cfg, C.marikoEmcMaxClock / (33.3 * 1000) / MC_ARB_DIV); //CYCLES_PER_UPDATE: The number of mcclk cycles per deadline timer update - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rcd, CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV) - 2) - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rp, CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA) - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rc, CEIL(GET_CYCLE_CEIL(C.tRC) / MC_ARB_DIV) - 1) - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_ras, CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV) - 2) - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_faw, CEIL(GET_CYCLE_CEIL(C.tFAW) / MC_ARB_DIV) - 1) - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rrd, CEIL(GET_CYCLE_CEIL(C.tRRD) / MC_ARB_DIV) - 1) - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rap2pre, CEIL(GET_CYCLE_CEIL(C.tRTP) / MC_ARB_DIV)) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rcd, CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV) - 2) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rp, CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rc, CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV) - 1) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_ras, CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV) - 2) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_faw, CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rrd, CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rap2pre, CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV)) WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_wap2pre, CEIL((WTP) / MC_ARB_DIV)) WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_r2r, CEIL(table->burst_regs.emc_rext / MC_ARB_DIV) - 1 + MC_ARB_SFA) WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_r2w, CEIL((R2W) / MC_ARB_DIV) - 1 + MC_ARB_SFA) WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_w2r, CEIL((W2R) / MC_ARB_DIV) - 1 + MC_ARB_SFA) - WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rfcpb, CEIL(GET_CYCLE_CEIL(C.tRFCpb) / MC_ARB_DIV)) + WRITE_PARAM_BURST_MC_REG(table, mc_emem_arb_timing_rfcpb, CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV)) u32 DA_TURNS = 0; DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_r2w / 2) << 16; //R2W TURN @@ -319,8 +332,8 @@ void MemMtcTableAutoAdjust(MarikoMtcTable* table, const MarikoMtcTable* ref) { table->pllmb_ss_ctrl1 = 0x0b55fe01; table->pllmb_ss_ctrl2 = 0x10170b55; - table->dram_timings.t_rp = C.tRPpb; - table->dram_timings.t_rfc = C.tRFCab; + table->dram_timings.t_rp = tRPpb; + table->dram_timings.t_rfc = tRFCab; //table->dram_timings.rl = 32; table->emc_cfg_2 = 0x0011083d; @@ -333,18 +346,76 @@ void MemMtcTableCustomAdjust(MarikoMtcTable* table) { constexpr u32 MC_ARB_DIV = 4; constexpr u32 MC_ARB_SFA = 2; - WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(C.tRC)); - WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(C.tRAS)); - WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(C.tRPpb)); - WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(C.tRPab)); - WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(C.tRCD)); - WRITE_PARAM_ALL_REG(table, emc_pdex2mrr,GET_CYCLE_CEIL(tPDEX2MRR)); + if (TIMING_PRESET_ONE) { + WRITE_PARAM_ALL_REG(table, emc_rc, GET_CYCLE_CEIL(tRC)); + WRITE_PARAM_ALL_REG(table, emc_ras, GET_CYCLE_CEIL(tRAS)); + WRITE_PARAM_ALL_REG(table, emc_rp, GET_CYCLE_CEIL(tRPpb)); + WRITE_PARAM_ALL_REG(table, emc_trpab, GET_CYCLE_CEIL(tRPab)); + WRITE_PARAM_ALL_REG(table, emc_rd_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_wr_rcd, GET_CYCLE_CEIL(tRCD)); + WRITE_PARAM_ALL_REG(table, emc_pdex2mrr,GET_CYCLE_CEIL(tPDEX2MRR)); - table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(C.tRCD) / MC_ARB_DIV) - 2; - table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(C.tRC) / MC_ARB_DIV) - 1; - table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(C.tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA; - table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(C.tRAS) / MC_ARB_DIV) - 2; + table->burst_mc_regs.mc_emem_arb_timing_rcd = CEIL(GET_CYCLE_CEIL(tRCD) / MC_ARB_DIV) - 2; + table->burst_mc_regs.mc_emem_arb_timing_rc = CEIL(GET_CYCLE_CEIL(tRC) / MC_ARB_DIV) - 1; + table->burst_mc_regs.mc_emem_arb_timing_rp = CEIL(GET_CYCLE_CEIL(tRPpb) / MC_ARB_DIV) - 1 + MC_ARB_SFA; + table->burst_mc_regs.mc_emem_arb_timing_ras = CEIL(GET_CYCLE_CEIL(tRAS) / MC_ARB_DIV) - 2; + + } + + if (TIMING_PRESET_TWO) { + WRITE_PARAM_ALL_REG(table, emc_tfaw, GET_CYCLE_CEIL(tFAW)); + WRITE_PARAM_ALL_REG(table, emc_rrd, GET_CYCLE_CEIL(tRRD)); + + table->burst_mc_regs.mc_emem_arb_timing_faw = CEIL(GET_CYCLE_CEIL(tFAW) / MC_ARB_DIV) - 1; + table->burst_mc_regs.mc_emem_arb_timing_rrd = CEIL(GET_CYCLE_CEIL(tRRD) / MC_ARB_DIV) - 1; + } + + if (TIMING_PRESET_THREE) { + WRITE_PARAM_ALL_REG(table, emc_r2p, GET_CYCLE_CEIL(tRTP)); + WRITE_PARAM_ALL_REG(table, emc_w2p, WTP); + WRITE_PARAM_ALL_REG(table, emc_tratm, RATM); + WRITE_PARAM_ALL_REG(table, emc_twatm, WATM); + WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN); + + table->burst_mc_regs.mc_emem_arb_timing_rap2pre = CEIL(GET_CYCLE_CEIL(tRTP) / MC_ARB_DIV); + table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV); + } + + if (TIMING_PRESET_FOUR) { + WRITE_PARAM_ALL_REG(table, emc_rfc, GET_CYCLE_CEIL(tRFCab)); + WRITE_PARAM_ALL_REG(table, emc_rfcpb, GET_CYCLE_CEIL(tRFCpb)); + WRITE_PARAM_ALL_REG(table, emc_txsr, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + WRITE_PARAM_ALL_REG(table, emc_txsrdll, MIN(GET_CYCLE_CEIL(tXSR), (u32)0x3fe)); + + table->burst_mc_regs.mc_emem_arb_timing_rfcpb = CEIL(GET_CYCLE_CEIL(tRFCpb) / MC_ARB_DIV); + } + + if (TIMING_PRESET_FIVE) { + WRITE_PARAM_ALL_REG(table, emc_w2r, W2R); + + table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA; + } + + if (TIMING_PRESET_SIX) { + WRITE_PARAM_ALL_REG(table, emc_refresh, REFRESH); + WRITE_PARAM_ALL_REG(table, emc_pre_refresh_req_cnt, REFRESH / 4); + WRITE_PARAM_ALL_REG(table, emc_trefbw, REFBW); + } + + if (TIMING_PRESET_SEVEN) { + WRITE_PARAM_ALL_REG(table, emc_r2w, R2W); + WRITE_PARAM_ALL_REG(table, emc_w2r, W2R); + WRITE_PARAM_ALL_REG(table, emc_w2p, WTP); + WRITE_PARAM_ALL_REG(table, emc_trtm, RTM); + WRITE_PARAM_ALL_REG(table, emc_twtm, WTM); + WRITE_PARAM_ALL_REG(table, emc_tratm, RATM); + WRITE_PARAM_ALL_REG(table, emc_twatm, WATM); + WRITE_PARAM_ALL_REG(table, emc_rw2pden, WTPDEN); + + table->burst_mc_regs.mc_emem_arb_timing_wap2pre = CEIL(WTP / MC_ARB_DIV); + table->burst_mc_regs.mc_emem_arb_timing_r2w = CEIL(R2W / MC_ARB_DIV) - 1 + MC_ARB_SFA; + table->burst_mc_regs.mc_emem_arb_timing_w2r = CEIL(W2R / MC_ARB_DIV) - 1 + MC_ARB_SFA; + } u32 DA_TURNS = 0; DA_TURNS |= u8(table->burst_mc_regs.mc_emem_arb_timing_r2w / 2) << 16; //R2W TURN diff --git a/Source/Atmosphere/stratosphere/loader/source/patch.py b/Source/Atmosphere/stratosphere/loader/source/patch.py new file mode 100644 index 00000000..7ea5d7c1 --- /dev/null +++ b/Source/Atmosphere/stratosphere/loader/source/patch.py @@ -0,0 +1,74 @@ +#!python3 + +import sys +import os + +def file_replace_str(file_path, search_replace_list): + assert file_path + assert search_replace_list + with open(file_path, "r") as f: + content = f.read() + + for entry in search_replace_list: + (search, replace) = entry + if search in content: + content = content.replace(search, replace) + else: + assert replace in content, f"Pattern \"{search}\" not found" + + with open(file_path, "w") as f: + f.write(content) + + +dir_path = os.path.dirname(__file__) + +os.chdir(dir_path) +os.system("git reset --hard") + +ldr_process_creation = os.path.join(dir_path, "ldr_process_creation.cpp") +file_replace_str(ldr_process_creation, + [("""#include "ldr_ro_manager.hpp" + +namespace ams::ldr {""", +"""#include "ldr_ro_manager.hpp" +#include "oc/oc_loader.hpp" + +namespace ams::ldr {"""), + (""" NsoHeader g_nso_headers[Nso_Count]; + + Result ValidateProgramVersion(ncm::ProgramId program_id, u32 version) {""", + """ NsoHeader g_nso_headers[Nso_Count]; + + /* Pcv/Ptm check cache. */ + bool g_is_pcv; + bool g_is_ptm; + + Result ValidateProgramVersion(ncm::ProgramId program_id, u32 version) {"""), + (""" R_UNLESS(meta->aci->program_id <= meta->acid->program_id_max, ldr::ResultInvalidProgramId()); + + /* Validate the kernel capabilities. */""", + """ R_UNLESS(meta->aci->program_id <= meta->acid->program_id_max, ldr::ResultInvalidProgramId()); + + /* Check if nca is pcv or ptm */ + g_is_pcv = meta->aci->program_id == ncm::SystemProgramId::Pcv; + g_is_ptm = meta->aci->program_id == ncm::SystemProgramId::Ptm; + + /* Validate the kernel capabilities. */"""), + (""" LocateAndApplyIpsPatchesToModule(nso_header->module_id, map_address, nso_size); + }""", + """ LocateAndApplyIpsPatchesToModule(nso_header->module_id, map_address, nso_size); + + /* Apply pcv and ptm patches. */ + if (g_is_pcv) + oc::pcv::Patch(map_address, nso_size); + if (g_is_ptm) + oc::ptm::Patch(map_address, nso_size); + }""")]) + +ldr_meta = os.path.join(dir_path, "ldr_meta.cpp") +file_replace_str(ldr_meta, + [(""" Result ValidateAcidSignature(Meta *meta) { + /* Loader did not check signatures prior to 10.0.0. */""", + """ Result ValidateAcidSignature(Meta *meta) { + R_SUCCEED(); + /* Loader did not check signatures prior to 10.0.0. */""")]) diff --git a/Source/MemTesterNX/source/main.c b/Source/MemTesterNX/source/main.c index 7ab9670c..0f8ef610 100644 --- a/Source/MemTesterNX/source/main.c +++ b/Source/MemTesterNX/source/main.c @@ -13,7 +13,7 @@ * */ -#define __version__ "4.5.1-multithread-ocs2" +#define __version__ "4.5.1-multithread" // Include the most common headers from the C standard library #include @@ -241,10 +241,9 @@ int main(int argc, char* argv[]) bool isDevKit8GB = false; printf("MemTesterNX version " __version__ " (%d-bit)\n"\ - "Based on memtester. Copyright (C) 2001-2020 Charles Cazabon, 2021 KazushiMe, 2025 Souldbminer.\n"\ + "Based on memtester. Copyright (C) 2001-2020 Charles Cazabon, 2021 KazushiMe.\n"\ "Licensed under the GNU General Public License version 2 (only).\n\n"\ "Support full RAM test (up to 8GB) with 3-4 threads.\n"\ - "Ensure to set your CPU and GPU freq to maximum to get the best result.\n"\ "It will be looping forever until error occurs or user exits to HOME screen.\n\n"\ "Press A: long test\n"\ "Press X: fast test\n"\ diff --git a/Source/ReverseNX-RT.diff(deprecated) b/Source/ReverseNX-RT.diff(deprecated) new file mode 100644 index 00000000..626ae888 --- /dev/null +++ b/Source/ReverseNX-RT.diff(deprecated) @@ -0,0 +1,287 @@ +diff --git a/Overlay/Makefile b/Overlay/Makefile +index 9656834..3b2ebd5 100644 +--- a/Overlay/Makefile ++++ b/Overlay/Makefile +@@ -38,7 +38,7 @@ include $(DEVKITPRO)/libnx/switch_rules + # NACP building is skipped as well. + #--------------------------------------------------------------------------------- + APP_TITLE := ReverseNX-RT +-APP_VERSION := 1.1.1 ++APP_VERSION := 1.1.1-OC + + TARGET := ReverseNX-RT-ovl + BUILD := build +diff --git a/Overlay/source/main.cpp b/Overlay/source/main.cpp +index 810295c..2b3aa52 100644 +--- a/Overlay/source/main.cpp ++++ b/Overlay/source/main.cpp +@@ -1,7 +1,202 @@ + #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 ++#include + #include "SaltyNX.h" + ++class ModeSync { ++public: ++ enum ReverseNXMode { ++ ReverseNX_NotValid = 0, ++ ReverseNX_SystemDefault = 0, ++ ReverseNX_Handheld, ++ ReverseNX_Docked, ++ ReverseNX_Undefined, ++ }; ++ ++ void SetMode(bool isDefault, bool setDock, char* descBuf, size_t bufSize) { ++ auto changeHandler = [this](ReverseNXMode newMode) { ++ if (this->currentMode == ReverseNX_Undefined || this->currentMode != newMode) { ++ if (R_FAILED(this->ipc->SetMode(newMode))) { ++ this->ipc->ipcStatus = Ipc::IpcStatus_ConnectFailed; ++ return; ++ } ++ this->currentMode = newMode; ++ } ++ }; ++ ++ tsl::hlp::ScopeGuard updateBufGuard([&] { this->ipc->UpdateStatusDesc(descBuf, bufSize); }); ++ ++ if (isDefault) { ++ changeHandler(ReverseNX_SystemDefault); ++ return; ++ } ++ ++ changeHandler(setDock ? ReverseNX_Docked : ReverseNX_Handheld); ++ } ++ ++ ModeSync() { ++ this->ipc = new Ipc; ++ this->ipc->Init(); ++ } ++ ++ ~ModeSync() { ++ this->ipc->Exit(); ++ delete this->ipc; ++ } ++ ++protected: ++ struct Ipc { ++ #define API_VER 2 ++ #define SERVICE_NAME "sysclkOC" ++ ++ enum SysClkIpcCmd { ++ SysClkIpcCmd_GetApiVersion = 0, ++ SysClkIpcCmd_GetConfigValues = 9, ++ SysClkIpcCmd_SetReverseNXRTMode = 11, ++ }; ++ ++ enum SysClkConfigValue { ++ SysClkConfigValue_SyncReverseNXMode = 4, ++ SysClkConfigValue_EnumMax = 8, ++ }; ++ ++ struct SysClkConfigValueList { ++ uint64_t values[SysClkConfigValue_EnumMax]; ++ }; ++ ++ enum IpcStatus { ++ IpcStatus_OK, ++ ++ IpcStatus_Unknown, ++ IpcStatus_NotRunning, ++ IpcStatus_InitFailed, ++ IpcStatus_ConnectFailed, ++ IpcStatus_UnsupportedVer, ++ ++ IpcStatus_Count, ++ }; ++ ++ static constexpr const char* IpcStatusStr[IpcStatus_Count] = { ++ "", ++ ++ "Unknown", ++ "Err: Not running", ++ "Err: Failed to init", ++ "Err: Failed to connect", ++ "Err: Unsupported version", ++ }; ++ ++ Result Init() { ++ Result rc = 0; ++ ++ rc = IpcInitialize(); ++ ++ rc = GetStatus(); ++ ++ return rc; ++ } ++ ++ void Exit() { ++ if (--refCnt == 0) ++ serviceClose(&service); ++ } ++ ++ bool IsServiceRunning() { ++ Handle handle; ++ SmServiceName name = smEncodeName(SERVICE_NAME); ++ if (R_FAILED(smRegisterService(&handle, name, false, 1))) { ++ return true; ++ } ++ svcCloseHandle(handle); ++ smUnregisterService(name); ++ return false; ++ } ++ ++ Result IpcInitialize(void) { ++ Result rc = 0; ++ refCnt++; ++ ++ if (serviceIsActive(&service)) ++ return 0; ++ ++ rc = smGetService(&service, SERVICE_NAME); ++ ++ if (R_FAILED(rc)) { ++ this->ipcStatus = IpcStatus_InitFailed; ++ rc = this->ipcStatus; ++ this->Exit(); ++ return rc; ++ } ++ ++ return rc; ++ } ++ ++ Result GetApiVersion(u32* outVer) { ++ return serviceDispatchOut(&service, SysClkIpcCmd_GetApiVersion, *outVer); ++ } ++ ++ Result GetConfigValues(SysClkConfigValueList* outConfigValues) { ++ return serviceDispatchOut(&service, SysClkIpcCmd_GetConfigValues, *outConfigValues); ++ } ++ ++ Result SetMode(ReverseNXMode mode) { ++ return serviceDispatchIn(&service, SysClkIpcCmd_SetReverseNXRTMode, mode); ++ } ++ ++ Result GetStatus() { ++ if (!IsServiceRunning()) { ++ this->ipcStatus = IpcStatus_NotRunning; ++ return this->ipcStatus; ++ } ++ ++ tsl::hlp::ScopeGuard exitSrvGuard([&] { this->Exit(); }); ++ ++ uint32_t api_ver; ++ if (R_FAILED(GetApiVersion(&api_ver))) { ++ this->ipcStatus = IpcStatus_ConnectFailed; ++ return this->ipcStatus; ++ } ++ ++ if (api_ver != API_VER) { ++ this->ipcStatus = IpcStatus_UnsupportedVer; ++ return this->ipcStatus; ++ } ++ ++ SysClkConfigValueList* list = new SysClkConfigValueList; ++ tsl::hlp::ScopeGuard listGuard([&] { delete list; }); ++ ++ if (R_FAILED(GetConfigValues(list))) { ++ this->ipcStatus = IpcStatus_ConnectFailed; ++ return this->ipcStatus; ++ } ++ ++ exitSrvGuard.dismiss(); ++ ++ shouldSync = bool(list->values[SysClkConfigValue_SyncReverseNXMode]); ++ this->ipcStatus = IpcStatus_OK; ++ return this->ipcStatus; ++ } ++ ++ void UpdateStatusDesc(char* buffer, size_t size) { ++ snprintf(buffer, size, ++ "Mode Sync: %s%s", ++ IpcStatusStr[ipcStatus], ++ (ipcStatus == IpcStatus_OK) ? ( ++ shouldSync ? "ON" : "OFF" ++ ) : "" ++ ); ++ } ++ ++ Service service = {}; ++ std::atomic refCnt = 0; ++ IpcStatus ipcStatus = IpcStatus_Unknown; ++ bool shouldSync = false; ++ }; ++ ++ Ipc* ipc = nullptr; ++ ReverseNXMode currentMode = ReverseNX_Undefined; ++}; ++ + bool* def = 0; + bool* isDocked = 0; + bool* pluginActive = 0; +@@ -17,6 +212,7 @@ bool plugin = false; + char DockedChar[32]; + char SystemChar[32]; + char PluginChar[36]; ++char SysclkChar[0x40]; + uint64_t PID = 0; + Handle remoteSharedMemory = 1; + SharedMemory _sharedmemory = {}; +@@ -73,7 +269,7 @@ bool CheckPort () { + + class GuiTest : public tsl::Gui { + public: +- GuiTest(u8 arg1, u8 arg2, bool arg3) { } ++ GuiTest(ModeSync* p) : modeSync(p) { } + + // 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 +@@ -112,6 +308,7 @@ public: + else { + renderer->drawString(SystemChar, false, x, y+40, 20, renderer->a(0xFFFF)); + renderer->drawString(DockedChar, false, x, y+60, 20, renderer->a(0xFFFF)); ++ renderer->drawString(SysclkChar, false, x, y+80, 20, renderer->a(0xFFFF)); + } + } + }), 100); +@@ -190,6 +387,8 @@ public: + + if (_def) sprintf(SystemChar, "Controlled by system: Yes"); + else sprintf(SystemChar, "Controlled by system: No"); ++ ++ modeSync->SetMode(_def, _isDocked, SysclkChar, sizeof(SysclkChar)); + } + else i++; + } +@@ -200,6 +399,8 @@ public: + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) override { + return false; // Return true here to singal the inputs have been consumed + } ++ ++ ModeSync* modeSync; + }; + + class OverlayTest : public tsl::Overlay { +@@ -248,9 +449,11 @@ public: + + }); + ++ modeSync = new ModeSync; + } // Called at the start to initialize all services necessary for this Overlay + + virtual void exitServices() override { ++ delete modeSync; + shmemClose(&_sharedmemory); + fsdevUnmountDevice("sdmc"); + } // Callet at the end to clean up all services previously initialized +@@ -260,8 +463,10 @@ public: + 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 ++ return initially(modeSync); // Initial Gui to load. It's possible to pass arguments to it's constructor like this + } ++ ++ ModeSync* modeSync = nullptr; + }; + + int main(int argc, char **argv) { diff --git a/Source/TinyMemBenchNX/source/main.c b/Source/TinyMemBenchNX/source/main.c index fe9bfe63..47100705 100644 --- a/Source/TinyMemBenchNX/source/main.c +++ b/Source/TinyMemBenchNX/source/main.c @@ -903,7 +903,7 @@ int main(int argc, char* argv[]) printf("TinyMemBenchNX v0.4.11\n\ (based on tinymembench-pthread, a multi-thread fork of simple benchmark for memory throughput and latency)\n\n"); - printf("Copyright (c) 2021-2022 KazushiMe\n"); + printf("Copyright (c) 2011-2016 Siarhei Siamashka\n"); printf("Copyright (c) 2023 hanai3Bi\n"); printf("\n"); diff --git a/Source/clkrst_query.cpp b/Source/clkrst_query.cpp index d10c0b6e..4f53a784 100644 --- a/Source/clkrst_query.cpp +++ b/Source/clkrst_query.cpp @@ -99,7 +99,7 @@ double ptoGetMHz(PTO_ID pto_id, u32 divider = 1, u32 presel_reg = 0, u32 presel_ val &= 0xFFFFFF; val *= divider; - double rate_mhz = (u64)val * 32768. / cycle_count / 1000..; + double rate_mhz = (u64)val * 32768. / cycle_count / 1000. / 1000.; usleep(10); REG(clkrst_base + 0x60) = pre_val; usleep(10); diff --git a/Source/sys-clk-OC/README.md b/Source/sys-clk-OC/README.md deleted file mode 100644 index e0743624..00000000 --- a/Source/sys-clk-OC/README.md +++ /dev/null @@ -1,212 +0,0 @@ -# sys-clk-OC - -Switch sysmodule allowing you to set cpu/gpu clocks according to the running application and docked state. - - -## Clock table (MHz) - -official means HOS official, unless specified - -### CPU clocks - -* 2397 → OC max for Mariko (with CPU UV) -* 2295 → OC max for Mariko -* 2193 -* 2091 → OC max for Erista -* 1963 → official and safe max for Mariko -* 1887 -* 1785 → official boost mode, safe max for Erista -* 1683 -* 1581 -* 1428 -* 1326 -* 1224 → sdev OC -* 1122 -* 1020 → official docked & handheld -* 918 -* 816 -* 714 -* 612 - -### GPU clocks - -* 1305 → N/A -* 1267 → official max for Mariko (Tegra X1+ official max) -* 1228 → recommended max for Hiopt -* 1152 -* 1075 → recommended max for SLT -* 998 → safe max for Mariko, max for Erista (Tegra X1 official max) -* 921 → safe max for Erista -* 844 -* 768 → official docked -* 691 -* 614 → recommended Mariko max for handheld -* 537 -* 460 → max handheld -* 384 → official handheld -* 307 → official handheld -* 230 -* 153 -* 76 → boost mode - -### MEM clocks - -From Hekate Minerva module [sys_sdrammtc.c](https://github.com/CTCaer/hekate/blob/master/modules/hekate_libsys_minerva/sys_sdrammtc.c#L65) - -- 3200 → l4t and closed version max for Mariko -- 2931 -- 2665 -- 2502 → max for Mariko -- 2400 -- 2361 → l4t and closed version max for Erista -- 2131 → JEDEC. max for Erista and official max for Mariko. lpddr4(x) official max -- 2099 -- 2064 -- 1996 → OCS mariko default -- 1932 -- 1894 -- 1862 → JEDEC. official max for Erista; OCS erista default -- 1795 -- 1728 -- 1600 → official docked & official boost mode -- 1331 → JEDEC. official handheld -- 1065 -- 800 -- 665 - -## Capping - -To protect the battery from excessive strain, clocks requested from config may be capped before applying, depending on your current profile: - -### Erista (Safe) -| | Handheld | Charging (USB) | Charging (Official) | Docked | -|:-------:|:--------:|:--------------:|:-------------------:|:------:| -| **MEM** | - | - | - | - | -| **CPU** | 1785 | 1785 | 1785 | 1785 | -| **GPU** | 460 | 768 | 921 | 921 | - - -### Erista (Unsafe allowed) -| | Handheld | Charging (USB) | Charging (Official) | Docked | -|:-------:|:--------:|:--------------:|:-------------------:|:------:| -| **MEM** | - | - | - | - | -| **CPU** | 1785 | 1785 | - | - | -| **GPU** | 460 | 768 | - | - | - - -### Mariko (Safe) -| | Handheld | Charging (USB) | Charging (Official) | Docked | -|:-------:|:--------:|:--------------:|:-------------------:|:------:| -| **MEM** | - | - | - | - | -| **CPU** | 1963 | 1963 | 1963 | 1963 | -| **GPU** | 768 | 921 | 998 | 998 | - - -### Mariko (Unsafe allowed) -| | Handheld | Charging (USB) | Charging (Official) | Docked | -|:-------:|:--------:|:--------------:|:-------------------:|:------:| -| **MEM** | - | - | - | - | -| **CPU** | 1963 | 1963 | - | - | -| **GPU** | 768 | 921 | - | - | - - -## Installation - -The following instructions assumes you have a Nintendo Switch running Atmosphère, updated to at least the latest stable version. -Copy the `atmosphere`, and `switch` folders at the root of your sdcard, overwriting files if prompted. Also copy the `config` folder if you're not updating, to include default settings. - -**Note:** sys-clk-overlay requires to have [Tesla](https://gbatemp.net/threads/tesla-the-nintendo-switch-overlay-menu.557362/) installed and running - -## Relevant files - -* Config file allows one to set custom clocks per docked state and title id, described below - - `/config/sys-clk/config.ini` - -* Log file where the logs are written if enabled - - `/config/sys-clk/log.txt` - -* Log flag file enables log writing if file exists - - `/config/sys-clk/log.flag` - -* CSV file where the title id, profile, clocks and temperatures are written if enabled - - `/config/sys-clk/context.csv` - -* sys-clk overlay (accessible from anywhere by invoking the [Tesla menu](https://gbatemp.net/threads/tesla-the-nintendo-switch-overlay-menu.557362/)) - - `/switch/.overlays/sys-clk-overlay.ovl` - -* sys-clk core sysmodule - - `/atmosphere/contents/00FF0000636C6BFF/exefs.nsp` - `/atmosphere/contents/00FF0000636C6BFF/flags/boot2.flag` - -## Config - -Presets can be customized by adding them to the ini config file located at `/config/sys-clk/config.ini`, using the following template for each app - -``` -[Application Title ID] -docked_cpu= -docked_gpu= -docked_mem= -handheld_charging_cpu= -handheld_charging_gpu= -handheld_charging_mem= -handheld_charging_usb_cpu= -handheld_charging_usb_gpu= -handheld_charging_usb_mem= -handheld_charging_official_cpu= -handheld_charging_official_gpu= -handheld_charging_official_mem= -handheld_cpu= -handheld_gpu= -handheld_mem= -``` - -* Replace `Application Title ID` with the title id of the game/application you're interested in customizing. -A list of games title id can be found in the [Switchbrew wiki](https://switchbrew.org/wiki/Title_list/Games). -* Frequencies are expressed in mhz, and will be scaled to the nearest possible values, described in the clock table below. -* If any key is omitted, value is empty or set to 0, it will be ignored, and stock clocks will apply. -* If charging, sys-clk will look for the frequencies in that order, picking the first found - 1. Charger specific config (USB or Official) `handheld_charging_usb_X` or `handheld_charging_official_X` - 2. Non specific charging config `handheld_charging_X` - 3. Handheld config `handheld_X` - -### Example 1: Zelda BOTW - -* Overclock CPU when docked or charging - -Leads to a smoother framerate overall (ex: in the korok forest) - -``` -[01007EF00011E000] -docked_cpu=1224 -handheld_charging_cpu=1224 -handheld_mem=1600 -``` - -### Example 2: Picross - -* Underclocks on handheld to save battery - -``` -[0100BA0003EEA000] -handheld_cpu=816 -handheld_gpu=153 -``` - -### Advanced - -The `[values]` section allows you to alter timings in sys-clk, you should not need to edit any of these unless you know what you are doing. Possible values are: - -| Key | Desc | Default | -|:------------------------:|-------------------------------------------------------------------------------|:---------:| -|**allow_unsafe_freq** | Allow unsafe frequencies (CPU > 1963.5 MHz, GPU > 921.6 MHz) | OFF | -|**uncapped_clocks** | Remove CPU/GPU clock cappings | OFF | -|**temp_log_interval_ms** | Defines how often sys-clk log temperatures, in milliseconds (`0` to disable) | 0 ms | -|**csv_write_interval_ms** | Defines how often sys-clk writes to the CSV, in milliseconds (`0` to disable) | 0 ms | -|**poll_interval_ms** | Defines how fast sys-clk checks and applies profiles, in milliseconds | 500 ms | \ No newline at end of file diff --git a/Source/sys-clk/.gitignore b/Source/sys-clk/.gitignore new file mode 100644 index 00000000..cc543c0e --- /dev/null +++ b/Source/sys-clk/.gitignore @@ -0,0 +1,5 @@ +/dist +.DS_Store +Thumbs.db +desktop.ini +.vscode \ No newline at end of file diff --git a/Source/sys-clk/.gitlab-ci.yml b/Source/sys-clk/.gitlab-ci.yml new file mode 100644 index 00000000..80ebec89 --- /dev/null +++ b/Source/sys-clk/.gitlab-ci.yml @@ -0,0 +1,17 @@ +image: $CI_SERVER_HOST:4567/libretro/infrastructure/libretro-build-libnx-devkitpro:latest + +variables: + PACKAGE_FOLDER: "sys-clk" + +stages: + - package + +nightly: + stage: package + script: + - bash build.sh $PACKAGE_FOLDER + artifacts: + name: $PACKAGE_FOLDER + expire_in: 24 hours + paths: + - $PACKAGE_FOLDER diff --git a/Source/sys-clk/.gitmodules b/Source/sys-clk/.gitmodules new file mode 100644 index 00000000..3db71a4d --- /dev/null +++ b/Source/sys-clk/.gitmodules @@ -0,0 +1,3 @@ +[submodule "overlay/lib/libultrahand"] + path = overlay/lib/libultrahand + url = https://github.com/ppkantorski/libultrahand diff --git a/Source/sys-clk/LICENSE b/Source/sys-clk/LICENSE new file mode 100644 index 00000000..72648e0e --- /dev/null +++ b/Source/sys-clk/LICENSE @@ -0,0 +1,7 @@ +-------------------------------------------------------------------------- +"THE BEER-WARE LICENSE" (Revision 42): +, , +wrote this file. As long as you retain this notice you can do whatever you +want with this stuff. If you meet any of us some day, and you think this +stuff is worth it, you can buy us a beer in return. - The sys-clk authors +-------------------------------------------------------------------------- diff --git a/Source/sys-clk/README.md b/Source/sys-clk/README.md new file mode 100644 index 00000000..593f5c5f --- /dev/null +++ b/Source/sys-clk/README.md @@ -0,0 +1,163 @@ +# sys-clk + +Switch sysmodule allowing you to set cpu/gpu/mem clocks according to the running application and docked state. + +## Installation + +The following instructions assumes you have a Nintendo Switch running Atmosphère, updated to at least the latest stable version. +Copy the `atmosphere`, and `switch` folders at the root of your sdcard, overwriting files if prompted. Also copy the `config` folder if you're not updating, to include default settings. + +**Note:** sys-clk-overlay requires to have [Tesla](https://gbatemp.net/threads/tesla-the-nintendo-switch-overlay-menu.557362/) installed and running + +## Relevant files + +* Config file allows one to set custom clocks per docked state and title id, described below + + `/config/sys-clk/config.ini` + +* Log file where the logs are written if enabled + + `/config/sys-clk/log.txt` + +* Log flag file enables log writing if file exists + + `/config/sys-clk/log.flag` + +* CSV file where the title id, profile, clocks and temperatures are written if enabled + + `/config/sys-clk/context.csv` + +* sys-clk manager app (accessible from the hbmenu) + + `/switch/sys-clk-manager.nro` + +* sys-clk overlay (accessible from anywhere by invoking the [Tesla menu](https://gbatemp.net/threads/tesla-the-nintendo-switch-overlay-menu.557362/)) + + `/switch/.overlays/sys-clk-overlay.ovl` + +* sys-clk core sysmodule + + `/atmosphere/contents/00FF0000636C6BFF/exefs.nsp` + `/atmosphere/contents/00FF0000636C6BFF/flags/boot2.flag` + +## Config + +Presets can be customized by adding them to the ini config file located at `/config/sys-clk/config.ini`, using the following template for each app + +``` +[Application Title ID] +docked_cpu= +docked_gpu= +docked_mem= +handheld_charging_cpu= +handheld_charging_gpu= +handheld_charging_mem= +handheld_charging_usb_cpu= +handheld_charging_usb_gpu= +handheld_charging_usb_mem= +handheld_charging_official_cpu= +handheld_charging_official_gpu= +handheld_charging_official_mem= +handheld_cpu= +handheld_gpu= +handheld_mem= +``` + +* Replace `Application Title ID` with the title id of the game/application you're interested in customizing. +A list of games title id can be found in the [Switchbrew wiki](https://switchbrew.org/wiki/Title_list/Games). +* Frequencies are expressed in mhz, and will be scaled to the nearest possible values, described in the clock table below. +* If any key is omitted, value is empty or set to 0, it will be ignored, and stock clocks will apply. +* If charging, sys-clk will look for the frequencies in that order, picking the first found + 1. Charger specific config (USB or Official) `handheld_charging_usb_X` or `handheld_charging_official_X` + 2. Non specific charging config `handheld_charging_X` + 3. Handheld config `handheld_X` + +### Example 1: Zelda BOTW + +* Overclock CPU when docked or charging +* Overclock MEM to docked clocks when handheld + +Leads to a smoother framerate overall (ex: in the korok forest) + +``` +[01007EF00011E000] +docked_cpu=1224 +handheld_charging_cpu=1224 +handheld_mem=1600 +``` + +### Example 2: Picross + +* Underclocks on handheld to save battery + +``` +[0100BA0003EEA000] +handheld_cpu=816 +handheld_gpu=153 +handheld_mem=800 +``` + +### Advanced + +The `[values]` section allows you to alter timings in sys-clk, you should not need to edit any of these unless you know what you are doing. Possible values are: + +| Key | Desc | Default | +|:-----------------------:|-------------------------------------------------------------------------------|:-------:| +|**temp_log_interval_ms** | Defines how often sys-clk logs temperatures, in milliseconds (`0` to disable) | 0 ms | +|**freq_log_interval_ms** | Defines how often sys-clk logs real freqs, in milliseconds (`0` to disable) | 0 ms | +|**power_log_interval_ms**| Defines how often sys-clk logs power usage, in milliseconds (`0` to disable) | 0 ms | +|**csv_write_interval_ms**| Defines how often sys-clk writes to the CSV, in milliseconds (`0` to disable) | 0 ms | +|**poll_interval_ms** | Defines how fast sys-clk checks and applies profiles, in milliseconds | 300 ms | + + +## Capping + +To protect the battery from excessive strain, clocks requested from config may be capped before applying, depending on your current profile: + +| | Handheld | Charging (USB) | Charging (Official) | Docked | +|:-----:|:--------:|:--------------:|:-------------------:|:------:| +|**MEM**| - | - | - | - | +|**CPU**| - | - | - | - | +|**GPU**| 460 MHz* | 768 MHz | - | - | +*\* GPU handheld max for Mariko is increased to 614 MHz* + +## Clock table (MHz) + +### MEM clocks +* 1600 → official docked, boost mode, max clock +* 1331 → official handheld +* 1065 +* 800 +* 665 + +### CPU clocks +* 1785 → max clock, boost mode +* 1683 +* 1581 +* 1428 +* 1326 +* 1224 → sdev oc +* 1122 +* 1020 → official docked & handheld +* 918 +* 816 +* 714 +* 612 + +### GPU clocks +* 921 → max clock +* 844 +* 768 → official docked +* 691 +* 614 +* 537 +* 460 → max handheld +* 384 → official handheld +* 307 → official handheld +* 230 +* 153 +* 76 → boost mode + +**Notes:** +1. GPU overclock is capped at 460MHz in handheld and capped at 768MHz if charging, unless you're using the official charger. +2. Clocks higher than 768MHz need the official charger is plugged in. diff --git a/Source/sys-clk/build.sh b/Source/sys-clk/build.sh new file mode 100644 index 00000000..70d72aa4 --- /dev/null +++ b/Source/sys-clk/build.sh @@ -0,0 +1,45 @@ +#!/bin/bash +set -e + +ROOT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" +DIST_DIR="$ROOT_DIR/dist" +CORES="$(nproc --all)" + +if [[ -n "$1" ]]; then + DIST_DIR="$1" +fi + +echo "DIST_DIR: $DIST_DIR" +echo "CORES: $CORES" + +echo "*** sysmodule ***" +TITLE_ID="$(grep -oP '"title_id":\s*"0x\K(\w+)' "$ROOT_DIR/sysmodule/perms.json")" + +pushd "$ROOT_DIR/sysmodule" +make -j$CORES +popd > /dev/null + +mkdir -p "$DIST_DIR/atmosphere/contents/$TITLE_ID/flags" +cp -vf "$ROOT_DIR/sysmodule/out/sys-clk.nsp" "$DIST_DIR/atmosphere/contents/$TITLE_ID/exefs.nsp" +>"$DIST_DIR/atmosphere/contents/$TITLE_ID/flags/boot2.flag" + +echo "*** manager ***" +pushd "$ROOT_DIR/manager" +make -j$CORES +popd > /dev/null + +mkdir -p "$DIST_DIR/switch" +cp -vf "$ROOT_DIR/manager/sys-clk-manager.nro" "$DIST_DIR/switch/sys-clk-manager.nro" + +echo "*** overlay ***" +pushd "$ROOT_DIR/overlay" +make -j$CORES +popd > /dev/null + +mkdir -p "$DIST_DIR/switch/.overlays" +cp -vf "$ROOT_DIR/overlay/out/sys-clk-overlay.ovl" "$DIST_DIR/switch/.overlays/sys-clk-overlay.ovl" + +echo "*** assets ***" +mkdir -p "$DIST_DIR/config/sys-clk" +cp -vf "$ROOT_DIR/config.ini.template" "$DIST_DIR/config/sys-clk/config.ini.template" +cp -vf "$ROOT_DIR/README.md" "$DIST_DIR/README.md" diff --git a/Source/sys-clk/common/include/sysclk.h b/Source/sys-clk/common/include/sysclk.h new file mode 100644 index 00000000..18e644f3 --- /dev/null +++ b/Source/sys-clk/common/include/sysclk.h @@ -0,0 +1,26 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus +extern "C" { +#endif + +#include "sysclk/ipc.h" +#include "sysclk/board.h" +#include "sysclk/clock_manager.h" +#include "sysclk/apm.h" +#include "sysclk/config.h" +#include "sysclk/errors.h" + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/Source/sys-clk/common/include/sysclk/apm.h b/Source/sys-clk/common/include/sysclk/apm.h new file mode 100644 index 00000000..c2106517 --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/apm.h @@ -0,0 +1,22 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include "board.h" + +typedef struct { + uint32_t id; + uint32_t cpu_hz; + uint32_t gpu_hz; + uint32_t mem_hz; +} SysClkApmConfiguration; + +extern SysClkApmConfiguration sysclk_g_apm_configurations[]; diff --git a/Source/sys-clk/common/include/sysclk/board.h b/Source/sys-clk/common/include/sysclk/board.h new file mode 100644 index 00000000..bc705b67 --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/board.h @@ -0,0 +1,126 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include +#include + +typedef enum +{ + SysClkSocType_Erista = 0, + SysClkSocType_Mariko, + SysClkSocType_EnumMax +} SysClkSocType; + +typedef enum +{ + SysClkProfile_Handheld = 0, + SysClkProfile_HandheldCharging, + SysClkProfile_HandheldChargingUSB, + SysClkProfile_HandheldChargingOfficial, + SysClkProfile_Docked, + SysClkProfile_EnumMax +} SysClkProfile; + +typedef enum +{ + SysClkModule_CPU = 0, + SysClkModule_GPU, + SysClkModule_MEM, + SysClkModule_EnumMax +} SysClkModule; + +typedef enum +{ + SysClkThermalSensor_SOC = 0, + SysClkThermalSensor_PCB, + SysClkThermalSensor_Skin, + SysClkThermalSensor_EnumMax +} SysClkThermalSensor; + +typedef enum +{ + SysClkPowerSensor_Now = 0, + SysClkPowerSensor_Avg, + SysClkPowerSensor_EnumMax +} SysClkPowerSensor; + +typedef enum +{ + SysClkRamLoad_All = 0, + SysClkRamLoad_Cpu, + SysClkRamLoad_EnumMax +} SysClkRamLoad; + +#define SYSCLK_ENUM_VALID(n, v) ((v) < n##_EnumMax) + +static inline const char* sysclkFormatModule(SysClkModule module, bool pretty) +{ + switch(module) + { + case SysClkModule_CPU: + return pretty ? "CPU" : "cpu"; + case SysClkModule_GPU: + return pretty ? "GPU" : "gpu"; + case SysClkModule_MEM: + return pretty ? "Memory" : "mem"; + default: + return NULL; + } +} + +static inline const char* sysclkFormatThermalSensor(SysClkThermalSensor thermSensor, bool pretty) +{ + switch(thermSensor) + { + case SysClkThermalSensor_SOC: + return pretty ? "SOC" : "soc"; + case SysClkThermalSensor_PCB: + return pretty ? "PCB" : "pcb"; + case SysClkThermalSensor_Skin: + return pretty ? "Skin" : "skin"; + default: + return NULL; + } +} + +static inline const char* sysclkFormatPowerSensor(SysClkPowerSensor powSensor, bool pretty) +{ + switch(powSensor) + { + case SysClkPowerSensor_Now: + return pretty ? "Now" : "now"; + case SysClkPowerSensor_Avg: + return pretty ? "Avg" : "avg"; + default: + return NULL; + } +} + +static inline const char* sysclkFormatProfile(SysClkProfile profile, bool pretty) +{ + switch(profile) + { + case SysClkProfile_Docked: + return pretty ? "Docked" : "docked"; + case SysClkProfile_Handheld: + return pretty ? "Handheld" : "handheld"; + case SysClkProfile_HandheldCharging: + return pretty ? "Charging" : "handheld_charging"; + case SysClkProfile_HandheldChargingUSB: + return pretty ? "USB Charger" : "handheld_charging_usb"; + case SysClkProfile_HandheldChargingOfficial: + return pretty ? "Official Charger" : "handheld_charging_official"; + default: + return NULL; + } +} diff --git a/Source/sys-clk/common/include/sysclk/client/ipc.h b/Source/sys-clk/common/include/sysclk/client/ipc.h new file mode 100644 index 00000000..6a05ec1d --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/client/ipc.h @@ -0,0 +1,38 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include "types.h" +#include "../config.h" +#include "../board.h" +#include "../ipc.h" + +bool sysclkIpcRunning(); +Result sysclkIpcInitialize(void); +void sysclkIpcExit(void); + +Result sysclkIpcGetAPIVersion(u32* out_ver); +Result sysclkIpcGetVersionString(char* out, size_t len); +Result sysclkIpcGetCurrentContext(SysClkContext* out_context); +Result sysclkIpcGetProfileCount(u64 tid, u8* out_count); +Result sysclkIpcSetEnabled(bool enabled); +Result sysclkIpcExitCmd(); +Result sysclkIpcSetOverride(SysClkModule module, u32 hz); +Result sysclkIpcGetProfiles(u64 tid, SysClkTitleProfileList* out_profiles); +Result sysclkIpcSetProfiles(u64 tid, SysClkTitleProfileList* profiles); +Result sysclkIpcGetConfigValues(SysClkConfigValueList* out_configValues); +Result sysclkIpcSetConfigValues(SysClkConfigValueList* configValues); +Result sysclkIpcGetFreqList(SysClkModule module, u32* list, u32 maxCount, u32* outCount); + +static inline Result sysclkIpcRemoveOverride(SysClkModule module) +{ + return sysclkIpcSetOverride(module, 0); +} diff --git a/Source/sys-clk/common/include/sysclk/client/types.h b/Source/sys-clk/common/include/sysclk/client/types.h new file mode 100644 index 00000000..2e67315a --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/client/types.h @@ -0,0 +1,29 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __SWITCH__ + +#include +#include + +#else + +#define R_FAILED(res) ((res) != 0) +#define R_SUCCEEDED(res) ((res) == 0) + +typedef std::uint32_t Result; +typedef std::uint32_t u32; +typedef std::int32_t s32; +typedef std::uint64_t u64; +typedef std::uint8_t u8; + +#endif diff --git a/Source/sys-clk/common/include/sysclk/clock_manager.h b/Source/sys-clk/common/include/sysclk/clock_manager.h new file mode 100644 index 00000000..26628c85 --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/clock_manager.h @@ -0,0 +1,37 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include "board.h" + +typedef struct +{ + uint8_t enabled; + uint64_t applicationId; + SysClkProfile profile; + uint32_t freqs[SysClkModule_EnumMax]; + uint32_t realFreqs[SysClkModule_EnumMax]; + uint32_t overrideFreqs[SysClkModule_EnumMax]; + uint32_t temps[SysClkThermalSensor_EnumMax]; + int32_t power[SysClkPowerSensor_EnumMax]; + uint32_t ramLoad[SysClkRamLoad_EnumMax]; +} SysClkContext; + +typedef struct +{ + union { + uint32_t mhz[SysClkProfile_EnumMax * SysClkModule_EnumMax]; + uint32_t mhzMap[SysClkProfile_EnumMax][SysClkModule_EnumMax]; + }; +} SysClkTitleProfileList; + +#define SYSCLK_FREQ_LIST_MAX 32 diff --git a/Source/sys-clk/common/include/sysclk/config.h b/Source/sys-clk/common/include/sysclk/config.h new file mode 100644 index 00000000..76f6d06d --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/config.h @@ -0,0 +1,79 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include + +typedef enum { + SysClkConfigValue_PollingIntervalMs = 0, + SysClkConfigValue_TempLogIntervalMs, + SysClkConfigValue_FreqLogIntervalMs, + SysClkConfigValue_PowerLogIntervalMs, + SysClkConfigValue_CsvWriteIntervalMs, + SysClkConfigValue_EnumMax, + SysClkConfigValue_UncappedClocks, +} SysClkConfigValue; + +typedef struct { + uint64_t values[SysClkConfigValue_UncappedClocks]; +} SysClkConfigValueList; + +static inline const char* sysclkFormatConfigValue(SysClkConfigValue val, bool pretty) +{ + switch(val) + { + case SysClkConfigValue_PollingIntervalMs: + return pretty ? "Polling Interval (ms)" : "poll_interval_ms"; + case SysClkConfigValue_TempLogIntervalMs: + return pretty ? "Temperature logging interval (ms)" : "temp_log_interval_ms"; + case SysClkConfigValue_FreqLogIntervalMs: + return pretty ? "Frequency logging interval (ms)" : "freq_log_interval_ms"; + case SysClkConfigValue_PowerLogIntervalMs: + return pretty ? "Power logging interval (ms)" : "power_log_interval_ms"; + case SysClkConfigValue_CsvWriteIntervalMs: + return pretty ? "CSV write interval (ms)" : "csv_write_interval_ms"; + default: + return NULL; + } +} + +static inline uint64_t sysclkDefaultConfigValue(SysClkConfigValue val) +{ + switch(val) + { + case SysClkConfigValue_PollingIntervalMs: + return 300ULL; + case SysClkConfigValue_TempLogIntervalMs: + case SysClkConfigValue_FreqLogIntervalMs: + case SysClkConfigValue_PowerLogIntervalMs: + case SysClkConfigValue_CsvWriteIntervalMs: + return 0ULL; + default: + return 0ULL; + } +} + +static inline uint64_t sysclkValidConfigValue(SysClkConfigValue val, uint64_t input) +{ + switch(val) + { + case SysClkConfigValue_PollingIntervalMs: + return input > 0; + case SysClkConfigValue_TempLogIntervalMs: + case SysClkConfigValue_FreqLogIntervalMs: + case SysClkConfigValue_PowerLogIntervalMs: + case SysClkConfigValue_CsvWriteIntervalMs: + return input >= 0; + default: + return false; + } +} \ No newline at end of file diff --git a/Source/sys-clk/common/include/sysclk/errors.h b/Source/sys-clk/common/include/sysclk/errors.h new file mode 100644 index 00000000..ed0d9a98 --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/errors.h @@ -0,0 +1,21 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#define SYSCLK_ERROR_MODULE 388 +#define SYSCLK_ERROR(desc) ((SYSCLK_ERROR_MODULE & 0x1FF) | (SysClkError_##desc & 0x1FFF)<<9) + +typedef enum +{ + SysClkError_Generic = 0, + SysClkError_ConfigNotLoaded = 1, + SysClkError_ConfigSaveFailed = 2, +} SysClkError; diff --git a/Source/sys-clk/common/include/sysclk/ipc.h b/Source/sys-clk/common/include/sysclk/ipc.h new file mode 100644 index 00000000..9591286a --- /dev/null +++ b/Source/sys-clk/common/include/sysclk/ipc.h @@ -0,0 +1,54 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include "board.h" +#include "clock_manager.h" + +#define SYSCLK_IPC_API_VERSION 4 +#define SYSCLK_IPC_SERVICE_NAME "sys:clk" + +enum SysClkIpcCmd +{ + SysClkIpcCmd_GetApiVersion = 0, + SysClkIpcCmd_GetVersionString = 1, + SysClkIpcCmd_GetCurrentContext = 2, + SysClkIpcCmd_Exit = 3, + SysClkIpcCmd_GetProfileCount = 4, + SysClkIpcCmd_GetProfiles = 5, + SysClkIpcCmd_SetProfiles = 6, + SysClkIpcCmd_SetEnabled = 7, + SysClkIpcCmd_SetOverride = 8, + SysClkIpcCmd_GetConfigValues = 9, + SysClkIpcCmd_SetConfigValues = 10, + SysClkIpcCmd_ToggleUncappedClocks = 11, + SysClkIpcCmd_GetFreqList = 12, +}; + + +typedef struct +{ + uint64_t tid; + SysClkTitleProfileList profiles; +} SysClkIpc_SetProfiles_Args; + +typedef struct +{ + SysClkModule module; + uint32_t hz; +} SysClkIpc_SetOverride_Args; + +typedef struct +{ + SysClkModule module; + uint32_t maxCount; +} SysClkIpc_GetFreqList_Args; \ No newline at end of file diff --git a/Source/sys-clk/common/src/apm_profile_table.c b/Source/sys-clk/common/src/apm_profile_table.c new file mode 100644 index 00000000..23a95438 --- /dev/null +++ b/Source/sys-clk/common/src/apm_profile_table.c @@ -0,0 +1,32 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include + +SysClkApmConfiguration sysclk_g_apm_configurations[] = { + {0x00010000, 1020000000, 384000000, 1600000000}, + {0x00010001, 1020000000, 768000000, 1600000000}, + {0x00010002, 1224000000, 691200000, 1600000000}, + {0x00020000, 1020000000, 230400000, 1600000000}, + {0x00020001, 1020000000, 307200000, 1600000000}, + {0x00020002, 1224000000, 230400000, 1600000000}, + {0x00020003, 1020000000, 307200000, 1331200000}, + {0x00020004, 1020000000, 384000000, 1331200000}, + {0x00020005, 1020000000, 307200000, 1065600000}, + {0x00020006, 1020000000, 384000000, 1065600000}, + {0x92220007, 1020000000, 460800000, 1600000000}, + {0x92220008, 1020000000, 460800000, 1331200000}, + {0x92220009, 1785000000, 76800000, 1600000000}, + {0x9222000A, 1785000000, 76800000, 1331200000}, + {0x9222000B, 1020000000, 76800000, 1600000000}, + {0x9222000C, 1020000000, 76800000, 1331200000}, + {0, 0, 0, 0}, +}; + diff --git a/Source/sys-clk/common/src/client/ipc.c b/Source/sys-clk/common/src/client/ipc.c new file mode 100644 index 00000000..17d5af50 --- /dev/null +++ b/Source/sys-clk/common/src/client/ipc.c @@ -0,0 +1,133 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#define NX_SERVICE_ASSUME_NON_DOMAIN +#include +#include +#include +#include + +static Service g_sysclkSrv; +static atomic_size_t g_refCnt; + +bool sysclkIpcRunning() +{ + Handle handle; + bool running = R_FAILED(smRegisterService(&handle, smEncodeName(SYSCLK_IPC_SERVICE_NAME), false, 1)); + + if (!running) + { + smUnregisterService(smEncodeName(SYSCLK_IPC_SERVICE_NAME)); + } + + return running; +} + +Result sysclkIpcInitialize(void) +{ + Result rc = 0; + + g_refCnt++; + + if (serviceIsActive(&g_sysclkSrv)) + return 0; + + rc = smGetService(&g_sysclkSrv, SYSCLK_IPC_SERVICE_NAME); + + if (R_FAILED(rc)) sysclkIpcExit(); + + return rc; +} + +void sysclkIpcExit(void) +{ + if (--g_refCnt == 0) + { + serviceClose(&g_sysclkSrv); + } +} + +Result sysclkIpcGetAPIVersion(u32* out_ver) +{ + return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetApiVersion, *out_ver); +} + +Result sysclkIpcGetVersionString(char* out, size_t len) +{ + return serviceDispatch(&g_sysclkSrv, SysClkIpcCmd_GetVersionString, + .buffer_attrs = { SfBufferAttr_HipcMapAlias | SfBufferAttr_Out }, + .buffers = {{out, len}}, + ); +} + +Result sysclkIpcGetCurrentContext(SysClkContext* out_context) +{ + return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetCurrentContext, *out_context); +} + +Result sysclkIpcGetProfileCount(u64 tid, u8* out_count) +{ + return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetProfileCount, tid, *out_count); +} + +Result sysclkIpcSetEnabled(bool enabled) +{ + u8 enabledRaw = (u8)enabled; + return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetEnabled, enabledRaw); +} + +Result sysclkIpcSetOverride(SysClkModule module, u32 hz) +{ + SysClkIpc_SetOverride_Args args = { + .module = module, + .hz = hz + }; + return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetOverride, args); +} + +Result sysclkIpcGetProfiles(u64 tid, SysClkTitleProfileList* out_profiles) +{ + return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetProfiles, tid, *out_profiles); +} + +Result sysclkIpcSetProfiles(u64 tid, SysClkTitleProfileList* profiles) +{ + SysClkIpc_SetProfiles_Args args; + args.tid = tid; + memcpy(&args.profiles, profiles, sizeof(SysClkTitleProfileList)); + return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetProfiles, args); +} + +Result sysclkIpcGetConfigValues(SysClkConfigValueList* out_configValues) +{ + return serviceDispatchOut(&g_sysclkSrv, SysClkIpcCmd_GetConfigValues, *out_configValues); +} + +Result sysclkIpcSetConfigValues(SysClkConfigValueList* configValues) +{ + return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_SetConfigValues, *configValues); +} + +Result SysClkIpcToggleUncappedClocks(bool toggled) +{ + return serviceDispatchIn(&g_sysclkSrv, SysClkIpcCmd_ToggleUncappedClocks, *toggled); +} + +Result sysclkIpcGetFreqList(SysClkModule module, u32* list, u32 maxCount, u32* outCount) +{ + SysClkIpc_GetFreqList_Args args = { + .module = module, + .maxCount = maxCount + }; + return serviceDispatchInOut(&g_sysclkSrv, SysClkIpcCmd_GetFreqList, args, *outCount, + .buffer_attrs = { SfBufferAttr_HipcAutoSelect | SfBufferAttr_Out }, + .buffers = {{list, maxCount * sizeof(u32)}}, + ); +} diff --git a/Source/sys-clk/config.ini.template b/Source/sys-clk/config.ini.template new file mode 100644 index 00000000..4305c725 --- /dev/null +++ b/Source/sys-clk/config.ini.template @@ -0,0 +1,19 @@ +[values] +; Defines how often sys-clk log temperatures, in milliseconds (set 0 to disable) +temp_log_interval_ms=0 +; Defines how often sys-clk writes to the CSV, in milliseconds (set 0 to disable) +csv_write_interval_ms=0 + +; Example #1: BOTW +; Overclock CPU when docked +; Overclock MEM to docked clocks when handheld +;[01007EF00011E000] +;docked_cpu=1224 +;handheld_mem=1600 + +; Example #2: Picross +; Underclock to save battery +;[0100BA0003EEA000] +;handheld_cpu=816 +;handheld_gpu=153 +;handheld_mem=800 \ No newline at end of file diff --git a/Source/sys-clk/overlay/.gitignore b/Source/sys-clk/overlay/.gitignore new file mode 100644 index 00000000..36a52c92 --- /dev/null +++ b/Source/sys-clk/overlay/.gitignore @@ -0,0 +1,2 @@ +/out +/build diff --git a/Source/sys-clk/overlay/Makefile b/Source/sys-clk/overlay/Makefile new file mode 100644 index 00000000..2a6a31af --- /dev/null +++ b/Source/sys-clk/overlay/Makefile @@ -0,0 +1,170 @@ +#--------------------------------------------------------------------------------- +.SUFFIXES: +#--------------------------------------------------------------------------------- + +ifeq ($(strip $(DEVKITPRO)),) +$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") +endif + +TOPDIR ?= $(CURDIR) +include $(DEVKITPRO)/libnx/switch_rules + +#--------------------------------------------------------------------------------- +# TARGET is the name of the output +# BUILD is the directory where object files & intermediate files will be placed +# SOURCES is a list of directories containing source code +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm". +#--------------------------------------------------------------------------------- +TARGET := sys-clk-overlay +BUILD := build +OUTDIR := out +RESOURCES := res +SOURCES := src src/ui/gui src/ui/elements ../common/src ../common/src/client +DATA := data +INCLUDES := ../common/include +EXEFS_SRC := exefs_src + +APP_TITLE := sys-clk-ocs2 +NO_ICON := 1 + +# This location should reflect where you place the libultrahand directory (lib can vary between projects). +include ${TOPDIR}/lib/libultrahand/ultrahand.mk + + +#--------------------------------------------------------------------------------- +# version control constants +#--------------------------------------------------------------------------------- +#TARGET_VERSION := $(shell git describe --dirty --always --tags) +APP_VERSION := 1.0.0-ocs2 +TARGET_VERSION := $(APP_VERSION) + +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- +DEFINES := -DDISABLE_IPC -DTARGET="\"$(TARGET)\"" -DTARGET_VERSION="\"$(TARGET_VERSION)\"" + +ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE + +CFLAGS := -Os -Wall -flto -fdata-sections -ffunction-sections -fno-rtti -fno-common \ + $(ARCH) $(DEFINES) + +CFLAGS += $(INCLUDE) -D__SWITCH__ + +# Enable appearance overriding +UI_OVERRIDE_PATH := /config/sys-clk/ +CFLAGS += -DUI_OVERRIDE_PATH="\"$(UI_OVERRIDE_PATH)\"" + +# Disable fstream +#NO_FSTREAM_DIRECTIVE := 1 +#CFLAGS += -DNO_FSTREAM_DIRECTIVE=$(NO_FSTREAM_DIRECTIVE) + + +CXXFLAGS := $(CFLAGS) -fno-exceptions -std=gnu++20 + +ASFLAGS := -g $(ARCH) +LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) + +LIBS := -lcurl -lz -lzzip -lmbedtls -lmbedx509 -lmbedcrypto -ljansson -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)/$(OUTDIR)/$(TARGET) +export TOPDIR := $(CURDIR) + +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + +export DEPSDIR := $(CURDIR)/$(BUILD) + +CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) +CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) +#--------------------------------------------------------------------------------- + export LD := $(CC) +#--------------------------------------------------------------------------------- +else +#--------------------------------------------------------------------------------- + export LD := $(CXX) +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- + +export OFILES := $(addsuffix .o,$(BINFILES)) \ + $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) + +export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) + +export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) + +export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC) + +.PHONY: $(BUILD) clean all + +#--------------------------------------------------------------------------------- +all: $(BUILD) + +$(BUILD): + @[ -d $@ ] || mkdir -p $@ + @[ -d $(OUTDIR) ] || mkdir -p $(OUTDIR) + @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile + +#--------------------------------------------------------------------------------- +clean: + @echo clean ... + @rm -fr $(BUILD) $(TARGET).ovl $(TARGET).nacp $(TARGET).nso $(TARGET).elf $(OUTDIR) + + +#--------------------------------------------------------------------------------- +else +.PHONY: all + +DEPENDS := $(OFILES:.o=.d) + +#--------------------------------------------------------------------------------- +# main targets +#--------------------------------------------------------------------------------- + +all: $(OUTPUT).ovl + +$(OUTPUT).ovl: $(OUTPUT).elf $(OUTPUT).nacp + @elf2nro $< $@ --nacp=$(OUTPUT).nacp + @echo "built ... $(notdir $(OUTPUT).ovl)" + @printf 'ULTR' >> $@ + @printf "Ultrahand signature has been added.\n" + +$(OUTPUT).elf: $(OFILES) + +#--------------------------------------------------------------------------------- +# you need a rule like this for each extension you use as binary data +#--------------------------------------------------------------------------------- +%.bin.o : %.bin +#--------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + +-include $(DEPENDS) + +#--------------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/overlay/data/logo_rgba.bin b/Source/sys-clk/overlay/data/logo_rgba.bin new file mode 100644 index 0000000000000000000000000000000000000000..d5b9ced7955408287a22583253cbde7de3d89d04 GIT binary patch literal 17160 zcmeI2S*TTI6vv%%ykLY4mKIn_SZG>=1xjcn6!l<84^adWCMA}b^;8s65Jg4NLsC!} zSqNS#AIyS6DS{h?B{Uc|k!6+@G!M7mU(Xl+v+mya?0wGh`0_3I^Q~{qcdb32J7Pqp z+=1MI+=1MI+=1MI+<|Hx7#tiNQ^m5XU6okbrhW(L|Eb_5@E$lIz9=KP*d~3lMXqz!X<^c7MbUN*9;aQN{AYrLUSJ8YWBW4C!@etXBhFPJ=PT^X zu3x$?{ABi;)lER}h$F#i;6|_;>;O%1*k1yiHv8X{cnoySNu=w}DARRRLyFVxN-g?3 z-%iCf)=ycl0dv7Za5vDmkOyNPWF60q7^i?AKqB>MYRr}P=*~!njdfSj`HF5dIL>9_ zk&OjEgGBoaY|c)~#`=`oAnT|GkJS!O{-vQl&1Xo@kWB$&V-92;%?*DYH`{^Jh-KG_f{pJv3w)>#d{oLt_pzpW_k5`wcuxGqD_`%zL;oJvPGchM89tLC!Md@bXr5~U8*In zO~0|A)HTX$m;H3Ftrd@b%w74rGQRP6UDhg}>+wGwya@EXR7ScUPIAA*Bj0IG`%FIH zE;@l<|7!A3P$69@lf6QHHZtFw-H`zBm`+2T19v}7YHn0Q4 z;}Fr{#v)(jw@Ya>OLpwnn(S}*DMkJ+!=`o(_{82>+9o#6?U*L*;myfjPb(gmn7hv0 zCgT5js9{B`oWtpfH4QuwV(NT6Df%JPb=v6$*&x_z!Z)H{t3AGzYiJd#OivCyKRPWa zvn`V2*!J8M5C3JJ9A5X86N+-xkr88eh`YGR9~=MH@GSc=z~2$p6!}$=5vNiORboXO zV*9bhcJPj9Gu$5gj^?J=#Mq|9MupckuLIlZp!66+x69&*ZTi-gVj+LX?7o6uV0*DM zl5Jekb)|+Fx5}Q}*Q+?Aeegxs6n$fz7-J%vYrbN)MjP#s_XWHEfA2;<3+P*<(~_b% zjabKGsAo^z%XE$`0gA8ZEcMc7!S>MkQ}%4KSO!K<8vlMTYADMwoSYiR1ATXN`jXA9 zK;MIwgQtPsj~mL83IsIk)`e>i_*mSLi6tnJ14U0fL-mUy5_EL|JM(;ZNn=B4*27+CyxlO`N$BWZl z9wYG>Oa<}!?tY2a3<_hUSX!~!lpMl(p4&N(T~}-H*mZd7xCne5>W*8TmrdWql>^!8 zXvkjAa3`i3;D?=CBaY5(C%r$4|tq=B*OT5(o;k+N4WI>3B%e_jWip6f;K zoTGjR7}7j&Gl=hbx<7RM-e13>>`|oy%;q47r2i3`SH(Zu9Gwm@pLc9%x}WufX-B7; koV98Pn9;pJ?`>;9rT2xZv9n$7K<+^9K<+^9K-~`f2SO)gxBvhE literal 0 HcmV?d00001 diff --git a/Source/sys-clk/overlay/lang/de.json b/Source/sys-clk/overlay/lang/de.json new file mode 100644 index 00000000..1c8c25d1 --- /dev/null +++ b/Source/sys-clk/overlay/lang/de.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "App-Profil bearbeiten", + "Advanced": "Erweitert", + "Edit Global Profile": "Globales Profil bearbeiten", + "Temporary Overrides": "Temporäre Überschreibungen", + "Temporary Overrides   Reset": "Temporäre Überschreibungen   Reset", + "Settings": "Einstellungen", + "Enable": "Aktivieren", + "Uncapped Clocks": "Unbegrenzte Taktraten", + "Override Boost Mode": "Boost-Modus überschreiben", + "Auto CPU Boost": "Automatischer CPU-Boost", + "Sync ReverseNX": "ReverseNX synchronisieren", + "GPU DVFS": "GPU-DVFS", + "Off": "Aus", + "Official Service Method": "Offizielle Servicemethode", + "Hijack Method": "Hijack-Methode", + "App ID": "App-ID", + "EOS mode": "EOS-Modus", + "Skin": "Look", + "Now": "Jetzt", + "Avg": "Ø", + "Docked": "Gedockt", + "Handheld": "Handheld", + "Charging": "Lädt", + "Official Charger": "Offizielles Ladegerät", + "USB Charger": "USB-Ladegerät", + "Docked   Reset": "Gedockt   Reset", + "Handheld   Reset": "Handheld   Reset", + "Charging   Reset": "Lädt   Reset", + "Official Charger   Reset": "Offizielles Ladegerät   Reset", + "USB Charger   Reset": "USB-Ladegerät   Reset", + "Memory": "Speicher", + "Do not override": "Nicht überschreiben", + "Profile": "Profil" +} diff --git a/Source/sys-clk/overlay/lang/en.json b/Source/sys-clk/overlay/lang/en.json new file mode 100644 index 00000000..cfd23082 --- /dev/null +++ b/Source/sys-clk/overlay/lang/en.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Edit App Profile", + "Advanced": "Advanced", + "Edit Global Profile": "Edit Global Profile", + "Temporary Overrides": "Temporary Overrides", + "Temporary Overrides   Reset": "Temporary Overrides   Reset", + "Settings": "Settings", + "Enable": "Enable", + "Uncapped Clocks": "Uncapped Clocks", + "Override Boost Mode": "Override Boost Mode", + "Auto CPU Boost": "Auto CPU Boost", + "Sync ReverseNX": "Sync ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Off", + "Official Service Method": "Official Service Method", + "Hijack Method": "Hijack Method", + "App ID": "App ID", + "EOS mode": "EOS mode", + "Skin": "Skin", + "Now": "Now", + "Avg": "Avg", + "Docked": "Docked", + "Handheld": "Handheld", + "Charging": "Charging", + "Official Charger": "Official Charger", + "USB Charger": "USB Charger", + "Docked   Reset": "Docked   Reset", + "Handheld   Reset": "Handheld   Reset", + "Charging   Reset": "Charging   Reset", + "Official Charger   Reset": "Official Charger   Reset", + "USB Charger   Reset": "USB Charger   Reset", + "Memory": "Memory", + "Do not override": "Do not overrride", + "Profile": "Profile" +} diff --git a/Source/sys-clk/overlay/lang/es.json b/Source/sys-clk/overlay/lang/es.json new file mode 100644 index 00000000..762ded5a --- /dev/null +++ b/Source/sys-clk/overlay/lang/es.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Editar perfil de la app", + "Advanced": "Avanzado", + "Edit Global Profile": "Editar perfil global", + "Temporary Overrides": "Anulaciones temporales", + "Temporary Overrides   Reset": "Anulaciones temporales   Reiniciar", + "Settings": "Configuración", + "Enable": "Habilitar", + "Uncapped Clocks": "Relojes sin límite", + "Override Boost Mode": "Sobrescribir modo Boost", + "Auto CPU Boost": "Impulso automático de CPU", + "Sync ReverseNX": "Sincronizar con ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Apagado", + "Official Service Method": "Método de servicio oficial", + "Hijack Method": "Método de secuestro", + "App ID": "ID App", + "EOS mode": "Modo EOS", + "Skin": "Tema", + "Now": "Ahora", + "Avg": "Med", + "Docked": "Conectado al dock", + "Handheld": "Portátil", + "Charging": "Cargando", + "Official Charger": "Cargador oficial", + "USB Charger": "Cargador USB", + "Docked   Reset": "Conectado al dock   Reiniciar", + "Handheld   Reset": "Portátil   Reiniciar", + "Charging   Reset": "Cargando   Reiniciar", + "Official Charger   Reset": "Cargador oficial   Reiniciar", + "USB Charger   Reset": "Cargador USB   Reiniciar", + "Memory": "Memoria", + "Do not override": "No sobrescribir", + "Profile": "Perfil" +} diff --git a/Source/sys-clk/overlay/lang/fr.json b/Source/sys-clk/overlay/lang/fr.json new file mode 100644 index 00000000..f85f6c44 --- /dev/null +++ b/Source/sys-clk/overlay/lang/fr.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Modifier profil", + "Advanced": "Avancé", + "Edit Global Profile": "Modifier global", + "Temporary Overrides": "Remplacements temporaires", + "Temporary Overrides   Reset": "Remplacements temporaires   Réinitialiser", + "Settings": "Paramètres", + "Enable": "Activer", + "Uncapped Clocks": "Horloges sans limite", + "Override Boost Mode": "Forcer mode Boost", + "Auto CPU Boost": "Boost CPU auto", + "Sync ReverseNX": "Synchroniser ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Éteint", + "Official Service Method": "Service officiel", + "Hijack Method": "Détournement", + "App ID": "ID App", + "EOS mode": "Mode EOS", + "Skin": "Skin", + "Now": "Act", + "Avg": "Moy", + "Docked": "Ancré", + "Handheld": "Portable", + "Charging": "En charge", + "Official Charger": "Chargeur off.", + "USB Charger": "Chargeur USB", + "Docked   Reset": "Ancré   Réinitialiser", + "Handheld   Reset": "Portable   Réinitialiser", + "Charging   Reset": "En charge   Réinitialiser", + "Official Charger   Reset": "Chargeur off.   Réinitialiser", + "USB Charger   Reset": "Chargeur USB   Réinitialiser", + "Memory": "Mémoire", + "Do not override": "Ne pas remplacer", + "Profile": "Profil" +} diff --git a/Source/sys-clk/overlay/lang/it.json b/Source/sys-clk/overlay/lang/it.json new file mode 100644 index 00000000..be885e89 --- /dev/null +++ b/Source/sys-clk/overlay/lang/it.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Modifica profilo app", + "Advanced": "Avanzate", + "Edit Global Profile": "Modifica profilo globale", + "Temporary Overrides": "Sostituzioni temporanee", + "Temporary Overrides   Reset": "Sostituzioni temporanee   Reimposta", + "Settings": "Impostazioni", + "Enable": "Abilita", + "Uncapped Clocks": "Clock senza limiti", + "Override Boost Mode": "Forza modalità Boost", + "Auto CPU Boost": "Boost CPU automatico", + "Sync ReverseNX": "Sincronizza con ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Spento", + "Official Service Method": "Servizio ufficiale", + "Hijack Method": "Dirottamento", + "App ID": "ID App", + "EOS mode": "Modalità EOS", + "Skin": "Tema", + "Now": "Ora", + "Avg": "Media", + "Docked": "In modalità dock", + "Handheld": "Portatile", + "Charging": "In carica", + "Official Charger": "Caricatore ufficiale", + "USB Charger": "Caricatore USB", + "Docked   Reset": "In modalità dock   Reimposta", + "Handheld   Reset": "Portatile   Reimposta", + "Charging   Reset": "In carica   Reimposta", + "Official Charger   Reset": "Caricatore ufficiale   Reimposta", + "USB Charger   Reset": "Caricatore USB   Reimposta", + "Memory": "Memoria", + "Do not override": "Non sovrascrivere", + "Profile": "Profilo" +} diff --git a/Source/sys-clk/overlay/lang/ja.json b/Source/sys-clk/overlay/lang/ja.json new file mode 100644 index 00000000..7714fa63 --- /dev/null +++ b/Source/sys-clk/overlay/lang/ja.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "アプリプロフィールを編集", + "Advanced": "詳細設定", + "Edit Global Profile": "グローバルプロフィールを編集", + "Temporary Overrides": "一時的なオーバーライド", + "Temporary Overrides   Reset": "一時的なオーバーライド   リセット", + "Settings": "設定", + "Enable": "有効化", + "Uncapped Clocks": "クロック制限解除", + "Override Boost Mode": "ブーストモードをオーバーライド", + "Auto CPU Boost": "自動CPUブースト", + "Sync ReverseNX": "ReverseNXと同期", + "GPU DVFS": "GPU DVFS", + "Off": "オフ", + "Official Service Method": "公式サービス", + "Hijack Method": "ハイジャック", + "App ID": "アプリID", + "EOS mode": "EOSモード", + "Skin": "スキン", + "Now": "現在", + "Avg": "平均", + "Docked": "ドックモード", + "Handheld": "携帯モード", + "Charging": "充電中", + "Official Charger": "公式充電器", + "USB Charger": "USB充電器", + "Docked   Reset": "ドックモード   リセット", + "Handheld   Reset": "携帯モード   リセット", + "Charging   Reset": "充電中   リセット", + "Official Charger   Reset": "公式充電器   リセット", + "USB Charger   Reset": "USB充電器   リセット", + "Memory": "メモリ", + "Do not override": "オーバーライドしない", + "Profile": "プロフィール" +} diff --git a/Source/sys-clk/overlay/lang/ko.json b/Source/sys-clk/overlay/lang/ko.json new file mode 100644 index 00000000..89c23de8 --- /dev/null +++ b/Source/sys-clk/overlay/lang/ko.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "앱 프로필 편집", + "Advanced": "고급 설정", + "Edit Global Profile": "글로벌 프로필 편집", + "Temporary Overrides": "임시 오버라이드", + "Temporary Overrides   Reset": "임시 오버라이드   리셋", + "Settings": "설정", + "Enable": "활성화", + "Uncapped Clocks": "클럭 제한 해제", + "Override Boost Mode": "부스트 모드 오버라이드", + "Auto CPU Boost": "자동 CPU 부스트", + "Sync ReverseNX": "ReverseNX 동기화", + "GPU DVFS": "GPU DVFS", + "Off": "끔", + "Official Service Method": "공식 서비스", + "Hijack Method": "하이재킹", + "App ID": "앱 ID", + "EOS mode": "EOS 모드", + "Skin": "스킨", + "Now": "현재", + "Avg": "평균", + "Docked": "독 모드", + "Handheld": "휴대 모드", + "Charging": "충전 중", + "Official Charger": "공식 충전기", + "USB Charger": "USB 충전기", + "Docked   Reset": "독 모드   리셋", + "Handheld   Reset": "휴대 모드   리셋", + "Charging   Reset": "충전 중   리셋", + "Official Charger   Reset": "공식 충전기   리셋", + "USB Charger   Reset": "USB 충전기   리셋", + "Memory": "메모리", + "Do not override": "오버라이드 안 함", + "Profile": "프로필" +} diff --git a/Source/sys-clk/overlay/lang/nl.json b/Source/sys-clk/overlay/lang/nl.json new file mode 100644 index 00000000..3016efcf --- /dev/null +++ b/Source/sys-clk/overlay/lang/nl.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "App-profiel bewerken", + "Advanced": "Geavanceerd", + "Edit Global Profile": "Globaal profiel bewerken", + "Temporary Overrides": "Tijdelijke overschrijvingen", + "Temporary Overrides   Reset": "Tijdelijke overschrijvingen   Resetten", + "Settings": "Instellingen", + "Enable": "Inschakelen", + "Uncapped Clocks": "Ongelimiteerde kloksnelheden", + "Override Boost Mode": "Boostmodus overschrijven", + "Auto CPU Boost": "Automatische CPU-boost", + "Sync ReverseNX": "ReverseNX synchroniseren", + "GPU DVFS": "GPU DVFS", + "Off": "Uit", + "Official Service Method": "Officiële service", + "Hijack Method": "Kapingsmethode", + "App ID": "App-ID", + "EOS mode": "EOS-modus", + "Skin": "Thema", + "Now": "Nu", + "Avg": "Gem", + "Docked": "In dockingstation", + "Handheld": "Handheld", + "Charging": "Bezig met opladen", + "Official Charger": "Officiële oplader", + "USB Charger": "USB-oplader", + "Docked   Reset": "In dockingstation   Resetten", + "Handheld   Reset": "Handheld   Resetten", + "Charging   Reset": "Bezig met opladen   Resetten", + "Official Charger   Reset": "Officiële oplader   Resetten", + "USB Charger   Reset": "USB-oplader   Resetten", + "Memory": "Geheugen", + "Do not override": "Niet overschrijven", + "Profile": "Profiel" +} diff --git a/Source/sys-clk/overlay/lang/pl.json b/Source/sys-clk/overlay/lang/pl.json new file mode 100644 index 00000000..1f28913a --- /dev/null +++ b/Source/sys-clk/overlay/lang/pl.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Edytuj profil aplikacji", + "Advanced": "Zaawansowane", + "Edit Global Profile": "Edytuj profil globalny", + "Temporary Overrides": "Tymczasowe nadpisania", + "Temporary Overrides   Reset": "Tymczasowe nadpisania   Resetuj", + "Settings": "Ustawienia", + "Enable": "Włącz", + "Uncapped Clocks": "Nieograniczone taktowanie", + "Override Boost Mode": "Nadpisz tryb Boost", + "Auto CPU Boost": "Automatyczny Boost CPU", + "Sync ReverseNX": "Synchronizuj z ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Wył.", + "Official Service Method": "Oficjalna usługa", + "Hijack Method": "Przejęcie", + "App ID": "ID app", + "EOS mode": "Tryb EOS", + "Skin": "Motyw", + "Now": "Teraz", + "Avg": "Średnia", + "Docked": "W dokowaniu", + "Handheld": "Tryb przenośny", + "Charging": "Ładowanie", + "Official Charger": "Oficjalna ładowarka", + "USB Charger": "Ładowarka USB", + "Docked   Reset": "W dokowaniu   Resetuj", + "Handheld   Reset": "Tryb przenośny   Resetuj", + "Charging   Reset": "Ładowanie   Resetuj", + "Official Charger   Reset": "Oficjalna ładowarka   Resetuj", + "USB Charger   Reset": "Ładowarka USB   Resetuj", + "Memory": "Pamięć", + "Do not override": "Nie nadpisuj", + "Profile": "Profil" +} diff --git a/Source/sys-clk/overlay/lang/pt.json b/Source/sys-clk/overlay/lang/pt.json new file mode 100644 index 00000000..7769abe3 --- /dev/null +++ b/Source/sys-clk/overlay/lang/pt.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Editar perfil do app", + "Advanced": "Avançado", + "Edit Global Profile": "Editar perfil global", + "Temporary Overrides": "Substituições temporárias", + "Temporary Overrides   Reset": "Substituições temporárias   Reiniciar", + "Settings": "Configurações", + "Enable": "Ativar", + "Uncapped Clocks": "Clock ilimitado", + "Override Boost Mode": "Substituir modo Boost", + "Auto CPU Boost": "Boost automático CPU", + "Sync ReverseNX": "Sync ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Desligado", + "Official Service Method": "Serviço oficial", + "Hijack Method": "Sequestro", + "App ID": "ID app", + "EOS mode": "Modo EOS", + "Skin": "Tema", + "Now": "Ag", + "Avg": "Méd", + "Docked": "Acoplado", + "Handheld": "Portátil", + "Charging": "Carregando", + "Official Charger": "Carreg. of.", + "USB Charger": "Carregador USB", + "Docked   Reset": "Acoplado   Reiniciar", + "Handheld   Reset": "Portátil   Reiniciar", + "Charging   Reset": "Carregando   Reiniciar", + "Official Charger   Reset": "Carreg. of.   Reiniciar", + "USB Charger   Reset": "Carregador USB   Reiniciar", + "Memory": "Memória", + "Do not override": "Não substituir", + "Profile": "Perfil" +} diff --git a/Source/sys-clk/overlay/lang/ru.json b/Source/sys-clk/overlay/lang/ru.json new file mode 100644 index 00000000..3b294a5e --- /dev/null +++ b/Source/sys-clk/overlay/lang/ru.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Профиль приложения", + "Advanced": "Продвинутые", + "Edit Global Profile": "Глобальный профиль", + "Temporary Overrides": "Временный профиль", + "Temporary Overrides   Reset": "Временный профиль   Сброс", + "Settings": "Настройки", + "Enable": "sys-clk", + "Uncapped Clocks": "Не ограничивать MHz", + "Override Boost Mode": "Замещать Boost", + "Auto CPU Boost": "Авто Boost CPU", + "Sync ReverseNX": "Синхр. с ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Отключен", + "Official Service Method": "Сервисный метод", + "Hijack Method": "Метод перехвата", + "App ID": "App ID", + "EOS mode": "Режим EOS", + "Skin": "Плата", + "Now": "Сейчас", + "Avg": "Средн.", + "Docked": "В доке", + "Handheld": "Портатив", + "Charging": "На зарядке", + "Official Charger": "Офиц. зарядка", + "USB Charger": "USB зарядка", + "Docked   Reset": "В доке   Сброс", + "Handheld   Reset": "Портатив   Сброс", + "Charging   Reset": "На зарядке   Сброс", + "Official Charger   Reset": "Офиц. зарядка   Сброс", + "USB Charger   Reset": "USB зарядка   Сброс", + "Memory": "RAM", + "Do not override": "По умолчанию", + "Profile": "Профиль" +} diff --git a/Source/sys-clk/overlay/lang/uk.json b/Source/sys-clk/overlay/lang/uk.json new file mode 100644 index 00000000..fda2e951 --- /dev/null +++ b/Source/sys-clk/overlay/lang/uk.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "Редагувати профіль", + "Advanced": "Розширені", + "Edit Global Profile": "Редагувати глобальний", + "Temporary Overrides": "Тимчасові заміни", + "Temporary Overrides   Reset": "Тимчасові заміни   Скидання", + "Settings": "Налаштування", + "Enable": "Увімкнути", + "Uncapped Clocks": "Без обмежень", + "Override Boost Mode": "Перезапис Boost", + "Auto CPU Boost": "Авто Boost CPU", + "Sync ReverseNX": "Синхр. ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "Вимкнено", + "Official Service Method": "Офіційний сервіс", + "Hijack Method": "Захоплення", + "App ID": "ID ап.", + "EOS mode": "Режим EOS", + "Skin": "Тема", + "Now": "Зараз", + "Avg": "Середн.", + "Docked": "У доку", + "Handheld": "Портативний", + "Charging": "Зарядка", + "Official Charger": "Оф. зарядка", + "USB Charger": "USB зарядка", + "Docked   Reset": "У доку   Скидання", + "Handheld   Reset": "Портативний   Скидання", + "Charging   Reset": "Зарядка   Скидання", + "Official Charger   Reset": "Оф. зарядка   Скидання", + "USB Charger   Reset": "USB зарядка   Скидання", + "Memory": "Пам’ять", + "Do not override": "Не змінювати", + "Profile": "Профіль" +} diff --git a/Source/sys-clk/overlay/lang/zh-cn.json b/Source/sys-clk/overlay/lang/zh-cn.json new file mode 100644 index 00000000..85fe9046 --- /dev/null +++ b/Source/sys-clk/overlay/lang/zh-cn.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "编辑应用配置", + "Advanced": "高级", + "Edit Global Profile": "编辑全局配置", + "Temporary Overrides": "临时覆盖", + "Temporary Overrides   Reset": "临时覆盖   重置", + "Settings": "设置", + "Enable": "启用", + "Uncapped Clocks": "无限时钟", + "Override Boost Mode": "覆盖加速模式", + "Auto CPU Boost": "自动CPU加速", + "Sync ReverseNX": "同步ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "关闭", + "Official Service Method": "官方服务", + "Hijack Method": "劫持", + "App ID": "应用ID", + "EOS mode": "EOS模式", + "Skin": "皮肤", + "Now": "当前", + "Avg": "平均", + "Docked": "底座模式", + "Handheld": "手持模式", + "Charging": "充电中", + "Official Charger": "官方充电器", + "USB Charger": "USB充电器", + "Docked   Reset": "底座模式   重置", + "Handheld   Reset": "手持模式   重置", + "Charging   Reset": "充电中   重置", + "Official Charger   Reset": "官方充电器   重置", + "USB Charger   Reset": "USB充电器   重置", + "Memory": "内存", + "Do not override": "不覆盖", + "Profile": "配置文件" +} diff --git a/Source/sys-clk/overlay/lang/zh-tw.json b/Source/sys-clk/overlay/lang/zh-tw.json new file mode 100644 index 00000000..1a846da4 --- /dev/null +++ b/Source/sys-clk/overlay/lang/zh-tw.json @@ -0,0 +1,35 @@ +{ + "Edit App Profile": "編輯應用設定", + "Advanced": "進階", + "Edit Global Profile": "編輯全域設定", + "Temporary Overrides": "臨時覆蓋", + "Temporary Overrides   Reset": "臨時覆蓋   重置", + "Settings": "設定", + "Enable": "啟用", + "Uncapped Clocks": "無限制時脈", + "Override Boost Mode": "覆蓋加速模式", + "Auto CPU Boost": "自動CPU加速", + "Sync ReverseNX": "同步ReverseNX", + "GPU DVFS": "GPU DVFS", + "Off": "關閉", + "Official Service Method": "官方服務", + "Hijack Method": "劫持", + "App ID": "應用ID", + "EOS mode": "EOS模式", + "Skin": "外觀主題", + "Now": "目前", + "Avg": "平均", + "Docked": "座充模式", + "Handheld": "手持模式", + "Charging": "充電中", + "Official Charger": "官方充電器", + "USB Charger": "USB充電器", + "Docked   Reset": "座充模式   重置", + "Handheld   Reset": "手持模式   重置", + "Charging   Reset": "充電中   重置", + "Official Charger   Reset": "官方充電器   重置", + "USB Charger   Reset": "USB充電器   重置", + "Memory": "記憶體", + "Do not override": "不覆蓋", + "Profile": "設定檔" +} diff --git a/Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml b/Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml new file mode 100644 index 00000000..57fdec3d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/.github/FUNDING.yml @@ -0,0 +1,2 @@ +github: ppkantorski +ko_fi: ppkantorski diff --git a/Source/sys-clk/overlay/lib/libultrahand/.gitmodules b/Source/sys-clk/overlay/lib/libultrahand/.gitmodules new file mode 100644 index 00000000..e69de29b diff --git a/Source/sys-clk/overlay/lib/libultrahand/.pics/libultrahand.png b/Source/sys-clk/overlay/lib/libultrahand/.pics/libultrahand.png new file mode 100644 index 0000000000000000000000000000000000000000..7165fb92ba7c7558d3cf1b1005dd8285ac2af77b GIT binary patch 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=^a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JZKG+J2{RMyPk$HW`!@b^F%S!3(>wW! zQI}WAJ*zZkma89WDTm@~IY2)bwmmz9Yj?h8{i<(I5?E>Hek;&S7|d#vPAmVuvigT4 z*+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 literal 0 HcmV?d00001 diff --git a/Source/sys-clk/overlay/lib/libultrahand/.pics/tmp b/Source/sys-clk/overlay/lib/libultrahand/.pics/tmp new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/.pics/tmp @@ -0,0 +1 @@ + diff --git a/Source/sys-clk/overlay/lib/libultrahand/LICENSE b/Source/sys-clk/overlay/lib/libultrahand/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Source/sys-clk/overlay/lib/libultrahand/README.md b/Source/sys-clk/overlay/lib/libultrahand/README.md new file mode 100644 index 00000000..d7a78ce8 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/README.md @@ -0,0 +1,211 @@ +# ☆ libultrahand +[![platform](https://img.shields.io/badge/platform-Switch-898c8c?logo=C++.svg)](https://gbatemp.net/forums/nintendo-switch.283/?prefix_id=44) +[![language](https://img.shields.io/badge/language-C++-ba1632?logo=C++.svg)](https://github.com/topics/cpp) +[![GPLv2 License](https://img.shields.io/badge/license-GPLv2-189c11.svg)](https://www.gnu.org/licenses/old-licenses/gpl-2.0.en.html) +[![Latest Version](https://img.shields.io/github/v/release/ppkantorski/libultrahand?label=latest%20version&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/ppkantorski/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) 2024 ppkantorski diff --git a/Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE b/Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE new file mode 100644 index 00000000..2f244ac8 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/SUB_LICENSE @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.c b/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.c new file mode 100644 index 00000000..ca824f0e --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.c @@ -0,0 +1,3191 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +/* cJSON */ +/* JSON parser in C. */ + +/* disable warnings about old C89 functions in MSVC */ +#if !defined(_CRT_SECURE_NO_DEPRECATE) && defined(_MSC_VER) +#define _CRT_SECURE_NO_DEPRECATE +#endif + +#ifdef __GNUC__ +#pragma GCC visibility push(default) +#endif +#if defined(_MSC_VER) +#pragma warning (push) +/* disable warning about single line comments in system headers */ +#pragma warning (disable : 4001) +#endif + +#include +#include +#include +#include +#include +#include +#include + +#ifdef ENABLE_LOCALES +#include +#endif + +#if defined(_MSC_VER) +#pragma warning (pop) +#endif +#ifdef __GNUC__ +#pragma GCC visibility pop +#endif + +#include "cJSON.h" + +/* define our own boolean type */ +#ifdef true +#undef true +#endif +#define true ((cJSON_bool)1) + +#ifdef false +#undef false +#endif +#define false ((cJSON_bool)0) + +/* define isnan and isinf for ANSI C, if in C99 or above, isnan and isinf has been defined in math.h */ +#ifndef isinf +#define isinf(d) (isnan((d - d)) && !isnan(d)) +#endif +#ifndef isnan +#define isnan(d) (d != d) +#endif + +#ifndef NAN +#ifdef _WIN32 +#define NAN sqrt(-1.0) +#else +#define NAN 0.0/0.0 +#endif +#endif + +typedef struct { + const unsigned char *json; + size_t position; +} error; +static error global_error = { NULL, 0 }; + +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void) +{ + return (const char*) (global_error.json + global_error.position); +} + +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item) +{ + if (!cJSON_IsString(item)) + { + return NULL; + } + + return item->valuestring; +} + +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item) +{ + if (!cJSON_IsNumber(item)) + { + return (double) NAN; + } + + return item->valuedouble; +} + +/* This is a safeguard to prevent copy-pasters from using incompatible C and header files */ +#if (CJSON_VERSION_MAJOR != 1) || (CJSON_VERSION_MINOR != 7) || (CJSON_VERSION_PATCH != 18) + #error cJSON.h and cJSON.c have different versions. Make sure that both have the same. +#endif + +CJSON_PUBLIC(const char*) cJSON_Version(void) +{ + static char version[15]; + sprintf(version, "%i.%i.%i", CJSON_VERSION_MAJOR, CJSON_VERSION_MINOR, CJSON_VERSION_PATCH); + + return version; +} + +/* Case insensitive string comparison, doesn't consider two NULL pointers equal though */ +static int case_insensitive_strcmp(const unsigned char *string1, const unsigned char *string2) +{ + if ((string1 == NULL) || (string2 == NULL)) + { + return 1; + } + + if (string1 == string2) + { + return 0; + } + + for(; tolower(*string1) == tolower(*string2); (void)string1++, string2++) + { + if (*string1 == '\0') + { + return 0; + } + } + + return tolower(*string1) - tolower(*string2); +} + +typedef struct internal_hooks +{ + void *(CJSON_CDECL *allocate)(size_t size); + void (CJSON_CDECL *deallocate)(void *pointer); + void *(CJSON_CDECL *reallocate)(void *pointer, size_t size); +} internal_hooks; + +#if defined(_MSC_VER) +/* work around MSVC error C2322: '...' address of dllimport '...' is not static */ +static void * CJSON_CDECL internal_malloc(size_t size) +{ + return malloc(size); +} +static void CJSON_CDECL internal_free(void *pointer) +{ + free(pointer); +} +static void * CJSON_CDECL internal_realloc(void *pointer, size_t size) +{ + return realloc(pointer, size); +} +#else +#define internal_malloc malloc +#define internal_free free +#define internal_realloc realloc +#endif + +/* strlen of character literals resolved at compile time */ +#define static_strlen(string_literal) (sizeof(string_literal) - sizeof("")) + +static internal_hooks global_hooks = { internal_malloc, internal_free, internal_realloc }; + +static unsigned char* cJSON_strdup(const unsigned char* string, const internal_hooks * const hooks) +{ + size_t length = 0; + unsigned char *copy = NULL; + + if (string == NULL) + { + return NULL; + } + + length = strlen((const char*)string) + sizeof(""); + copy = (unsigned char*)hooks->allocate(length); + if (copy == NULL) + { + return NULL; + } + memcpy(copy, string, length); + + return copy; +} + +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks) +{ + if (hooks == NULL) + { + /* Reset hooks */ + global_hooks.allocate = malloc; + global_hooks.deallocate = free; + global_hooks.reallocate = realloc; + return; + } + + global_hooks.allocate = malloc; + if (hooks->malloc_fn != NULL) + { + global_hooks.allocate = hooks->malloc_fn; + } + + global_hooks.deallocate = free; + if (hooks->free_fn != NULL) + { + global_hooks.deallocate = hooks->free_fn; + } + + /* use realloc only if both free and malloc are used */ + global_hooks.reallocate = NULL; + if ((global_hooks.allocate == malloc) && (global_hooks.deallocate == free)) + { + global_hooks.reallocate = realloc; + } +} + +/* Internal constructor. */ +static cJSON *cJSON_New_Item(const internal_hooks * const hooks) +{ + cJSON* node = (cJSON*)hooks->allocate(sizeof(cJSON)); + if (node) + { + memset(node, '\0', sizeof(cJSON)); + } + + return node; +} + +/* Delete a cJSON structure. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) +{ + cJSON *next = NULL; + while (item != NULL) + { + next = item->next; + if (!(item->type & cJSON_IsReference) && (item->child != NULL)) + { + cJSON_Delete(item->child); + } + if (!(item->type & cJSON_IsReference) && (item->valuestring != NULL)) + { + global_hooks.deallocate(item->valuestring); + item->valuestring = NULL; + } + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + global_hooks.deallocate(item->string); + item->string = NULL; + } + global_hooks.deallocate(item); + item = next; + } +} + +/* get the decimal point character of the current locale */ +static unsigned char get_decimal_point(void) +{ +#ifdef ENABLE_LOCALES + struct lconv *lconv = localeconv(); + return (unsigned char) lconv->decimal_point[0]; +#else + return '.'; +#endif +} + +typedef struct +{ + const unsigned char *content; + size_t length; + size_t offset; + size_t depth; /* How deeply nested (in arrays/objects) is the input at the current offset. */ + internal_hooks hooks; +} parse_buffer; + +/* check if the given size is left to read in a given parse buffer (starting with 1) */ +#define can_read(buffer, size) ((buffer != NULL) && (((buffer)->offset + size) <= (buffer)->length)) +/* check if the buffer can be accessed at the given index (starting with 0) */ +#define can_access_at_index(buffer, index) ((buffer != NULL) && (((buffer)->offset + index) < (buffer)->length)) +#define cannot_access_at_index(buffer, index) (!can_access_at_index(buffer, index)) +/* get a pointer to the buffer at the position */ +#define buffer_at_offset(buffer) ((buffer)->content + (buffer)->offset) + +/* Parse the input text to generate a number, and populate the result into item. */ +static cJSON_bool parse_number(cJSON * const item, parse_buffer * const input_buffer) +{ + double number = 0; + unsigned char *after_end = NULL; + unsigned char *number_c_string; + unsigned char decimal_point = get_decimal_point(); + size_t i = 0; + size_t number_string_length = 0; + cJSON_bool has_decimal_point = false; + + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; + } + + /* copy the number into a temporary buffer and replace '.' with the decimal point + * of the current locale (for strtod) + * This also takes care of '\0' not necessarily being available for marking the end of the input */ + for (i = 0; can_access_at_index(input_buffer, i); i++) + { + switch (buffer_at_offset(input_buffer)[i]) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + case '+': + case '-': + case 'e': + case 'E': + number_string_length++; + break; + + case '.': + number_string_length++; + has_decimal_point = true; + break; + + default: + goto loop_end; + } + } +loop_end: + /* malloc for temporary buffer, add 1 for '\0' */ + number_c_string = (unsigned char *) input_buffer->hooks.allocate(number_string_length + 1); + if (number_c_string == NULL) + { + return false; /* allocation failure */ + } + + memcpy(number_c_string, buffer_at_offset(input_buffer), number_string_length); + number_c_string[number_string_length] = '\0'; + + if (has_decimal_point) + { + for (i = 0; i < number_string_length; i++) + { + if (number_c_string[i] == '.') + { + /* replace '.' with the decimal point of the current locale (for strtod) */ + number_c_string[i] = decimal_point; + } + } + } + + number = strtod((const char*)number_c_string, (char**)&after_end); + if (number_c_string == after_end) + { + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return false; /* parse_error */ + } + + item->valuedouble = number; + + /* use saturation in case of overflow */ + if (number >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)number; + } + + item->type = cJSON_Number; + + input_buffer->offset += (size_t)(after_end - number_c_string); + /* free the temporary buffer */ + input_buffer->hooks.deallocate(number_c_string); + return true; +} + +/* don't ask me, but the original cJSON_SetNumberValue returns an integer or double */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number) +{ + if (number >= INT_MAX) + { + object->valueint = INT_MAX; + } + else if (number <= (double)INT_MIN) + { + object->valueint = INT_MIN; + } + else + { + object->valueint = (int)number; + } + + return object->valuedouble = number; +} + +/* Note: when passing a NULL valuestring, cJSON_SetValuestring treats this as an error and return NULL */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring) +{ + char *copy = NULL; + size_t v1_len; + size_t v2_len; + /* if object's type is not cJSON_String or is cJSON_IsReference, it should not set valuestring */ + if ((object == NULL) || !(object->type & cJSON_String) || (object->type & cJSON_IsReference)) + { + return NULL; + } + /* return NULL if the object is corrupted or valuestring is NULL */ + if (object->valuestring == NULL || valuestring == NULL) + { + return NULL; + } + + v1_len = strlen(valuestring); + v2_len = strlen(object->valuestring); + + if (v1_len <= v2_len) + { + /* strcpy does not handle overlapping string: [X1, X2] [Y1, Y2] => X2 < Y1 or Y2 < X1 */ + if (!( valuestring + v1_len < object->valuestring || object->valuestring + v2_len < valuestring )) + { + return NULL; + } + strcpy(object->valuestring, valuestring); + return object->valuestring; + } + copy = (char*) cJSON_strdup((const unsigned char*)valuestring, &global_hooks); + if (copy == NULL) + { + return NULL; + } + if (object->valuestring != NULL) + { + cJSON_free(object->valuestring); + } + object->valuestring = copy; + + return copy; +} + +typedef struct +{ + unsigned char *buffer; + size_t length; + size_t offset; + size_t depth; /* current nesting depth (for formatted printing) */ + cJSON_bool noalloc; + cJSON_bool format; /* is this print a formatted print */ + internal_hooks hooks; +} printbuffer; + +/* realloc printbuffer if necessary to have at least "needed" bytes more */ +static unsigned char* ensure(printbuffer * const p, size_t needed) +{ + unsigned char *newbuffer = NULL; + size_t newsize = 0; + + if ((p == NULL) || (p->buffer == NULL)) + { + return NULL; + } + + if ((p->length > 0) && (p->offset >= p->length)) + { + /* make sure that offset is valid */ + return NULL; + } + + if (needed > INT_MAX) + { + /* sizes bigger than INT_MAX are currently not supported */ + return NULL; + } + + needed += p->offset + 1; + if (needed <= p->length) + { + return p->buffer + p->offset; + } + + if (p->noalloc) { + return NULL; + } + + /* calculate new buffer size */ + if (needed > (INT_MAX / 2)) + { + /* overflow of int, use INT_MAX if possible */ + if (needed <= INT_MAX) + { + newsize = INT_MAX; + } + else + { + return NULL; + } + } + else + { + newsize = needed * 2; + } + + if (p->hooks.reallocate != NULL) + { + /* reallocate with realloc if available */ + newbuffer = (unsigned char*)p->hooks.reallocate(p->buffer, newsize); + if (newbuffer == NULL) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + } + else + { + /* otherwise reallocate manually */ + newbuffer = (unsigned char*)p->hooks.allocate(newsize); + if (!newbuffer) + { + p->hooks.deallocate(p->buffer); + p->length = 0; + p->buffer = NULL; + + return NULL; + } + + memcpy(newbuffer, p->buffer, p->offset + 1); + p->hooks.deallocate(p->buffer); + } + p->length = newsize; + p->buffer = newbuffer; + + return newbuffer + p->offset; +} + +/* calculate the new length of the string in a printbuffer and update the offset */ +static void update_offset(printbuffer * const buffer) +{ + const unsigned char *buffer_pointer = NULL; + if ((buffer == NULL) || (buffer->buffer == NULL)) + { + return; + } + buffer_pointer = buffer->buffer + buffer->offset; + + buffer->offset += strlen((const char*)buffer_pointer); +} + +/* securely comparison of floating-point variables */ +static cJSON_bool compare_double(double a, double b) +{ + double maxVal = fabs(a) > fabs(b) ? fabs(a) : fabs(b); + return (fabs(a - b) <= maxVal * DBL_EPSILON); +} + +/* Render the number nicely from the given item into a string. */ +static cJSON_bool print_number(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + double d = item->valuedouble; + int length = 0; + size_t i = 0; + unsigned char number_buffer[26] = {0}; /* temporary buffer to print the number into */ + unsigned char decimal_point = get_decimal_point(); + double test = 0.0; + + if (output_buffer == NULL) + { + return false; + } + + /* This checks for NaN and Infinity */ + if (isnan(d) || isinf(d)) + { + length = sprintf((char*)number_buffer, "null"); + } + else if(d == (double)item->valueint) + { + length = sprintf((char*)number_buffer, "%d", item->valueint); + } + else + { + /* Try 15 decimal places of precision to avoid nonsignificant nonzero digits */ + length = sprintf((char*)number_buffer, "%1.15g", d); + + /* Check whether the original double can be recovered */ + if ((sscanf((char*)number_buffer, "%lg", &test) != 1) || !compare_double((double)test, d)) + { + /* If not, print with 17 decimal places of precision */ + length = sprintf((char*)number_buffer, "%1.17g", d); + } + } + + /* sprintf failed or buffer overrun occurred */ + if ((length < 0) || (length > (int)(sizeof(number_buffer) - 1))) + { + return false; + } + + /* reserve appropriate space in the output */ + output_pointer = ensure(output_buffer, (size_t)length + sizeof("")); + if (output_pointer == NULL) + { + return false; + } + + /* copy the printed number to the output and replace locale + * dependent decimal point with '.' */ + for (i = 0; i < ((size_t)length); i++) + { + if (number_buffer[i] == decimal_point) + { + output_pointer[i] = '.'; + continue; + } + + output_pointer[i] = number_buffer[i]; + } + output_pointer[i] = '\0'; + + output_buffer->offset += (size_t)length; + + return true; +} + +/* parse 4 digit hexadecimal number */ +static unsigned parse_hex4(const unsigned char * const input) +{ + unsigned int h = 0; + size_t i = 0; + + for (i = 0; i < 4; i++) + { + /* parse digit */ + if ((input[i] >= '0') && (input[i] <= '9')) + { + h += (unsigned int) input[i] - '0'; + } + else if ((input[i] >= 'A') && (input[i] <= 'F')) + { + h += (unsigned int) 10 + input[i] - 'A'; + } + else if ((input[i] >= 'a') && (input[i] <= 'f')) + { + h += (unsigned int) 10 + input[i] - 'a'; + } + else /* invalid */ + { + return 0; + } + + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + } + } + + return h; +} + +/* converts a UTF-16 literal to UTF-8 + * A literal can be one or two sequences of the form \uXXXX */ +static unsigned char utf16_literal_to_utf8(const unsigned char * const input_pointer, const unsigned char * const input_end, unsigned char **output_pointer) +{ + long unsigned int codepoint = 0; + unsigned int first_code = 0; + const unsigned char *first_sequence = input_pointer; + unsigned char utf8_length = 0; + unsigned char utf8_position = 0; + unsigned char sequence_length = 0; + unsigned char first_byte_mark = 0; + + if ((input_end - first_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + /* get the first utf16 sequence */ + first_code = parse_hex4(first_sequence + 2); + + /* check that the code is valid */ + if (((first_code >= 0xDC00) && (first_code <= 0xDFFF))) + { + goto fail; + } + + /* UTF16 surrogate pair */ + if ((first_code >= 0xD800) && (first_code <= 0xDBFF)) + { + const unsigned char *second_sequence = first_sequence + 6; + unsigned int second_code = 0; + sequence_length = 12; /* \uXXXX\uXXXX */ + + if ((input_end - second_sequence) < 6) + { + /* input ends unexpectedly */ + goto fail; + } + + if ((second_sequence[0] != '\\') || (second_sequence[1] != 'u')) + { + /* missing second half of the surrogate pair */ + goto fail; + } + + /* get the second utf16 sequence */ + second_code = parse_hex4(second_sequence + 2); + /* check that the code is valid */ + if ((second_code < 0xDC00) || (second_code > 0xDFFF)) + { + /* invalid second half of the surrogate pair */ + goto fail; + } + + + /* calculate the unicode codepoint from the surrogate pair */ + codepoint = 0x10000 + (((first_code & 0x3FF) << 10) | (second_code & 0x3FF)); + } + else + { + sequence_length = 6; /* \uXXXX */ + codepoint = first_code; + } + + /* encode as UTF-8 + * takes at maximum 4 bytes to encode: + * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx */ + if (codepoint < 0x80) + { + /* normal ascii, encoding 0xxxxxxx */ + utf8_length = 1; + } + else if (codepoint < 0x800) + { + /* two bytes, encoding 110xxxxx 10xxxxxx */ + utf8_length = 2; + first_byte_mark = 0xC0; /* 11000000 */ + } + else if (codepoint < 0x10000) + { + /* three bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx */ + utf8_length = 3; + first_byte_mark = 0xE0; /* 11100000 */ + } + else if (codepoint <= 0x10FFFF) + { + /* four bytes, encoding 1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx */ + utf8_length = 4; + first_byte_mark = 0xF0; /* 11110000 */ + } + else + { + /* invalid unicode codepoint */ + goto fail; + } + + /* encode as utf8 */ + for (utf8_position = (unsigned char)(utf8_length - 1); utf8_position > 0; utf8_position--) + { + /* 10xxxxxx */ + (*output_pointer)[utf8_position] = (unsigned char)((codepoint | 0x80) & 0xBF); + codepoint >>= 6; + } + /* encode first byte */ + if (utf8_length > 1) + { + (*output_pointer)[0] = (unsigned char)((codepoint | first_byte_mark) & 0xFF); + } + else + { + (*output_pointer)[0] = (unsigned char)(codepoint & 0x7F); + } + + *output_pointer += utf8_length; + + return sequence_length; + +fail: + return 0; +} + +/* Parse the input text into an unescaped cinput, and populate item. */ +static cJSON_bool parse_string(cJSON * const item, parse_buffer * const input_buffer) +{ + const unsigned char *input_pointer = buffer_at_offset(input_buffer) + 1; + const unsigned char *input_end = buffer_at_offset(input_buffer) + 1; + unsigned char *output_pointer = NULL; + unsigned char *output = NULL; + + /* not a string */ + if (buffer_at_offset(input_buffer)[0] != '\"') + { + goto fail; + } + + { + /* calculate approximate size of the output (overestimate) */ + size_t allocation_length = 0; + size_t skipped_bytes = 0; + while (((size_t)(input_end - input_buffer->content) < input_buffer->length) && (*input_end != '\"')) + { + /* is escape sequence */ + if (input_end[0] == '\\') + { + if ((size_t)(input_end + 1 - input_buffer->content) >= input_buffer->length) + { + /* prevent buffer overflow when last input character is a backslash */ + goto fail; + } + skipped_bytes++; + input_end++; + } + input_end++; + } + if (((size_t)(input_end - input_buffer->content) >= input_buffer->length) || (*input_end != '\"')) + { + goto fail; /* string ended unexpectedly */ + } + + /* This is at most how much we need for the output */ + allocation_length = (size_t) (input_end - buffer_at_offset(input_buffer)) - skipped_bytes; + output = (unsigned char*)input_buffer->hooks.allocate(allocation_length + sizeof("")); + if (output == NULL) + { + goto fail; /* allocation failure */ + } + } + + output_pointer = output; + /* loop through the string literal */ + while (input_pointer < input_end) + { + if (*input_pointer != '\\') + { + *output_pointer++ = *input_pointer++; + } + /* escape sequence */ + else + { + unsigned char sequence_length = 2; + if ((input_end - input_pointer) < 1) + { + goto fail; + } + + switch (input_pointer[1]) + { + case 'b': + *output_pointer++ = '\b'; + break; + case 'f': + *output_pointer++ = '\f'; + break; + case 'n': + *output_pointer++ = '\n'; + break; + case 'r': + *output_pointer++ = '\r'; + break; + case 't': + *output_pointer++ = '\t'; + break; + case '\"': + case '\\': + case '/': + *output_pointer++ = input_pointer[1]; + break; + + /* UTF-16 literal */ + case 'u': + sequence_length = utf16_literal_to_utf8(input_pointer, input_end, &output_pointer); + if (sequence_length == 0) + { + /* failed to convert UTF16-literal to UTF-8 */ + goto fail; + } + break; + + default: + goto fail; + } + input_pointer += sequence_length; + } + } + + /* zero terminate the output */ + *output_pointer = '\0'; + + item->type = cJSON_String; + item->valuestring = (char*)output; + + input_buffer->offset = (size_t) (input_end - input_buffer->content); + input_buffer->offset++; + + return true; + +fail: + if (output != NULL) + { + input_buffer->hooks.deallocate(output); + output = NULL; + } + + if (input_pointer != NULL) + { + input_buffer->offset = (size_t)(input_pointer - input_buffer->content); + } + + return false; +} + +/* Render the cstring provided to an escaped version that can be printed. */ +static cJSON_bool print_string_ptr(const unsigned char * const input, printbuffer * const output_buffer) +{ + const unsigned char *input_pointer = NULL; + unsigned char *output = NULL; + unsigned char *output_pointer = NULL; + size_t output_length = 0; + /* numbers of additional characters needed for escaping */ + size_t escape_characters = 0; + + if (output_buffer == NULL) + { + return false; + } + + /* empty string */ + if (input == NULL) + { + output = ensure(output_buffer, sizeof("\"\"")); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "\"\""); + + return true; + } + + /* set "flag" to 1 if something needs to be escaped */ + for (input_pointer = input; *input_pointer; input_pointer++) + { + switch (*input_pointer) + { + case '\"': + case '\\': + case '\b': + case '\f': + case '\n': + case '\r': + case '\t': + /* one character escape sequence */ + escape_characters++; + break; + default: + if (*input_pointer < 32) + { + /* UTF-16 escape sequence uXXXX */ + escape_characters += 5; + } + break; + } + } + output_length = (size_t)(input_pointer - input) + escape_characters; + + output = ensure(output_buffer, output_length + sizeof("\"\"")); + if (output == NULL) + { + return false; + } + + /* no characters have to be escaped */ + if (escape_characters == 0) + { + output[0] = '\"'; + memcpy(output + 1, input, output_length); + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; + } + + output[0] = '\"'; + output_pointer = output + 1; + /* copy the string */ + for (input_pointer = input; *input_pointer != '\0'; (void)input_pointer++, output_pointer++) + { + if ((*input_pointer > 31) && (*input_pointer != '\"') && (*input_pointer != '\\')) + { + /* normal character, copy */ + *output_pointer = *input_pointer; + } + else + { + /* character needs to be escaped */ + *output_pointer++ = '\\'; + switch (*input_pointer) + { + case '\\': + *output_pointer = '\\'; + break; + case '\"': + *output_pointer = '\"'; + break; + case '\b': + *output_pointer = 'b'; + break; + case '\f': + *output_pointer = 'f'; + break; + case '\n': + *output_pointer = 'n'; + break; + case '\r': + *output_pointer = 'r'; + break; + case '\t': + *output_pointer = 't'; + break; + default: + /* escape and print as unicode codepoint */ + sprintf((char*)output_pointer, "u%04x", *input_pointer); + output_pointer += 4; + break; + } + } + } + output[output_length + 1] = '\"'; + output[output_length + 2] = '\0'; + + return true; +} + +/* Invoke print_string_ptr (which is useful) on an item. */ +static cJSON_bool print_string(const cJSON * const item, printbuffer * const p) +{ + return print_string_ptr((unsigned char*)item->valuestring, p); +} + +/* Predeclare these prototypes. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer); +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer); +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer); + +/* Utility to jump whitespace and cr/lf */ +static parse_buffer *buffer_skip_whitespace(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL)) + { + return NULL; + } + + if (cannot_access_at_index(buffer, 0)) + { + return buffer; + } + + while (can_access_at_index(buffer, 0) && (buffer_at_offset(buffer)[0] <= 32)) + { + buffer->offset++; + } + + if (buffer->offset == buffer->length) + { + buffer->offset--; + } + + return buffer; +} + +/* skip the UTF-8 BOM (byte order mark) if it is at the beginning of a buffer */ +static parse_buffer *skip_utf8_bom(parse_buffer * const buffer) +{ + if ((buffer == NULL) || (buffer->content == NULL) || (buffer->offset != 0)) + { + return NULL; + } + + if (can_access_at_index(buffer, 4) && (strncmp((const char*)buffer_at_offset(buffer), "\xEF\xBB\xBF", 3) == 0)) + { + buffer->offset += 3; + } + + return buffer; +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + size_t buffer_length; + + if (NULL == value) + { + return NULL; + } + + /* Adding null character size due to require_null_terminated. */ + buffer_length = strlen(value) + sizeof(""); + + return cJSON_ParseWithLengthOpts(value, buffer_length, return_parse_end, require_null_terminated); +} + +/* Parse an object - create a new root, and populate. */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated) +{ + parse_buffer buffer = { 0, 0, 0, 0, { 0, 0, 0 } }; + cJSON *item = NULL; + + /* reset error position */ + global_error.json = NULL; + global_error.position = 0; + + if (value == NULL || 0 == buffer_length) + { + goto fail; + } + + buffer.content = (const unsigned char*)value; + buffer.length = buffer_length; + buffer.offset = 0; + buffer.hooks = global_hooks; + + item = cJSON_New_Item(&global_hooks); + if (item == NULL) /* memory fail */ + { + goto fail; + } + + if (!parse_value(item, buffer_skip_whitespace(skip_utf8_bom(&buffer)))) + { + /* parse failure. ep is set. */ + goto fail; + } + + /* if we require null-terminated JSON without appended garbage, skip and then check for a null terminator */ + if (require_null_terminated) + { + buffer_skip_whitespace(&buffer); + if ((buffer.offset >= buffer.length) || buffer_at_offset(&buffer)[0] != '\0') + { + goto fail; + } + } + if (return_parse_end) + { + *return_parse_end = (const char*)buffer_at_offset(&buffer); + } + + return item; + +fail: + if (item != NULL) + { + cJSON_Delete(item); + } + + if (value != NULL) + { + error local_error; + local_error.json = (const unsigned char*)value; + local_error.position = 0; + + if (buffer.offset < buffer.length) + { + local_error.position = buffer.offset; + } + else if (buffer.length > 0) + { + local_error.position = buffer.length - 1; + } + + if (return_parse_end != NULL) + { + *return_parse_end = (const char*)local_error.json + local_error.position; + } + + global_error = local_error; + } + + return NULL; +} + +/* Default options for cJSON_Parse */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) +{ + return cJSON_ParseWithOpts(value, 0, 0); +} + +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length) +{ + return cJSON_ParseWithLengthOpts(value, buffer_length, 0, 0); +} + +#define cjson_min(a, b) (((a) < (b)) ? (a) : (b)) + +static unsigned char *print(const cJSON * const item, cJSON_bool format, const internal_hooks * const hooks) +{ + static const size_t default_buffer_size = 256; + printbuffer buffer[1]; + unsigned char *printed = NULL; + + memset(buffer, 0, sizeof(buffer)); + + /* create buffer */ + buffer->buffer = (unsigned char*) hooks->allocate(default_buffer_size); + buffer->length = default_buffer_size; + buffer->format = format; + buffer->hooks = *hooks; + if (buffer->buffer == NULL) + { + goto fail; + } + + /* print the value */ + if (!print_value(item, buffer)) + { + goto fail; + } + update_offset(buffer); + + /* check if reallocate is available */ + if (hooks->reallocate != NULL) + { + printed = (unsigned char*) hooks->reallocate(buffer->buffer, buffer->offset + 1); + if (printed == NULL) { + goto fail; + } + buffer->buffer = NULL; + } + else /* otherwise copy the JSON over to a new buffer */ + { + printed = (unsigned char*) hooks->allocate(buffer->offset + 1); + if (printed == NULL) + { + goto fail; + } + memcpy(printed, buffer->buffer, cjson_min(buffer->length, buffer->offset + 1)); + printed[buffer->offset] = '\0'; /* just to be sure */ + + /* free the buffer */ + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + return printed; + +fail: + if (buffer->buffer != NULL) + { + hooks->deallocate(buffer->buffer); + buffer->buffer = NULL; + } + + if (printed != NULL) + { + hooks->deallocate(printed); + printed = NULL; + } + + return NULL; +} + +/* Render a cJSON item/entity/structure to text. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) +{ + return (char*)print(item, true, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item) +{ + return (char*)print(item, false, &global_hooks); +} + +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if (prebuffer < 0) + { + return NULL; + } + + p.buffer = (unsigned char*)global_hooks.allocate((size_t)prebuffer); + if (!p.buffer) + { + return NULL; + } + + p.length = (size_t)prebuffer; + p.offset = 0; + p.noalloc = false; + p.format = fmt; + p.hooks = global_hooks; + + if (!print_value(item, &p)) + { + global_hooks.deallocate(p.buffer); + p.buffer = NULL; + return NULL; + } + + return (char*)p.buffer; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format) +{ + printbuffer p = { 0, 0, 0, 0, 0, 0, { 0, 0, 0 } }; + + if ((length < 0) || (buffer == NULL)) + { + return false; + } + + p.buffer = (unsigned char*)buffer; + p.length = (size_t)length; + p.offset = 0; + p.noalloc = true; + p.format = format; + p.hooks = global_hooks; + + return print_value(item, &p); +} + +/* Parser core - when encountering text, process appropriately. */ +static cJSON_bool parse_value(cJSON * const item, parse_buffer * const input_buffer) +{ + if ((input_buffer == NULL) || (input_buffer->content == NULL)) + { + return false; /* no input */ + } + + /* parse the different types of values */ + /* null */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "null", 4) == 0)) + { + item->type = cJSON_NULL; + input_buffer->offset += 4; + return true; + } + /* false */ + if (can_read(input_buffer, 5) && (strncmp((const char*)buffer_at_offset(input_buffer), "false", 5) == 0)) + { + item->type = cJSON_False; + input_buffer->offset += 5; + return true; + } + /* true */ + if (can_read(input_buffer, 4) && (strncmp((const char*)buffer_at_offset(input_buffer), "true", 4) == 0)) + { + item->type = cJSON_True; + item->valueint = 1; + input_buffer->offset += 4; + return true; + } + /* string */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '\"')) + { + return parse_string(item, input_buffer); + } + /* number */ + if (can_access_at_index(input_buffer, 0) && ((buffer_at_offset(input_buffer)[0] == '-') || ((buffer_at_offset(input_buffer)[0] >= '0') && (buffer_at_offset(input_buffer)[0] <= '9')))) + { + return parse_number(item, input_buffer); + } + /* array */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '[')) + { + return parse_array(item, input_buffer); + } + /* object */ + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '{')) + { + return parse_object(item, input_buffer); + } + + return false; +} + +/* Render a value to text. */ +static cJSON_bool print_value(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output = NULL; + + if ((item == NULL) || (output_buffer == NULL)) + { + return false; + } + + switch ((item->type) & 0xFF) + { + case cJSON_NULL: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "null"); + return true; + + case cJSON_False: + output = ensure(output_buffer, 6); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "false"); + return true; + + case cJSON_True: + output = ensure(output_buffer, 5); + if (output == NULL) + { + return false; + } + strcpy((char*)output, "true"); + return true; + + case cJSON_Number: + return print_number(item, output_buffer); + + case cJSON_Raw: + { + size_t raw_length = 0; + if (item->valuestring == NULL) + { + return false; + } + + raw_length = strlen(item->valuestring) + sizeof(""); + output = ensure(output_buffer, raw_length); + if (output == NULL) + { + return false; + } + memcpy(output, item->valuestring, raw_length); + return true; + } + + case cJSON_String: + return print_string(item, output_buffer); + + case cJSON_Array: + return print_array(item, output_buffer); + + case cJSON_Object: + return print_object(item, output_buffer); + + default: + return false; + } +} + +/* Build an array from input text. */ +static cJSON_bool parse_array(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* head of the linked list */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (buffer_at_offset(input_buffer)[0] != '[') + { + /* not an array */ + goto fail; + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ']')) + { + /* empty array */ + goto success; + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + /* parse next value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || buffer_at_offset(input_buffer)[0] != ']') + { + goto fail; /* expected end of array */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Array; + item->child = head; + + input_buffer->offset++; + + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an array to text */ +static cJSON_bool print_array(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_element = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output array. */ + /* opening square bracket */ + output_pointer = ensure(output_buffer, 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer = '['; + output_buffer->offset++; + output_buffer->depth++; + + while (current_element != NULL) + { + if (!print_value(current_element, output_buffer)) + { + return false; + } + update_offset(output_buffer); + if (current_element->next) + { + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ','; + if(output_buffer->format) + { + *output_pointer++ = ' '; + } + *output_pointer = '\0'; + output_buffer->offset += length; + } + current_element = current_element->next; + } + + output_pointer = ensure(output_buffer, 2); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ']'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Build an object from the text. */ +static cJSON_bool parse_object(cJSON * const item, parse_buffer * const input_buffer) +{ + cJSON *head = NULL; /* linked list head */ + cJSON *current_item = NULL; + + if (input_buffer->depth >= CJSON_NESTING_LIMIT) + { + return false; /* to deeply nested */ + } + input_buffer->depth++; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '{')) + { + goto fail; /* not an object */ + } + + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == '}')) + { + goto success; /* empty object */ + } + + /* check if we skipped to the end of the buffer */ + if (cannot_access_at_index(input_buffer, 0)) + { + input_buffer->offset--; + goto fail; + } + + /* step back to character in front of the first element */ + input_buffer->offset--; + /* loop through the comma separated array elements */ + do + { + /* allocate next item */ + cJSON *new_item = cJSON_New_Item(&(input_buffer->hooks)); + if (new_item == NULL) + { + goto fail; /* allocation failure */ + } + + /* attach next item to list */ + if (head == NULL) + { + /* start the linked list */ + current_item = head = new_item; + } + else + { + /* add to the end and advance */ + current_item->next = new_item; + new_item->prev = current_item; + current_item = new_item; + } + + if (cannot_access_at_index(input_buffer, 1)) + { + goto fail; /* nothing comes after the comma */ + } + + /* parse the name of the child */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_string(current_item, input_buffer)) + { + goto fail; /* failed to parse name */ + } + buffer_skip_whitespace(input_buffer); + + /* swap valuestring and string, because we parsed the name */ + current_item->string = current_item->valuestring; + current_item->valuestring = NULL; + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != ':')) + { + goto fail; /* invalid object */ + } + + /* parse the value */ + input_buffer->offset++; + buffer_skip_whitespace(input_buffer); + if (!parse_value(current_item, input_buffer)) + { + goto fail; /* failed to parse value */ + } + buffer_skip_whitespace(input_buffer); + } + while (can_access_at_index(input_buffer, 0) && (buffer_at_offset(input_buffer)[0] == ',')); + + if (cannot_access_at_index(input_buffer, 0) || (buffer_at_offset(input_buffer)[0] != '}')) + { + goto fail; /* expected end of object */ + } + +success: + input_buffer->depth--; + + if (head != NULL) { + head->prev = current_item; + } + + item->type = cJSON_Object; + item->child = head; + + input_buffer->offset++; + return true; + +fail: + if (head != NULL) + { + cJSON_Delete(head); + } + + return false; +} + +/* Render an object to text. */ +static cJSON_bool print_object(const cJSON * const item, printbuffer * const output_buffer) +{ + unsigned char *output_pointer = NULL; + size_t length = 0; + cJSON *current_item = item->child; + + if (output_buffer == NULL) + { + return false; + } + + /* Compose the output: */ + length = (size_t) (output_buffer->format ? 2 : 1); /* fmt: {\n */ + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + + *output_pointer++ = '{'; + output_buffer->depth++; + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + output_buffer->offset += length; + + while (current_item) + { + if (output_buffer->format) + { + size_t i; + output_pointer = ensure(output_buffer, output_buffer->depth); + if (output_pointer == NULL) + { + return false; + } + for (i = 0; i < output_buffer->depth; i++) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += output_buffer->depth; + } + + /* print key */ + if (!print_string_ptr((unsigned char*)current_item->string, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + length = (size_t) (output_buffer->format ? 2 : 1); + output_pointer = ensure(output_buffer, length); + if (output_pointer == NULL) + { + return false; + } + *output_pointer++ = ':'; + if (output_buffer->format) + { + *output_pointer++ = '\t'; + } + output_buffer->offset += length; + + /* print value */ + if (!print_value(current_item, output_buffer)) + { + return false; + } + update_offset(output_buffer); + + /* print comma if not last */ + length = ((size_t)(output_buffer->format ? 1 : 0) + (size_t)(current_item->next ? 1 : 0)); + output_pointer = ensure(output_buffer, length + 1); + if (output_pointer == NULL) + { + return false; + } + if (current_item->next) + { + *output_pointer++ = ','; + } + + if (output_buffer->format) + { + *output_pointer++ = '\n'; + } + *output_pointer = '\0'; + output_buffer->offset += length; + + current_item = current_item->next; + } + + output_pointer = ensure(output_buffer, output_buffer->format ? (output_buffer->depth + 1) : 2); + if (output_pointer == NULL) + { + return false; + } + if (output_buffer->format) + { + size_t i; + for (i = 0; i < (output_buffer->depth - 1); i++) + { + *output_pointer++ = '\t'; + } + } + *output_pointer++ = '}'; + *output_pointer = '\0'; + output_buffer->depth--; + + return true; +} + +/* Get Array size/item / object item. */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) +{ + cJSON *child = NULL; + size_t size = 0; + + if (array == NULL) + { + return 0; + } + + child = array->child; + + while(child != NULL) + { + size++; + child = child->next; + } + + /* FIXME: Can overflow here. Cannot be fixed without breaking the API */ + + return (int)size; +} + +static cJSON* get_array_item(const cJSON *array, size_t index) +{ + cJSON *current_child = NULL; + + if (array == NULL) + { + return NULL; + } + + current_child = array->child; + while ((current_child != NULL) && (index > 0)) + { + index--; + current_child = current_child->next; + } + + return current_child; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index) +{ + if (index < 0) + { + return NULL; + } + + return get_array_item(array, (size_t)index); +} + +static cJSON *get_object_item(const cJSON * const object, const char * const name, const cJSON_bool case_sensitive) +{ + cJSON *current_element = NULL; + + if ((object == NULL) || (name == NULL)) + { + return NULL; + } + + current_element = object->child; + if (case_sensitive) + { + while ((current_element != NULL) && (current_element->string != NULL) && (strcmp(name, current_element->string) != 0)) + { + current_element = current_element->next; + } + } + else + { + while ((current_element != NULL) && (case_insensitive_strcmp((const unsigned char*)name, (const unsigned char*)(current_element->string)) != 0)) + { + current_element = current_element->next; + } + } + + if ((current_element == NULL) || (current_element->string == NULL)) { + return NULL; + } + + return current_element; +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, false); +} + +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string) +{ + return get_object_item(object, string, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string) +{ + return cJSON_GetObjectItem(object, string) ? 1 : 0; +} + +/* Utility for array list handling. */ +static void suffix_object(cJSON *prev, cJSON *item) +{ + prev->next = item; + item->prev = prev; +} + +/* Utility for handling references. */ +static cJSON *create_reference(const cJSON *item, const internal_hooks * const hooks) +{ + cJSON *reference = NULL; + if (item == NULL) + { + return NULL; + } + + reference = cJSON_New_Item(hooks); + if (reference == NULL) + { + return NULL; + } + + memcpy(reference, item, sizeof(cJSON)); + reference->string = NULL; + reference->type |= cJSON_IsReference; + reference->next = reference->prev = NULL; + return reference; +} + +static cJSON_bool add_item_to_array(cJSON *array, cJSON *item) +{ + cJSON *child = NULL; + + if ((item == NULL) || (array == NULL) || (array == item)) + { + return false; + } + + child = array->child; + /* + * To find the last item in array quickly, we use prev in array + */ + if (child == NULL) + { + /* list is empty, start new one */ + array->child = item; + item->prev = item; + item->next = NULL; + } + else + { + /* append to the end */ + if (child->prev) + { + suffix_object(child->prev, item); + array->child->prev = item; + } + } + + return true; +} + +/* Add item to array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) +{ + return add_item_to_array(array, item); +} + +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic push +#endif +#ifdef __GNUC__ +#pragma GCC diagnostic ignored "-Wcast-qual" +#endif +/* helper function to cast away const */ +static void* cast_away_const(const void* string) +{ + return (void*)string; +} +#if defined(__clang__) || (defined(__GNUC__) && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 5)))) + #pragma GCC diagnostic pop +#endif + + +static cJSON_bool add_item_to_object(cJSON * const object, const char * const string, cJSON * const item, const internal_hooks * const hooks, const cJSON_bool constant_key) +{ + char *new_key = NULL; + int new_type = cJSON_Invalid; + + if ((object == NULL) || (string == NULL) || (item == NULL) || (object == item)) + { + return false; + } + + if (constant_key) + { + new_key = (char*)cast_away_const(string); + new_type = item->type | cJSON_StringIsConst; + } + else + { + new_key = (char*)cJSON_strdup((const unsigned char*)string, hooks); + if (new_key == NULL) + { + return false; + } + + new_type = item->type & ~cJSON_StringIsConst; + } + + if (!(item->type & cJSON_StringIsConst) && (item->string != NULL)) + { + hooks->deallocate(item->string); + } + + item->string = new_key; + item->type = new_type; + + return add_item_to_array(object, item); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, false); +} + +/* Add an item to an object with constant string as key */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item) +{ + return add_item_to_object(object, string, item, &global_hooks, true); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item) +{ + if (array == NULL) + { + return false; + } + + return add_item_to_array(array, create_reference(item, &global_hooks)); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item) +{ + if ((object == NULL) || (string == NULL)) + { + return false; + } + + return add_item_to_object(object, string, create_reference(item, &global_hooks), &global_hooks, false); +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name) +{ + cJSON *null = cJSON_CreateNull(); + if (add_item_to_object(object, name, null, &global_hooks, false)) + { + return null; + } + + cJSON_Delete(null); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name) +{ + cJSON *true_item = cJSON_CreateTrue(); + if (add_item_to_object(object, name, true_item, &global_hooks, false)) + { + return true_item; + } + + cJSON_Delete(true_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name) +{ + cJSON *false_item = cJSON_CreateFalse(); + if (add_item_to_object(object, name, false_item, &global_hooks, false)) + { + return false_item; + } + + cJSON_Delete(false_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean) +{ + cJSON *bool_item = cJSON_CreateBool(boolean); + if (add_item_to_object(object, name, bool_item, &global_hooks, false)) + { + return bool_item; + } + + cJSON_Delete(bool_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number) +{ + cJSON *number_item = cJSON_CreateNumber(number); + if (add_item_to_object(object, name, number_item, &global_hooks, false)) + { + return number_item; + } + + cJSON_Delete(number_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) +{ + cJSON *string_item = cJSON_CreateString(string); + if (add_item_to_object(object, name, string_item, &global_hooks, false)) + { + return string_item; + } + + cJSON_Delete(string_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw) +{ + cJSON *raw_item = cJSON_CreateRaw(raw); + if (add_item_to_object(object, name, raw_item, &global_hooks, false)) + { + return raw_item; + } + + cJSON_Delete(raw_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name) +{ + cJSON *object_item = cJSON_CreateObject(); + if (add_item_to_object(object, name, object_item, &global_hooks, false)) + { + return object_item; + } + + cJSON_Delete(object_item); + return NULL; +} + +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name) +{ + cJSON *array = cJSON_CreateArray(); + if (add_item_to_object(object, name, array, &global_hooks, false)) + { + return array; + } + + cJSON_Delete(array); + return NULL; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item) +{ + if ((parent == NULL) || (item == NULL) || (item != parent->child && item->prev == NULL)) + { + return NULL; + } + + if (item != parent->child) + { + /* not the first element */ + item->prev->next = item->next; + } + if (item->next != NULL) + { + /* not the last element */ + item->next->prev = item->prev; + } + + if (item == parent->child) + { + /* first element */ + parent->child = item->next; + } + else if (item->next == NULL) + { + /* last element */ + parent->child->prev = item->prev; + } + + /* make sure the detached item doesn't point anywhere anymore */ + item->prev = NULL; + item->next = NULL; + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which) +{ + if (which < 0) + { + return NULL; + } + + return cJSON_DetachItemViaPointer(array, get_array_item(array, (size_t)which)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which) +{ + cJSON_Delete(cJSON_DetachItemFromArray(array, which)); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItem(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON *to_detach = cJSON_GetObjectItemCaseSensitive(object, string); + + return cJSON_DetachItemViaPointer(object, to_detach); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObject(object, string)); +} + +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string) +{ + cJSON_Delete(cJSON_DetachItemFromObjectCaseSensitive(object, string)); +} + +/* Replace array/object items with new ones. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem) +{ + cJSON *after_inserted = NULL; + + if (which < 0 || newitem == NULL) + { + return false; + } + + after_inserted = get_array_item(array, (size_t)which); + if (after_inserted == NULL) + { + return add_item_to_array(array, newitem); + } + + if (after_inserted != array->child && after_inserted->prev == NULL) { + /* return false if after_inserted is a corrupted array item */ + return false; + } + + newitem->next = after_inserted; + newitem->prev = after_inserted->prev; + after_inserted->prev = newitem; + if (after_inserted == array->child) + { + array->child = newitem; + } + else + { + newitem->prev->next = newitem; + } + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement) +{ + if ((parent == NULL) || (parent->child == NULL) || (replacement == NULL) || (item == NULL)) + { + return false; + } + + if (replacement == item) + { + return true; + } + + replacement->next = item->next; + replacement->prev = item->prev; + + if (replacement->next != NULL) + { + replacement->next->prev = replacement; + } + if (parent->child == item) + { + if (parent->child->prev == parent->child) + { + replacement->prev = replacement; + } + parent->child = replacement; + } + else + { /* + * To find the last item in array quickly, we use prev in array. + * We can't modify the last item's next pointer where this item was the parent's child + */ + if (replacement->prev != NULL) + { + replacement->prev->next = replacement; + } + if (replacement->next == NULL) + { + parent->child->prev = replacement; + } + } + + item->next = NULL; + item->prev = NULL; + cJSON_Delete(item); + + return true; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem) +{ + if (which < 0) + { + return false; + } + + return cJSON_ReplaceItemViaPointer(array, get_array_item(array, (size_t)which), newitem); +} + +static cJSON_bool replace_item_in_object(cJSON *object, const char *string, cJSON *replacement, cJSON_bool case_sensitive) +{ + if ((replacement == NULL) || (string == NULL)) + { + return false; + } + + /* replace the name in the replacement */ + if (!(replacement->type & cJSON_StringIsConst) && (replacement->string != NULL)) + { + cJSON_free(replacement->string); + } + replacement->string = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if (replacement->string == NULL) + { + return false; + } + + replacement->type &= ~cJSON_StringIsConst; + + return cJSON_ReplaceItemViaPointer(object, get_object_item(object, string, case_sensitive), replacement); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, false); +} + +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object, const char *string, cJSON *newitem) +{ + return replace_item_in_object(object, string, newitem, true); +} + +/* Create basic types: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_NULL; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_True; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = boolean ? cJSON_True : cJSON_False; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Number; + item->valuedouble = num; + + /* use saturation in case of overflow */ + if (num >= INT_MAX) + { + item->valueint = INT_MAX; + } + else if (num <= (double)INT_MIN) + { + item->valueint = INT_MIN; + } + else + { + item->valueint = (int)num; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_String; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)string, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) + { + item->type = cJSON_String | cJSON_IsReference; + item->valuestring = (char*)cast_away_const(string); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Object | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child) { + cJSON *item = cJSON_New_Item(&global_hooks); + if (item != NULL) { + item->type = cJSON_Array | cJSON_IsReference; + item->child = (cJSON*)cast_away_const(child); + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type = cJSON_Raw; + item->valuestring = (char*)cJSON_strdup((const unsigned char*)raw, &global_hooks); + if(!item->valuestring) + { + cJSON_Delete(item); + return NULL; + } + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if(item) + { + item->type=cJSON_Array; + } + + return item; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) +{ + cJSON *item = cJSON_New_Item(&global_hooks); + if (item) + { + item->type = cJSON_Object; + } + + return item; +} + +/* Create Arrays: */ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if (!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber((double)numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (numbers == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for(i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateNumber(numbers[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p, n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count) +{ + size_t i = 0; + cJSON *n = NULL; + cJSON *p = NULL; + cJSON *a = NULL; + + if ((count < 0) || (strings == NULL)) + { + return NULL; + } + + a = cJSON_CreateArray(); + + for (i = 0; a && (i < (size_t)count); i++) + { + n = cJSON_CreateString(strings[i]); + if(!n) + { + cJSON_Delete(a); + return NULL; + } + if(!i) + { + a->child = n; + } + else + { + suffix_object(p,n); + } + p = n; + } + + if (a && a->child) { + a->child->prev = n; + } + + return a; +} + +/* Duplication */ +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse); + +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse) +{ + return cJSON_Duplicate_rec(item, 0, recurse ); +} + +cJSON * cJSON_Duplicate_rec(const cJSON *item, size_t depth, cJSON_bool recurse) +{ + cJSON *newitem = NULL; + cJSON *child = NULL; + cJSON *next = NULL; + cJSON *newchild = NULL; + + /* Bail on bad ptr */ + if (!item) + { + goto fail; + } + /* Create new item */ + newitem = cJSON_New_Item(&global_hooks); + if (!newitem) + { + goto fail; + } + /* Copy over all vars */ + newitem->type = item->type & (~cJSON_IsReference); + newitem->valueint = item->valueint; + newitem->valuedouble = item->valuedouble; + if (item->valuestring) + { + newitem->valuestring = (char*)cJSON_strdup((unsigned char*)item->valuestring, &global_hooks); + if (!newitem->valuestring) + { + goto fail; + } + } + if (item->string) + { + newitem->string = (item->type&cJSON_StringIsConst) ? item->string : (char*)cJSON_strdup((unsigned char*)item->string, &global_hooks); + if (!newitem->string) + { + goto fail; + } + } + /* If non-recursive, then we're done! */ + if (!recurse) + { + return newitem; + } + /* Walk the ->next chain for the child. */ + child = item->child; + while (child != NULL) + { + if(depth >= CJSON_CIRCULAR_LIMIT) { + goto fail; + } + newchild = cJSON_Duplicate_rec(child, depth + 1, true); /* Duplicate (with recurse) each item in the ->next chain */ + if (!newchild) + { + goto fail; + } + if (next != NULL) + { + /* If newitem->child already set, then crosswire ->prev and ->next and move on */ + next->next = newchild; + newchild->prev = next; + next = newchild; + } + else + { + /* Set newitem->child and move to it */ + newitem->child = newchild; + next = newchild; + } + child = child->next; + } + if (newitem && newitem->child) + { + newitem->child->prev = newchild; + } + + return newitem; + +fail: + if (newitem != NULL) + { + cJSON_Delete(newitem); + } + + return NULL; +} + +static void skip_oneline_comment(char **input) +{ + *input += static_strlen("//"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if ((*input)[0] == '\n') { + *input += static_strlen("\n"); + return; + } + } +} + +static void skip_multiline_comment(char **input) +{ + *input += static_strlen("/*"); + + for (; (*input)[0] != '\0'; ++(*input)) + { + if (((*input)[0] == '*') && ((*input)[1] == '/')) + { + *input += static_strlen("*/"); + return; + } + } +} + +static void minify_string(char **input, char **output) { + (*output)[0] = (*input)[0]; + *input += static_strlen("\""); + *output += static_strlen("\""); + + + for (; (*input)[0] != '\0'; (void)++(*input), ++(*output)) { + (*output)[0] = (*input)[0]; + + if ((*input)[0] == '\"') { + (*output)[0] = '\"'; + *input += static_strlen("\""); + *output += static_strlen("\""); + return; + } else if (((*input)[0] == '\\') && ((*input)[1] == '\"')) { + (*output)[1] = (*input)[1]; + *input += static_strlen("\""); + *output += static_strlen("\""); + } + } +} + +CJSON_PUBLIC(void) cJSON_Minify(char *json) +{ + char *into = json; + + if (json == NULL) + { + return; + } + + while (json[0] != '\0') + { + switch (json[0]) + { + case ' ': + case '\t': + case '\r': + case '\n': + json++; + break; + + case '/': + if (json[1] == '/') + { + skip_oneline_comment(&json); + } + else if (json[1] == '*') + { + skip_multiline_comment(&json); + } else { + json++; + } + break; + + case '\"': + minify_string(&json, (char**)&into); + break; + + default: + into[0] = json[0]; + json++; + into++; + } + } + + /* and null-terminate. */ + *into = '\0'; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Invalid; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_False; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xff) == cJSON_True; +} + + +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & (cJSON_True | cJSON_False)) != 0; +} +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_NULL; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Number; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_String; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Array; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Object; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item) +{ + if (item == NULL) + { + return false; + } + + return (item->type & 0xFF) == cJSON_Raw; +} + +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive) +{ + if ((a == NULL) || (b == NULL) || ((a->type & 0xFF) != (b->type & 0xFF))) + { + return false; + } + + /* check if type is valid */ + switch (a->type & 0xFF) + { + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + case cJSON_Number: + case cJSON_String: + case cJSON_Raw: + case cJSON_Array: + case cJSON_Object: + break; + + default: + return false; + } + + /* identical objects are equal */ + if (a == b) + { + return true; + } + + switch (a->type & 0xFF) + { + /* in these cases and equal type is enough */ + case cJSON_False: + case cJSON_True: + case cJSON_NULL: + return true; + + case cJSON_Number: + if (compare_double(a->valuedouble, b->valuedouble)) + { + return true; + } + return false; + + case cJSON_String: + case cJSON_Raw: + if ((a->valuestring == NULL) || (b->valuestring == NULL)) + { + return false; + } + if (strcmp(a->valuestring, b->valuestring) == 0) + { + return true; + } + + return false; + + case cJSON_Array: + { + cJSON *a_element = a->child; + cJSON *b_element = b->child; + + for (; (a_element != NULL) && (b_element != NULL);) + { + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + + a_element = a_element->next; + b_element = b_element->next; + } + + /* one of the arrays is longer than the other */ + if (a_element != b_element) { + return false; + } + + return true; + } + + case cJSON_Object: + { + cJSON *a_element = NULL; + cJSON *b_element = NULL; + cJSON_ArrayForEach(a_element, a) + { + /* TODO This has O(n^2) runtime, which is horrible! */ + b_element = get_object_item(b, a_element->string, case_sensitive); + if (b_element == NULL) + { + return false; + } + + if (!cJSON_Compare(a_element, b_element, case_sensitive)) + { + return false; + } + } + + /* doing this twice, once on a and b to prevent true comparison if a subset of b + * TODO: Do this the proper way, this is just a fix for now */ + cJSON_ArrayForEach(b_element, b) + { + a_element = get_object_item(a, b_element->string, case_sensitive); + if (a_element == NULL) + { + return false; + } + + if (!cJSON_Compare(b_element, a_element, case_sensitive)) + { + return false; + } + } + + return true; + } + + default: + return false; + } +} + +CJSON_PUBLIC(void *) cJSON_malloc(size_t size) +{ + return global_hooks.allocate(size); +} + +CJSON_PUBLIC(void) cJSON_free(void *object) +{ + global_hooks.deallocate(object); + object = NULL; +} diff --git a/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.h b/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.h new file mode 100644 index 00000000..37520bbc --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/common/cJSON.h @@ -0,0 +1,306 @@ +/* + Copyright (c) 2009-2017 Dave Gamble and cJSON contributors + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*/ + +#ifndef cJSON__h +#define cJSON__h + +#ifdef __cplusplus +extern "C" +{ +#endif + +#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32)) +#define __WINDOWS__ +#endif + +#ifdef __WINDOWS__ + +/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options: + +CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols +CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default) +CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol + +For *nix builds that support visibility attribute, you can define similar behavior by + +setting default visibility to hidden by adding +-fvisibility=hidden (for gcc) +or +-xldscope=hidden (for sun cc) +to CFLAGS + +then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does + +*/ + +#define CJSON_CDECL __cdecl +#define CJSON_STDCALL __stdcall + +/* export symbols by default, this is necessary for copy pasting the C and header file */ +#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_EXPORT_SYMBOLS +#endif + +#if defined(CJSON_HIDE_SYMBOLS) +#define CJSON_PUBLIC(type) type CJSON_STDCALL +#elif defined(CJSON_EXPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL +#elif defined(CJSON_IMPORT_SYMBOLS) +#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL +#endif +#else /* !__WINDOWS__ */ +#define CJSON_CDECL +#define CJSON_STDCALL + +#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY) +#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type +#else +#define CJSON_PUBLIC(type) type +#endif +#endif + +/* project version */ +#define CJSON_VERSION_MAJOR 1 +#define CJSON_VERSION_MINOR 7 +#define CJSON_VERSION_PATCH 18 + +#include + +/* cJSON Types: */ +#define cJSON_Invalid (0) +#define cJSON_False (1 << 0) +#define cJSON_True (1 << 1) +#define cJSON_NULL (1 << 2) +#define cJSON_Number (1 << 3) +#define cJSON_String (1 << 4) +#define cJSON_Array (1 << 5) +#define cJSON_Object (1 << 6) +#define cJSON_Raw (1 << 7) /* raw json */ + +#define cJSON_IsReference 256 +#define cJSON_StringIsConst 512 + +/* The cJSON structure: */ +typedef struct cJSON +{ + /* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */ + struct cJSON *next; + struct cJSON *prev; + /* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */ + struct cJSON *child; + + /* The type of the item, as above. */ + int type; + + /* The item's string, if type==cJSON_String and type == cJSON_Raw */ + char *valuestring; + /* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */ + int valueint; + /* The item's number, if type==cJSON_Number */ + double valuedouble; + + /* The item's name string, if this item is the child of, or is in the list of subitems of an object. */ + char *string; +} cJSON; + +typedef struct cJSON_Hooks +{ + /* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */ + void *(CJSON_CDECL *malloc_fn)(size_t sz); + void (CJSON_CDECL *free_fn)(void *ptr); +} cJSON_Hooks; + +typedef int cJSON_bool; + +/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_NESTING_LIMIT +#define CJSON_NESTING_LIMIT 1000 +#endif + +/* Limits the length of circular references can be before cJSON rejects to parse them. + * This is to prevent stack overflows. */ +#ifndef CJSON_CIRCULAR_LIMIT +#define CJSON_CIRCULAR_LIMIT 10000 +#endif + +/* returns the version of cJSON as a string */ +CJSON_PUBLIC(const char*) cJSON_Version(void); + +/* Supply malloc, realloc and free functions to cJSON */ +CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks); + +/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */ +/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */ +CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length); +/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */ +/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */ +CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated); +CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated); + +/* Render a cJSON entity to text for transfer/storage. */ +CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item); +/* Render a cJSON entity to text for transfer/storage without any formatting. */ +CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item); +/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */ +CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt); +/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */ +/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */ +CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format); +/* Delete a cJSON entity and all subentities. */ +CJSON_PUBLIC(void) cJSON_Delete(cJSON *item); + +/* Returns the number of items in an array (or object). */ +CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array); +/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */ +CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index); +/* Get item "string" from object. Case insensitive. */ +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string); +CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string); +/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */ +CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void); + +/* Check item type and return its value */ +CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item); +CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item); + +/* These functions check the type of an item */ +CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item); +CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item); + +/* These calls create a cJSON item of the appropriate type. */ +CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean); +CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num); +CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string); +/* raw json */ +CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw); +CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void); +CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void); + +/* Create a string where valuestring references a string so + * it will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string); +/* Create an object/array that only references it's elements so + * they will not be freed by cJSON_Delete */ +CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child); +CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child); + +/* These utilities create an Array of count items. + * The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/ +CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count); +CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count); + +/* Append item to the specified array/object. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item); +/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object. + * WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before + * writing to `item->string` */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item); +/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */ +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item); +CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item); + +/* Remove/Detach items from Arrays/Objects. */ +CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string); +CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string); + +/* Update array items. */ +CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */ +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem); +CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem); + +/* Duplicate a cJSON item */ +CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse); +/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will + * need to be released. With recurse!=0, it will duplicate any children connected to the item. + * The item->next and ->prev pointers are always zero on return from Duplicate. */ +/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal. + * case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */ +CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive); + +/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings. + * The input pointer json cannot point to a read-only address area, such as a string constant, + * but should point to a readable and writable address area. */ +CJSON_PUBLIC(void) cJSON_Minify(char *json); + +/* Helper functions for creating and adding items to an object at the same time. + * They return the added item or NULL on failure. */ +CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean); +CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number); +CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string); +CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw); +CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name); +CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name); + +/* When assigning an integer value, it needs to be propagated to valuedouble too. */ +#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number)) +/* helper for the cJSON_SetNumberValue macro */ +CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number); +#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number)) +/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */ +CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring); + +/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/ +#define cJSON_SetBoolValue(object, boolValue) ( \ + (object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \ + (object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \ + cJSON_Invalid\ +) + +/* Macro for iterating over an array or object */ +#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next) + +/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */ +CJSON_PUBLIC(void *) cJSON_malloc(size_t size); +CJSON_PUBLIC(void) cJSON_free(void *object); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libtesla/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/README.md b/Source/sys-clk/overlay/lib/libultrahand/libtesla/README.md new file mode 100644 index 00000000..5782d161 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libtesla/README.md @@ -0,0 +1,32 @@ +# libtesla + +

+ +

+ +libtesla is the interface between the Tesla overlay loader and user-made Overlays. It handles all layer creation, UI creation, drawing and input management. +It's main goal is to make sure all overlays look and feel similar and don't differenciate themselves from the switch's native overlays. + +## Screenshots + +
+ + +
+ +`Overlays do NOT show up on Screenshots. These pictures were taken using a capture card` + +## Example + +An example for how to use libtesla can be found here: https://github.com/WerWolv/libtesla/tree/master/example +To create your own Overlay, please consider creating a new repository using the official Tesla overlay template: https://github.com/WerWolv/Tesla-Template + +**Please Note:** While it is possible to create overlays without libtesla, it's highly recommended to not do so. libtesla handles showing and hiding of overlays, button combo detection, layer creation and a lot more. Not using it will lead to an inconsistent user experience when using multiple different overlays ultimately making it worse for the end user. If something's missing, please consider opening a PR here. + +## Credits + +- **switchbrew** for nx-hbloader which is used as basis for overlay loading +- **kardch** for the amazing icon +- **All the devs on AtlasNX, RetroNX and Switchbrew** for their feedback +- **All overlay devs** for making something awesome out of this :) + diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile b/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile new file mode 100644 index 00000000..cdb011ae --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/Makefile @@ -0,0 +1,209 @@ +#--------------------------------------------------------------------------------- +.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 new file mode 100644 index 00000000..bf4c2522 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libtesla/example/source/main.cpp @@ -0,0 +1,100 @@ +#define TESLA_INIT_IMPL // If you have more than one file using the tesla header, only define this in the main one +#include // The Tesla Header + + +class GuiSecondary : public tsl::Gui { +public: + GuiSecondary() {} + + virtual tsl::elm::Element* createUI() override { + auto *rootFrame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2 - Secondary Gui"); + + rootFrame->setContent(new tsl::elm::DebugRectangle(tsl::Color{ 0x8, 0x3, 0x8, 0xF })); + + return rootFrame; + } +}; + +class GuiTest : public tsl::Gui { +public: + GuiTest(u8 arg1, u8 arg2, bool arg3) { } + + // Called when this Gui gets loaded to create the UI + // Allocate all elements on the heap. libtesla will make sure to clean them up when not needed anymore + virtual tsl::elm::Element* createUI() override { + // A OverlayFrame is the base element every overlay consists of. This will draw the default Title and Subtitle. + // If you need more information in the header or want to change it's look, use a HeaderOverlayFrame. + auto frame = new tsl::elm::OverlayFrame("Tesla Example", "v1.3.2"); + + // A list that can contain sub elements and handles scrolling + auto list = new tsl::elm::List(); + + // List Items + list->addItem(new tsl::elm::CategoryHeader("List items")); + + auto *clickableListItem = new tsl::elm::ListItem("Clickable List Item", "..."); + clickableListItem->setClickListener([](u64 keys) { + if (keys & HidNpadButton_A) { + tsl::changeTo(); + return true; + } + + return false; + }); + + list->addItem(clickableListItem); + list->addItem(new tsl::elm::ListItem("Default List Item")); + list->addItem(new tsl::elm::ListItem("Default List Item with an extra long name to trigger truncation and scrolling")); + list->addItem(new tsl::elm::ToggleListItem("Toggle List Item", true)); + + // Custom Drawer, a element that gives direct access to the renderer + list->addItem(new tsl::elm::CategoryHeader("Custom Drawer", true)); + list->addItem(new tsl::elm::CustomDrawer([](tsl::gfx::Renderer *renderer, s32 x, s32 y, s32 w, s32 h) { + renderer->drawCircle(x + 40, y + 40, 20, true, renderer->a(0xF00F)); + renderer->drawCircle(x + 50, y + 50, 20, true, renderer->a(0xF0F0)); + renderer->drawRect(x + 130, y + 30, 60, 40, renderer->a(0xFF00)); + renderer->drawString("Hello :)", false, x + 250, y + 70, 20, renderer->a(0xFF0F)); + renderer->drawRect(x + 40, y + 90, 300, 10, renderer->a(0xF0FF)); + }), 100); + + // Track bars + list->addItem(new tsl::elm::CategoryHeader("Track bars")); + list->addItem(new tsl::elm::TrackBar("\u2600")); + list->addItem(new tsl::elm::StepTrackBar("\uE13C", 20)); + list->addItem(new tsl::elm::NamedStepTrackBar("\uE132", { "Selection 1", "Selection 2", "Selection 3" })); + + // Add the list to the frame for it to be drawn + frame->setContent(list); + + // Return the frame to have it become the top level element of this Gui + return frame; + } + + // Called once every frame to update values + virtual void update() override { + + } + + // Called once every frame to handle inputs not handled by other UI elements + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) override { + return false; // Return true here to signal the inputs have been consumed + } +}; + +class OverlayTest : public tsl::Overlay { +public: + // libtesla already initialized fs, hid, pl, pmdmnt, hid:sys and set:sys + virtual void initServices() override {} // Called at the start to initialize all services necessary for this Overlay + virtual void exitServices() override {} // Called at the end to clean up all services previously initialized + + virtual void onShow() override {} // Called before overlay wants to change from invisible to visible state + virtual void onHide() override {} // Called before overlay wants to change from visible to invisible state + + virtual std::unique_ptr loadInitialGui() override { + return initially(1, 2, true); // Initial Gui to load. It's possible to pass arguments to it's constructor like this + } +}; + +int main(int argc, char **argv) { + return tsl::loop(argc, argv); +} diff --git a/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h b/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h new file mode 100644 index 00000000..392ca11d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/stb_truetype.h @@ -0,0 +1,5265 @@ +// 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) +{ + // Read format once - single memory access + stbtt_uint16 format = FAST_USHORT(data + index_map); + + // Variables used across multiple cases or frequently in loops + stbtt_uint32 low, high, mid; + stbtt_uint8 *group; + stbtt_uint32 start_char, end_char; + stbtt_uint32 uc; + + // Switch for jump table optimization + switch (format) { + case 4: { // Windows fonts - most common + // Early exit for out-of-range Unicode + if ((unsigned)unicode_codepoint > 0xffff) return 0; + + // Cache all header values in one go - burst read + stbtt_uint8 *header = data + index_map; + stbtt_uint16 segcount = FAST_USHORT(header + 6) >> 1; + stbtt_uint16 searchRange = FAST_USHORT(header + 8) >> 1; + stbtt_uint16 entrySelector = FAST_USHORT(header + 10); + stbtt_uint16 rangeShift = FAST_USHORT(header + 12) >> 1; + + // Optimized binary search with fewer memory accesses + stbtt_uint32 endCount = index_map + 14; + stbtt_uint32 search = endCount; + + // Use the precomputed rangeShift for initial jump + if (unicode_codepoint >= FAST_USHORT(data + search + (rangeShift << 1))) + search += rangeShift << 1; + + search -= 2; + + // Unrolled binary search - most critical path + while (entrySelector) { + searchRange >>= 1; + stbtt_uint32 test_pos = search + (searchRange << 1); + if (unicode_codepoint > FAST_USHORT(data + test_pos)) + search = test_pos; + --entrySelector; + } + + search += 2; + stbtt_uint16 item = (stbtt_uint16)((search - endCount) >> 1); + + // Calculate all offsets upfront - better instruction scheduling + stbtt_uint32 base1 = index_map + 14; + stbtt_uint32 startCode_offset = base1 + (segcount << 1) + 2 + (item << 1); + stbtt_uint32 endCode_offset = endCount + (item << 1); + stbtt_uint32 idRangeOffset_offset = base1 + (segcount * 6) + 2 + (item << 1); + + stbtt_uint16 start = FAST_USHORT(data + startCode_offset); + stbtt_uint16 end = FAST_USHORT(data + endCode_offset); + + // Single comparison using unsigned arithmetic trick + if ((unsigned)(unicode_codepoint - start) > (unsigned)(end - start)) + return 0; + + stbtt_uint16 offset = FAST_USHORT(data + idRangeOffset_offset); + if (offset == 0) { + stbtt_uint32 idDelta_offset = base1 + (segcount << 2) + 2 + (item << 1); + return (stbtt_uint16)(unicode_codepoint + FAST_SHORT(data + idDelta_offset)); + } + + return FAST_USHORT(data + offset + ((unicode_codepoint - start) << 1) + idRangeOffset_offset); + } + + case 12: { // 32-bit format + stbtt_uint32 ngroups = FAST_ULONG(data + index_map + 12); + uc = (stbtt_uint32)unicode_codepoint; + + // Optimized binary search with minimal memory access + low = 0; high = ngroups; + stbtt_uint8 *groups_base = data + index_map + 16; + + while (low < high) { + mid = (low + high) >> 1; + group = groups_base + (mid * 12); + + start_char = FAST_ULONG(group); + if (uc < start_char) { + high = mid; + } else { + end_char = FAST_ULONG(group + 4); + if (uc <= end_char) { + stbtt_uint32 start_glyph = FAST_ULONG(group + 8); + return start_glyph + uc - start_char; + } + low = mid + 1; + } + } + return 0; + } + + case 13: { // 32-bit format, many-to-one mapping + stbtt_uint32 ngroups = FAST_ULONG(data + index_map + 12); + uc = (stbtt_uint32)unicode_codepoint; + + low = 0; high = ngroups; + stbtt_uint8 *groups_base = data + index_map + 16; + + while (low < high) { + mid = (low + high) >> 1; + group = groups_base + (mid * 12); + + start_char = FAST_ULONG(group); + if (uc < start_char) { + high = mid; + } else { + end_char = FAST_ULONG(group + 4); + if (uc <= end_char) { + return FAST_ULONG(group + 8); // Same glyph for all chars in range + } + low = mid + 1; + } + } + return 0; + } + + case 0: { // Apple byte encoding - simple and fast + stbtt_int32 bytes = FAST_USHORT(data + index_map + 2); + return ((unsigned)unicode_codepoint < (unsigned)(bytes - 6)) ? + data[index_map + 6 + unicode_codepoint] : 0; + } + + case 6: { // Trimmed table mapping + stbtt_uint32 first = FAST_USHORT(data + index_map + 6); + stbtt_uint32 count = FAST_USHORT(data + index_map + 8); + uc = (stbtt_uint32)unicode_codepoint; + stbtt_uint32 offset = uc - first; + return (offset < count) ? FAST_USHORT(data + index_map + 10 + (offset << 1)) : 0; + } + + default: + return 0; // Unsupported format + } +} + + +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 new file mode 100644 index 00000000..fc5aba53 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libtesla/include/tesla.hpp @@ -0,0 +1,13617 @@ +/******************************************************************************** + * 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) 2024 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 + +#include // unused, but preserved for projects that might need it +#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; +volatile bool triggerExitNow = false; +volatile bool isRendering = false; +volatile bool delayUpdate = false; +volatile bool pendingExit = false; +volatile bool wasRendering = false; + +LEvent renderingStopEvent = {0}; +bool FullMode = true; +bool deactivateOriginalFooter = false; +//bool fontCache = true; +bool disableJumpTo = false; + +// Check for mini/micro mode flags +bool isMiniOrMicroMode = false; + +#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 bool screenshotsAreDisabled = 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}; + +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 + } + } + + static bool overrideBackButton = false; // for properly overriding the automatic "go back" functionality of KEY_B button presses + + // 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 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("AAAAAA"); + static Color overlayVersionTextColor = RGB888("AAAAAA"); + static Color ultOverlayVersionTextColor = RGB888("00FFDD"); + static Color packageVersionTextColor = RGB888("AAAAAA"); + static Color ultPackageVersionTextColor = RGB888("00FFDD"); + static Color onTextColor = RGB888("00FFDD"); + static Color offTextColor = RGB888("AAAAAA"); + + #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 trackBarColor = RGB888("555555"); + + 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() { // NOTE: This needs to be called once in your application. + // Fetch all theme settings at once from the INI file + auto themeData = ult::getParsedDataFromIniFile(ult::THEME_CONFIG_INI_PATH); + if (themeData.count(ult::THEME_STR) > 0) { + auto& themeSection = themeData[ult::THEME_STR]; + + // Fetch and process each theme setting using a helper to simplify fetching and fallback + auto getValue = [&](const std::string& key) { + return themeSection.count(key) ? themeSection[key] : ult::defaultThemeSettingsMap[key]; + }; + + // Convert hex color to Color and manage default values and conversion + auto getColor = [&](const std::string& key, size_t alpha = 15) { + //std::string hexColor = getValue(key); + return RGB888(getValue(key), alpha); + }; + + auto getAlpha = [&](const std::string& key) { + std::string alphaStr = getValue(key); + return !alphaStr.empty() ? ult::stoi(alphaStr) : ult::stoi(ult::defaultThemeSettingsMap[key]); + }; + + //disableColorfulLogo = (getValue("disable_colorful_logo") == ult::TRUE_STR); + + #if IS_LAUNCHER_DIRECTIVE + logoColor1 = getColor("logo_color_1"); + logoColor2 = getColor("logo_color_2"); + #endif + + defaultBackgroundAlpha = getAlpha("bg_alpha"); + defaultBackgroundColor = getColor("bg_color", defaultBackgroundAlpha); + defaultTextColor = getColor("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"); + + #if IS_LAUNCHER_DIRECTIVE + dynamicLogoRGB1 = getColor("dynamic_logo_color_1"); + dynamicLogoRGB2 = getColor("dynamic_logo_color_2"); + #endif + + //disableSelectionBG = (getValue("disable_selection_bg") == ult::TRUE_STR); + //disableSelectionValueColor = (getValue("disable_selection_value_color") == ult::TRUE_STR); + 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); + + trackBarColor = getColor("trackbar_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); + 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 && !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::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; + } + + // Function to load key combo mappings from both overlays.ini and packages.ini + static void loadEntryKeyCombos() { + 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) { + 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) { + return s_localFont; + } + 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) { + return s_localFont; + } + 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 { + // Need to upgrade to write lock + readLock.unlock(); + std::unique_lock writeLock(s_translationCacheMutex); + + // Double-check pattern + translatedIt = ult::translationCache.find(originalString); + if (translatedIt != ult::translationCache.end()) { + text = translatedIt->second; + } else { + ult::translationCache[originalString] = originalString; + 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) { + // All variables moved outside the loop + const u16* framebuffer = static_cast(this->getCurrentFramebuffer()); + u32 offset; + u8 currentAlpha; + u8 invAlpha; + Color src = {0}, end = {0}; + u32 currentX; + + for (s32 i = 0; i < count; ++i) { + // Early exit for transparent pixels + currentAlpha = alpha[i]; + if (currentAlpha == 0) + continue; + + currentX = baseX + i; + offset = this->getPixelOffset(currentX, baseY); + if (offset == UINT32_MAX) [[unlikely]] + continue; + + // Direct framebuffer access and color construction + src = framebuffer[offset]; + invAlpha = 0xF - currentAlpha; + + // Direct member assignment instead of constructor + end.r = blendColor(src.r, red[i], currentAlpha); + end.g = blendColor(src.g, green[i], currentAlpha); + end.b = blendColor(src.b, blue[i], currentAlpha); + end.a = (currentAlpha + (src.a * invAlpha >> 4)); + + this->setPixelAtOffset(offset, end); + } + } + + + /** + * @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) { + 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); + } + } 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); + } + + y++; + radiusError += yChange; + yChange += 2; + + if (((radiusError << 1) + xChange) > 0) { + x--; + radiusError += xChange; + xChange += 2; + } + } + } + + 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 (unchanged for exact visual match) + this->drawRect(startX, startY - thickness, adjustedWidth, thickness, highlightColor); // Top border + this->drawRect(startX, startY + adjustedHeight, adjustedWidth, thickness, highlightColor); // Bottom border + this->drawRect(startX - thickness, startY, thickness, adjustedHeight, highlightColor); // Left border + this->drawRect(startX + adjustedWidth, startY, thickness, adjustedHeight, highlightColor); // Right border + + // Optimized filled quarter circle drawing - all 4 corners in one pass + s32 cx = radius; + s32 cy = 0; + s32 radiusError = 0; + s32 xChange = 1 - (radius << 1); + s32 yChange = 0; + + while (cx >= cy) { + // Draw horizontal spans for all 4 corners simultaneously + // Upper-left corner (quadrant 2) - two horizontal lines + for (s32 i = leftCornerX - cx; i <= leftCornerX; i++) { + this->setPixelBlendDst(i, topCornerY - cy, highlightColor); + } + for (s32 i = leftCornerX - cy; i <= leftCornerX; i++) { + this->setPixelBlendDst(i, topCornerY - cx, highlightColor); + } + + // Lower-left corner (quadrant 3) - two horizontal lines + for (s32 i = leftCornerX - cx; i <= leftCornerX; i++) { + this->setPixelBlendDst(i, bottomCornerY + cy, highlightColor); + } + for (s32 i = leftCornerX - cy; i <= leftCornerX; i++) { + this->setPixelBlendDst(i, bottomCornerY + cx, highlightColor); + } + + // Upper-right corner (quadrant 1) - two horizontal lines + for (s32 i = rightCornerX; i <= rightCornerX + cx; i++) { + this->setPixelBlendDst(i, topCornerY - cy, highlightColor); + } + for (s32 i = rightCornerX; i <= rightCornerX + cy; i++) { + this->setPixelBlendDst(i, topCornerY - cx, highlightColor); + } + + // Lower-right corner (quadrant 4) - two horizontal lines + for (s32 i = rightCornerX; i <= rightCornerX + cx; i++) { + this->setPixelBlendDst(i, bottomCornerY + cy, highlightColor); + } + for (s32 i = rightCornerX; i <= rightCornerX + cy; i++) { + this->setPixelBlendDst(i, bottomCornerY + cx, highlightColor); + } + + // Bresenham circle algorithm step + cy++; + radiusError += yChange; + yChange += 2; + + if (((radiusError << 1) + xChange) > 0) { + cx--; + radiusError += xChange; + xChange += 2; + } + } + } + + + // Pre-compute all horizontal spans for the entire shape + struct HorizontalSpan { + s32 start_x, end_x; + }; + + // Define processChunk as a static member function + // Optimized processRoundedRectChunk - assumes bounds checking done by caller + 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) { + // Original rectangle bounds + const s32 orig_x = x, orig_y = y; + const s32 orig_x_end = x + w, orig_y_end = y + h; + + // Calculate clipping bounds + const s32 clip_x = std::max(0, x); + const s32 clip_x_end = std::min(static_cast(cfg::FramebufferWidth), x + w); + + // Use ORIGINAL coordinates to determine corner regions + const s32 orig_x_left = orig_x + radius, orig_x_right = orig_x_end - radius; + const s32 orig_y_top = orig_y + radius, orig_y_bottom = orig_y_end - radius; + const s32 r2 = radius * radius; + const u8 red = color.r, green = color.g, blue = color.b, alpha = color.a; + + alignas(64) u8 redArray[512], greenArray[512], blueArray[512], alphaArray[512]; + for (s32 i = 0; i < 512; i += 8) { + redArray[i] = redArray[i+1] = redArray[i+2] = redArray[i+3] = + redArray[i+4] = redArray[i+5] = redArray[i+6] = redArray[i+7] = red; + greenArray[i] = greenArray[i+1] = greenArray[i+2] = greenArray[i+3] = + greenArray[i+4] = greenArray[i+5] = greenArray[i+6] = greenArray[i+7] = green; + blueArray[i] = blueArray[i+1] = blueArray[i+2] = blueArray[i+3] = + blueArray[i+4] = blueArray[i+5] = blueArray[i+6] = blueArray[i+7] = blue; + alphaArray[i] = alphaArray[i+1] = alphaArray[i+2] = alphaArray[i+3] = + alphaArray[i+4] = alphaArray[i+5] = alphaArray[i+6] = alphaArray[i+7] = alpha; + } + + s32 orig_span_start, orig_span_end; + s32 dx; + for (s32 y_current = startRow; y_current < endRow; ++y_current) { + // Skip if outside original rectangle bounds + if (y_current < orig_y || y_current >= orig_y_end) continue; + + + + if (y_current >= orig_y_top && y_current < orig_y_bottom) { + // Middle section - full width + orig_span_start = orig_x; + orig_span_end = orig_x_end; + } else { + // Corner section + const s32 dy_abs = (y_current < orig_y_top) ? (orig_y_top - y_current) : (y_current - orig_y_bottom); + const s32 dy2 = dy_abs * dy_abs; + if (dy2 > r2) continue; + + // Compute dx using integer square root approximation + dx = 0; + const s32 t = r2 - dy2; + while (dx * dx <= t) { + dx++; + } + dx--; // Get the largest dx where dx^2 + dy2 <= r2 + + // Calculate the span for this row in the original rectangle + orig_span_start = std::max(orig_x_left - dx, orig_x); + orig_span_end = std::min(orig_x_right + dx, orig_x_end); + } + + // Clip the original span to visible bounds + const s32 span_start = std::max(orig_span_start, clip_x); + const s32 span_end = std::min(orig_span_end, clip_x_end); + + if (span_start >= span_end) continue; + + // Batch rendering + for (s32 x_pos = span_start; x_pos < span_end; x_pos += 512) { + self->setPixelBlendDstBatch(x_pos, y_current, redArray, greenArray, blueArray, alphaArray, std::min(512, span_end - x_pos)); + } + } + } + + + + /** + * @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(fb_width, x + w); + const s32 clampedYEnd = std::min(fb_height, 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(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(fb_width, x + w); + const s32 clampedYEnd = std::min(fb_height, y + h); + + // Early exit if nothing to draw after clamping + if (clampedX >= clampedXEnd || 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) { + // Early exit for degenerate cases + //if (w <= 0 || h <= 0) return; + + // Calculate radius and bounds + const s32 radius = h >> 1; // h / 2 + //if (radius <= 0) return; + + // Get framebuffer bounds + const s32 fb_width = cfg::FramebufferWidth; + const s32 fb_height = cfg::FramebufferHeight; + + // Calculate clipped drawing bounds + const s32 clip_left = std::max(0, x); + const s32 clip_top = std::max(0, y); + const s32 clip_right = std::min(fb_width, x + w); + const s32 clip_bottom = std::min(fb_height, y + h); + + // Early exit if completely clipped + if (clip_left >= clip_right || clip_top >= clip_bottom) return; + + // Shape parameters + const s32 center_y = y + radius; + const s32 rect_left = x + radius; + const s32 rect_right = x + w - radius; + const s32 radius_sq = radius * radius; + + // Choose drawing method based on alpha + const bool fullOpacity = (color.a == 0xF); + + // Pre-compute variables + s32 y_curr, x_curr; + s32 dy, dy_sq, x_offset_sq; + s32 x_offset, row_start, row_end; + //u32 pixel_offset; + + // Main drawing loop + for (y_curr = clip_top; y_curr < clip_bottom; ++y_curr) { + dy = y_curr - center_y; + dy_sq = dy * dy; + + // Skip rows outside the shape + if (dy_sq > radius_sq) continue; + + // Calculate horizontal extent for this row + x_offset_sq = radius_sq - dy_sq; + + // Fast integer square root with better rounding + if (radius <= 32) { + // Direct calculation for small values + x_offset = 0; + while (x_offset * x_offset <= x_offset_sq) { + x_offset++; + } + // More intelligent step-back: only if we're significantly over + // This reduces the "flat edge" appearance + if (x_offset > 0) { + s32 current_sq = x_offset * x_offset; + s32 prev_sq = (x_offset - 1) * (x_offset - 1); + // Only step back if we're closer to the previous value + if (current_sq - x_offset_sq > x_offset_sq - prev_sq) { + x_offset--; + } + } + } else { + // Newton's method for larger values (converges in ~4 iterations) + x_offset = radius; // Initial guess + for (int i = 0; i < 4; ++i) { + x_offset = (x_offset + x_offset_sq / x_offset) >> 1; + } + // Ensure we're close to the actual value + while ((x_offset + 1) * (x_offset + 1) <= x_offset_sq) x_offset++; + while (x_offset * x_offset > x_offset_sq) x_offset--; + } + + // Calculate row bounds + row_start = rect_left - x_offset; + row_end = rect_right + x_offset; + + // Clip to visible area + row_start = std::max(row_start, clip_left); + row_end = std::min(row_end, clip_right); + + if (row_start >= row_end) continue; + + // Draw the row + if (fullOpacity) { + // Use setPixel for full opacity + for (x_curr = row_start; x_curr < row_end; ++x_curr) { + //this->setPixel(x_curr, y_curr, color); + //const u32 pixel_offset = this->getPixelOffset(x, y); + this->setPixelAtOffset(this->getPixelOffset(x_curr, y_curr), color); + } + } else { + // Blended drawing + for (x_curr = row_start; x_curr < row_end; ++x_curr) { + this->setPixelBlendDst(x_curr, y_curr, color); + } + } + } + } + + // 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] + }); + } + } + + // Fixed compilation errors - simplified SIMD version + static constexpr uint8x16_t lut = {0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255}; + const uint8x16_t mask_low = vdupq_n_u8(0x0F); + // Pre-computed lookup table for 4-bit to 8-bit conversion + static constexpr u8 expand4to8[16] = { + 0, 17, 34, 51, 68, 85, 102, 119, 136, 153, 170, 187, 204, 221, 238, 255 + }; + +// inline void processBMPChunk(const s32 x, const s32 y, const s32 screenW, const u8 *preprocessedData, +// const s32 startRow, const s32 endRow) { +// const s32 bytesPerRow = screenW * 2; +// const s32 endX16 = screenW & ~15; +// +// // Pre-declare all variables outside loops to avoid repeated allocations +// const u8 *rowPtr; +// s32 baseY; +// s32 x1; +// const u8* ptr; +// uint8x16x2_t packed; +// uint8x16_t high1, low1, high2, low2; +// uint8x16_t red, green, blue, alpha; +// alignas(16) u8 red_vals[16], green_vals[16], blue_vals[16], alpha_vals[16]; +// s32 baseX; +// s32 pixelX; +// u32 offset; +// Color color = {0}, src = {0}, end = {0}; +// const u16* framebuffer; +// u8 p1, p2; +// +// for (s32 y1 = startRow; y1 < endRow; ++y1) { +// rowPtr = preprocessedData + (y1 * bytesPerRow); +// baseY = y + y1; +// +// x1 = 0; +// +// // SIMD processing for 16 pixels at once +// for (; x1 < endX16; x1 += 16) { +// ptr = rowPtr + (x1 << 1); +// packed = vld2q_u8(ptr); +// +// // Expand 4-bit to 8-bit values +// high1 = vshrq_n_u8(packed.val[0], 4); +// low1 = vandq_u8(packed.val[0], mask_low); +// high2 = vshrq_n_u8(packed.val[1], 4); +// low2 = vandq_u8(packed.val[1], mask_low); +// +// red = vqtbl1q_u8(lut, high1); +// green = vqtbl1q_u8(lut, low1); +// blue = vqtbl1q_u8(lut, high2); +// alpha = vqtbl1q_u8(lut, low2); +// +// // Store to arrays and process individually +// vst1q_u8(red_vals, red); +// vst1q_u8(green_vals, green); +// vst1q_u8(blue_vals, blue); +// vst1q_u8(alpha_vals, alpha); +// +// baseX = x + x1; +// +// // Process 16 pixels with minimal function call overhead +// for (int i = 0; i < 16; ++i) { +// // Skip transparent pixels +// if (alpha_vals[i] == 0) continue; +// +// pixelX = baseX + i; +// offset = this->getPixelOffset(pixelX, baseY); +// +// if (offset != UINT32_MAX) { +// color = {red_vals[i], green_vals[i], blue_vals[i], alpha_vals[i]}; +// +// framebuffer = static_cast(this->getCurrentFramebuffer()); +// src = Color(framebuffer[offset]); +// +// end = { +// blendColor(src.r, color.r, color.a), +// blendColor(src.g, color.g, color.a), +// blendColor(src.b, color.b, color.a), +// src.a +// }; +// +// this->setPixelAtOffset(offset, end); +// } +// } +// } +// +// // Handle remaining pixels (less than 16) +// for (; x1 < screenW; ++x1) { +// p1 = rowPtr[x1 << 1]; +// p2 = rowPtr[(x1 << 1) + 1]; +// +// setPixelBlendSrc(x + x1, baseY, { +// expand4to8[p1 >> 4], expand4to8[p1 & 0x0F], +// expand4to8[p2 >> 4], expand4to8[p2 & 0x0F] +// }); +// } +// } +// +// ult::inPlotBarrier.arrive_and_wait(); +// } + + + inline void processBMPChunk(const s32 x, const s32 y, const s32 screenW, const u8 *preprocessedData, + const s32 startRow, const s32 endRow, const u8 globalAlphaLimit) { + const s32 bytesPerRow = screenW * 2; + const s32 endX16 = screenW & ~15; + + // Create SIMD vector for alpha limit + const uint8x16_t alpha_limit_vec = vdupq_n_u8(globalAlphaLimit); + + // Pre-declare all variables outside loops + const u8 *rowPtr; + s32 baseY; + s32 x1; + const u8* ptr; + uint8x16x2_t packed; + uint8x16_t high1, low1, high2, low2; + uint8x16_t red, green, blue, alpha; + alignas(16) u8 red_vals[16], green_vals[16], blue_vals[16], alpha_vals[16]; + s32 baseX; + s32 pixelX; + u32 offset; + Color color = {0}, src = {0}, end = {0}; + const u16* framebuffer; + u8 p1, p2; + + for (s32 y1 = startRow; y1 < endRow; ++y1) { + rowPtr = preprocessedData + (y1 * bytesPerRow); + baseY = y + y1; + + x1 = 0; + + // SIMD processing for 16 pixels at once + for (; x1 < endX16; x1 += 16) { + ptr = rowPtr + (x1 << 1); + packed = vld2q_u8(ptr); + + // Expand 4-bit to 8-bit values + high1 = vshrq_n_u8(packed.val[0], 4); + low1 = vandq_u8(packed.val[0], mask_low); + high2 = vshrq_n_u8(packed.val[1], 4); + low2 = vandq_u8(packed.val[1], mask_low); + + red = vqtbl1q_u8(lut, high1); + green = vqtbl1q_u8(lut, low1); + blue = vqtbl1q_u8(lut, high2); + alpha = vqtbl1q_u8(lut, low2); + + // Apply alpha limit using SIMD min operation + alpha = vminq_u8(alpha, alpha_limit_vec); + + // Store to arrays and process individually + vst1q_u8(red_vals, red); + vst1q_u8(green_vals, green); + vst1q_u8(blue_vals, blue); + vst1q_u8(alpha_vals, alpha); + + baseX = x + x1; + + // Process 16 pixels with minimal function call overhead + for (int i = 0; i < 16; ++i) { + // Skip transparent pixels + if (alpha_vals[i] == 0) continue; + + pixelX = baseX + i; + offset = this->getPixelOffset(pixelX, baseY); + + if (offset != UINT32_MAX) { + color = {red_vals[i], green_vals[i], blue_vals[i], alpha_vals[i]}; + + framebuffer = static_cast(this->getCurrentFramebuffer()); + src = Color(framebuffer[offset]); + + end = { + blendColor(src.r, color.r, color.a), + blendColor(src.g, color.g, color.a), + blendColor(src.b, color.b, color.a), + src.a + }; + + this->setPixelAtOffset(offset, end); + } + } + } + + // Handle remaining pixels (less than 16) with pre-computed alpha limit + for (; x1 < screenW; ++x1) { + p1 = rowPtr[x1 << 1]; + p2 = rowPtr[(x1 << 1) + 1]; + + u8 alpha = expand4to8[p2 & 0x0F]; + alpha = (alpha < globalAlphaLimit) ? alpha : globalAlphaLimit; + + setPixelBlendSrc(x + x1, baseY, { + expand4to8[p1 >> 4], expand4to8[p1 & 0x0F], + expand4to8[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) { + // s32 startRow; + // + // // Divide rows among ult::renderThreads + // //s32 chunkSize = (screenH + ult::numThreads - 1) / ult::numThreads; + // for (unsigned i = 0; i < ult::numThreads; ++i) { + // startRow = i * ult::bmpChunkSize; + // //s32 endRow = std::min(startRow + ult::bmpChunkSize, screenH); + // + // // Bind the member function and create the thread + // ult::renderThreads[i] = std::thread(std::bind(&tsl::gfx::Renderer::processBMPChunk, this, x, y, screenW, preprocessedData, startRow, std::min(startRow + ult::bmpChunkSize, screenH))); + // } + // + // // Join all ult::renderThreads + // for (auto& t : ult::renderThreads) { + // t.join(); + // } + //} + + 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) { + // drawBitmapRGBA4444(0, 0, cfg::FramebufferWidth, cfg::FramebufferHeight, ult::wallpaperData.data()); + // } + // + // ult::inPlot.store(false, std::memory_order_release); + //} + + 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; + + s32 px; + + // Completely unroll small bitmaps for maximum speed + if (w <= 8 && h <= 8) [[likely]] { + // 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: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, a(c)); src += 4; + } + pixel7: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, a(c)); src += 4; + } + pixel6: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, a(c)); src += 4; + } + pixel5: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, a(c)); src += 4; + } + pixel4: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, a(c)); src += 4; + } + pixel3: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, a(c)); src += 4; + } + pixel2: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, a(c)); src += 4; + } + pixel1: { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px, rowY, a(c)); src += 4; + } + } + return; + } + + // Fallback to vectorized version for larger bitmaps + const s32 vectorWidth = w & ~7; // Process 8 pixels at a time + const s32 remainder = w & 7; + + for (s32 py = 0; py < h; ++py) { + const s32 rowY = y + py; + px = x; + + // Process 8 pixels at once (cache-friendly) + for (s32 i = 0; i < vectorWidth; i += 8) { + // Prefetch next cache line + __builtin_prefetch(src + 64, 0, 3); + + // Process 8 pixels with minimal overhead + for (int j = 0; j < 8; ++j) { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, (c)); + src += 4; + } + } + + // Handle remainder + for (s32 i = 0; i < remainder; ++i) { + const Color c = {static_cast(src[0] >> 4), static_cast(src[1] >> 4), + static_cast(src[2] >> 4), static_cast(src[3] >> 4)}; + setPixelBlendSrc(px++, rowY, (c)); + 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 + } + + //struct Glyph { + // stbtt_fontinfo *currFont; + // float currFontSize; + // int bounds[4]; + // int xAdvance; + // u8 *glyphBmp; + // int width, height; + //}; + + 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) { // NEW parameter + + // 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 { + // Need to upgrade to write lock + readLock.unlock(); + std::unique_lock writeLock(s_translationCacheMutex); + + // Double-check pattern + translatedIt = ult::translationCache.find(originalString); + if (translatedIt != ult::translationCache.end()) { + text = translatedIt->second; + } else { + ult::translationCache[originalString] = originalString; + text = originalString; + } + } + } + #else + text = originalString; + #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 (both highlight color and delimiters must be provided) + const bool highlightingEnabled = highlightColor && highlightStartChar != 0 && highlightEndChar != 0; + + // Get font metrics for consistent line height using a standard character + // This ensures consistent line spacing regardless of which specific characters are used + 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; // Changed to s32 for consistency + s32 maxY = y + lineHeight; // Initialize with at least one line height + bool inHighlight = false; + const Color* currentColor = &defaultColor; + + // Pre-declare variables used in loops to avoid repeated allocations + u32 currCharacter; + ssize_t codepointWidth; + std::shared_ptr glyph; + bool symbolProcessed; + size_t remainingLength; + u32 symChar; + ssize_t symWidth; + size_t i; + + // Main processing loop with pointer arithmetic for ASCII optimization + if (isAsciiOnly && !specialSymbols) { + // Fast ASCII-only path + for (const char* p = textPtr; p < textEnd && currX < maxWidthLimit; ++p) { + currCharacter = static_cast(*p); + + // Handle highlighting with configurable delimiters + if (highlightingEnabled) { + if (currCharacter == highlightStartChar) { + inHighlight = true; + } else if (currCharacter == highlightEndChar) { + inHighlight = false; + } + currentColor = (currCharacter == highlightStartChar || currCharacter == highlightEndChar) ? + &defaultColor : (inHighlight ? highlightColor : &defaultColor); + } + + // Handle newline + if (currCharacter == '\n') { + maxX = std::max(currX, maxX); + currX = x; + currY += lineHeight; // Use consistent line height + maxY = std::max(maxY, currY + lineHeight); // Update maxY for new line + continue; + } + + // Get glyph (now thread-safe) + // Get glyph - UPDATED to use notification cache when requested + if (useNotificationCache) { + glyph = FontManager::getOrCreateNotificationGlyph(currCharacter, monospace, fontSize); + } else { + glyph = FontManager::getOrCreateGlyph(currCharacter, monospace, fontSize); + } + if (!glyph) continue; + + // Track maximum Y position reached using consistent line height + maxY = std::max(maxY, currY + lineHeight); + + // Render if needed + if (draw && glyph->glyphBmp && currCharacter > 32) { // Space is 32 + renderGlyph(glyph, currX, currY, *currentColor); + } + + 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 + symbolProcessed = false; + if (specialSymbols) { + remainingLength = itStrEnd - itStr; + for (const auto& symbol : *specialSymbols) { + if (remainingLength >= symbol.length() && + std::equal(symbol.begin(), symbol.end(), itStr)) { + + // Process special symbol + for (i = 0; i < symbol.length(); ) { + symWidth = decode_utf8(&symChar, + reinterpret_cast(&symbol[i])); + if (symWidth <= 0) break; + + if (symChar == '\n') { + maxX = std::max(currX, maxX); + currX = x; + currY += lineHeight; // Use consistent line height + maxY = std::max(maxY, currY + lineHeight); // Update maxY for new line + } else { + glyph = FontManager::getOrCreateGlyph(symChar, monospace, fontSize); + if (glyph) { + // Track maximum Y position reached using consistent line height + maxY = std::max(maxY, currY + lineHeight); + + if (draw && glyph->glyphBmp && symChar > 32) { + renderGlyph(glyph, currX, currY, *highlightColor); + } + currX += static_cast(glyph->xAdvance * glyph->currFontSize); + } + } + i += symWidth; + } + itStr += symbol.length(); + symbolProcessed = true; + break; + } + } + } + + if (symbolProcessed) continue; + + // Decode character + if (isAsciiOnly) { + currCharacter = static_cast(*itStr); + codepointWidth = 1; + } else { + codepointWidth = decode_utf8(&currCharacter, reinterpret_cast(&(*itStr))); + if (codepointWidth <= 0) break; + } + + itStr += codepointWidth; + + // Handle highlighting with configurable delimiters + if (highlightingEnabled) { + if (currCharacter == highlightStartChar) { + inHighlight = true; + } else if (currCharacter == highlightEndChar) { + inHighlight = false; + } + currentColor = (currCharacter == highlightStartChar || currCharacter == highlightEndChar) ? + &defaultColor : (inHighlight ? highlightColor : &defaultColor); + } + + // Handle newline + if (currCharacter == '\n') { + maxX = std::max(currX, maxX); + currX = x; + currY += lineHeight; // Use consistent line height + maxY = std::max(maxY, currY + lineHeight); // Update maxY for new line + continue; + } + + // Get glyph (now thread-safe) + glyph = FontManager::getOrCreateGlyph(currCharacter, monospace, fontSize); + if (!glyph) continue; + + // Track maximum Y position reached using consistent line height + maxY = std::max(maxY, currY + lineHeight); + + // Render if needed + if (draw && glyph->glyphBmp && currCharacter > 32) { + renderGlyph(glyph, currX, currY, *currentColor); + } + + currX += static_cast(glyph->xAdvance * glyph->currFontSize); + } + } + + maxX = std::max(currX, maxX); + // Return consistent height based on proper font metrics + 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 { + // Need to upgrade to write lock + readLock.unlock(); + std::unique_lock writeLock(s_translationCacheMutex); + + // Double-check pattern + translatedIt = ult::translationCache.find(originalString); + if (translatedIt != ult::translationCache.end()) { + text = translatedIt->second; + } else { + ult::translationCache[originalString] = originalString; + 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(); + // //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; + // + // //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::LayerPosX += x; + // cfg::LayerPosY += y; + // ASSERT_FATAL(viSetLayerPosition(&this->m_layer, cfg::LayerPosX, cfg::LayerPosY)); + //} + + 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 void 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, topSeparatorColor); + if (!ult::hideWidgetBackdrop) { + drawUniformRoundedRect( + 247, 15 + 2 - 2, + (ult::extendedWidgetBackdrop + ? tsl::cfg::FramebufferWidth - 255 + : tsl::cfg::FramebufferWidth - 215), + 64 + 2, 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 + ); + } + } + } + #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) { + if (!glyph->glyphBmp || color.a == 0) return; + + const s32 xPos = static_cast(x + glyph->bounds[0]); + const s32 yPos = static_cast(y + glyph->bounds[1]); + + // Quick bounds check + if (xPos >= cfg::FramebufferWidth || yPos >= cfg::FramebufferHeight || + xPos + glyph->width <= 0 || yPos + glyph->height <= 0) return; + + // Calculate clipping + 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); + + // Move variable declarations outside loops + const s32 simdEnd = std::min(endX, (startX + 7) & ~7); + s32 bmpX; + uint8_t alpha; + s32 pixelX; + //Color tmpColor = {0}; + + // Render with optimized inner loop + const uint8_t* bmpPtr = glyph->glyphBmp + startY * glyph->width; + for (s32 bmpY = startY; bmpY < endY; ++bmpY) { + const s32 pixelY = yPos + bmpY; + bmpX = startX; + + // Process 8 pixels at once + for (; bmpX < simdEnd; ++bmpX) { + alpha = bmpPtr[bmpX] >> 4; + if (alpha) { + pixelX = xPos + bmpX; + if (alpha == 0xF) { + this->setPixel(pixelX, pixelY, color); + } else { + this->setPixelBlendDst(pixelX, pixelY, Color(color.r, color.g, color.b, alpha)); + } + } + } + + // Process remaining pixels + for (; bmpX < endX; ++bmpX) { + alpha = bmpPtr[bmpX] >> 4; + if (alpha) { + pixelX = xPos + bmpX; + if (alpha == 0xF) { + this->setPixel(pixelX, pixelY, color); + } else { + this->setPixelBlendDst(pixelX, pixelY, Color(color.r, color.g, color.b, alpha)); + } + } + } + bmpPtr += glyph->width; + } + } + + + /** + * @brief Adds the layer from screenshot and recording stacks + */ + inline void addScreenshotStacks() { + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Screenshot)); + ASSERT_FATAL(tsl::hlp::viAddToLayerStack(&this->m_layer, ViLayerStack_Recording)); + screenshotsAreDisabled = false; + } + + /** + * @brief Removes the layer from screenshot and recording stacks + */ + inline void removeScreenshotStacks() { + ASSERT_FATAL(tsl::hlp::viRemoveFromLayerStack(&this->m_layer, ViLayerStack_Screenshot)); + ASSERT_FATAL(tsl::hlp::viRemoveFromLayerStack(&this->m_layer, ViLayerStack_Recording)); + screenshotsAreDisabled = true; + } + + 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; + } + } + + // Replace divisions and modulos with bit operations - EXACT same logic + //return ((((y & 127) >> 4) + ((x >> 5) << 3) + ((y >> 7) * 112)) << 9) + // *512 = <<9 + // (((y & 15) >> 3) << 8) + // ((y % 16) / 8) * 256 + // (((x & 31) >> 4) << 7) + // ((x % 32) / 16) * 128 + // (((y & 7) >> 1) << 5) + // ((y % 8) / 2) * 32 + // (((x & 15) >> 3) << 4) + // ((x % 16) / 8) * 16 + // ((y & 1) << 3) + // (y % 2) * 8 + // (x & 7); // x % 8 + + //return ((((y & 127) >> 4) + ((x >> 5) << 3) + ((y >> 7) * (((cfg::FramebufferWidth / 2) >> 4) << 3))) << 9) + // *512 = <<9 + // (((y & 15) >> 3) << 8) + // ((y % 16) / 8) * 256 + // (((x & 31) >> 4) << 7) + // ((x % 32) / 16) * 128 + // (((y & 7) >> 1) << 5) + // ((y % 8) / 2) * 32 + // (((x & 15) >> 3) << 4) + // ((x % 16) / 8) * 16 + // ((y & 1) << 3) + // (y % 2) * 8 + // (x & 7); // x % 8 + + //return ((((y & 127) >> 4) + ((x >> 5) << 3) + ((y >> 7) * offsetWidthVar)) << 9) + // *512 = <<9 + // (((y & 15) >> 3) << 8) + // ((y % 16) / 8) * 256 + // (((x & 31) >> 4) << 7) + // ((x % 32) / 16) * 128 + // (((y & 7) >> 1) << 5) + // ((y % 8) / 2) * 32 + // (((x & 15) >> 3) << 4) + // ((x % 16) / 8) * 16 + // ((y & 1) << 3) + // (y % 2) * 8 + // (x & 7); // x % 8 + + 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); + + //const u32 y_hi = y >> 7; + //const u32 y_mid = (y >> 4) & 7; // bits 4-6 of y + //const u32 y_lo = y & 15; // bits 0-3 of y + // + //const u32 x_hi = x >> 5; // bits 5+ of x + //const u32 x_lo = x & 31; // bits 0-4 of x + // + //return ((y_mid + (x_hi << 3) + (y_hi * offsetWidthVar)) << 9) + + // ((y_lo >> 3) << 8) + ((x_lo >> 4) << 7) + + // (((y_lo & 7) >> 1) << 5) + (((x_lo & 15) >> 3) << 4) + + // ((y_lo & 1) << 3) + (x_lo & 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() { + static PlFontData stdFontData, localFontData, extFontData; + + // Nintendo's default font + TSL_R_TRY(plGetSharedFontByType(&stdFontData, PlSharedFontType_Standard)); + + u8 *fontBuffer = reinterpret_cast(stdFontData.address); + stbtt_InitFont(&this->m_stdFont, fontBuffer, stbtt_GetFontOffsetForIndex(fontBuffer, 0)); + + u64 languageCode; + if (R_SUCCEEDED(setGetSystemLanguage(&languageCode))) { + // Check if need localization font + SetLanguage setLanguage; + TSL_R_TRY(setMakeLanguage(languageCode, &setLanguage)); + this->m_hasLocalFont = true; + switch (setLanguage) { + case SetLanguage_ZHCN: + case SetLanguage_ZHHANS: + TSL_R_TRY(plGetSharedFontByType(&localFontData, PlSharedFontType_ChineseSimplified)); + break; + case SetLanguage_KO: + TSL_R_TRY(plGetSharedFontByType(&localFontData, PlSharedFontType_KO)); + break; + case SetLanguage_ZHTW: + case SetLanguage_ZHHANT: + TSL_R_TRY(plGetSharedFontByType(&localFontData, PlSharedFontType_ChineseTraditional)); + 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 + // Check if rendering is active by testing if the stop event is NOT signaled + if (isRendering) { // Returns true if event is signaled + memcpy(this->getNextFramebuffer(), this->getCurrentFramebuffer(), this->getFramebufferSize()); + + static u32 lastFPS = 0; + static u64 cachedIntervalNs = 0; + + if (__builtin_expect(TeslaFPS != lastFPS, 0)) { // Hint: FPS changes are rare + cachedIntervalNs = 1000*1000*1000ULL / TeslaFPS; + lastFPS = TeslaFPS; + } + + // Wait for frame interval or rendering stop event + leventWait(&renderingStopEvent, cachedIntervalNs); + } + #endif + this->waitForVSync(); + framebufferEnd(&this->m_framebuffer); + this->m_currentFramebuffer = nullptr; + if (tsl::clearGlyphCacheNow.load(std::memory_order_acquire)) { + tsl::clearGlyphCacheNow.store(false, std::memory_order_release); + tsl::gfx::FontManager::clearCache(); // exclusive clear + } + } + + + }; + + 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 + } + + /** + * @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 = (std::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; + if (t_ns >= 100000000) // 100ms in nanoseconds + this->m_highlightShaking = false; + else { + // Use faster random generation if available, or cache amplitude + static int cachedAmplitude = std::rand() % 5 + 5; + if (t_ns % 10000000 == 0) // Update amplitude less frequently + cachedAmplitude = std::rand() % 5 + 5; + amplitude = cachedAmplitude; + + const int shakeOffset = shakeAnimation(t_ns, amplitude); + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: y = -shakeOffset; break; + case FocusDirection::Down: y = shakeOffset; break; + case FocusDirection::Left: x = -shakeOffset; break; + case FocusDirection::Right: x = shakeOffset; break; + default: break; + } + + x = std::clamp(x, -amplitude, amplitude); + y = std::clamp(y, -amplitude, amplitude); + } + } + + 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 = (std::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; + if (t_ns >= 100000000) // 100ms in nanoseconds + this->m_highlightShaking = false; + else { + // Use cached amplitude like in drawClickAnimation + static int cachedAmplitude = std::rand() % 5 + 5; + if (t_ns % 10000000 == 0) + cachedAmplitude = std::rand() % 5 + 5; + amplitude = cachedAmplitude; + + const int shakeOffset = shakeAnimation(t_ns, amplitude); + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: y = -shakeOffset; break; + case FocusDirection::Down: y = shakeOffset; break; + case FocusDirection::Left: x = -shakeOffset; break; + case FocusDirection::Right: x = shakeOffset; break; + default: break; + } + + x = std::clamp(x, -amplitude, amplitude); + y = std::clamp(y, -amplitude, amplitude); + } + } + + 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 + //float activePercentage = 0.0f; + //if (ult::downloadPercentage > 0) { + // activePercentage = ult::downloadPercentage; + //} else if (ult::unzipPercentage > 0) { + // activePercentage = ult::unzipPercentage; + //} else if (ult::copyPercentage > 0) { + // activePercentage = ult::copyPercentage; + //} + 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; + } + + 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; }; + }; + + //static std::vector m_lastFrameItems; // for smooth handling of jumpToItem navigation + //static bool m_hasValidFrame = false; + //static float m_lastFrameOffset = 0.0f; + // Static cache with instance validation + + //#if IS_STATUS_MONITOR_DIRECTIVE + // /** + // * @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) {} + // virtual ~CustomDrawer() { + // m_isTable = true; + // } + // + // virtual void draw(gfx::Renderer* renderer) override { + // this->m_renderFunc(renderer, this->getX(), this->getY(), this->getWidth(), this->getHeight()); + // } + // + // virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override {} + // + // private: + // std::function m_renderFunc; + // }; + //#else + /** + * @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, 10.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; + }; + + + /** + * @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}; + static constexpr double cycleDuration = 1.6; + float counter = 0; + float countOffset; + float progress; + 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; + } + + ~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.load(std::memory_order_acquire)) { + ult::themeIsInitialized.store(true, std::memory_order_release); + 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); + } + + const bool isUltrahandMenu = (m_title == ult::CAPITAL_ULTRAHAND_PROJECT_NAME && + m_subtitle.find("Ultrahand Package") == std::string::npos && + m_subtitle.find("Ultrahand Script") == std::string::npos); + + if (isUltrahandMenu) { + #if USING_WIDGET_DIRECTIVE + renderer->drawWidget(); + #endif + + if (ult::touchingMenu.load(std::memory_order_acquire) && ult::inMainMenu.load(std::memory_order_acquire)) { + renderer->drawRoundedRect(0.0f + 7, 12.0f, 245.0f - 13, 73.0f, 10.0f, a(clickColor)); + } + + x = 20; + fontSize = 42; + offset = 6; + countOffset = 0; + + if (ult::useDynamicLogo) { + const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); + + // High precision time calculation to prevent stepping artifacts + const double currentTimeCount = static_cast(currentTime_ns) / 1000000000.0; + + // Pre-calculate time base once per frame for consistent wave sync + const double timeBase = std::fmod(currentTimeCount, cycleDuration); + + // Pre-calculate wave constants - NOW MATCHES CYCLE DURATION + const double waveScale = 2.0 * ult::_M_PI / cycleDuration; + static constexpr double phaseShift = ult::_M_PI / 2.0; + + for (const char letter : ult::SPLIT_PROJECT_NAME_1) { + // Smooth, precise wave calculation + const double wavePhase = waveScale * (timeBase + static_cast(countOffset)); + const double rawProgress = std::cos(wavePhase - phaseShift); + + // Apply double smoothstep for ultra-smooth color transitions + const double normalizedProgress = (rawProgress + 1.0) * 0.5; // Convert to 0-1 + const double smoothedProgress = normalizedProgress * normalizedProgress * (3.0 - 2.0 * normalizedProgress); + // Apply smoothstep again for even smoother transitions + const double ultraSmoothProgress = smoothedProgress * smoothedProgress * (3.0 - 2.0 * smoothedProgress); + + // Pure floating point interpolation - no dithering to eliminate flicker + const double blend = std::max(0.0, std::min(1.0, ultraSmoothProgress)); + + // High precision floating point color interpolation + 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); + x += renderer->drawString(letterStr, false, x, y + offset, fontSize, highlightColor).first; + countOffset -= static_cast(cycleDuration / 8.0); + } + } 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 (m_showWidget) + renderer->drawWidget(); + + x = 20; + y = 52 -2; + fontSize = 32; + + if (m_subtitle.find("Ultrahand Script") != std::string::npos) { + renderer->drawString(m_title, false, x, y, fontSize, (defaultScriptColor)); + } else { + titleColor = defaultPackageColor; // Default to green + + // Ultra-fast color selection using first character optimization + if (!m_colorSelection.empty()) { + const char firstChar = m_colorSelection[0]; + const size_t len = m_colorSelection.length(); + + // Fast path: check first char + length for unique combinations + switch (firstChar) { + case 'g': // green + if (len == 5 && m_colorSelection == "green") { + titleColor = {0x0, 0xF, 0x0, 0xF}; + } + break; + case 'r': // red + if (len == 3 && m_colorSelection == "red") { + titleColor = RGB888("#F7253E"); + } + break; + case 'b': // blue + if (len == 4 && m_colorSelection == "blue") { + titleColor = {0x7, 0x7, 0xF, 0xF}; + } + break; + case 'y': // yellow + if (len == 6 && m_colorSelection == "yellow") { + titleColor = {0xF, 0xF, 0x0, 0xF}; + } + break; + case 'o': // orange + if (len == 6 && m_colorSelection == "orange") { + titleColor = {0xFF, 0xA5, 0x00, 0xFF}; + } + break; + case 'p': // pink or purple + if (len == 4 && m_colorSelection == "pink") { + titleColor = {0xFF, 0x69, 0xB4, 0xFF}; + } else if (len == 6 && m_colorSelection == "purple") { + titleColor = {0x80, 0x00, 0x80, 0xFF}; + } + break; + case 'w': // white + if (len == 5 && m_colorSelection == "white") { + titleColor = {0xF, 0xF, 0xF, 0xF}; + } + break; + case 'u': // ultra + if (len == 5 && m_colorSelection == "ultra") { + for (const char letter : m_title) { + progress = ult::calculateAmplitude(counter - x * 0.0001F); + + const tsl::Color highlightColor = { + static_cast((0xA - 0xF) * (3 - 1.5 * progress) + 0xF), + static_cast((0xA - 0xF) * 1.5 * progress + 0xF), + static_cast((0xA - 0xF) * (1.25 - progress) + 0xF), + 0xF + }; + + const std::string letterStr(1, letter); + renderer->drawString(letterStr.c_str(), false, x, y, fontSize, (highlightColor)); + const auto letterWidth = renderer->getTextDimensions(letterStr, false, fontSize).first; + x += letterWidth; + counter -= 0.00004F; + } + goto skip_normal_draw; + } + break; + case '#': // hex color + if (len == 7 && ult::isValidHexColor(m_colorSelection.substr(1))) { + titleColor = RGB888(m_colorSelection.substr(1)); + } + break; + } + } + + renderer->drawString(m_title, false, x, y, fontSize, (titleColor)); + y += 2; + skip_normal_draw:; + } + } + static const std::vector specialChars2 = {""}; + if (m_title == ult::CAPITAL_ULTRAHAND_PROJECT_NAME) { + renderer->drawStringWithColoredSections(ult::versionLabel, false, specialChars2, 20, y+25, 15, (bannerVersionTextColor), textSeparatorColor); + } else { + std::string subtitle = m_subtitle; + const size_t pos = subtitle.find("?Ultrahand Script"); + if (pos != std::string::npos) { + subtitle.erase(pos, 17); // "?Ultrahand Script".length() = 17 + } + renderer->drawStringWithColoredSections(subtitle, false, specialChars2, 20, y+23, 15, (bannerVersionTextColor), textSeparatorColor); + } + + #else + if (m_noClickableItems != ult::noClickableItems.load(std::memory_order_acquire)) { + ult::noClickableItems.store(m_noClickableItems, std::memory_order_release); + } + #if USING_WIDGET_DIRECTIVE + if (m_showWidget) + renderer->drawWidget(); + #endif + + renderer->drawString(m_title, false, 20, 52-2, 32, (defaultOverlayColor)); + renderer->drawString(m_subtitle, false, 20, y+2+23+2, 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 / 2.0f; + 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, 10.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, 10.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, 10.0f, a(clickColor)); + } + } + #endif + + + #if IS_LAUNCHER_DIRECTIVE + + const std::string menuBottomLine = + "\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 menuBottomLine = + "\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 specialChars = {"\uE0E1","\uE0E0","\uE0ED","\uE0EE","\uE0E5"}; + renderer->drawStringWithColoredSections(menuBottomLine, false, specialChars, + 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 / 1000000000.0; + 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 auto whiteColor = tsl::Color(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) { + m_title = title; + } + + /** + * @brief Changes the subtitle of the menu + * + * @param title Subtitle to change to + */ + inline void setSubtitle(const std::string &subtitle) { + m_subtitle = subtitle; + } + + protected: + Element *m_contentElement = nullptr; + }; + + #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(180'000); // sleep thread for initial values to auto-load + + m_isItem = false; + } + + virtual ~HeaderOverlayFrame() { + if (this->m_contentElement != nullptr) + delete this->m_contentElement; + } + + + virtual void draw(gfx::Renderer *renderer) override { + if (!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)); + renderer->drawWallpaper(); + } else { + renderer->fillScreen({ 0x0, 0x0, 0x0, 0x0}); + } + + y = 50; + offset = 0; + + renderer->drawString(this->m_title, false, 20, 50, 32, (defaultOverlayColor)); + renderer->drawString(this->m_subtitle, false, 20, y+2+23+2, 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 + static const auto gapWidth = renderer->getTextDimensions(ult::GAP_1, false, 23).first; + static 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 + static const auto backTextWidth = renderer->getTextDimensions("\uE0E1" + ult::GAP_2 + ult::BACK, false, 23).first; + static 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 + static const float _backWidth = backTextWidth + gapWidth; + if (_backWidth != ult::backWidth.load(std::memory_order_acquire)) + ult::backWidth.store(_backWidth, std::memory_order_release); + static const float _selectWidth = selectTextWidth + gapWidth; + if (_selectWidth != ult::selectWidth.load(std::memory_order_acquire)) + ult::selectWidth.store(_selectWidth, std::memory_order_release); + + static 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, 10.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, 10.0f, a(clickColor)); + } + } + + // Render the text with special character handling + if (!deactivateOriginalFooter) { + const std::string menuBottomLine = + "\uE0E1" + ult::GAP_2 + ult::BACK + ult::GAP_1 + + (!m_noClickableItems + ? "\uE0E0" + ult::GAP_2 + ult::OK + ult::GAP_1 + : ""); + 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)); + } + } + + + + 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.load(std::memory_order_acquire)) { + ult::themeIsInitialized.store(true, std::memory_order_release); + 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, 10.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, 10.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::mutex s_lastFrameItemsMutex; + static std::vector s_lastFrameItems; + static std::atomic s_isForwardCache(false); // NEW VARIABLE FOR FORWARD CACHING + static std::atomic s_hasValidFrame(false); + static std::atomic s_cachedTopBound{0}; + static std::atomic s_cachedBottomBound{0}; + static std::atomic s_cachedHeight{0}; + static std::atomic s_cachedListHeight{0}; + static std::atomic s_cachedActualContentBottom{0}; + static std::atomic s_shouldDrawScrollbar(false); + static std::atomic s_cachedScrollbarHeight{0}; + static std::atomic s_cachedScrollbarOffset{0}; + static std::atomic s_cachedScrollbarX{0}; + static std::atomic s_cachedScrollbarY{0}; + static std::atomic s_currentScrollVelocity{0}; + + static std::atomic s_directionalKeyReleased{false}; + static std::atomic s_cacheForwardFrameOnce(true); + static std::atomic lastInternalTouchRelease(true); + static std::atomic s_hasClearedCache(false); + + //static std::atomic s_skipCaching(false); + + static std::mutex s_safeToSwapMutex; + //static std::mutex s_safeTransitionMutex; + static std::atomic s_safeToSwap{false}; + + static std::atomic fullDeconstruction{false}; + static std::atomic skipDeconstruction{false}; + static std::atomic skipOnce{false}; + + static std::atomic isTableScrolling{false}; + + class List : public Element { + + public: + List() : Element() { + if (fullDeconstruction.load(std::memory_order_acquire)) { + return; + } + + s_safeToSwap.store(false, std::memory_order_release); + //s_directionalKeyReleased.store(false, std::memory_order_release); + //std::lock_guard lock(s_safeTransitionMutex); + //s_safeToSwap.store(false, std::memory_order_release); + + // Initialize instance state + m_hasForwardCached = false; + 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; + + { + std::lock_guard lock(s_lastFrameItemsMutex); + + s_hasClearedCache.store(false, std::memory_order_release); + + if (skipDeconstruction.load(std::memory_order_acquire)) { + purgePendingItems(); + } else { + s_cacheForwardFrameOnce.store(true, std::memory_order_release); + skipOnce.store(false, std::memory_order_release); + } + } + } + + virtual ~List() { + if (fullDeconstruction.load(std::memory_order_acquire)) { + std::lock_guard lock(s_lastFrameItemsMutex); // Add this + + purgePendingItems(); + + if (s_isForwardCache.load(std::memory_order_acquire)) { + clearStaticCacheUnsafe(true); + s_isForwardCache.store(false, std::memory_order_release); + } else { + clearStaticCacheUnsafe(); + } + clearItems(); + + return; + } + + s_safeToSwap.store(false, std::memory_order_release); + //s_directionalKeyReleased.store(false, std::memory_order_release); + //std::lock_guard lock(s_safeTransitionMutex); + //s_safeToSwap.store(false, std::memory_order_release); + + // NOW take mutex for shared static variable operations + { + std::lock_guard lock(s_lastFrameItemsMutex); + + if (!skipDeconstruction.load(std::memory_order_acquire)) { + purgePendingItems(); + + if (!s_isForwardCache.load(std::memory_order_acquire)) { + clearStaticCacheUnsafe(); + clearItems(); + } + + s_isForwardCache.store(false, std::memory_order_release); + s_cacheForwardFrameOnce.store(true, std::memory_order_release); + } + + if (m_cachingDisabled || (skipOnce.load(std::memory_order_acquire) && skipDeconstruction.load(std::memory_order_acquire))) { + purgePendingItems(); + clearItems(); + } else if (skipDeconstruction.load(std::memory_order_acquire)) { + skipOnce.store(true, std::memory_order_release); + } + } + } + + + virtual void draw(gfx::Renderer* renderer) override { + if (fullDeconstruction.load(std::memory_order_acquire)) { + return; + } + + s_safeToSwap.store(false, std::memory_order_release); + std::lock_guard lock(s_safeToSwapMutex); + //s_safeToSwap.store(false, std::memory_order_release); + + // Early exit optimizations + if (m_clearList) { + if (!s_isForwardCache.load(std::memory_order_acquire)) { + clearStaticCacheUnsafe(); + + } else { + clearStaticCacheUnsafe(true); + } + clearItems(); + s_isForwardCache.store(false, std::memory_order_release); + s_cacheForwardFrameOnce.store(true, std::memory_order_release); + return; + } + { + std::lock_guard lock(s_lastFrameItemsMutex); + // Process pending operations in batch + if (!m_itemsToAdd.empty()) addPendingItems(); + if (!m_itemsToRemove.empty()) removePendingItems(); + } + + // Only lock when checking s_lastFrameItems.empty() + bool shouldResetCache = false; + { + std::lock_guard lock(s_lastFrameItemsMutex); + if (!s_hasValidFrame.load(std::memory_order_acquire) && s_lastFrameItems.empty() && + !s_cacheForwardFrameOnce.load(std::memory_order_acquire)) { + shouldResetCache = true; + } + } + + if (shouldResetCache) { + s_cacheForwardFrameOnce.store(true, std::memory_order_release); + } + + // This part is for fixing returning to Ultrahand without rendering that first frame skip + static bool checkOnce = true; + if (checkOnce && m_pendingJump && !s_hasValidFrame.load(std::memory_order_acquire) && + !s_isForwardCache.load(std::memory_order_acquire)) { + checkOnce = false; + return; + } else { + static bool checkOnce2 = true; + if (checkOnce2) { + checkOnce = true; + checkOnce2 = false; + } + } + + // Check if we should render cached frame + if ((m_pendingJump || !m_hasForwardCached) && + (s_hasValidFrame.load(std::memory_order_acquire) || s_isForwardCache.load(std::memory_order_acquire))) { + { + std::lock_guard lock(s_lastFrameItemsMutex); + // Render using cached frame state if available + renderCachedFrame(renderer); // This method handles its own locking + + // Clear cache after rendering + if (s_isForwardCache.load(std::memory_order_acquire)) + clearStaticCacheUnsafe(true); // This method handles its own locking + else + clearStaticCacheUnsafe(); // This method handles its own locking + } + + return; + } + + // Cache bounds for hot loop + const s32 topBound = getTopBound(); + const s32 bottomBound = getBottomBound(); + const s32 height = getHeight(); + + renderer->enableScissoring(getLeftBound(), topBound-8, getWidth() + 8, height + 14); + + { + std::lock_guard lock(s_lastFrameItemsMutex); + // Optimized visibility culling + for (Element* entry : m_items) { + if (entry->getBottomBound() > topBound && entry->getTopBound() < bottomBound) { + entry->frame(renderer); + } + } + } + + renderer->disableScissoring(); + + // Draw scrollbar only when needed + if (m_listHeight > height) { + drawScrollbar(renderer, height); + updateScrollAnimation(); + } + + // Handle caching operations - lock only for the critical section + { + std::lock_guard lock(s_lastFrameItemsMutex); + + if (!s_isForwardCache.load(std::memory_order_acquire) && s_hasValidFrame.load(std::memory_order_acquire)) { + // Clear cache after rendering (this is called within the lock) + clearStaticCacheUnsafe(); // New unsafe version for use within lock + s_hasValidFrame.store(false, std::memory_order_release); + s_cacheForwardFrameOnce.store(true, std::memory_order_release); + } + + if (!m_cachingDisabled) { + if (s_cacheForwardFrameOnce.load(std::memory_order_acquire) && + !s_hasValidFrame.load(std::memory_order_acquire)) { + // Cache current frame (this is called within the lock) + cacheCurrentFrameUnsafe(true); // New unsafe version for use within lock + s_cacheForwardFrameOnce.store(false, std::memory_order_release); + s_isForwardCache.store(true, std::memory_order_release); + s_hasValidFrame.store(true, std::memory_order_release); + m_hasForwardCached = true; + } + cacheCurrentScrollbar(); + } + + //if (m_cachingDisabled ||(s_hasValidFrame.load(std::memory_order_acquire) && s_isForwardCache.load(std::memory_order_acquire))) + // s_safeToSwap.store(true, std::memory_order_release); + } + s_safeToSwap.store(true, std::memory_order_release); + } + + + 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; + + static bool delayedHandle = false; + + // NEW: Handle pending jump to specific item + if (m_pendingJump && !delayedHandle) { + delayedHandle = true; + return handleJumpToItem(oldFocus); + } else if (m_pendingJump) { + m_pendingJump = false; + delayedHandle = false; + return handleJumpToItem(oldFocus); // needs to be handled 2x for proper rendering + } + + if (jumpToBottom.load(std::memory_order_acquire)) { + jumpToBottom.store(false, std::memory_order_release); + return handleJumpToBottom(oldFocus); + } + if (jumpToTop.load(std::memory_order_acquire)) { + jumpToTop.store(false, std::memory_order_release); + return handleJumpToTop(oldFocus); + } + if (skipDown.load(std::memory_order_acquire)) { + skipDown.store(false, std::memory_order_release); + return handleSkipDown(oldFocus); + } + if (skipUp.load(std::memory_order_acquire)) { + skipUp.store(false, std::memory_order_release); + 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; + //else + // m_pendingJump = false; + //if (g_overlayFilename == "ovlmenu.ovl") return; + 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_lastNavigationTime = 0; + m_lastScrollTime = 0; + } + + inline void disableCaching() { + m_cachingDisabled = 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_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; + + //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: + // Method to explicitly preserve cache when navigating away + //void preserveCacheForReturn() { + // if (m_instanceId == s_cachedInstanceId && s_hasValidFrame) { + // // Cache is already preserved for this instance + // return; + // } + // cacheCurrentFrame(); + //} + + // Method to check if this instance has a valid cached frame + //bool hasCachedFrame() const { + // return s_hasValidFrame && s_cachedInstanceId == m_instanceId; + //} + + //static size_t generateInstanceId() { + // return s_nextInstanceId++; + //} + + // Thread-safe versions (handle their own locking) + static void clearStaticCache(bool preservePointers = false) { + std::lock_guard lock(s_lastFrameItemsMutex); + clearStaticCacheUnsafe(preservePointers); + } + + void cacheCurrentFrame(bool preservePointers = false) { + std::lock_guard lock(s_lastFrameItemsMutex); + cacheCurrentFrameUnsafe(preservePointers); + } + + + static void clearStaticCacheUnsafe(bool preservePointers = false) { + //std::lock_guard lock(s_lastFrameItemsMutex); + if (!preservePointers) { + // Normal case: delete elements and clear + for (Element* el : s_lastFrameItems) { + delete el; + } + } + + s_lastFrameItems.clear(); + //s_lastFrameItems.shrink_to_fit(); + + // CRITICAL: Always reset these, even for forward cache! + s_hasValidFrame.store(false, std::memory_order_release); // This MUST be false after clearing + s_isForwardCache.store(false, std::memory_order_release); + + s_cachedTopBound.store(0, std::memory_order_release); + s_cachedBottomBound.store(0, std::memory_order_release); + s_cachedHeight.store(0, std::memory_order_release); + s_cachedListHeight.store(0, std::memory_order_release); + s_cachedActualContentBottom.store(0, std::memory_order_release); + + s_shouldDrawScrollbar.store(false, std::memory_order_release); + s_cachedScrollbarHeight.store(0, std::memory_order_release); + s_cachedScrollbarOffset.store(0, std::memory_order_release); + s_cachedScrollbarX.store(0, std::memory_order_release); + s_cachedScrollbarY.store(0, std::memory_order_release); + } + + void cacheCurrentFrameUnsafe(bool preservePointers = false) { + //std::lock_guard lock(s_lastFrameItemsMutex); + if (!preservePointers) { + for (Element* el : s_lastFrameItems) delete el; + } + + s_lastFrameItems = m_items; + + // Store new cache values using atomic stores + s_cachedTopBound.store(getTopBound(), std::memory_order_release); + s_cachedBottomBound.store(getBottomBound(), std::memory_order_release); + s_cachedHeight.store(getHeight(), std::memory_order_release); + s_cachedListHeight.store(m_listHeight, std::memory_order_release); + + if (preservePointers) + s_isForwardCache.store(true, std::memory_order_release); + + s_hasValidFrame.store(true, std::memory_order_release); + } + + void cacheCurrentScrollbar() { + const s32 cachedHeight = s_cachedHeight.load(std::memory_order_acquire); + const s32 cachedListHeight = s_cachedListHeight.load(std::memory_order_acquire); + + s_shouldDrawScrollbar.store((cachedListHeight > cachedHeight), std::memory_order_release); + + if (s_shouldDrawScrollbar.load(std::memory_order_acquire)) { + const float viewHeight = static_cast(cachedHeight); + const float totalHeight = static_cast(cachedListHeight); + const u32 maxScroll = std::max(static_cast(totalHeight - viewHeight), 1u); + + u32 scrollbarHeight = std::min( + static_cast((viewHeight * viewHeight) / totalHeight), + static_cast(viewHeight) + ); + + u32 scrollbarOffset = std::min( + static_cast((m_offset / maxScroll) * (viewHeight - scrollbarHeight)), + static_cast(viewHeight - scrollbarHeight) // corrected potential bug + ); + + scrollbarHeight -= SCROLLBAR_HEIGHT_TRIM; + + s_cachedScrollbarHeight.store(scrollbarHeight, std::memory_order_release); + s_cachedScrollbarOffset.store(scrollbarOffset, std::memory_order_release); + s_cachedScrollbarX.store(getRightBound() + SCROLLBAR_X_OFFSET, std::memory_order_release); + s_cachedScrollbarY.store(getY() + scrollbarOffset + SCROLLBAR_Y_OFFSET, std::memory_order_release); + } + } + + void renderCachedFrame(gfx::Renderer* renderer) { + const s32 cachedTopBound = s_cachedTopBound.load(std::memory_order_acquire); + const s32 cachedBottomBound = s_cachedBottomBound.load(std::memory_order_acquire); + const s32 cachedHeight = s_cachedHeight.load(std::memory_order_acquire); + + renderer->enableScissoring(getLeftBound(), cachedTopBound - 8, getWidth() + 8, cachedHeight + 14); + + for (Element* entry : s_lastFrameItems) { + if (entry && + entry->getBottomBound() > cachedTopBound && + entry->getTopBound() < cachedBottomBound) { + entry->frame(renderer); + } + } + + renderer->disableScissoring(); + + if (s_shouldDrawScrollbar.load(std::memory_order_acquire)) { + const u32 scrollbarX = s_cachedScrollbarX.load(std::memory_order_acquire); + const u32 scrollbarY = s_cachedScrollbarY.load(std::memory_order_acquire); + const u32 scrollbarHeight = s_cachedScrollbarHeight.load(std::memory_order_acquire); + + renderer->drawRect(scrollbarX, scrollbarY, 5, scrollbarHeight, a(trackBarColor)); + renderer->drawCircle(scrollbarX + 2, scrollbarY, 2, true, a(trackBarColor)); + renderer->drawCircle(scrollbarX + 2, scrollbarY + scrollbarHeight, 2, true, a(trackBarColor)); + } + } + + + void clearItems() { + //std::lock_guard lock(s_lastFrameItemsMutex); + // Clear static cache if it belongs to this instance + //if (s_cachedInstanceId == m_instanceId) { + // clearStaticCache(); + //} + + 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; + } + + void addPendingItems() { + 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 = {}; + //m_itemsToAdd.clear(); + //m_itemsToAdd.shrink_to_fit(); + 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; // shorten very slightly + + renderer->drawRect(scrollbarX, scrollbarY, 5, scrollbarHeight, a(trackBarColor)); + renderer->drawCircle(scrollbarX + 2, scrollbarY, 2, true, a(trackBarColor)); + renderer->drawCircle(scrollbarX + 2, scrollbarY + scrollbarHeight, 2, true, a(trackBarColor)); + } + + + 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) { + float emergencySpeed = 0.6f; + + if (itemBottom < m_offset || itemTop > viewBottom) { + emergencySpeed = 0.9f; + } + + 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) { + itemHeight = m_items[i]->getHeight(); + 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 Element* handleDownFocus(Element* oldFocus) { + static bool triggerShakeOnce = true; + updateHoldState(); + + // Check if the next item is non-focusable BEFORE we do anything else + if (m_focusedIndex + 1 < int(m_items.size())) { + Element* nextItem = m_items[m_focusedIndex + 1]; + if (!nextItem->m_isItem) { + isTableScrolling.store(true, std::memory_order_release); // Set this IMMEDIATELY + } + } + + // If holding and at boundary, try to scroll first + if (m_isHolding && m_stoppedAtBoundary && !isAtBottom()) { + scrollDown(); + m_stoppedAtBoundary = false; + return oldFocus; + } + + Element* result = navigateDown(oldFocus); + + if (result != oldFocus) { + m_lastNavigationResult = NavigationResult::Success; + m_stoppedAtBoundary = false; + triggerShakeOnce = true; + return result; + } + + // Check if we can still scroll down + if (!isAtBottom()) { + scrollDown(); + return oldFocus; + } + + // At absolute bottom - check for wrapping + if (!m_isHolding && !m_hasWrappedInCurrentSequence && isAtBottom()) { + //if (s_directionalKeyReleased.load(std::memory_order_acquire)) { + // s_directionalKeyReleased.store(false, std::memory_order_release); + // m_hasWrappedInCurrentSequence = true; + // m_lastNavigationResult = NavigationResult::Wrapped; + // triggerShakeOnce = true; // Reset when wrapping + // return handleJumpToTop(oldFocus); + //} else + // s_directionalKeyReleased.store(false, std::memory_order_release); + + s_directionalKeyReleased.store(false, std::memory_order_release); + m_hasWrappedInCurrentSequence = true; + m_lastNavigationResult = NavigationResult::Wrapped; + triggerShakeOnce = true; // Reset when wrapping + return handleJumpToTop(oldFocus); + } + + // Set boundary flag + if (m_isHolding) { + m_stoppedAtBoundary = true; + if (triggerShakeOnce) { + // Find the last focusable item to shake + for (ssize_t i = static_cast(m_focusedIndex); i >= 0; --i) { + if (m_items[i]->m_isItem) { + m_items[i]->shakeHighlight(FocusDirection::Down); + break; + } + } + triggerShakeOnce = false; + } + } else + triggerShakeOnce = true; + + m_lastNavigationResult = NavigationResult::HitBoundary; + return oldFocus; + } + + inline Element* handleUpFocus(Element* oldFocus) { + static bool triggerShakeOnce = true; + updateHoldState(); + + // Check if the previous item is non-focusable BEFORE we do anything else + if (m_focusedIndex > 0) { + Element* prevItem = m_items[m_focusedIndex - 1]; + if (prevItem->isTable()) { + isTableScrolling.store(true, std::memory_order_release); // Set this IMMEDIATELY + } + } + + // If holding and at boundary, try to scroll first + if (m_isHolding && m_stoppedAtBoundary && !isAtTop()) { + scrollUp(); + m_stoppedAtBoundary = false; + return oldFocus; + } + + Element* result = navigateUp(oldFocus); + + if (result != oldFocus) { + m_lastNavigationResult = NavigationResult::Success; + m_stoppedAtBoundary = false; + triggerShakeOnce = true; + return result; + } + + // Check if we can still scroll up + if (!isAtTop()) { + scrollUp(); + return oldFocus; + } + + // At absolute top - check for wrapping + if (!m_isHolding && !m_hasWrappedInCurrentSequence && isAtTop()) { + //if (s_directionalKeyReleased.load(std::memory_order_acquire)) { + // s_directionalKeyReleased.store(false, std::memory_order_release); + // m_hasWrappedInCurrentSequence = true; + // m_lastNavigationResult = NavigationResult::Wrapped; + // triggerShakeOnce = true; // Reset when wrapping + // return handleJumpToBottom(oldFocus); + //} else + // s_directionalKeyReleased.store(false, std::memory_order_release); + + s_directionalKeyReleased.store(false, std::memory_order_release); + m_hasWrappedInCurrentSequence = true; + m_lastNavigationResult = NavigationResult::Wrapped; + triggerShakeOnce = true; // Reset when wrapping + return handleJumpToBottom(oldFocus); + } + + // Set boundary flag + if (m_isHolding) { + m_stoppedAtBoundary = true; + if (triggerShakeOnce) { + // Find the first focusable item to shake + for (size_t i = m_focusedIndex; i < m_items.size(); ++i) { + if (m_items[i]->m_isItem) { + m_items[i]->shakeHighlight(FocusDirection::Up); + break; + } + } + triggerShakeOnce = false; + } + } else + triggerShakeOnce = true; + + m_lastNavigationResult = NavigationResult::HitBoundary; + 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; + } + + inline void resetNavigationState() { + m_hasWrappedInCurrentSequence = false; + m_lastNavigationResult = NavigationResult::None; + m_isHolding = false; + m_stoppedAtBoundary = 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); + } + + // Add these methods to handle jumps with smooth scrolling + Element* handleJumpToBottom(Element* oldFocus) { + if (m_items.empty()) return oldFocus; + + invalidate(); + resetNavigationState(); + jumpToBottom.store(false, std::memory_order_release); // Reset flag + + // Calculate target offset once (good optimization to keep) + const float targetOffset = (m_listHeight > getHeight()) ? + static_cast(m_listHeight - getHeight()) : 0.0f; + static constexpr float tolerance = 5.0f; + + // Find the 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; + } + } + + // Check if we're already at the bottom with proper tolerance + bool alreadyAtBottom = false; + if (lastFocusableIndex < m_items.size()) { + alreadyAtBottom = (m_focusedIndex == lastFocusableIndex) && + (std::abs(m_nextOffset - targetOffset) <= tolerance); + } + + if (alreadyAtBottom) { + return oldFocus; // Already at bottom, do nothing + } + + // Not at bottom - perform the jump using SAME logic as wrapToBottom + if (lastFocusableIndex < m_items.size()) { + m_focusedIndex = lastFocusableIndex; + m_nextOffset = targetOffset; // Use same calculation as wrapToBottom + + Element* newFocus = m_items[lastFocusableIndex]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus) { + return newFocus; + } + } + + // No focusable items - just set target to bottom (same as wrapToBottom) + m_nextOffset = targetOffset; + return oldFocus; + } + + Element* handleJumpToTop(Element* oldFocus) { + if (m_items.empty()) return oldFocus; + + invalidate(); + resetNavigationState(); + jumpToTop.store(false, std::memory_order_release); // Reset flag + + // Define constants for clarity and consistency + static constexpr float targetOffset = 0.0f; + static constexpr float tolerance = 0.0f; + + // Find the first focusable item + size_t firstFocusableIndex = m_items.size(); // Default to invalid + for (size_t i = 0; i < m_items.size(); ++i) { + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test) { + firstFocusableIndex = i; + break; + } + } + + // Check if we're already at the top with proper tolerance + bool alreadyAtTop = false; + if (firstFocusableIndex < m_items.size()) { + alreadyAtTop = (m_focusedIndex == firstFocusableIndex) && + (std::abs(m_nextOffset - targetOffset) <= tolerance); + } + + if (alreadyAtTop) { + return oldFocus; // Already at top, do nothing + } + + // Not at top - perform the jump using SAME logic as wrapToTop + if (firstFocusableIndex < m_items.size()) { + m_focusedIndex = firstFocusableIndex; + m_nextOffset = targetOffset; // Same as wrapToTop + + Element* newFocus = m_items[firstFocusableIndex]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus) { + return newFocus; + } + } + + // No focusable items - just set target to top (same as wrapToTop) + m_nextOffset = targetOffset; + return oldFocus; + } + + Element* handleSkipDown(Element* oldFocus) { + if (m_items.empty()) return oldFocus; + + invalidate(); + resetNavigationState(); + + // Calculate target offset once (good optimization to keep) + const float targetOffset = (m_listHeight > getHeight()) ? + static_cast(m_listHeight - getHeight()) : 0.0f; + static constexpr float tolerance = 0.0f; + + // Find the 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; + } + } + + // Check if we're already at the bottom with proper tolerance + bool alreadyAtBottom = false; + if (lastFocusableIndex < m_items.size()) { + alreadyAtBottom = (m_focusedIndex == lastFocusableIndex) && + (std::abs(m_nextOffset - targetOffset) <= tolerance); + } + + if (alreadyAtBottom) { + return oldFocus; // Already at bottom, do nothing + } + + + const float viewHeight = static_cast(getHeight()); + const float maxOffset = (m_listHeight > getHeight()) ? static_cast(m_listHeight - getHeight()) : 0.0f; + + // Calculate the target viewport center after skipping + const float targetViewportTop = std::min(m_offset + viewHeight, maxOffset); + + // Check if we traveled less than a full viewport + const float actualTravelDistance = targetViewportTop - m_offset; + const bool traveledFullViewport = (actualTravelDistance >= viewHeight - tolerance); + const float targetViewportCenter = targetViewportTop + (viewHeight / 2.0f + VIEW_CENTER_OFFSET); + + // Find the item closest to the center of the new viewport + 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); + + // Check if this item is focusable and closer to center + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test && test->m_isItem && distanceFromCenter < bestDistance) { + targetIndex = i; + bestDistance = distanceFromCenter; + foundFocusable = true; + } + + itemTop += itemHeight; + } + + if (foundFocusable) { + bool nearBottom = true; + if (targetIndex > m_focusedIndex && traveledFullViewport) { + m_focusedIndex = targetIndex; + nearBottom = false; + } + isTableScrolling.store(false, std::memory_order_release); + updateScrollOffset(); // This will center the cursor properly + + Element* newFocus = m_items[targetIndex]->requestFocus(oldFocus, FocusDirection::None); + return (newFocus && newFocus != oldFocus && !nearBottom && traveledFullViewport) ? newFocus : handleJumpToBottom(oldFocus); + } else { + isTableScrolling.store(true, std::memory_order_release); + m_nextOffset = targetViewportTop; + + // NEW: Find the last focusable item that's still visible + float searchItemTop = 0.0f; + size_t lastVisibleFocusable = m_focusedIndex; // Default to current + + for (size_t i = 0; i < m_items.size(); ++i) { + const float itemHeight = m_items[i]->getHeight(); + const float itemBottom = searchItemTop + itemHeight; + + // Stop if we've gone past the new viewport + if (searchItemTop >= targetViewportTop + viewHeight) break; + + // Check if this item is focusable and visible in the new viewport + if (itemBottom > targetViewportTop) { + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test && test->m_isItem) { + lastVisibleFocusable = i; + } + } + + searchItemTop += itemHeight; + } + + // Focus on the last visible focusable item + if (lastVisibleFocusable != m_focusedIndex) { + m_focusedIndex = lastVisibleFocusable; + Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus) { + return newFocus; + } + } + } + + return oldFocus; + } + + Element* handleSkipUp(Element* oldFocus) { + if (m_items.empty()) return oldFocus; + + invalidate(); + resetNavigationState(); + + // Define constants for clarity and consistency + static constexpr float targetOffset = 0.0f; + static constexpr float tolerance = 0.0f; + + // Find the first focusable item + size_t firstFocusableIndex = m_items.size(); // Default to invalid + for (size_t i = 0; i < m_items.size(); ++i) { + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test) { + firstFocusableIndex = i; + break; + } + } + + // Check if we're already at the top with proper tolerance + bool alreadyAtTop = false; + if (firstFocusableIndex < m_items.size()) { + alreadyAtTop = (m_focusedIndex == firstFocusableIndex) && + (std::abs(m_nextOffset - targetOffset) <= tolerance); + } + + if (alreadyAtTop) { + return oldFocus; // Already at top, do nothing + } + + + const float viewHeight = static_cast(getHeight()); + + // Calculate the target viewport center after skipping + const float targetViewportTop = std::max(0.0f, m_offset - viewHeight); + + // Check if we traveled less than a full viewport + const float actualTravelDistance = m_offset - targetViewportTop; + const bool traveledFullViewport = (actualTravelDistance >= viewHeight - tolerance); + + const float targetViewportCenter = targetViewportTop + (viewHeight / 2.0f + VIEW_CENTER_OFFSET); + + // Find the item closest to the center of the new viewport + 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); + + // Check if this item is focusable and closer to center + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test && test->m_isItem && distanceFromCenter < bestDistance) { + targetIndex = i; + bestDistance = distanceFromCenter; + foundFocusable = true; + } + + itemTop += itemHeight; + } + + if (foundFocusable) { + + bool nearTop = true; + if (targetIndex < m_focusedIndex && traveledFullViewport) { + m_focusedIndex = targetIndex; + nearTop = false; + } + //if (traveledFullViewport) + isTableScrolling.store(false, std::memory_order_release); + updateScrollOffset(); // This will center the cursor properly + + Element* newFocus = m_items[targetIndex]->requestFocus(oldFocus, FocusDirection::None); + return (newFocus && newFocus != oldFocus && !nearTop && traveledFullViewport) ? newFocus : handleJumpToTop(oldFocus); + } else { + isTableScrolling.store(true, std::memory_order_release); + m_nextOffset = targetViewportTop; + + // NEW: Find the first focusable item that's still visible + float searchItemTop = 0.0f; + size_t firstVisibleFocusable = m_focusedIndex; // Default to current + + for (size_t i = 0; i < m_items.size(); ++i) { + const float itemHeight = m_items[i]->getHeight(); + const float itemBottom = searchItemTop + itemHeight; + + // Check if this item is visible in the new viewport + if (itemBottom > targetViewportTop && searchItemTop < targetViewportTop + viewHeight) { + Element* test = m_items[i]->requestFocus(nullptr, FocusDirection::None); + if (test && test->m_isItem) { + firstVisibleFocusable = i; + break; // Take the first one for skip up + } + } + + searchItemTop += itemHeight; + } + + // Focus on the first visible focusable item + if (firstVisibleFocusable != m_focusedIndex) { + m_focusedIndex = firstVisibleFocusable; + Element* newFocus = m_items[m_focusedIndex]->requestFocus(oldFocus, FocusDirection::None); + if (newFocus && newFocus != oldFocus) { + 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; + + #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_useScriptKey(useScriptKey) { + m_isItem = 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_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_touched && Element::getInputMode() == InputMode::Touch && ult::touchInBounds; + + if (useClickTextColor) [[unlikely]] { + if (ult::expandedMemory) + renderer->drawRectMultiThreaded(this->getX() + 4, this->getY(), this->getWidth() - 8, this->getHeight(), aWithOpacity(clickColor)); + else + renderer->drawRect(this->getX() + 4, this->getY(), this->getWidth() - 8, this->getHeight(), aWithOpacity(clickColor)); + } + + const s32 yOffset = ((tsl::style::ListItemDefaultHeight - m_listItemHeight) /2.0) +0.5f; // Bit shift for division by 2 + + 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 = {}; + #endif + // Fast path for non-truncated text + if (!m_truncated) [[likely]] { + const Color textColor = m_focused + ? (!ult::useSelectionText + ? (m_hasCustomTextColor ? m_customTextColor : defaultTextColor) + : (useClickTextColor + ? clickTextColor + : selectedTextColor)) + : (m_hasCustomTextColor + ? m_customTextColor + : (useClickTextColor + ? clickTextColor + : defaultTextColor)); + + renderer->drawStringWithColoredSections(m_text_clean, false, specialChars, this->getX() + 19, this->getY() + 45 - yOffset, 23, + textColor, (m_focused ? starColor : selectionStarColor)); + } 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 (m_useClickAnimation) + triggerClickAnimation(); + } else if (keys & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) [[unlikely]] { + m_clickAnimationProgress = 0; + } + return Element::onClick(keys); + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + if (event == TouchEvent::Touch) [[likely]] { + if ((m_touched = inBounds(currX, currY))) [[likely]] { + m_touchStartTime_ns = armTicksToNs(armGetSystemTick()); + } + return false; + } + + if (event == TouchEvent::Release && m_touched) [[likely]] { + m_touched = false; + if (Element::getInputMode() == InputMode::Touch) [[likely]] { + #if IS_LAUNCHER_DIRECTIVE + const s64 keyToUse = determineKeyOnTouchRelease(m_useScriptKey); + const bool handled = onClick(keyToUse); + #else + const s64 keyToUse = determineKeyOnTouchRelease(false); + const bool handled = onClick(keyToUse); + #endif + m_clickAnimationProgress = 0; + return handled; + } + } + return false; + } + + virtual void setFocused(bool state) override { + if (state != m_focused) [[likely]] { + 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_faint != faint) [[likely]] { + m_value = value; + m_faint = faint; + //m_useVersionColor = useVersionColor; + m_maxWidth = 0; + if (!value.empty()) applyInitialTranslations(true); + } + } + + inline void setTextColor(Color color) { + m_customTextColor = color; + m_hasCustomTextColor = true; + } + + inline void setValueColor(Color color) { + m_customValueColor = color; + m_hasCustomValueColor = true; + } + + inline void clearTextColor() { + m_hasCustomTextColor = false; + } + + inline void clearValueColor() { + m_hasCustomValueColor = false; + } + + inline void disableClickAnimation() { + m_useClickAnimation = false; + } + + inline void enableClickAnimation() { + 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) const override { + // return matchesJumpCriteria(jumpText, jumpValue, true); // Default to exact match + //} + + 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; + u32 m_listItemHeight; + + #if IS_LAUNCHER_DIRECTIVE + bool m_useScriptKey = false; + #endif + + bool m_scroll = false; + bool m_truncated = false; + bool m_faint = false; + //bool m_useVersionColor = false; + bool m_touched = false; + + bool m_hasCustomTextColor = false; + bool m_hasCustomValueColor = false; + Color m_customTextColor = {0}; + Color m_customValueColor = {0}; + bool m_useClickAnimation = true; + + float m_scrollOffset = 0.0f; + u32 m_maxWidth = 0; + u32 m_textWidth = 0; + + private: + void applyInitialTranslations(bool isValue = false) { + std::string& target = isValue ? m_value : m_text_clean; + ult::applyLangReplacements(target, isValue); + ult::convertComboToUnicode(target); + + // Thread-safe translation cache access + #ifdef UI_OVERRIDE_PATH + { + // Use the processed target as the key for translation lookup + 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; // Apply translation to target, not text + } else { + // Need to upgrade to write lock + readLock.unlock(); + std::unique_lock writeLock(tsl::gfx::s_translationCacheMutex); + + // Double-check pattern + translatedIt = ult::translationCache.find(originalKey); + if (translatedIt != ult::translationCache.end()) { + target = translatedIt->second; + } else { + // Store the original as both key and value if no translation exists + ult::translationCache[originalKey] = originalKey; + // target already contains the correct value, no need to modify + } + } + } + #endif + } + + void calculateWidths(gfx::Renderer* renderer) { + if (m_value.empty()) { + m_maxWidth = getWidth() - 62; + } else { + //auto valueWidth = renderer->getTextDimensions(m_value, false, 20).first; + m_maxWidth = getWidth() - renderer->getTextDimensions(m_value, false, 20).first - 66; + } + + //auto textWidth = renderer->getTextDimensions(m_text, false, 23).first; + const u32 width = renderer->getTextDimensions(m_text_clean, false, 23).first; + m_truncated = width > m_maxWidth + 20; + + if (m_truncated) [[unlikely]] { + // Optimized string building for scroll text + m_scrollText.clear(); + m_scrollText.reserve(m_text_clean.size() * 2 + 8); // Pre-allocate for text + spaces + text + + // Build scroll text efficiently: "text text" + m_scrollText.append(m_text_clean).append(" "); + //auto scrollWidth = renderer->getTextDimensions(m_scrollText, false, 23).first; + 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); + + //Color textColor = m_hasCustomTextColor ? m_customTextColor : + // (useClickTextColor ? clickTextColor : selectedTextColor); + + renderer->drawStringWithColoredSections(m_scrollText, false, specialSymbols, getX() + 19 - static_cast(m_scrollOffset), getY() + 45 - yOffset, 23, + !ult::useSelectionText ? defaultTextColor: (useClickTextColor ? clickTextColor : selectedTextColor), (starColor)); + renderer->disableScissoring(); + handleScrolling(); + } else { + //Color textColor = m_hasCustomTextColor ? m_customTextColor : + // (useClickTextColor ? clickTextColor : defaultTextColor); + + renderer->drawStringWithColoredSections(m_ellipsisText, false, specialSymbols, getX() + 19, getY() + 45 - yOffset, 23, + m_hasCustomTextColor ? m_customTextColor : (useClickTextColor ? clickTextColor : defaultTextColor), (starColor)); + } + } + + + void handleScrolling() { + const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); + const u64 elapsed_ns = currentTime_ns - timeIn_ns; + + // Frame rate compensation - cache calculations to reduce stutter + static u64 lastUpdateTime = 0; + static float cachedScrollOffset = 0.0f; + + // Pre-compute constants as statics to avoid recalculation + static bool constantsInitialized = false; + static double totalCycleDuration; + static double delayDuration; + static double scrollDuration; + static double accelTime; + static double constantVelocityTime; + static double maxVelocity; + static double accelDistance; + static double constantVelocityDistance; + static double minScrollDistance; + static double invAccelTime; // 1/accelTime for multiplication instead of division + static double invDecelTime; // 1/decelTime for multiplication instead of division + static double invBillion; // 1/1000000000.0 for ns to seconds conversion + + if (!constantsInitialized || minScrollDistance != static_cast(m_textWidth)) { + // Constants for velocity-based scrolling + delayDuration = 2.0; + static constexpr double pauseDuration = 1.0; + maxVelocity = 166.0; + 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) [[likely]] { + // Delay phase - no scrolling + cachedScrollOffset = 0.0f; + } else if (cyclePosition < delayDuration + scrollDuration) [[likely]] { + // 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; // Multiply instead of divide + 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; // Multiply instead of divide + const double oneMinusT = 1.0 - t; + const double smoothT = 1.0 - oneMinusT * oneMinusT; // Avoid repeated calculation + distance = accelDistance + constantVelocityDistance + (smoothT * (minScrollDistance - accelDistance - constantVelocityDistance)); + } + + // Use branchless min with conditional move behavior + cachedScrollOffset = static_cast(distance < minScrollDistance ? distance : minScrollDistance); + } else [[unlikely]] { + // Pause phase - stay at end + 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) [[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); // Relaxed ordering is sufficient + } + + Color determineValueTextColor(bool useClickTextColor, bool lastRunningInterpreter) const { + // Check if selection value colors should be disabled + if (m_focused && ult::useSelectionValue) { + // Use selection colors when focused and selection colors are enabled + if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { + return useClickTextColor ? (clickTextColor) : + (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_faint ? offTextColor : (inprogressTextColor); + } + + if (m_value == ult::INPROGRESS_SYMBOL) { + return m_faint ? offTextColor : (inprogressTextColor); + } + + if (m_value == ult::CROSSMARK_SYMBOL) { + return m_faint ? offTextColor : (invalidTextColor); + } + + // For normal values when focused, use selectedValueTextColor + return useClickTextColor ? clickTextColor : selectedValueTextColor; + } + + // If focused but selection colors are disabled, or if not focused, use original logic + // Check for custom value color first + if (m_hasCustomValueColor) { + return m_customValueColor; + } + + // Original logic for all other cases + if (m_value == ult::DROPDOWN_SYMBOL || m_value == ult::OPTION_SYMBOL) { + return (m_focused ? (useClickTextColor ? clickTextColor : (m_faint ? offTextColor : (ult::useSelectionText ? selectedTextColor : defaultTextColor))) : + (useClickTextColor ? clickTextColor : (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_faint ? offTextColor : (inprogressTextColor); + } + + if (m_value == ult::INPROGRESS_SYMBOL) { + return m_faint ? offTextColor : (inprogressTextColor); + } + + if (m_value == ult::CROSSMARK_SYMBOL) { + return m_faint ? offTextColor : (invalidTextColor); + } + + return (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; // More efficient than division + + #if IS_LAUNCHER_DIRECTIVE + if (touchDurationInSeconds >= 0.7f) [[unlikely]] { + ult::longTouchAndRelease.store(true, std::memory_order_release); + return useScriptKey ? SCRIPT_KEY : STAR_KEY; + } + #endif + if (touchDurationInSeconds >= 0.3f) [[unlikely]] { + //if (useScriptKey) + 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 item that goes into a list (this version uses value and faint color sourcing) + * + */ + class ListItemV2 : public Element { + public: + u32 width, height; + u64 m_touchStartTime_ns; // Track the time when touch starts + + /** + * @brief Constructor + * + * @param text Initial description text + */ + ListItemV2(const std::string& text, const std::string& value = "", Color valueColor = onTextColor, Color faintColor = offTextColor) + : Element(), m_text(text), m_value(value), m_valueColor{valueColor}, m_faintColor{faintColor} { + } + virtual ~ListItemV2() {} + + + virtual void draw(gfx::Renderer *renderer) override { + static float lastBottomBound; + bool useClickTextColor = false; + if (this->m_touched && Element::getInputMode() == InputMode::Touch) { + if (ult::touchInBounds) { + //renderer->drawRect(ELEMENT_BOUNDS(this), a(clickColor)); + renderer->drawRect( this->getX()+4, this->getY(), this->getWidth()-8, this->getHeight(), a(clickColor)); + useClickTextColor = true; + } + //renderer->drawRect(ELEMENT_BOUNDS(this), tsl::style::color::ColorClickAnimation); + } + + // Calculate vertical offset to center the text + const s32 yOffset = (tsl::style::ListItemDefaultHeight - this->m_listItemHeight) / 2; + + if (this->m_maxWidth == 0) { + if (this->m_value.length() > 0) { + //std::tie(width, height) = renderer->drawString(this->m_value, false, 0, 0, 20, a(tsl::style::color::ColorTransparent)); + //auto valueWidth = renderer->getTextDimensions(this->m_value, false, 20).first; + width = renderer->getTextDimensions(this->m_value, false, 20).first; + this->m_maxWidth = this->getWidth() - width - 70 +4; + } else { + this->m_maxWidth = this->getWidth() - 40 -10 -12; + } + + //std::tie(width, height) = renderer->drawString(this->m_text, false, 0, 0, 23, a(tsl::style::color::ColorTransparent)); + //auto textWidth = renderer->getTextDimensions(this->m_text, false, 23).first; + width = renderer->getTextDimensions(this->m_text, false, 23).first; + this->m_trunctuated = width > this->m_maxWidth+20; + + if (this->m_trunctuated) { + this->m_scrollText = this->m_text + " "; + //std::tie(width, height) = renderer->drawString(this->m_scrollText, false, 0, 0, 23, a(tsl::style::color::ColorTransparent)); + //auto scrollWidth = renderer->getTextDimensions(this->m_scrollText, false, 23).first; + width = renderer->getTextDimensions(this->m_scrollText, false, 23).first; + this->m_scrollText += this->m_text; + this->m_textWidth = width; + + this->m_ellipsisText = renderer->limitStringLength(this->m_text, false, 23, this->m_maxWidth); + } else { + this->m_textWidth = width; + } + } + + if (lastBottomBound != this->getTopBound()) + renderer->drawRect(this->getX()+4, this->getTopBound(), this->getWidth()+6 +4, 1, a(separatorColor)); + renderer->drawRect(this->getX()+4, this->getBottomBound(), this->getWidth()+6 +4, 1, a(separatorColor)); + + lastBottomBound = this->getBottomBound(); + + + if (this->m_trunctuated) { + if (this->m_focused) { + if (this->m_value.length() > 0) + renderer->enableScissoring(this->getX()+6, 97, this->m_maxWidth + 30 -3, tsl::cfg::FramebufferHeight-73-97); + else + renderer->enableScissoring(this->getX()+6, 97, this->m_maxWidth + 40 +9, tsl::cfg::FramebufferHeight-73-97); + renderer->drawString(this->m_scrollText, false, this->getX() + 20-1 - this->m_scrollOffset, this->getY() + 45 - yOffset, 23, a(selectedTextColor)); + renderer->disableScissoring(); + + // Handle scrolling with frame rate compensation + const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); + const u64 elapsed_ns = currentTime_ns - this->timeIn_ns; + + // Frame rate compensation - cache calculations to reduce stutter + static u64 lastUpdateTime = 0; + static float cachedScrollOffset = 0.0f; + + // Pre-compute constants as statics to avoid recalculation + static bool constantsInitialized = false; + static double totalCycleDuration; + static double delayDuration; + static double scrollDuration; + static double accelTime; + static double constantVelocityTime; + static double maxVelocity; + static double accelDistance; + static double constantVelocityDistance; + static double minScrollDistance; + static double invAccelTime; // 1/accelTime for multiplication instead of division + static double invDecelTime; // 1/decelTime for multiplication instead of division + static double invBillion; // 1/1000000000.0 for ns to seconds conversion + + if (!constantsInitialized || minScrollDistance != static_cast(this->m_textWidth)) { + // Constants for velocity-based scrolling + delayDuration = 2.0; + static constexpr double pauseDuration = 1.0; + maxVelocity = 166.0; + accelTime = 0.5; + static constexpr double decelTime = 0.5; + + // Pre-calculate derived constants + minScrollDistance = static_cast(this->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 + 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; // Multiply instead of divide + 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; // Multiply instead of divide + const double oneMinusT = 1.0 - t; + const double smoothT = 1.0 - oneMinusT * oneMinusT; // Avoid repeated calculation + distance = accelDistance + constantVelocityDistance + (smoothT * (minScrollDistance - accelDistance - constantVelocityDistance)); + } + + // Use branchless min with conditional move behavior + cachedScrollOffset = static_cast(distance < minScrollDistance ? distance : minScrollDistance); + } else { + // Pause phase - stay at end + cachedScrollOffset = static_cast(this->m_textWidth); + } + + lastUpdateTime = currentTime_ns; + } + + // Use cached value for consistent display + this->m_scrollOffset = cachedScrollOffset; + + // Reset timer when cycle completes + if (elapsed_seconds >= totalCycleDuration) { + this->timeIn_ns = currentTime_ns; + } + } else { + renderer->drawString(this->m_ellipsisText, false, this->getX() + 20-1, this->getY() + 45 - yOffset, 23, a(!useClickTextColor ? defaultTextColor : clickTextColor)); + } + } else { + // Render the text with special character handling + #if IS_LAUNCHER_DIRECTIVE + static const std::vector specialChars = {ult::STAR_SYMBOL}; + #else + static const std::vector specialChars = {}; + #endif + renderer->drawStringWithColoredSections(this->m_text, false, specialChars, this->getX() + 20-1, this->getY() + 45 - yOffset, 23, + (this->m_focused ? (!useClickTextColor ? selectedTextColor : clickTextColor) : (!useClickTextColor ? defaultTextColor : clickTextColor)), + (this->m_focused ? starColor : selectionStarColor) + ); + } + + + // CUSTOM SECTION START (modification for submenu footer color) + //const std::string& value = this->m_value; + const s32 xPosition = this->getX() + this->m_maxWidth + 44 + 3; + const s32 yPosition = this->getY() + 45 - yOffset; + static constexpr s32 fontSize = 20; + //bool isFaint = ; + //bool isFocused = this->m_focused; + + + //static bool lastRunningInterpreter = ult::runningInterpreter.load(std::memory_order_acquire); + + // Determine text color + const auto textColor = this->m_faint ? a(m_faintColor) : a(m_valueColor); + + if (this->m_value != ult::INPROGRESS_SYMBOL) { + // Draw the string with the determined text color + renderer->drawString(this->m_value, false, xPosition, yPosition, fontSize, textColor); + } else { + static size_t throbberCounter = 0; + + + // Reset counter to prevent overflow (every full cycle) + if (throbberCounter >= 10 * ult::THROBBER_SYMBOLS.size()) { + throbberCounter = 0; + } + + // Get current throbber symbol (changes every 10 frames) + const size_t symbolIndex = (throbberCounter / 10) % ult::THROBBER_SYMBOLS.size(); + const std::string& currentSymbol = ult::THROBBER_SYMBOLS[symbolIndex]; + + // Instance-specific counter for independent throbber animation + ++throbberCounter; + + renderer->drawString(currentSymbol, false, xPosition, yPosition, fontSize, textColor); + } + //lastRunningInterpreter = ult::runningInterpreter.load(std::memory_order_acquire); + } + + virtual void layout(u16 parentX, u16 parentY, u16 parentWidth, u16 parentHeight) override { + this->setBoundaries(this->getX()+2+1, this->getY(), this->getWidth()+8+1, m_listItemHeight); + } + + virtual bool onClick(u64 keys) override { + if (keys & KEY_A) { + this->triggerClickAnimation(); + } + else if (keys & (KEY_UP | KEY_DOWN | KEY_LEFT | KEY_RIGHT)) + this->m_clickAnimationProgress = 0; + + return Element::onClick(keys); + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + if (event == TouchEvent::Touch) + this->m_touched = this->inBounds(currX, currY); + + if (event == TouchEvent::Release && this->m_touched) { + this->m_touched = false; + + if (Element::getInputMode() == InputMode::Touch) { + const bool handled = this->onClick(KEY_A); + + this->m_clickAnimationProgress = 0; + return handled; + } + } + + + return false; + } + + + virtual void setFocused(bool state) override { + this->m_scroll = false; + this->m_scrollOffset = 0; + this->timeIn_ns = armTicksToNs(armGetSystemTick()); + Element::setFocused(state); + } + + virtual Element* requestFocus(Element *oldFocus, FocusDirection direction) override { + return this; + } + + /** + * @brief Sets the left hand description text of the list item + * + * @param text Text + */ + inline void setText(const std::string& text) { + this->m_text = text; + this->m_scrollText = ""; + this->m_ellipsisText = ""; + this->m_maxWidth = 0; + } + + /** + * @brief Sets the right hand value text of the list item + * + * @param value Text + * @param faint Should the text be drawn in a glowing green or a faint gray + */ + inline void setValue(const std::string& value, bool faint = false) { + this->m_value = value; + this->m_faint = faint; + this->m_maxWidth = 0; + } + + /** + * @brief Sets the value color + * + * @param value_color color of the value + */ + inline void setValueColor(Color value_color) { + this->m_valueColor = value_color; + } + + /** + * @brief Sets the faint color + * + * @param faint_color color of the faint + */ + inline void setFaintColor(Color faint_color) { + this->m_faintColor = faint_color; + } + + /** + * @brief Gets the left hand description text of the list item + * + * @return Text + */ + inline const std::string& getText() const { + return this->m_text; + } + + /** + * @brief Gets the right hand value text of the list item + * + * @return Value + */ + inline const std::string& getValue() { + return this->m_value; + } + + protected: + u64 timeIn_ns; + + std::string m_text; + std::string m_value; + std::string m_scrollText; + std::string m_ellipsisText; + u32 m_listItemHeight = tsl::style::ListItemDefaultHeight; + + #if IS_LAUNCHER_DIRECTIVE + bool m_useScriptKey = false; + #endif + Color m_valueColor; + Color m_faintColor; + + bool m_scroll = false; + bool m_trunctuated = false; + bool m_faint = false; + + bool m_touched = false; + + u16 m_maxScroll = 0; + u16 m_scrollOffset = 0; + u32 m_maxWidth = 0; + u32 m_textWidth = 0; + u16 m_scrollAnimationCounter = 0; + }; + + /** + * @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) + : ListItem(text, "", isMini), m_state(initialState), m_onValue(onValue), m_offValue(offValue) { + this->setState(this->m_state); + } + + virtual ~ToggleListItem() {} + + virtual bool onClick(u64 keys) override { + + // Handle KEY_A for toggling + if (keys & KEY_A) { + this->m_state = !this->m_state; + + this->setState(this->m_state); + this->m_stateChangedListener(this->m_state); + + return ListItem::onClick(keys); + } + #if IS_LAUNCHER_DIRECTIVE + // Handle SCRIPT_KEY for executing script logic + else if (keys & SCRIPT_KEY) { + // Trigger the script key listener + if (this->m_scriptKeyListener) { + this->m_scriptKeyListener(this->m_state); // Pass the current state to the script key listener + } + return ListItem::onClick(keys); + } + #endif + return false; + } + + /** + * @brief Gets the current state of the toggle + * + * @return State + */ + virtual 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) { + 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; + + 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; + } + + 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, (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 Element* requestFocus(Element *oldFocus, FocusDirection direction) { + return this; + } + + virtual bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState leftJoyStick, HidAnalogStickState rightJoyStick) override { + if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) + return true; + + if (keysHeld & KEY_LEFT) { + if (this->m_value > 0) { + this->m_value--; + this->m_valueChangedListener(this->m_value); + return true; + } + } + + if (keysHeld & KEY_RIGHT) { + if (this->m_value < 100) { + this->m_value++; + this->m_valueChangedListener(this->m_value); + return true; + } + } + + 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; + static constexpr s32 circleRadius = 16; + + const bool touchInCircle = (std::abs(initialX - circleCenterX) <= circleRadius) && (std::abs(initialY - circleCenterY) <= circleRadius); + + + if (event == TouchEvent::Release) { + this->m_interactionLocked = false; + touchInSliderBounds = false; + return false; + } + + if (!this->m_interactionLocked && (touchInCircle || touchInSliderBounds)) { + touchInSliderBounds = true; + if (currX > this->getLeftBound() + 50 && currX < this->getRightBound() && currY > this->getTopBound() && currY < this->getBottomBound()) { + s16 newValue = (static_cast(currX - (this->getX() + 60)) / static_cast(this->getWidth() - 95)) * 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()); + } + + return true; + } + } + else + this->m_interactionLocked = 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; + + s32 xPos = this->getX() + 59; + s32 yPos = this->getY() + 40 + 16 - 1; + s32 width = this->getWidth() - 95; + u16 handlePos = width * (this->m_value) / (100); + + 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 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(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 = (this->m_units == "%" || this->m_units == "°C" || this->m_units == "°F") ? + ult::to_string(this->m_value) + this->m_units : + ult::to_string(this->m_value) + (this->m_units.empty() ? "" : " ") + this->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, a(tsl::style::color::ColorText)); + } + + //renderer->drawRect(this->getX(), this->getY(), this->getWidth(), 1, a(tsl::style::color::ColorFrame)); + //renderer->drawRect(this->getX(), this->getBottomBound(), this->getWidth(), 1, a(tsl::style::color::ColorFrame)); + + //u16 handlePos = (this->getWidth() - 95) * static_cast(this->m_value) / 100; + //renderer->drawCircle(this->getX() + 60, this->getY() + 42, 2, true, a(tsl::style::color::ColorHighlight)); + //renderer->drawCircle(this->getX() + 60 + this->getWidth() - 95, this->getY() + 42, 2, true, a(tsl::style::color::ColorFrame)); + //renderer->drawRect(this->getX() + 60 + handlePos, this->getY() + 40, this->getWidth() - 95 - handlePos, 5, a(tsl::style::color::ColorFrame)); + //renderer->drawRect(this->getX() + 60, this->getY() + 40, handlePos, 5, a(tsl::style::color::ColorHighlight)); + // + //renderer->drawCircle(this->getX() + 62 + handlePos, this->getY() + 42, 18, true, a(tsl::style::color::ColorHandle)); + //renderer->drawCircle(this->getX() + 62 + handlePos, this->getY() + 42, 18, false, a(tsl::style::color::ColorFrame)); + + + if (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)); + 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 = (std::cos(2.0 * ult::_M_PI * std::fmod(time_seconds, 1.0) - ult::_M_PI / 2) + 1.0) / 2.0; + + // High precision floating point color interpolation + 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) { + //const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); + t_ns = currentTime_ns - this->m_highlightShakingStartTime; // Changed + if (t_ns >= 100000000) // 100ms in nanoseconds + this->m_highlightShaking = false; + else { + amplitude = std::rand() % 5 + 5; + + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: + y -= shakeAnimation(t_ns, amplitude); // Changed parameter + break; + case FocusDirection::Down: + y += shakeAnimation(t_ns, amplitude); // Changed parameter + break; + case FocusDirection::Left: + x -= shakeAnimation(t_ns, amplitude); // Changed parameter + break; + case FocusDirection::Right: + x += shakeAnimation(t_ns, amplitude); // Changed parameter + break; + default: + break; + } + + x = std::clamp(x, -amplitude, amplitude); + y = std::clamp(y, -amplitude, amplitude); + } + } + + 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)); + + if (!ult::onTrackBar.load(std::memory_order_acquire)) + ult::onTrackBar.store(true, std::memory_order_release); + } + + /** + * @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; + + // V2 Style properties + bool m_useV2Style = false; + std::string m_label; + std::string m_units; + std::string m_selection; // Used for named step trackbars + }; + + + /** + * @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 { + static u32 tick = 0; + + if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) { + tick = 0; + return true; + } + + if (keysHeld & (KEY_LEFT | KEY_RIGHT)) { + if ((tick == 0 || tick > 20) && (tick % 3) == 0) { + if (keysHeld & KEY_LEFT && this->m_value > 0) { + this->m_value = std::max(this->m_value - (100 / (this->m_numSteps - 1)), 0); + } else if (keysHeld & KEY_RIGHT && this->m_value < 100) { + this->m_value = std::min(this->m_value + (100 / (this->m_numSteps - 1)), 100); + } else { + return false; + } + this->m_valueChangedListener(this->getProgress()); + } + tick++; + return true; + } else { + tick = 0; + } + + return false; + } + + virtual bool onTouch(TouchEvent event, s32 currX, s32 currY, s32 prevX, s32 prevY, s32 initialX, s32 initialY) override { + if (this->inBounds(initialX, initialY)) { + if (currY > this->getTopBound() && currY < this->getBottomBound()) { + s16 newValue = (static_cast(currX - (this->getX() + 60)) / static_cast(this->getWidth() - 95)) * 100; + + if (newValue < 0) { + newValue = 0; + } else if (newValue > 100) { + newValue = 100; + } else { + newValue = std::round(newValue / (100.0F / (this->m_numSteps - 1))) * (100.0F / (this->m_numSteps - 1)); + } + + if (newValue != this->m_value) { + 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: + /** + * @brief Constructor + * + * @param icon Icon shown next to the track bar + * @param stepDescriptions Step names displayed above the track bar + * @param useV2Style Whether to use V2 visual style (label + value instead of icon) + * @param label Label text for V2 style + */ + 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; + // Initialize 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 { + // Store previous value to update selection + const u8 prevProgress = this->getProgress(); + + // Call parent input handling + const bool result = StepTrackBar::handleInput(keysDown, keysHeld, touchPos, leftJoyStick, rightJoyStick); + + // Update selection if progress changed + if (result && 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 { + // Store previous value to update selection + const u8 prevProgress = this->getProgress(); + + // Call parent touch handling + const bool result = StepTrackBar::onTouch(event, currX, currY, prevX, prevY, initialX, initialY); + + // Update selection if progress changed + 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); + + // Update selection when progress is set programmatically + const u8 currentIndex = this->getProgress(); + if (currentIndex < m_stepDescriptions.size()) { + this->m_selection = m_stepDescriptions[currentIndex]; + } + } + + virtual void draw(gfx::Renderer *renderer) override { + // TrackBar width excluding the handle areas + u16 trackBarWidth = this->getWidth() - 95; + + // Base X and Y coordinates + u16 baseX = this->getX() + 59; + const u16 baseY = this->getY() + 44; // 50 - 3 + + s32 iconOffset = 0; + + if (!m_useV2Style && m_icon[0] != '\0') { + s32 iconWidth = 23;//tsl::gfx::calculateStringWidth(m_icon, 23); + iconOffset = 14 + iconWidth; + baseX += iconOffset; + trackBarWidth -= iconOffset; + } + + // Calculate the spacing between each step + const float stepSpacing = static_cast(trackBarWidth) / (this->m_numSteps - 1); + + // Calculate the halfway point index + const u8 halfNumSteps = (this->m_numSteps - 1) / 2; + // Draw step rectangles + u16 stepX; + for (u8 i = 0; i < this->m_numSteps; i++) { + stepX = baseX + std::round(i * stepSpacing); + + // Subtract 1 from the X position for steps on the right side of the center + if (i > halfNumSteps) { + stepX -= 1; + } + // Adjust the last step to avoid overshooting + if (i == this->m_numSteps - 1) { + stepX = baseX + trackBarWidth -1; + } + + renderer->drawRect(stepX, baseY, 1, 8, a(trackBarEmptyColor)); + } + + const u8 currentDescIndex = std::clamp(this->m_value / (100 / (this->m_numSteps - 1)), 0, this->m_numSteps - 1); + + // Update selection for current index + if (currentDescIndex < m_stepDescriptions.size()) { + this->m_selection = m_stepDescriptions[currentDescIndex]; + } + + // Only draw the step description above the bar if not using V2 style (V2 style shows it on the right) + if (!m_useV2Style) { + const auto descWidth = renderer->getTextDimensions(this->m_stepDescriptions[currentDescIndex].c_str(), false, 15).first; + renderer->drawString(this->m_stepDescriptions[currentDescIndex].c_str(), false, ((baseX +1) + (trackBarWidth) / 2) - (descWidth / 2), this->getY() + 20 + 6, 15, (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); + } + + // Draw the parent trackbar + StepTrackBar::draw(renderer); + } + + protected: + std::vector m_stepDescriptions; + + }; + + + + /** + * @brief A customizable analog trackbar going from minValue to maxValue + * + */ + class TrackBarV2 : public Element { + public: + u64 lastUpdate_ns; + + Color highlightColor = {0xf, 0xf, 0xf, 0xf}; + float progress; + float counter = 0.0; + s32 x, y; + s32 amplitude; + u32 descWidth, descHeight; + + // Add setScriptKeyListener function + void setScriptKeyListener(std::function listener) { + m_scriptKeyListener = std::move(listener); + } + + + // Ensure the order of initialization matches the order of declaration + 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 ((!usingStepTrackbar && !usingNamedStepTrackbar) || numSteps == -1) { + m_numSteps = (maxValue - minValue)+1; + } + + bool loadedValue = false; + //if (!m_packagePath.empty()) { + // std::string initialIndex = ult::parseValueFromIniSection(m_packagePath + "config.ini", m_label, "index"); + // + // if (!initialIndex.empty()) { + // m_index = static_cast(ult::stoi(initialIndex)); // convert initializedValue to s16 + // } + // if (!m_usingNamedStepTrackbar) { + // std::string initialValue = ult::parseValueFromIniSection(m_packagePath + "config.ini", m_label, "value"); + // + // if (!initialValue.empty()) { + // m_value = static_cast(ult::stoi(initialValue)); // convert initializedValue to s16 + // loadedValue = true; + // } + // } + //} + + if (!m_packagePath.empty()) { + // Load config INI once and extract both values + auto configIniData = ult::getParsedDataFromIniFile(m_packagePath + "config.ini"); + auto sectionIt = configIniData.find(m_label); + + if (sectionIt != configIniData.end()) { + // Get index value + auto indexIt = sectionIt->second.find("index"); + if (indexIt != sectionIt->second.end() && !indexIt->second.empty()) { + m_index = static_cast(ult::stoi(indexIt->second)); // convert initializedValue to s16 + } + + // Get value if not using named step trackbar + 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)); // convert initializedValue to s16 + loadedValue = true; + } + } + } + } + + if (m_index > m_numSteps -1) m_index = m_numSteps - 1; + else if (m_index < 0) m_index = 0; + + if (!loadedValue) + m_value = minValue + m_index * (static_cast(maxValue - minValue) / (m_numSteps - 1)); + + if (m_value > maxValue) m_value = maxValue; + else 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_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; + + // Placeholder replacement - cache lengths once + 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) { + // Replace value placeholder + for (size_t pos = 0; (pos = arg.find(valuePlaceholder, pos)) != std::string::npos; pos += valueStrLen) { + arg.replace(pos, valuePlaceholderLen, valueStr); + } + + // Replace index placeholder if needed + 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 { + static bool holding = false; + static u64 holdStartTime_ns; + static u64 prevKeysHeld = 0; + + const u64 keysReleased = prevKeysHeld & ~keysHeld; + prevKeysHeld = keysHeld; + + const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); + const u64 elapsed_ns = currentTime_ns - lastUpdate_ns; + + static bool wasLastHeld = false; + + 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)) { + if (!m_unlockedTrackbar) { + //ult::allowSlide = !ult::allowSlide; + //ult::allowSlide.fetch_xor(true, std::memory_order_acq_rel); + 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; + } + + // Handle SCRIPT_KEY press + if ((keysDown & SCRIPT_KEY) && !(keysHeld & ~SCRIPT_KEY & ALL_KEYS_MASK)) { + if (m_scriptKeyListener) { + m_scriptKeyListener(); + } + return true; + } + + + // Allow sliding only if KEY_A has been pressed + if (ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) { + + if (((keysReleased & KEY_LEFT) || (keysReleased & KEY_RIGHT)) || + (wasLastHeld && !((keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT)))) { + + wasLastHeld = false; + updateAndExecute(); + lastUpdate_ns = armTicksToNs(armGetSystemTick()); + + holding = false; + return true; + } + + if (keysDown & KEY_LEFT && keysDown & KEY_RIGHT) + return true; + + if (keysDown & KEY_LEFT) { + if (this->m_value > m_minValue) { + this->m_index--; + this->m_value--; + this->m_valueChangedListener(this->m_value); + updateAndExecute(false); + lastUpdate_ns = armTicksToNs(armGetSystemTick()); + return true; + } + } + + if (keysDown & KEY_RIGHT) { + if (this->m_value < m_maxValue) { + this->m_index++; + this->m_value++; + this->m_valueChangedListener(this->m_value); + updateAndExecute(false); + lastUpdate_ns = armTicksToNs(armGetSystemTick()); + return true; + } + } + + + + if (keysHeld & KEY_LEFT && keysHeld & KEY_RIGHT) + return true; + + // Check if the button is being held down + if (((keysHeld & KEY_LEFT) || (keysHeld & KEY_RIGHT))) { + + if (!holding) { + holding = true; + holdStartTime_ns = armTicksToNs(armGetSystemTick()); + } + + const u64 holdDuration_ns = currentTime_ns - holdStartTime_ns; + + // Define the duration boundaries in nanoseconds + static constexpr u64 initialInterval_ns = 67000000ULL; // 67ms in nanoseconds + static constexpr u64 shortInterval_ns = 10000000ULL; // 10ms in nanoseconds + static constexpr u64 transitionPoint_ns = 2000000000ULL; // 2000ms in nanoseconds + + // Calculate transition factor (t) from 0 to 1 based on how far we are from the transition point + const float t = std::min(1.0f, static_cast(holdDuration_ns) / static_cast(transitionPoint_ns)); + + // Smooth transition between intervals + const u64 currentInterval_ns = static_cast((initialInterval_ns - shortInterval_ns) * (1.0f - t) + shortInterval_ns); + + if (elapsed_ns >= currentInterval_ns) { + if (keysHeld & KEY_LEFT) { + if (this->m_value > m_minValue) { + this->m_index--; + this->m_value--; + this->m_valueChangedListener(this->m_value); + if (m_executeOnEveryTick) { + updateAndExecute(false); + } + lastUpdate_ns = armTicksToNs(armGetSystemTick()); + wasLastHeld = true; + return true; + } + } + + if (keysHeld & KEY_RIGHT) { + if (this->m_value < m_maxValue) { + this->m_index++; + this->m_value++; + this->m_valueChangedListener(this->m_value); + if (m_executeOnEveryTick) { + updateAndExecute(false); + } + lastUpdate_ns = armTicksToNs(armGetSystemTick()); + wasLastHeld = true; + return true; + } + } + } + } else { + holding = false; // Reset holding state if no relevant key is held + } + } + + 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; + + const bool touchInCircle = (std::abs(initialX - circleCenterX) <= circleRadius) && (std::abs(initialY - circleCenterY) <= circleRadius); + + if (!m_unlockedTrackbar && !ult::allowSlide.load(std::memory_order_acquire)) + return false; + + if ((touchInCircle || touchInSliderBounds)) { + + touchInSliderBounds = true; + + //s16 newIndex = static_cast((currX - (this->getX() + 59)) / static_cast(this->getWidth() - 95) * (m_numSteps - 1)); + + // Clamp the index within valid range + const s16 newIndex = std::max(static_cast(0), std::min(static_cast((currX - (this->getX() + 59)) / static_cast(this->getWidth() - 95) * (m_numSteps - 1)), 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); + } + } else { + if (event == TouchEvent::Release) { + updateAndExecute(); + if (event == TouchEvent::Release) + touchInSliderBounds = false; + } + } + + 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; + 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; + + + // Draw track bar background + drawBar(renderer, xPos, yPos-3, width, trackBarEmptyColor, !m_usingNamedStepTrackbar); + + + // Determine visual appearance: look locked if KEY_R is held and trackbar is unlocked + const bool shouldAppearLocked = m_unlockedTrackbar && m_keyRHeld; + const bool visuallyUnlocked = (m_unlockedTrackbar && !m_keyRHeld) || touchInSliderBounds; + + if (!this->m_focused) { + drawBar(renderer, xPos, yPos-3, handlePos, trackBarFullColor, !m_usingNamedStepTrackbar); + renderer->drawCircle(xPos + handlePos, yPos, 16, true, a(trackBarSliderBorderColor)); + 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)); + // For focused state, check both allowSlide and visual unlock state + 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); + + static std::string valuePart; + if (!m_usingNamedStepTrackbar) + valuePart = (this->m_units == "%" || this->m_units == "°C" || this->m_units == "°F") ? ult::to_string(this->m_value) + this->m_units : ult::to_string(this->m_value) + (this->m_units.empty() ? "" : " ") + this->m_units; + else + valuePart = this->m_selection; + + const auto valueWidth = renderer->getTextDimensions(valuePart, false, 16).first; + + renderer->drawString(labelPart, false, xPos, 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, (onTextColor)); + renderer->drawString(valuePart, false, this->getWidth() -17 - valueWidth, this->getY() + 14 + 16, 16, + (this->m_focused && ult::useSelectionValue) ? selectedValueTextColor : onTextColor); + + + if (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)); + 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 { + + // Calculate progress using ARM ticks instead of chrono + const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); + const double timeInSeconds = static_cast(currentTime_ns) / 1000000000.0; + progress = ((std::cos(2.0 * ult::_M_PI * std::fmod(timeInSeconds, 1.0) - ult::_M_PI / 2) + 1.0) / 2.0); + + static u64 clickStartTime_ns; + static bool clickActive = false; + + Color clickColor1 = highlightColor1; + Color clickColor2 = clickColor; + + // Activate `clickStartTime_ns` when `triggerClick` is set to true + if (triggerClick && !clickActive) { + clickStartTime_ns = currentTime_ns; + clickActive = true; + // Within the cycle, perform the highlight effect + if (progress >= 0.5) { + clickColor1 = clickColor; + clickColor2 = highlightColor2; + } + } + static auto lastLabel = m_label; + + if (lastLabel != m_label) { + clickActive = false; + triggerClick = false; + } + lastLabel = m_label; + + if (clickActive) { + const u64 elapsedTime_ns = currentTime_ns - clickStartTime_ns; + if (elapsedTime_ns < 500000000ULL) { // 500ms in nanoseconds + // High precision floating point color interpolation for click colors + 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 { + // End the effect after one cycle + clickActive = false; + triggerClick = false; + } + + } else { + // Determine if should appear locked: unlocked trackbar with KEY_R held + const bool shouldAppearLocked = m_unlockedTrackbar && m_keyRHeld; + + if ((ult::allowSlide.load(std::memory_order_acquire) || m_unlockedTrackbar) && !shouldAppearLocked) { + // High precision floating point color interpolation for unlocked trackbar + 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 { + // High precision floating point color interpolation for locked trackbar (or visually locked) + 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) { + //const u64 currentTime_ns = armTicksToNs(armGetSystemTick()); + t_ns = currentTime_ns - this->m_highlightShakingStartTime; + if (t_ns >= 100000000ULL) // 100ms in nanoseconds + this->m_highlightShaking = false; + else { + amplitude = std::rand() % 5 + 5; + + switch (this->m_highlightShakingDirection) { + case FocusDirection::Up: + y -= shakeAnimation(t_ns, amplitude); + break; + case FocusDirection::Down: + y += shakeAnimation(t_ns, amplitude); + break; + case FocusDirection::Left: + x -= shakeAnimation(t_ns, amplitude); + break; + case FocusDirection::Right: + x += shakeAnimation(t_ns, amplitude); + break; + default: + break; + } + + x = std::clamp(x, -amplitude, amplitude); + y = std::clamp(y, -amplitude, amplitude); + } + } + + 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)); + + ult::onTrackBar.store(true, std::memory_order_release); + + if (clickActive) { + const u64 elapsedTime_ns = currentTime_ns - clickStartTime_ns; + + // Handle click animation progress and animColor rendering + auto clickAnimationProgress = tsl::style::ListItemHighlightLength * (1.0f - (static_cast(elapsedTime_ns) / 500000000.0f)); // 500ms in nanoseconds + + // Ensure progress does not go below 0 + 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 getProgress() { + return this->m_value; + } + + virtual void setProgress(u8 value) { + this->m_value = value; + } + + void setValueChangedListener(std::function valueChangedListener) { + this->m_valueChangedListener = valueChangedListener; + } + + protected: + std::string m_label; + std::string m_packagePath; + std::string m_selection; + s16 m_value = 0; + s16 m_minValue; + s16 m_maxValue; + std::string m_units; + bool m_interactionLocked = false; + bool m_keyRHeld = false; // Track KEY_R state for visual appearance + + std::function m_valueChangedListener = [](u8) {}; + + // New member variables to store the function and its parameters + 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; + + }; + + + /** + * @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)) { + 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; + } + + // 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) { + 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) { + 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_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}; + + 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) + { + 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 = priority; + 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; + + pending_queue_.push(data); + + if (!is_active_) { + startNext_NoLock(); + //pending_event_fire_.store(true, std::memory_order_release); + eventFire(¬ificationEvent); + + #if IS_STATUS_MONITOR_DIRECTIVE + if (isRendering) { + isRendering = false; + wasRendering = true; + + leventSignal(&renderingStopEvent); + } + #endif + } + } + + + 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 + 2; // 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, defaultTextColor + ); + } + #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, defaultTextColor + ); + #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, defaultTextColor); + return; + } + + // Split the line into parts + const std::string before = line.substr(0, ultrahandPos); + const std::string ultra = ult::SPLIT_PROJECT_NAME_1; + 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, ultraWidth = 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; + + // For "Ultra" width, we need to handle dynamic vs static rendering differently + if (ult::useDynamicLogo) { + // Calculate width by measuring each character (since dynamic rendering might have slight differences) + for (const char letter : ultra) { + const std::string letterStr(1, letter); + const auto [lw, lh] = renderer->getNotificationTextDimensions(letterStr, false, fontSize); + ultraWidth += lw; + } + } else { + const auto [uw, uh] = renderer->getNotificationTextDimensions(ultra, false, fontSize); + ultraWidth = uw; + } + + // 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, defaultTextColor); + currentX += beforeWidth; + } + + // Draw dynamic "Ultra" part + 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 : ultra) { + const double wavePhase = waveScale * (timeBase + static_cast(countOffset)); + const double rawProgress = std::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); + const auto [letterWidth, letterHeight] = renderer->drawNotificationString(letterStr, false, currentX, y, fontSize, highlightColor); + currentX += letterWidth; + countOffset -= static_cast(cycleDuration / 8.0); + } + } else { + renderer->drawNotificationString(ultra, false, currentX, y, fontSize, logoColor1); + currentX += ultraWidth; + } + + // 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, defaultTextColor); + } + } + #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; + } + + //if (pending_event_fire_.load(std::memory_order_acquire) && + // !ult::launchingOverlay.load(std::memory_order_acquire) && + // generation_ == notificationGeneration.load(std::memory_order_acquire)) + //{ + // pending_event_fire_.store(false, std::memory_order_release); + // + // if ((current_state_.activeText.empty() || current_state_.state == PromptState::Inactive) && pending_queue_.empty()) { + // eventFire(¬ificationEvent); + // } + //} + + //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); + } + + //void forceCompleteTransition() { + // std::lock_guard lg(state_mutex_); + // current_state_ = NotificationState{}; + // while (!pending_queue_.empty()) pending_queue_.pop(); + // is_active_ = false; + // //pending_event_fire_.store(false, std::memory_order_release); + //} + // + //void freezeState() { + // generation_++; + // enabled_.store(false, std::memory_order_release); + // { + // std::lock_guard lg(state_mutex_); + // is_active_ = false; + // } + // //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 (this->m_disableNextAnimation) { + this->m_animationCounter = MAX_ANIMATION_COUNTER; + this->m_disableNextAnimation = false; + } + else { + this->m_fadeInAnimationPlaying = true; + this->m_animationCounter = 0; + } + + ult::isHidden.store(false); + this->onShow(); + + //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 + } + + /** + * @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; + } + + // Static state management - made atomic for thread safety + static std::atomic screenshotStacksAdded{false}; + static std::atomic notificationCacheNeedsClearing{false}; + + auto& renderer = gfx::Renderer::get(); + renderer.startFrame(); + + // Handle main UI rendering + if (!promptOnly) { + // Screenshot management - thread-safe + if (!screenshotStacksAdded.load(std::memory_order_acquire)) { + renderer.addScreenshotStacks(); + screenshotStacksAdded.store(true, std::memory_order_release); + } + + this->animationLoop(); + this->getCurrentGui()->update(); + this->getCurrentGui()->draw(&renderer); + + // Mark that we may need to clear notification cache later + notificationCacheNeedsClearing.store(true, std::memory_order_release); + } else { + // Prompt-only mode - clean up screenshots + if (screenshotStacksAdded.load(std::memory_order_acquire) && !screenshotsAreDisabled) { + renderer.removeScreenshotStacks(); + screenshotStacksAdded.store(false, std::memory_order_release); + } + renderer.clearScreen(); + } + + // Notification handling - safer approach with consistent ordering + { + if (notification) { + + if (notification->isActive()) { + // Snapshot pointer to avoid it becoming null mid-use + notification->update(); + notification->draw(&renderer, promptOnly); + notificationCacheNeedsClearing.store(true, std::memory_order_release); + } 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(); + auto topElement = currentGui->getTopElement(); + + + 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); + else if (keysDown & KEY_DOWN && !(keysHeld & ~KEY_DOWN & ALL_KEYS_MASK)) + currentFocus->shakeHighlight(FocusDirection::Down); + else if (keysDown & KEY_LEFT && !(keysHeld & ~KEY_LEFT & ALL_KEYS_MASK)) + currentFocus->shakeHighlight(FocusDirection::Left); + else if (keysDown & KEY_RIGHT && !(keysHeld & ~KEY_RIGHT & ALL_KEYS_MASK)) + currentFocus->shakeHighlight(FocusDirection::Right); + } + #endif + + #if IS_STATUS_MONITOR_DIRECTIVE + if (FullMode && !deactivateOriginalFooter) { + if (ult::simulatedSelect.load(std::memory_order_acquire)) { + ult::simulatedSelect.store(false, std::memory_order_release); + keysDown |= KEY_A; + } + if (ult::simulatedBack.load(std::memory_order_acquire)) { + ult::simulatedBack.store(false, std::memory_order_release); + keysDown |= KEY_B; + } + + if (!overrideBackButton) { + if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { + if (!currentGui->handleInput(KEY_B,0,{},{},{})) { + this->goBack(); + //ult::simulatedBackComplete = true; + } + return; + } + } + } else { + if (ult::simulatedSelect.load(std::memory_order_acquire)) + ult::simulatedSelect.store(false, std::memory_order_release); + if (ult::simulatedBack.load(std::memory_order_acquire)) + ult::simulatedBack.store(false, std::memory_order_release); + } + #else + if (ult::simulatedSelect.load(std::memory_order_acquire)) { + ult::simulatedSelect.store(false, std::memory_order_release); + keysDown |= KEY_A; + } + + if (ult::simulatedBack.load(std::memory_order_acquire)) { + ult::simulatedBack.store(false, std::memory_order_release); + keysDown |= KEY_B; + //ult::simulatedBack = false; + } + + if (!overrideBackButton) { + if (keysDown & KEY_B && !(keysHeld & ~KEY_B & ALL_KEYS_MASK)) { + if (!currentGui->handleInput(KEY_B,0,{},{},{})) { + this->goBack(); + //ult::simulatedBackComplete = true; + } + return; + } + } + #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 + } + + 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.load(std::memory_order_acquire)) { + ult::longTouchAndRelease.store(false, std::memory_order_release); + hasScrolled = true; + } else if (ult::shortTouchAndRelease.load(std::memory_order_acquire)) { // cant be handled correctly without knowing where it is going after release + ult::shortTouchAndRelease.store(false, std::memory_order_release); + 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); + + 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) 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 + 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 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(); + } + + if (tsl::elm::skipDeconstruction.load(std::memory_order_acquire)) + tsl::elm::skipDeconstruction.store(false, std::memory_order_release); + + // Close overlay if stack is empty + if (this->m_guiStack.empty()) { + this->close(); + } + } + + void pop(u32 count = 1) { + isNavigatingBackwards.store(true, std::memory_order_release); + + // Clamp count to available stack size to prevent underflow + const u32 actualCount = std::min(count, static_cast(this->m_guiStack.size())); + + if (actualCount > 1) { + 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); + } + + + /** + * @brief Background event polling loop thread + * + * @param args Used to pass in a pointer to a \ref SharedThreadData struct + */ + static void backgroundEventPoller(void *args) { + + 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); + + 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 + static constexpr int SWIPE_RIGHT_BOUND = 16; // 16 + 80 + static constexpr int SWIPE_LEFT_BOUND = (1280 - 16); + static constexpr u64 TOUCH_THRESHOLD_NS = 150'000'000ULL; // 150ms in nanoseconds + static constexpr u64 FAST_SWAP_THRESHOLD_NS = 150'000'000ULL; + + // Global underscan monitoring - run at most once every 300ms + static auto lastUnderscanPixels = std::make_pair(0, 0); + static bool firstUnderscanCheck = true; + static u64 lastUnderscanCheckNs = 0; // store last execution in nanoseconds + static 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; + + while (shData->running.load(std::memory_order_acquire)) { + + const u64 nowTick = armGetSystemTick(); + const u64 nowNs = armTicksToNs(nowTick); + + + + // Scan for input changes from both controllers + padUpdate(&pad_p1); + padUpdate(&pad_handheld); + + // Read in HID values + { + if (ult::launchingOverlay.load(std::memory_order_acquire)) + break; + std::scoped_lock lock(shData->dataMutex); + if (ult::launchingOverlay.load(std::memory_order_acquire)) + break; + + // 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 (!isMiniOrMicroMode) + 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) { + const auto 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); + static u64 lastNotifCheck = 0; + + if (armTicksToNs(nowTick - lastNotifCheck) >= 300'000'000ULL) { + lastNotifCheck = nowTick; + + DIR* dir = opendir(ult::NOTIFICATIONS_PATH.c_str()); + if (dir) { + + if (ult::useNotifications) { + std::string filename, fullPath, prioStr; + + struct dirent* entry; + + const std::string& notifPath = ult::NOTIFICATIONS_PATH; + + static std::vector shownFiles; + + // Structure to hold file info with creation time + struct NotificationFile { + std::string filename; + std::string fullPath; + time_t creationTime; + int priority; + }; + + std::vector notificationFiles; + + // --- 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; + } + } + + static std::string text; + static int fontSize; + static int priority; + + // --- Collect notification files with creation time --- + while ((entry = readdir(dir)) != nullptr) { + if (entry->d_type != DT_REG) continue; + + filename = entry->d_name; + const size_t filenameLen = filename.size(); + + // Must end with ".notify" + if (filenameLen <= 7 || filename.compare(filenameLen - 7, 7, ".notify") != 0) + continue; + + // Skip if already shown + if (std::find(shownFiles.begin(), shownFiles.end(), filename) != shownFiles.end()) + continue; + + // --- Build path --- + fullPath.clear(); + fullPath = notifPath; + fullPath += filename; + + // --- Get file creation/modification time --- + struct stat fileStat; + time_t creationTime = 0; + if (stat(fullPath.c_str(), &fileStat) == 0) { + // Use modification time as creation time (more universally supported) + creationTime = fileStat.st_mtime; + } + + // --- Read priority from JSON --- + priority = 20; // default + 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); + } + } + + // Add to collection + notificationFiles.push_back({filename, fullPath, creationTime, priority}); + } + + closedir(dir); + + // --- Sort files by priority (higher first), then creation time (older first) --- + std::sort(notificationFiles.begin(), notificationFiles.end(), + [](const NotificationFile& a, const NotificationFile& b) { + // Primary sort: Higher priority first + if (a.priority != b.priority) { + return a.priority > b.priority; + } + // Secondary sort: Older creation time first (FIFO within same priority) + return a.creationTime < b.creationTime; + }); + + // --- Process files in chronological order --- + for (const auto& notifFile : notificationFiles) { + // --- Load JSON (safe outside notification lock) --- + text = ult::getStringFromJsonFile(notifFile.fullPath, "text"); + if (!text.empty()) { + fontSize = 28; // default + + std::unique_ptr root( + ult::readJsonFromFile(notifFile.fullPath), 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, notifFile.priority, notifFile.filename); + } + + // Mark file as shown + shownFiles.push_back(notifFile.filename); + } + } + + } else { + // --- Notifications disabled: delete all files --- + struct dirent* entry; + std::string fullPath; + + while ((entry = readdir(dir)) != nullptr) { + if (entry->d_type != DT_REG) continue; + + const char* fname = entry->d_name; + const size_t len = strlen(fname); + + if (len > 7 && strcmp(fname + len - 7, ".notify") == 0) { + fullPath.clear(); + fullPath = ult::NOTIFICATIONS_PATH; + fullPath.append(fname, len); + + remove(fullPath.c_str()); + } + } + closedir(dir); + } + } + } + } + + + + + + // Combine inputs from both controllers + const u64 kDown_p1 = padGetButtonsDown(&pad_p1); + const u64 kDown_handheld = padGetButtonsDown(&pad_handheld); + const u64 kHeld_p1 = padGetButtons(&pad_p1); + 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) { + 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); + + // 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"); + 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 != "ovlmenu.ovl") { + // 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 == "ovlmenu.ovl") { + 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 && !isMiniOrMicroMode) { + 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 + if (isMiniOrMicroMode) { + 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 (isMiniOrMicroMode) { + 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 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); + 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 if (strncmp(src, "--promptDuration", 16) == 0) { + // // skip any existing --promptDuration (we’ll re-add it) + // src += 16; + // while (src < end && *src == ' ') src++; + // while (src < end && *src != ' ' && *src != '\0') src++; + //} + 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++; + } + + // Add prompt duration + //{ + // const s64 duration = notification->remainingTime(); // nanoseconds left + // if (duration > 0) { + // const std::string promptArg = " --promptDuration " + std::to_string(duration); + // if ((p + promptArg.size()) < bufferEnd) { + // memcpy(p, promptArg.c_str(), promptArg.size()); + // p += promptArg.size(); + // } + // } + //} + + // 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 const struct option_entry options[] = { + {"direct", 6, 1}, + {"skipCombo", 9, 2}, + {"lastTitleID", 11, 3}, + {"foregroundFix", 13, 4}, + {"package", 7, 5} + }; + + + /** + * @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"); + + + + // Initialize buffer sizes based on expanded memory setting + if (ult::expandedMemory) { + ult::COPY_BUFFER_SIZE = 262144; + ult::HEX_BUFFER_SIZE = 8192; + ult::UNZIP_READ_BUFFER = 262144; + ult::UNZIP_WRITE_BUFFER = 131072; + ult::DOWNLOAD_READ_BUFFER = 262144; + ult::DOWNLOAD_WRITE_BUFFER = 131072; + } + + if (argc > 0) { + g_overlayFilename = ult::getNameFromPath(argv[0]); + lastOverlayFilename = g_overlayFilename; + + lastOverlayMode.clear(); + bool skip; + for (u8 arg = 1; arg < argc; arg++) { + const char* s = argv[arg]; + #if IS_STATUS_MONITOR_DIRECTIVE + if (s[0] == '-') { + if (s[1] == 'm') { + if (strcasecmp(s, "-mini") == 0 || strcasecmp(s, "-micro") == 0) { + isMiniOrMicroMode = true; + } + } else if (s[1] == '-' && s[2] == 'm') { + if (strcasecmp(s, "--miniOverlay") == 0 || strcasecmp(s, "--microOverlay") == 0) { + isMiniOrMicroMode = true; + } + } + } + #endif + 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 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 < 5; i++) { + 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; + } + } + } + } + + 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); + + 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(); + }); + #if !IS_LAUNCHER_DIRECTIVE + tsl::initializeUltrahandSettings(); + #endif + overlay->initScreen(); + overlay->changeTo(overlay->loadInitialGui()); + + #if IS_LAUNCHER_DIRECTIVE + { + bool inOverlay; + bool shouldFireEvent = false; + auto configData = ult::getParsedDataFromIniFile(ult::ULTRAHAND_CONFIG_INI_PATH); + bool needsUpdate = false; + + if (ult::firstBoot) { + configData[ult::ULTRAHAND_PROJECT_NAME][ult::IN_OVERLAY_STR] = ult::FALSE_STR; + needsUpdate = true; + } + + auto projectIt = configData.find(ult::ULTRAHAND_PROJECT_NAME); + if (projectIt != configData.end()) { + auto overlayIt = projectIt->second.find(ult::IN_OVERLAY_STR); + inOverlay = (overlayIt == projectIt->second.end() || overlayIt->second != ult::FALSE_STR); + } else { + inOverlay = true; + } + + if (inOverlay && skipCombo) { + configData[ult::ULTRAHAND_PROJECT_NAME][ult::IN_OVERLAY_STR] = ult::FALSE_STR; + needsUpdate = true; + shouldFireEvent = true; + } + + if (needsUpdate) { + ult::saveIniFileData(ult::ULTRAHAND_CONFIG_INI_PATH, configData); + } + + if (shouldFireEvent) { + eventFire(&shData.comboEvent); + } + } + #else + if (skipCombo) { + eventFire(&shData.comboEvent); + } + #endif + + overlay->disableNextAnimation(); + + { + 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.load(std::memory_order_acquire)) { + mainComboHasTriggered.store(false, std::memory_order_acquire); + 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); + + 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 (!isMiniOrMicroMode) + hlp::requestForeground(true); + #else + hlp::requestForeground(true); + #endif + + overlay->show(); + if (!comboBreakout && !(notification && notification->isActive())) + overlay->clearScreen(); + } + + 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_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_acquire); + launchComboHasTriggered.store(false, std::memory_order_acquire); + eventClear(&shData.comboEvent); + } + } + //if (notification) + // notification->forceShutdown(); + + //while (notification && notification->isActive()) { + // notification->update(true, true); // No file ops, allow state transitions + // svcSleepThread(10'000'000); // 1ms sleep + //} + //tsl::notificationGeneration.fetch_add(1, std::memory_order_release); + + // 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; + + // Synchronize notification shutdown + //if (notification) { + // notification->forceShutdown(); // Immediate disable of new notifications + // while (notification->isActive()) { + // notification->update(true, true); // No file ops, allow state transitions + // svcSleepThread(1'000'000); // 1ms sleep + // } + // + // notificationGeneration.fetch_add(1, std::memory_order_release); + // delete notification; + // + // //lock.unlock(); + //} + + + eventClose(&shData.comboEvent); + + // 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) { + 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 + ASSERT_FATAL(timeInitialize()); // CUSTOM MODIFICATION + __libnx_init_time(); // CUSTOM MODIFICATION + timeExit(); // CUSTOM MODIFICATION + + #if USING_WIDGET_DIRECTIVE + ult::powerInit(); + i2cInitialize(); + #endif + + fsdevMountSdmc(); + splInitialize(); + spsmInitialize(); + //i2cInitialize(); + //ASSERT_FATAL(socketInitializeDefault()); + //ASSERT_FATAL(nifmInitialize(NifmServiceType_User)); + }); + ASSERT_FATAL(smInitialize()); // needed to prevent issues with powering device into sleep + + #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); + + smExit(); + //socketExit(); + //nifmExit(); + spsmExit(); + splExit(); + fsdevUnmountAll(); + + #if USING_WIDGET_DIRECTIVE + i2cExit(); + ult::powerExit(); // CUSTOM MODIFICATION + #endif + + fsExit(); + hidExit(); + plExit(); + pmdmntExit(); + hidsysExit(); + setsysExit(); + + // Final cleanup + tsl::gfx::FontManager::cleanup(); + } + +} + +#endif \ No newline at end of file diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE new file mode 100644 index 00000000..d159169d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md b/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md new file mode 100644 index 00000000..9966139d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/README.md @@ -0,0 +1,69 @@ +# libultra + +![Ultrahand Logo](https://github.com/ppkantorski/Ultrahand-Overlay/blob/main/.pics/ultrahand.png) + + +## Overview + +`libultra` is a powerful collection of helper functions designed specifically for the Ultrahand Overlay project. This library offers a comprehensive set of utilities aimed at simplifying common tasks and enhancing the efficiency of your projects within the Ultrahand Overlay ecosystem. + +## Features + +### [Ultra Header](/libultra/include/ultra.hpp) + +- **ultra.hpp**: The main header file for the `libultra` library, including all essential functions and declarations for seamless integration into your projects. + +### [Debug Functions](/libultra/include/debug_funcs.hpp) + +- **debug_funcs.hpp**: A collection of functions tailored for debugging purposes, aiding in identifying and resolving issues within your codebase. + +### [Download Functions](/libultra/include/download_funcs.hpp) + +- **download_funcs.hpp**: Utilities for managing file downloads, enabling seamless retrieval of resources from external sources. + +### [Get Functions](/libultra/include/get_funcs.hpp) + +- **get_funcs.hpp**: Functions for retrieving data from various sources, simplifying the process of fetching information within your applications. + +### [Hex Functions](/libultra/include/hex_funcs.hpp) + +- **hex_funcs.hpp**: Tools for working with hexadecimal data, facilitating operations such as conversion and manipulation of hexadecimal values. + +### [INI Functions](/libultra/include/ini_funcs.hpp) + +- **ini_funcs.hpp**: Helper functions for handling INI configuration files, offering a convenient way to manage application settings. + +### [JSON Functions](/libultra/include/json_funcs.hpp) + +- **json_funcs.hpp**: Utilities for parsing and manipulating JSON data, providing easy integration with JSON-based APIs and services. + +### [List Functions](/libultra/include/list_funcs.hpp) + +- **list_funcs.hpp**: Functions for working with lists and arrays, offering essential operations like sorting, searching, and manipulation of list elements. + +### [Mod Functions](/libultra/include/mod_funcs.hpp) + +- **mod_funcs.hpp**: Functions for manipulating game mods, facilitating operations and management tasks related to modifications in gaming environments. + +### [Path Functions](/libultra/include/path_funcs.hpp) + +- **path_funcs.hpp**: Tools for working with file paths and directories, simplifying file system operations within your applications. + +### [String Functions](/libultra/include/string_funcs.hpp) + +- **string_funcs.hpp**: A collection of string manipulation functions, providing utilities for tasks such as formatting, searching, and modification of strings. + + +## Usage + +To build Ultrahand overlays with `libultra` + `libtesla`, simply add the `lib` folder to your project, then import `tesla.hpp`. + +## Contribution + +Contributions to `libultra` are welcome. If you have ideas for additional helper functions or improvements to existing ones, feel free to submit a pull request or open an issue on GitHub. + +## License + +Licensed under both [GPLv2](LICENSE) and [CC-BY-4.0](SUB_LICENSE). + +Copyright (c) 2024 ppkantorski diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE b/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE new file mode 100644 index 00000000..2f244ac8 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/SUB_LICENSE @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 4.0 International Public License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution 4.0 International Public License ("Public License"). To the +extent this Public License may be interpreted as a contract, You are +granted the Licensed Rights in consideration of Your acceptance of +these terms and conditions, and the Licensor grants You such rights in +consideration of benefits the Licensor receives from making the +Licensed Material available under these terms and conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + j. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp new file mode 100644 index 00000000..ea8acba5 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/debug_funcs.hpp @@ -0,0 +1,52 @@ +/******************************************************************************** + * 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) 2024 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 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 new file mode 100644 index 00000000..b0d0958c --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/download_funcs.hpp @@ -0,0 +1,89 @@ +/******************************************************************************** + * 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) 2024 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; + + // User agent string for curl requests + inline 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"; + + // Custom deleters for CURL handles + struct CurlDeleter { + void operator()(CURL* curl) const; + }; + + // 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 new file mode 100644 index 00000000..f2ad167d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/get_funcs.hpp @@ -0,0 +1,160 @@ +/******************************************************************************** + * 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) 2024 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 new file mode 100644 index 00000000..f4e226bc --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/global_vars.hpp @@ -0,0 +1,171 @@ +/******************************************************************************** + * 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) 2024 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 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 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 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 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 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::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/hex_funcs.hpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp new file mode 100644 index 00000000..bdd29144 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/hex_funcs.hpp @@ -0,0 +1,211 @@ +/******************************************************************************** + * 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) 2024 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); +} + +#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 new file mode 100644 index 00000000..c85da275 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ini_funcs.hpp @@ -0,0 +1,344 @@ +/******************************************************************************** + * 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) 2024 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(); + //} + + + void 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); +} + +#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 new file mode 100644 index 00000000..40b43488 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/json_funcs.hpp @@ -0,0 +1,107 @@ +/******************************************************************************** + * 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) 2024 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& 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 new file mode 100644 index 00000000..baa347dd --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/list_funcs.hpp @@ -0,0 +1,110 @@ +/******************************************************************************** + * 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) 2024 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); + + + // 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); + + + // 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 new file mode 100644 index 00000000..fcbcc51d --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/mod_funcs.hpp @@ -0,0 +1,108 @@ +/******************************************************************************** + * 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 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); + + // 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 new file mode 100644 index 00000000..2eea6781 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/path_funcs.hpp @@ -0,0 +1,279 @@ +/******************************************************************************** + * 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) 2024 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 + + +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& logSource = ""); + + + 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. + * + * @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. + */ + void moveFilesOrDirectoriesByPattern(const std::string& sourcePathPattern, const std::string& destinationPath, + const std::string& logSource = "", const std::string& logDestination = ""); + + + + /** + * @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. + * + * @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. + */ + void copyFileOrDirectoryByPattern(const std::string& sourcePathPattern, const std::string& toDirectory, + const std::string& logSource = "", const std::string& logDestination = ""); + + + + + + /** + * @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 new file mode 100644 index 00000000..607859bd --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/string_funcs.hpp @@ -0,0 +1,273 @@ +/******************************************************************************** + * 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) 2024 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); + + + /** + * @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 new file mode 100644 index 00000000..ea65a334 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/tsl_utils.hpp @@ -0,0 +1,719 @@ +/******************************************************************************** + * 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) 2024 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 { + 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 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 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 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 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 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 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 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 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 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 SELECTION_IS_EMPTY; + + //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 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 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; + + extern const std::string loaderInfo; + extern const std::string loaderTitle; + extern const bool expandedMemory; + + 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 new file mode 100644 index 00000000..7333c6a3 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/include/ultra.hpp @@ -0,0 +1,47 @@ +/******************************************************************************** + * 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 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" + +#endif // ULTRA_HPP \ 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 new file mode 100644 index 00000000..c4c4fec4 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/debug_funcs.cpp @@ -0,0 +1,60 @@ +/******************************************************************************** + * File: debug_funcs.cpp + * Author: ppkantorski + * Description: + * This source file contains the implementation of debugging functions for the + * Ultrahand Overlay project. + ********************************************************************************/ + +#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 std::string& message) { + //if (disableLogging) + // return; + + std::time_t currentTime = std::time(nullptr); + std::tm* timeInfo = std::localtime(¤tTime); + char timestamp[30]; // Exact size for "[YYYY-MM-DD HH:MM:SS] " + null terminator + strftime(timestamp, sizeof(timestamp), "[%Y-%m-%d %H:%M:%S] ", timeInfo); + + // Depending on the directive, use either std::ofstream or stdio functions + #if !USING_FSTREAM_DIRECTIVE + // Use stdio functions to open, write, and close the file + { + std::lock_guard lock(logMutex); // Locks the mutex for thread-safe access + + FILE* file = fopen(logFilePath.c_str(), "a"); // Open the file in append mode + if (file != nullptr) { + fprintf(file, "%s%s\n", timestamp, message.c_str()); + fclose(file); // Close the file after writing + } else { + // Handle error when file opening fails (if necessary) + // printf("Failed to open log file: %s\n", logFilePath.c_str()); + } + } + #else + // Use std::ofstream if !USING_FSTREAM_DIRECTIVE is not defined + { + std::lock_guard lock(logMutex); // Locks the mutex for the duration of this block + + std::ofstream file(logFilePath.c_str(), std::ios::app); + if (file.is_open()) { + file << timestamp << message << "\n"; + } else { + // Handle error when file opening fails + // std::cerr << "Failed to open log file: " << logFilePath << std::endl; + } + } + #endif + } + #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 new file mode 100644 index 00000000..c3d9fbad --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/download_funcs.cpp @@ -0,0 +1,812 @@ +/******************************************************************************** + * 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) 2024 ppkantorski + ********************************************************************************/ + +#include "download_funcs.hpp" + + +namespace ult { + +size_t DOWNLOAD_READ_BUFFER = 16*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"; + +// 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); + + + +struct FileDeleter { + void operator()(FILE* f) const { if (f) fclose(f); } +}; + +// Definition of CurlDeleter +void CurlDeleter::operator()(CURL* curl) const { + if (curl) { + curl_easy_cleanup(curl); + } +} + +// 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); + //size_t totalBytes = size * nmemb; + file.write(static_cast(ptr), size * nmemb); + 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); + } +} + +/** + * @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) { + 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); + } +#endif + + // Ensure curl is initialized + initializeCurl(); + + 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(); +#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_2TLS); // Enable HTTP/2 + 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 + + CURLcode result = curl_easy_perform(curl.get()); + +#if USING_FSTREAM_DIRECTIVE + file.close(); +#else + file.reset(); +#endif + + if (result != CURLE_OK) { + #if USING_LOGGING_DIRECTIVE + 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); + // Only update percentage if we're tracking it + 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); + 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, buffer.get(), bufferSize)) > 0) { + if (abortUnzip.load(std::memory_order_relaxed)) { + extractSuccess = false; + break; // RAII will handle cleanup + } + + // Write data to file + if (outputFile.write(buffer.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); + } + + // 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 new file mode 100644 index 00000000..84f117e3 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/get_funcs.cpp @@ -0,0 +1,506 @@ +/******************************************************************************** + * 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) 2024 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 new file mode 100644 index 00000000..edaf41b7 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/global_vars.cpp @@ -0,0 +1,178 @@ +/******************************************************************************** + * 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) 2024 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/"; + + // 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 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 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"; + + // 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 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 = ""; + + 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/hex_funcs.cpp b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp new file mode 100644 index 00000000..c795f23c --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/hex_funcs.cpp @@ -0,0 +1,881 @@ +/******************************************************************************** + * 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) 2024 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); + + std::vector binaryData; + if (hexData.length() % 2 != 0) { + fclose(file); + return offsets; + } + + + const size_t hexLen = hexData.length(); + binaryData.resize(hexLen / 2); + 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.data(); + const size_t patternLen = binaryData.size(); + const unsigned char firstByte = patternPtr[0]; + + std::vector buffer(HEX_BUFFER_SIZE); + size_t bytesRead = 0; + size_t offset = 0; + + + while ((bytesRead = fread(buffer.data(), 1, HEX_BUFFER_SIZE, file)) > 0) { + const unsigned char* bufPtr = buffer.data(); + + // 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); + + std::vector binaryData; + if (hexData.length() % 2 != 0) { + file.close(); + return offsets; + } + + + const size_t hexLen = hexData.length(); + binaryData.resize(hexLen / 2); + 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.data(); + const size_t patternLen = binaryData.size(); + const unsigned char firstByte = patternPtr[0]; + + std::vector buffer(HEX_BUFFER_SIZE); + size_t bytesRead = 0; + size_t offset = 0; + + while (file.read(reinterpret_cast(buffer.data()), HEX_BUFFER_SIZE) || file.gcount() > 0) { + bytesRead = file.gcount(); + const unsigned char* bufPtr = buffer.data(); + + // 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); + fseek(file, 0, SEEK_SET); + + if (offset >= fileSize) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Offset exceeds file size."); + #endif + fclose(file); + return; + } + + // Convert the hex string to binary data + std::vector binaryData(hexData.length() / 2); + std::string byteString; + for (size_t i = 0, j = 0; i < hexData.length(); i += 2, ++j) { + byteString = hexData.substr(i, 2); + binaryData[j] = static_cast(ult::stoi(byteString, nullptr, 16)); + } + + // 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.data(), sizeof(unsigned char), binaryData.size(), file); + if (bytesWritten != binaryData.size()) { + #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(); + file.seekg(0, std::ios::beg); + + if (offset >= fileSize) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Offset exceeds file size."); + #endif + return; + } + + // Convert the hex string to binary data + std::vector binaryData(hexData.length() / 2); + std::string byteString; + for (size_t i = 0, j = 0; i < hexData.length(); i += 2, ++j) { + byteString = hexData.substr(i, 2); + binaryData[j] = static_cast(ult::stoi(byteString, nullptr, 16)); + } + + // Move to the specified offset and write the binary data directly to the file + file.seekp(offset); + file.write(reinterpret_cast(binaryData.data()), binaryData.size()); + 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); + std::vector hexBuffer(length); + std::vector hexStream(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 ""; + } + + const size_t bytesRead = fread(hexBuffer.data(), sizeof(char), length, file); + if (bytesRead == length) { + static constexpr char hexDigits[] = "0123456789ABCDEF"; + for (size_t i = 0; i < length; ++i) { + hexStream[i * 2] = hexDigits[(hexBuffer[i] >> 4) & 0xF]; + hexStream[i * 2 + 1] = hexDigits[hexBuffer[i] & 0xF]; + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error reading data from file or end of file reached."); + #endif + fclose(file); + return ""; + } + + fclose(file); + #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 ""; + } + + file.read(hexBuffer.data(), length); + if (file.gcount() == static_cast(length)) { + static constexpr char hexDigits[] = "0123456789ABCDEF"; + for (size_t i = 0; i < length; ++i) { + hexStream[i * 2] = hexDigits[(hexBuffer[i] >> 4) & 0xF]; + hexStream[i * 2 + 1] = hexDigits[hexBuffer[i] & 0xF]; + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Error reading data from file or end of file reached."); + #endif + return ""; + } + + file.close(); + #endif + + std::string result(hexStream.begin(), hexStream.end()); + result = stringToUppercase(result); + + 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 + } +} 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 new file mode 100644 index 00000000..939c9ab5 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/ini_funcs.cpp @@ -0,0 +1,2465 @@ +/******************************************************************************** + * 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) 2024 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; + + auto lines = split(str, '\n'); + std::string lastHeader = ""; + + //std::string trimmedLine; + + size_t delimiterPos; + //std::string key, value; + + std::string newLine1, newLine2; + + for (auto& line : lines) { + trim(line); + + // Ignore empty lines and comments + if (line.empty() || line.front() == '#') { + // Clear line to reuse capacity + line.clear(); + continue; + } + + if (line.front() == '[' && line.back() == ']') { + lastHeader = line.substr(1, line.size() - 2); + iniData[lastHeader]; // Ensures the section exists even if it remains empty + + } else { + delimiterPos = line.find('='); + if (delimiterPos != std::string::npos) { + //key = trim(trimmedLine.substr(0, delimiterPos)); + //value = trim(trimmedLine.substr(delimiterPos + 1)); + if (!lastHeader.empty()) { + //iniData[lastHeader][key] = value; + newLine1 = line.substr(0, delimiterPos); + trim(newLine1); + newLine2 = line.substr(delimiterPos + 1); + trim(newLine2); + iniData[lastHeader][newLine1] = newLine2; + + // Clear strings to reuse capacity + newLine1.clear(); + newLine2.clear(); + } + } + } + // Clear line to reuse capacity + line.clear(); + } + + 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; // Return empty map if file cannot be opened + } + + char buffer[1024]; + std::string line; + std::string currentSection; + size_t delimiterPos; + std::string key, value; + + // Cache iterator to current section to avoid repeated map lookups + std::map* currentSectionMap = nullptr; + + size_t len; + const char* start; + const char* end; + + while (fgets(buffer, sizeof(buffer), file)) { + // More efficient newline removal + len = strlen(buffer); + if (len > 0 && buffer[len-1] == '\n') { + buffer[len-1] = '\0'; + --len; + if (len > 0 && buffer[len-1] == '\r') { + buffer[len-1] = '\0'; + --len; + } + } + + // Early exit for empty lines + if (len == 0) continue; + + // Manual trim for better performance - find start of non-whitespace + start = buffer; + while (*start == ' ' || *start == '\t') ++start; + + // Find end of non-whitespace (working backwards from known end) + end = buffer + 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; + + // Check for section header first (most efficient check) + if (*start == '[' && *end == ']') { + // Remove the brackets and set the current section + if (len > 2) { + currentSection.assign(start + 1, len - 2); + currentSectionMap = &parsedData[currentSection]; + } + // Clear section string to reuse capacity + currentSection.clear(); + } else if (currentSectionMap != nullptr) { + // Look for '=' delimiter - scan from start for efficiency + delimiterPos = 0; + const char* eq_pos = start; + while (eq_pos <= end && *eq_pos != '=') { + ++eq_pos; + ++delimiterPos; + } + + if (eq_pos <= end) { // Found '=' delimiter + // Extract key (start to delimiter) + const char* key_end = eq_pos - 1; + while (key_end >= start && (*key_end == ' ' || *key_end == '\t')) --key_end; + + if (key_end >= start) { + key.assign(start, key_end - start + 1); + + // Extract value (after delimiter to end) + const char* val_start = eq_pos + 1; + while (val_start <= end && (*val_start == ' ' || *val_start == '\t')) ++val_start; + + if (val_start <= end) { + value.assign(val_start, end - val_start + 1); + } else { + value.clear(); + } + + (*currentSectionMap)[key] = std::move(value); + } + } + // Clear strings to reuse capacity + key.clear(); + value.clear(); + } + } + + fclose(file); + #else + std::ifstream configFile(configIniPath); + if (!configFile) { + return parsedData; // Return empty map if file cannot be opened + } + + std::string line; + std::string currentSection; + size_t delimiterPos; + std::string key, value; + + size_t start, end, key_end, val_start; + + // Cache iterator to current section to avoid repeated map lookups + std::map* currentSectionMap = nullptr; + + while (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; + } + + // Check for section header first + if (line[start] == '[' && line[end] == ']') { + // Remove the brackets and set the current section + if (end > start + 1) { + currentSection.assign(line, start + 1, end - start - 1); + currentSectionMap = &parsedData[currentSection]; + } + // Clear strings to reuse capacity + line.clear(); + currentSection.clear(); + } else if (currentSectionMap != nullptr) { + // Look for '=' delimiter within the trimmed range + delimiterPos = line.find('=', start); + if (delimiterPos != std::string::npos && delimiterPos <= end) { + // Extract and trim key + key_end = delimiterPos - 1; + while (key_end > start && (line[key_end] == ' ' || line[key_end] == '\t')) { + --key_end; + } + + if (key_end >= start) { + key.assign(line, start, key_end - start + 1); + + // Extract and trim value + val_start = delimiterPos + 1; + while (val_start <= end && (line[val_start] == ' ' || line[val_start] == '\t')) { + ++val_start; + } + + if (val_start <= end) { + value.assign(line, val_start, end - val_start + 1); + } else { + value.clear(); + } + + (*currentSectionMap)[key] = std::move(value); + } + } + // Clear strings to reuse capacity + line.clear(); + key.clear(); + value.clear(); + } + } + + 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. + * + * @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) { + // logMessage("Failed to open the file: " + configIniPath); + return sectionData; // Return empty map if file cannot be opened + } + + char buffer[1024]; + std::string line; + //line.reserve(1024); // Reserve to match buffer size + + std::string currentSection; + //currentSection.reserve(64); // Reserve for section names + + size_t delimiterPos; + std::string key, value; + //key.reserve(128); // Reserve for key names + //value.reserve(256); // Reserve for values + + bool inTargetSection = false; // To track if we're in the desired section + + size_t len; + + while (fgets(buffer, sizeof(buffer), file)) { + // More efficient newline removal + 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); + + if (line.empty()) { + line.clear(); // Clear even for empty lines + continue; // Skip empty lines + } + + if (line[0] == '[' && line.back() == ']') { + // More efficient section name extraction + currentSection.assign(line, 1, line.size() - 2); + // Check if this is the section we're interested in + inTargetSection = (currentSection == sectionName); + + // Early exit optimization: if we were in target section and hit a new section, we're done + if (!inTargetSection && !sectionData.empty()) { + // Clear before breaking + line.clear(); + currentSection.clear(); + break; // Found target section and processed it, no need to continue + } + + // Clear strings to reuse capacity + line.clear(); + currentSection.clear(); + } else if (inTargetSection) { + // Look for key-value pairs within the target section + delimiterPos = line.find('='); + if (delimiterPos != std::string::npos) { + key.assign(line, 0, delimiterPos); // More efficient than substr + trim(key); + value.assign(line, delimiterPos + 1, std::string::npos); // More efficient than substr + trim(value); + sectionData[std::move(key)] = std::move(value); // Move semantics to avoid copies + + // Clear strings after moving to reuse capacity + //key.clear(); + //value.clear(); + } + line.clear(); + } else { + line.clear(); // Clear line when not in target section + } + } + + fclose(file); + #else + std::ifstream configFile(configIniPath); + if (!configFile) { + // logMessage("Failed to open the file: " + configIniPath); + return sectionData; // Return empty map if file cannot be opened + } + + std::string line; + //line.reserve(1024); // Reserve for typical line length + + std::string currentSection; + //currentSection.reserve(64); // Reserve for section names + + size_t delimiterPos; + std::string key, value; + //key.reserve(128); // Reserve for key names + //value.reserve(256); // Reserve for values + + bool inTargetSection = false; // To track if we're in the desired section + + while (getline(configFile, line)) { + // Remove carriage return if present (getline already removes \n) + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + + trim(line); + + if (line.empty()) { + line.clear(); // Clear even for empty lines + continue; // Skip empty lines + } + + if (line[0] == '[' && line.back() == ']') { + // More efficient section name extraction + currentSection.assign(line, 1, line.size() - 2); + // Check if this is the section we're interested in + inTargetSection = (currentSection == sectionName); + + // Early exit optimization: if we were in target section and hit a new section, we're done + if (!inTargetSection && !sectionData.empty()) { + // Clear before breaking + line.clear(); + currentSection.clear(); + break; // Found target section and processed it, no need to continue + } + + // Clear strings to reuse capacity + line.clear(); + currentSection.clear(); + } else if (inTargetSection) { + // Look for key-value pairs within the target section + delimiterPos = line.find('='); + if (delimiterPos != std::string::npos) { + key.assign(line, 0, delimiterPos); // More efficient than substr + trim(key); + value.assign(line, delimiterPos + 1, std::string::npos); // More efficient than substr + trim(value); + sectionData[std::move(key)] = std::move(value); // Move semantics to avoid copies + + // Clear strings after moving to reuse capacity + //key.clear(); + //value.clear(); + } + line.clear(); + } else { + line.clear(); // Clear line when not in target section + } + } + + configFile.close(); + #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]; + std::string currentSection; + std::string currentKey; + + //size_t delimiterPos; + bool inTargetSection = false; + bool wasInTargetSection = false; // Track if we've been in the target section + + size_t len; + const char* start; + const char* end; + + while (fgets(buffer, sizeof(buffer), file)) { + // More efficient newline removal + len = strlen(buffer); + if (len > 0 && buffer[len-1] == '\n') { + buffer[len-1] = '\0'; + --len; + if (len > 0 && buffer[len-1] == '\r') { + buffer[len-1] = '\0'; + --len; + } + } + + // Early exit for empty lines + if (len == 0) continue; + + // Manual trim for better performance - find start of non-whitespace + start = buffer; + while (*start == ' ' || *start == '\t') ++start; + + // Find end of non-whitespace (working backwards from known end) + end = buffer + 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; + + // Check for section header first + if (*start == '[' && *end == ']') { + if (len > 2) { + currentSection.assign(start + 1, len - 2); + inTargetSection = (currentSection == sectionName); + + // Early exit: if we WERE in target section and now we're not, key wasn't found + if (wasInTargetSection && !inTargetSection) { + break; // Left target section without finding key + } + + if (inTargetSection) { + wasInTargetSection = true; + } + } + // Clear section string to reuse capacity + currentSection.clear(); + } else if (inTargetSection) { + // Look for '=' delimiter - scan from start for efficiency + const char* eq_pos = start; + while (eq_pos <= end && *eq_pos != '=') { + ++eq_pos; + } + + if (eq_pos <= end) { // Found '=' delimiter + // Extract and trim key + const char* key_end = eq_pos - 1; + while (key_end >= start && (*key_end == ' ' || *key_end == '\t')) --key_end; + + if (key_end >= start) { + currentKey.assign(start, key_end - start + 1); + + if (currentKey == keyName) { + // Extract and trim value + const char* val_start = eq_pos + 1; + while (val_start <= end && (*val_start == ' ' || *val_start == '\t')) ++val_start; + + if (val_start <= end) { + value.assign(val_start, end - val_start + 1); + } + currentKey.clear(); // Clear before breaking + // Found the key, exit + break; + } + } + } + // Clear key string to reuse capacity + currentKey.clear(); + } + } + + fclose(file); + #else + std::ifstream file(filePath); + if (!file) { + return value; + } + + std::string line; + std::string currentSection; + std::string currentKey; + + size_t delimiterPos; + bool inTargetSection = false; + bool wasInTargetSection = false; // Track if we've been in the target section + + size_t start, end, key_end, val_start; + while (std::getline(file, line)) { + 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; + } + + // Check for section header first + if (line[start] == '[' && line[end] == ']') { + if (end > start + 1) { + currentSection.assign(line, start + 1, end - start - 1); + inTargetSection = (currentSection == sectionName); + + // Early exit: if we WERE in target section and now we're not, key wasn't found + if (wasInTargetSection && !inTargetSection) { + // Clear strings to reuse capacity + line.clear(); + currentSection.clear(); + break; // Left target section without finding key + } + + if (inTargetSection) { + wasInTargetSection = true; + } + } + // Clear strings to reuse capacity + line.clear(); + currentSection.clear(); + } else if (inTargetSection) { + // Look for '=' delimiter within the trimmed range + delimiterPos = line.find('=', start); + if (delimiterPos != std::string::npos && delimiterPos <= end) { + // Extract and trim key + key_end = delimiterPos - 1; + while (key_end > start && (line[key_end] == ' ' || line[key_end] == '\t')) { + --key_end; + } + + if (key_end >= start) { + currentKey.assign(line, start, key_end - start + 1); + + if (currentKey == keyName) { + // Extract and trim value + val_start = delimiterPos + 1; + while (val_start <= end && (line[val_start] == ' ' || line[val_start] == '\t')) { + ++val_start; + } + + if (val_start <= end) { + value.assign(line, val_start, end - val_start + 1); + } + // Found the key, exit + break; + } + } + } + // Clear strings to reuse capacity + line.clear(); + currentKey.clear(); + } + } + + 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(); + //} + + + void syncIniValue(std::map>& packageConfigData, + const std::string& packageConfigIniPath, + const std::string& optionName, + const std::string& key, + std::string& value) { + auto optionIt = packageConfigData.find(optionName); + if (optionIt != packageConfigData.end()) { + auto it = optionIt->second.find(key); + if (it != optionIt->second.end()) { + value = it->second; // Update value only if the key exists + //} else { + // setIniFileValue(packageConfigIniPath, optionName, key, value); // Set INI file value if key not found + //} + } else { + // Key not found - add it to in-memory data and save entire structure + packageConfigData[optionName][key] = value; + saveIniFileData(packageConfigIniPath, packageConfigData); + } + } + } + + + /** + * @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 {}; // Return empty vector if file can't be opened + + std::vector>>> options; + + char line[1024]; + std::string currentSection; + std::vector> sectionCommands; + std::string strLine; + + size_t len; + //const char* start; + //const char* end; + + while (fgets(line, sizeof(line), packageFile)) { + // 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; + + // Check for comments early (most efficient check) + if (line[0] == '#') continue; + + // Assign the processed line + strLine.assign(line, len); + + if (strLine[0] == '[' && strLine.back() == ']') { // Section headers + if (!currentSection.empty()) { + options.emplace_back(std::move(currentSection), std::move(sectionCommands)); + //sectionCommands.clear(); + //sectionCommands.shrink_to_fit(); // Free capacity after move + } + currentSection.assign(strLine, 1, strLine.size() - 2); + } else if (!currentSection.empty()) { // Command lines within sections + sectionCommands.push_back(parseCommandLine(strLine)); + } + + // Clear strLine content to free string memory + strLine.clear(); + } + + if (!currentSection.empty()) { + options.emplace_back(std::move(currentSection), std::move(sectionCommands)); + } + + fclose(packageFile); + #else + std::ifstream packageFile(packageIniPath); + if (!packageFile) return {}; // Return empty vector if file can't be opened + + std::vector>>> options; + + std::string line, currentSection; + std::vector> sectionCommands; + + while (std::getline(packageFile, line)) { + // Remove carriage return if present (getline already removes \n) + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + + // Early exits for empty lines and comments + if (line.empty() || line[0] == '#') continue; + + if (line[0] == '[' && line.back() == ']') { // Section headers + if (!currentSection.empty()) { + options.emplace_back(std::move(currentSection), std::move(sectionCommands)); + //sectionCommands.clear(); + //sectionCommands.shrink_to_fit(); // Free capacity after move + } + currentSection.assign(line, 1, line.size() - 2); + } else if (!currentSection.empty()) { // Command lines within sections + sectionCommands.push_back(parseCommandLine(line)); + } + // Clear line content to reuse capacity + line.clear(); + } + + 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 {}; // Return empty vector if file can't be opened + + std::vector> sectionCommands; + + char line[1024]; + std::string currentSection; + bool inTargetSection = false; + std::string strLine; + + size_t len; + + while (fgets(line, sizeof(line), packageFile)) { + // 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; + + // Check for comments early (most efficient check) + if (line[0] == '#') continue; + + // Assign the processed line + strLine.assign(line, len); + + if (strLine[0] == '[' && strLine.back() == ']') { // Section headers + currentSection.assign(strLine, 1, strLine.size() - 2); + inTargetSection = (currentSection == sectionName); // Check if this is the target section + + // Early exit optimization: if we were in target section and hit a new section, we're done + if (!inTargetSection && !sectionCommands.empty()) { + break; // Found target section and processed it, no need to continue + } + } else if (inTargetSection) { // Only parse commands within the target section + sectionCommands.push_back(parseCommandLine(strLine)); + } + + // Clear strings to reuse capacity + strLine.clear(); + currentSection.clear(); + } + + fclose(packageFile); + #else + std::ifstream packageFile(packageIniPath); + + if (!packageFile) return {}; // Return empty vector if file can't be opened + + std::string line, currentSection; + std::vector> sectionCommands; + bool inTargetSection = false; + + while (std::getline(packageFile, line)) { + // Remove carriage return if present (getline already removes \n) + if (!line.empty() && line.back() == '\r') { + line.pop_back(); + } + + // Early exits for empty lines and comments + if (line.empty() || line[0] == '#') continue; + + if (line[0] == '[' && line.back() == ']') { // Section headers + currentSection.assign(line, 1, line.size() - 2); + inTargetSection = (currentSection == sectionName); // Check if this is the target section + + // Early exit optimization: if we were in target section and hit a new section, we're done + if (!inTargetSection && !sectionCommands.empty()) { + break; // Found target section and processed it, no need to continue + } + } else if (inTargetSection) { // Only parse commands within the target section + sectionCommands.push_back(parseCommandLine(line)); + } + + // Clear strings to reuse capacity + strLine.clear(); + currentSection.clear(); + } + + packageFile.close(); + #endif + + return sectionCommands; // Return only the commands from the target section + } + + + /** + * @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) { + // Handle error: could not open file + return; + } + + for (const auto& section : data) { + fprintf(file, "[%s]\n", section.first.c_str()); + for (const auto& kv : section.second) { + fprintf(file, "%s=%s\n", kv.first.c_str(), kv.second.c_str()); + } + fprintf(file, "\n"); // Separate sections with a newline + } + + fclose(file); + #else + 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(); + #endif + } +} \ 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 new file mode 100644 index 00000000..132dffc1 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/json_funcs.cpp @@ -0,0 +1,400 @@ +/******************************************************************************** + * 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) 2024 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& text, size_t fontSize) { + u64 tick = armGetSystemTick(); + std::string filename = "20-" + std::to_string(tick) + ".notify"; // priority 20 default + + // Build full path + 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 new file mode 100644 index 00000000..f5128d90 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/list_funcs.cpp @@ -0,0 +1,467 @@ +/******************************************************************************** + * 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) 2024 ppkantorski + ********************************************************************************/ + +#include +#include + +namespace ult { + // 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 + std::vector readListFromFile(const std::string& filePath, size_t maxLines) { + 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; + } + + // More efficient newline removal + 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; + } + + // 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) { + 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'; + } + lines.insert(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)) { + 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("Failed 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("Failed to open file: " + filePath); + #endif + return; + } + + for (const auto& entry : fileSet) { + file << entry << '\n'; + } + + file.close(); + #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); + std::unordered_set duplicateFiles; + + // Find intersection (common elements) between the two sets + for (const auto& entry : fileSet1) { + if (fileSet2.count(entry)) { + duplicateFiles.insert(entry); + } + } + + // Write the duplicates to the output file + writeSetToFile(duplicateFiles, 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) { + 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 + return; + } + + // OPTIMIZATION 1: Larger buffer for better I/O performance + static constexpr size_t BUFFER_SIZE = 8192; + char buffer[BUFFER_SIZE]; + + while (fgets(buffer, BUFFER_SIZE, file)) { + // OPTIMIZATION 2: Find newline directly instead of strlen() + char* newlinePos = strchr(buffer, '\n'); + if (newlinePos) { + *newlinePos = '\0'; // Remove newline in-place + } + + // OPTIMIZATION 3: Pass buffer directly - no string construction overhead + callback(std::string(buffer)); + } + + fclose(file); + + #else + // OPTIMIZATION 4: Use faster I/O for fstream version + std::ifstream file(filePath); + if (!file.is_open()) { + #if USING_LOGGING_DIRECTIVE + logMessage("Unable to open file: " + filePath); + #endif + return; + } + + // OPTIMIZATION 5: Reserve string capacity to avoid reallocations + std::string line; + line.reserve(256); // Reasonable default for most lines + + while (std::getline(file, line)) { + callback(line); + } + #endif + } + + + void compareWildcardFilesLists( + const std::string& wildcardPatternFilePath, + const std::string& txtFilePath, + const std::string& outputTxtFilePath + ) { + // STEP 1: Read target file into fast lookup set (only once) + const std::unordered_set targetLines = readSetFromFile(txtFilePath); + std::unordered_set duplicates; + + // STEP 2: Get wildcard files + std::vector wildcardFiles = getFilesListByWildcards(wildcardPatternFilePath); + + // STEP 3: Process each wildcard file line-by-line (minimum memory) + for (auto& filePath : wildcardFiles) { + if (filePath == txtFilePath) { + filePath = ""; + continue; + } + + // Process line-by-line without loading entire file into memory + processFileLines(filePath, [&](const std::string& line) { + // O(1) lookup + O(1) insert if duplicate found + if (targetLines.count(line)) { + duplicates.insert(line); + } + }); + filePath = ""; + } + + // STEP 4: Write results + 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 new file mode 100644 index 00000000..29cc246e --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/mod_funcs.cpp @@ -0,0 +1,736 @@ +/******************************************************************************** + * 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 ppkantorski + ********************************************************************************/ + +#include + +namespace ult { + + //const std::string CHEAT_HEADER = "// auto generated by pchtxt2cheat\n\n"; + const std::string CHEAT_TYPE = "04000000"; + const std::string CHEAT_EXT = ".txt"; + 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 new file mode 100644 index 00000000..2c593a15 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/path_funcs.cpp @@ -0,0 +1,1446 @@ +/******************************************************************************** + * 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) 2024 ppkantorski + ********************************************************************************/ + +#include "path_funcs.hpp" + + +namespace ult { + std::atomic abortFileOp(false); + + size_t COPY_BUFFER_SIZE = 65536/8; // 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) + + // 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. + * + * 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) { + std::vector stack; + + // Batch logging optimization - collect successful deletions instead of logging immediately + std::vector successfulDeletions; + const bool needsLogging = !logSource.empty(); + + 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; + } + + stack.push_back(pathToDelete); + struct stat pathStat; + std::string currentPath, filePath; + bool isEmpty; + + while (!stack.empty()) { + currentPath = stack.back(); + + if (stat(currentPath.c_str(), &pathStat) != 0) { + stack.pop_back(); + continue; + } + + if (S_ISREG(pathStat.st_mode)) { // It's a file + stack.pop_back(); // Remove from stack before deletion + if (remove(currentPath.c_str()) == 0) { + // Batch logging - store successful deletion instead of writing immediately + if (needsLogging) { + successfulDeletions.push_back(currentPath); + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete file: " + currentPath); + #endif + } + } else if (S_ISDIR(pathStat.st_mode)) { // It's a directory + DIR* directory = opendir(currentPath.c_str()); + if (!directory) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open directory: " + currentPath); + #endif + stack.pop_back(); + continue; + } + + dirent* entry; + isEmpty = true; + while ((entry = readdir(directory)) != nullptr) { + const std::string& fileName = entry->d_name; + if (fileName != "." && fileName != "..") { + filePath = currentPath + fileName; + stack.push_back(filePath + (filePath.back() == '/' ? "" : "/")); + isEmpty = false; + } + } + closedir(directory); + + if (isEmpty) { + stack.pop_back(); // Directory is now empty, safe to remove from stack + if (rmdir(currentPath.c_str()) == 0) { + // Note: Typically we don't log directory deletions, only files + // If you want to log directory deletions too, uncomment the lines below: + // if (needsLogging) { + // successfulDeletions.push_back(currentPath); + // } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete directory: " + currentPath); + #endif + } + } + } else { + stack.pop_back(); // Unknown file type, just remove from stack + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Unknown file type: " + currentPath); + #endif + } + } + + // KEY OPTIMIZATION: Batch write all successful deletions to log file at the end + // This eliminates the overhead of logging inside the hot loop + 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. + * + * @param pathPattern The pattern used to match and delete files or directories. + */ + void deleteFileOrDirectoryByPattern(const std::string& pathPattern, const std::string& logSource) { + //logMessage("pathPattern: "+pathPattern); + std::vector fileList = getFilesListByWildcards(pathPattern); + + for (auto& path : fileList) { + //logMessage("path: "+path); + deleteFileOrDirectory(path, logSource); + path = ""; + } + } + + 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; + } + + // Batch logging optimization - collect successful operations instead of logging immediately + std::vector successfulSources, successfulDestinations; + bool needsLogging = !logSource.empty() || !logDestination.empty(); + + std::vector> stack; + std::vector directoriesToRemove; + + stack.push_back({sourcePath, destinationPath}); + + // Variables moved outside the loop to avoid repeated allocation + std::string name, fullPathSrc, fullPathDst; + dirent* entry; + DIR* dir; + + std::string currentSource, currentDestination; + while (!stack.empty()) { + std::tie(currentSource, currentDestination) = stack.back(); + stack.pop_back(); + + dir = opendir(currentSource.c_str()); + if (!dir) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open source directory: " + currentSource); + #endif + continue; + } + + while ((entry = readdir(dir)) != nullptr) { + name = entry->d_name; + if (name == "." || name == "..") continue; + + // Optimize string concatenation - avoid repeated substr operations + fullPathSrc = currentSource; + if (!fullPathSrc.empty() && fullPathSrc.back() == '/') { + fullPathSrc.pop_back(); + } + fullPathSrc += "/" + name; + + fullPathDst = currentDestination; + if (!fullPathDst.empty() && fullPathDst.back() == '/') { + fullPathDst.pop_back(); + } + fullPathDst += "/" + name; + + if (entry->d_type == DT_DIR) { + if (mkdir(fullPathDst.c_str(), 0777) != 0 && errno != EEXIST) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to create destination directory: " + fullPathDst); + #endif + continue; + } + stack.push_back({fullPathSrc, fullPathDst}); + directoriesToRemove.push_back(fullPathSrc); + + // Log each subdirectory that gets successfully created + if (needsLogging) { + successfulSources.push_back(fullPathSrc + "/"); + successfulDestinations.push_back(fullPathDst + "/"); + } + } else { + remove(fullPathDst.c_str()); + if (rename(fullPathSrc.c_str(), fullPathDst.c_str()) == 0) { + // Batch logging - store successful operations instead of writing immediately + if (needsLogging) { + successfulSources.push_back(fullPathSrc); + successfulDestinations.push_back(fullPathDst); + } + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to move: " + fullPathSrc); + #endif + } + } + } + closedir(dir); + } + + // Clean up source directories in reverse order + for (auto it = directoriesToRemove.rbegin(); it != directoriesToRemove.rend(); ++it) { + if (rmdir(it->c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete source directory: " + *it); + #endif + } + } + + if (rmdir(sourcePath.c_str()) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to delete source directory: " + sourcePath); + #endif + } + + // KEY OPTIMIZATION: Batch write all successful operations to log files at the end + // This eliminates the overhead of logging inside the hot loop + if (needsLogging && !successfulSources.empty()) { + #if !USING_FSTREAM_DIRECTIVE + if (!logSource.empty()) { + createDirectory(getParentDirFromPath(logSource)); + if (FILE* logFile = fopen(logSource.c_str(), "a")) { + for (auto it = successfulSources.rbegin(); it != successfulSources.rend(); ++it) { + writeLog(logFile, *it); + } + 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")) { + for (auto it = successfulDestinations.rbegin(); it != successfulDestinations.rend(); ++it) { + writeLog(logFile, *it); + } + 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()) { + for (auto it = successfulSources.rbegin(); it != successfulSources.rend(); ++it) { + writeLog(logSourceFile, *it); + } + 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()) { + for (auto it = successfulDestinations.rbegin(); it != successfulDestinations.rend(); ++it) { + writeLog(logDestFile, *it); + } + logDestFile.close(); + } + #if USING_LOGGING_DIRECTIVE + else { + if (!disableLogging) + logMessage("Failed to open destination log file: " + logDestination); + } + #endif + } + #endif + } + } + + 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. + * + * @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. + */ + void moveFilesOrDirectoriesByPattern(const std::string& sourcePathPattern, const std::string& destinationPath, + const std::string& logSource, const std::string& logDestination) { + + std::vector fileList = getFilesListByWildcards(sourcePathPattern); + + //std::string fileListAsString; + //for (const std::string& filePath : fileList) + // fileListAsString += filePath + "\n"; + //logMessage("File List:\n" + fileListAsString); + + //logMessage("pre loop"); + std::string folderName, fixedDestinationPath; + + // Iterate through the file list + for (std::string& sourceFileOrDirectory : fileList) { + //logMessage("sourceFileOrDirectory: "+sourceFileOrDirectory); + // if sourceFile is a file (Needs condition handling) + if (!isDirectory(sourceFileOrDirectory)) { + //logMessage("destinationPath: "+destinationPath); + moveFileOrDirectory(sourceFileOrDirectory.c_str(), destinationPath.c_str(), logSource, logDestination); + } else if (isDirectory(sourceFileOrDirectory)) { + // if sourceFile is a directory (needs conditoin handling) + folderName = getNameFromPath(sourceFileOrDirectory); + fixedDestinationPath = destinationPath + folderName + "/"; + + //logMessage("fixedDestinationPath: "+fixedDestinationPath); + + moveFileOrDirectory(sourceFileOrDirectory.c_str(), fixedDestinationPath.c_str(), logSource, logDestination); + } + sourceFileOrDirectory = ""; + } + //logMessage("post loop"); + } + + /** + * @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; + std::queue directories; + directories.push(path); + std::string currentPath, newPath; + + while (!directories.empty()) { + currentPath = directories.front(); + directories.pop(); + + DIR* dir = opendir(currentPath.c_str()); + if (!dir) { + continue; // Cannot open directory, skip it + } + + dirent* entry; + while ((entry = readdir(dir)) != nullptr) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { + continue; // Skip "." and ".." + } + newPath = currentPath + "/" + entry->d_name; + + if (lstat(newPath.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)) { + directories.push(newPath); // Push subdirectory onto queue for processing + } + } + 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; + + // Batch logging optimization - collect successful operations instead of logging immediately + std::vector successfulSources, successfulDestinations; + bool needsLogging = !logSource.empty() || !logDestination.empty(); + bool filesCopied = false; + + if (isTopLevelCall) { + totalSize = getTotalSize(fromPath); + totalBytesCopied = &tempBytesCopied; + } + + if (toPath.back() != '/') { + // If toPath is a file, create its parent directory and copy the file + createDirectory(getParentDirFromPath(toPath)); + copySingleFile(fromPath, toPath, *totalBytesCopied, totalSize, logSource, logDestination); + return; + } + + // Ensure the toPath directory exists + createDirectory(toPath); + + std::vector> directories; + directories.emplace_back(fromPath, toPath); // Use emplace_back for efficiency + + size_t currentDirectoryIndex = 0; + + // Pre-declare strings to avoid repeated allocations + std::string filename, toFilePath, toDirPath, currentFromPath, currentToPath; + std::string subFromPath, subToPath; + + struct stat fromStat; + + while (currentDirectoryIndex < directories.size()) { + if (abortFileOp.load(std::memory_order_acquire)) { + copyPercentage.store(-1, std::memory_order_release); + return; + } + + // Use structured binding more efficiently + const auto& [currentFrom, currentTo] = directories[currentDirectoryIndex++]; + currentFromPath = currentFrom; + currentToPath = currentTo; + + if (stat(currentFromPath.c_str(), &fromStat) != 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to get stat of " + currentFromPath); + #endif + continue; + } + + if (S_ISREG(fromStat.st_mode)) { + // If it's a regular file, copy it to the toPath directory + filename = getNameFromPath(currentFromPath); + + // More efficient path building + toFilePath.assign(getParentDirFromPath(currentToPath)); + toFilePath += '/'; + toFilePath += filename; + + createDirectory(getParentDirFromPath(toFilePath)); // Ensure the parent directory exists + copySingleFile(currentFromPath, toFilePath, *totalBytesCopied, totalSize, logSource, logDestination); + + // Mark that files were copied + filesCopied = true; + + if (totalSize > 0) { + copyPercentage.store(static_cast((*totalBytesCopied * 100) / totalSize), std::memory_order_release); // Update progress + } + } else if (S_ISDIR(fromStat.st_mode)) { + // If it's a directory, iterate over its contents and add them to the vector for processing + DIR* dir = opendir(currentFromPath.c_str()); + if (!dir) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open directory: " + currentFromPath); + #endif + continue; + } + + bool hasContent = false; + // Cache current path lengths for efficient string building + dirent* entry; + while ((entry = readdir(dir)) != nullptr) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) continue; + + hasContent = true; + + // More efficient path building + subFromPath.clear(); + subFromPath.assign(currentFromPath); + subFromPath += '/'; + subFromPath += entry->d_name; + + subToPath.clear(); + subToPath.assign(currentToPath); + subToPath += '/'; + subToPath += entry->d_name; + + directories.emplace_back(std::move(subFromPath), std::move(subToPath)); // Use move semantics + } + closedir(dir); + + // Log this directory if it has content and we need logging + if (hasContent && needsLogging) { + successfulSources.push_back(currentFromPath + "/"); + successfulDestinations.push_back(currentToPath + "/"); + } + } + } + + // Batch write all successful operations to log files at the end + if (isTopLevelCall && needsLogging && filesCopied && !successfulSources.empty()) { + #if !USING_FSTREAM_DIRECTIVE + if (!logSource.empty()) { + createDirectory(getParentDirFromPath(logSource)); + if (FILE* logFile = fopen(logSource.c_str(), "a")) { + for (auto it = successfulSources.rbegin(); it != successfulSources.rend(); ++it) { + writeLog(logFile, *it); + } + 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")) { + for (auto it = successfulDestinations.rbegin(); it != successfulDestinations.rend(); ++it) { + writeLog(logFile, *it); + } + 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()) { + for (auto it = successfulSources.rbegin(); it != successfulSources.rend(); ++it) { + writeLog(logSourceFile, *it); + } + 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()) { + for (auto it = successfulDestinations.rbegin(); it != successfulDestinations.rend(); ++it) { + writeLog(logDestFile, *it); + } + 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); // Set progress to 100% on completion of top-level call + } + } + + + + /** + * @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. + * + * @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. + */ + void copyFileOrDirectoryByPattern(const std::string& sourcePathPattern, const std::string& toDirectory, + const std::string& logSource, const std::string& logDestination) { + std::vector fileList = getFilesListByWildcards(sourcePathPattern); + long long totalSize = 0; + for (const std::string& path : fileList) { + totalSize += getTotalSize(path); + } + + long long totalBytesCopied = 0; + for (std::string& sourcePath : fileList) { + copyFileOrDirectory(sourcePath, toDirectory, &totalBytesCopied, totalSize, logSource, logDestination); + sourcePath = ""; + } + //copyPercentage.store(-1, std::memory_order_release); // Reset after operation + } + + + + /** + * @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) { + std::vector 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(); + } + + /** + * @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 + std::vector allMatches = ult::getFilesListByWildcards(wildcardPattern); + if (allMatches.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 : allMatches) { + 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 = ""; + } + } + + /** + * @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* rootDir = opendir(sourcePath.c_str()); + if (!rootDir) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Path is not a directory or cannot open: " + sourcePath); + #endif + return; + } + closedir(rootDir); + + std::vector stack; + stack.push_back(sourcePath); + + struct dirent* entry; + struct stat pathStat{}; + std::string subDirPath; // reuse for directories + std::string filePath; // reuse for dot-underscore files + + while (!stack.empty()) { + const std::string currentPath = std::move(stack.back()); + stack.pop_back(); + + DIR* directory = opendir(currentPath.c_str()); + if (!directory) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to open directory: " + currentPath); + #endif + continue; + } + + while ((entry = readdir(directory)) != nullptr) { + const char* fileName = entry->d_name; + + // Skip "." and ".." + if (fileName[0] == '.' && + (fileName[1] == '\0' || (fileName[1] == '.' && fileName[2] == '\0'))) { + continue; + } + + // Handle directories first + if (entry->d_type == DT_DIR) { + subDirPath.clear(); + subDirPath = currentPath; + if (!subDirPath.empty() && subDirPath.back() != '/') + subDirPath += '/'; + subDirPath += fileName; + stack.push_back(std::move(subDirPath)); + continue; + } + + // Only care about "._" files + if (!(fileName[0] == '.' && fileName[1] == '_')) + continue; + + // Only process files or unknown types + if (entry->d_type != DT_REG && entry->d_type != DT_UNKNOWN) + continue; + + filePath.clear(); + filePath = currentPath; + if (!filePath.empty() && filePath.back() != '/') + filePath += '/'; + filePath += fileName; + + // If type unknown, verify with stat + if (entry->d_type == DT_UNKNOWN) { + if (stat(filePath.c_str(), &pathStat) != 0 || !S_ISREG(pathStat.st_mode)) + continue; + } + + if (remove(filePath.c_str()) == 0) { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Removed dot-underscore file: " + filePath); + #endif + } else { + #if USING_LOGGING_DIRECTIVE + if (!disableLogging) + logMessage("Failed to remove dot-underscore file: " + filePath); + #endif + } + } + + closedir(directory); + } + } +} \ 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 new file mode 100644 index 00000000..8cef0b74 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/string_funcs.cpp @@ -0,0 +1,609 @@ +/******************************************************************************** + * 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) 2024 ppkantorski + ********************************************************************************/ + +#include "string_funcs.hpp" + +namespace ult { + + + // Custom string conversion methods in place of std:: + std::string to_string(int value) { + char buffer[12]; // Sufficient for 32-bit int + snprintf(buffer, sizeof(buffer), "%d", value); + return std::string(buffer); + } + + int stoi(const std::string& str, std::size_t* pos, int base) { + char* end; + const long result = std::strtol(str.c_str(), &end, base); + + if (pos) { + *pos = end - str.c_str(); // Set the position to the last character processed + } + + // Handle out-of-range or conversion issues here if needed + return static_cast(result); + } + + + float stof(const std::string& str) { + return strtof(str.c_str(), nullptr); + } + + + // Mimics std::getline() with a delimiter + bool StringStream::getline(std::string& output, char delimiter) { + if (position >= data.size()) { + return false; + } + + const size_t nextPos = data.find(delimiter, position); + + if (nextPos != std::string::npos) { + output.assign(data, position, nextPos - position); // No temporary string creation + position = nextPos + 1; + } else { + output.assign(data, position, data.size() - position); // No temporary string creation + position = data.size(); + } + + return true; + } + + // Mimics operator >> to split by whitespace + StringStream& StringStream::operator>>(std::string& output) { + // Skip leading whitespace + while (position < data.size() && std::isspace(data[position])) { + ++position; + } + + if (position >= data.size()) { + output.clear(); + validState = false; + return *this; + } + + size_t nextPos = position; + while (nextPos < data.size() && !std::isspace(data[nextPos])) { + ++nextPos; + } + + output.assign(data, position, nextPos - position); // Replace substr() with assign() + position = nextPos; + + validState = true; + return *this; + } + + // Overload << operator for std::string + StringStream& StringStream::operator<<(const std::string& input) { + data += input; + return *this; + } + + // Overload << operator for const char* + StringStream& StringStream::operator<<(const char* input) { + data += input; + return *this; + } + + // Overload << operator for char + StringStream& StringStream::operator<<(char input) { + data += input; + return *this; + } + + // Overload << operator for int (handles hex mode) + StringStream& StringStream::operator<<(int input) { + if (hexMode) { + char buffer[20]; // Buffer large enough for hex conversion + sprintf(buffer, "%x", input); // Convert integer to hex string + data += buffer; + } else { + data += ult::to_string(input); + } + return *this; + } + + // Define the new overload for long long + StringStream& StringStream::operator<<(long long input) { + data += std::to_string(input); + return *this; + } + + // Return the current buffer content + std::string StringStream::str() const { + return data; + } + + + + /** + * @brief Trims leading and trailing whitespaces from a string. + * + * This function removes leading and trailing whitespaces, tabs, newlines, carriage returns, form feeds, + * and vertical tabs from the input string. + * + * @param str The input string to trim. + * @return The trimmed string. + */ + void trim(std::string& str) { + const size_t first = str.find_first_not_of(" \t\n\r\f\v"); + if (first == std::string::npos) { + str.clear(); // Fix: clear all-whitespace strings + return; + } + + const size_t last = str.find_last_not_of(" \t\n\r\f\v"); + + // True in-place modification - no temporary string creation + if (last + 1 < str.length()) { + str.erase(last + 1); // Remove trailing whitespace + } + if (first > 0) { + str.erase(0, first); // Remove leading whitespace + } + } + + + // Function to trim newline characters from the end of a string + void trimNewline(std::string& str) { + const size_t end = str.find_last_not_of("\n"); + if (end == std::string::npos) { + str.clear(); // If the string consists entirely of newlines, clear it + } else { + str.erase(end + 1); // Remove all characters after the last non-newline character + } + } + + + /** + * @brief Removes all white spaces from a string. + * + * This function removes all white spaces, including spaces, tabs, newlines, carriage returns, form feeds, + * and vertical tabs from the input string. + * + * @param str The input string to remove white spaces from. + * @return The string with white spaces removed. + */ + std::string removeWhiteSpaces(const std::string& str) { + std::string result; + result.reserve(str.size()); // Reserve space for the result to avoid reallocations + + std::remove_copy_if(str.begin(), str.end(), std::back_inserter(result), [](unsigned char c) { + return std::isspace(c); + }); + + return result; + } + + + + /** + * @brief Removes quotes from a string. + * + * This function removes single and double quotes from the beginning and end of the input string. + * + * @param str The input string to remove quotes from. + * @return The string with quotes removed. + */ + void removeQuotes(std::string& str) { + if (str.size() >= 2) { + const char front = str[0]; + const char back = str[str.size() - 1]; + if ((front == '\'' && back == '\'') || (front == '"' && back == '"')) { + str.erase(0, 1); + str.pop_back(); + } + } + } + + + /** + * @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); + + // In-place multiple slash removal - no temporary string creation + if (!path.empty()) { + size_t writePos = 0; + bool previousSlash = false; + + for (size_t i = 0; i < path.length(); ++i) { + if (path[i] == '/') { + if (!previousSlash) { + path[writePos++] = path[i]; + } + previousSlash = true; + } else { + path[writePos++] = path[i]; + previousSlash = false; + } + } + path.resize(writePos); + } + + // First handle "./" replacement if present + if (!packagePath.empty() && path.length() >= 2 && path[0] == '.' && path[1] == '/') { + // Handle "./" - replace with packagePath + path.replace(0, 2, packagePath); + } + + size_t dotDotPos, lastSlash; + std::string beforeDotDot; + + // Then handle any "../" sequences that may exist anywhere in the path + while (!path.empty()) { + dotDotPos = path.find("../"); + if (dotDotPos == std::string::npos) { + break; // No more "../" sequences found + } + + // Found "../" sequence at dotDotPos + beforeDotDot = path.substr(0, dotDotPos); + + // Remove trailing slash from the part before "../" + if (!beforeDotDot.empty() && beforeDotDot.back() == '/') { + beforeDotDot.pop_back(); + } + + // Go up one level + lastSlash = beforeDotDot.find_last_of('/'); + if (lastSlash != std::string::npos) { + beforeDotDot = beforeDotDot.substr(0, lastSlash + 1); + } else { + // No slash found, we're at root level + beforeDotDot = "/"; + } + + // Replace the path up to and including this "../" with the resolved path + path = beforeDotDot + path.substr(dotDotPos + 3); + } + + // Direct character comparison instead of substr() 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.compare(0, 7, "http://") == 0) || (path.compare(0, 8, "https://") == 0)) { + return; // No need to modify the string if it already has a prefix + } else { + path = "https://" + path; // Prepend "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.find_last_of('.'); // Single char instead of string + 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() || ((str[0] != '-') && !std::isdigit(str[0])) || (str[0] == '-' && str.size() == 1)) { + return false; + } + for (size_t i = 1; i < str.size(); ++i) { + if (!std::isdigit(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 size_t pos = input.find('?'); + if (pos != std::string::npos) { + input.resize(pos); // Modify the string in-place to remove everything after the '?' + } + } + + + 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 new file mode 100644 index 00000000..efbdcf7e --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/libultra/source/tsl_utils.cpp @@ -0,0 +1,1684 @@ +/******************************************************************************** + * 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) 2024 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; + + 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); + result[key] = value; + key.clear(); + value.clear(); + + pos = valueEnd + 1; // Move to the next key-value 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; + ApmPerformanceMode perfMode = ApmPerformanceMode_Invalid; + + // Initialize the APM service + rc = apmInitialize(); + if (R_FAILED(rc)) { + return false; // Fail early if initialization fails + } + + // Get the current performance mode + rc = apmGetPerformanceMode(&perfMode); + apmExit(); // Clean up the APM service + + if (R_FAILED(rc)) { + return false; // Fail early if performance mode check fails + } + + // Check if the performance mode indicates docked state + if (perfMode == ApmPerformanceMode_Boost) { + return true; // System is docked (boost mode active) + } + + return false; // Not docked (normal mode or handheld) + } + + //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 getTitleIdAsString() { + u64 pid = 0, tid = 0; + if (R_FAILED(pmdmntGetApplicationProcessId(&pid))) + return NULL_STR; + + if (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 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 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"; + + 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 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 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 MODES = "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 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 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 SELECTION_IS_EMPTY = "Selection is empty!"; + + + //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 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"; + 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"; + 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"; + MODES = "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"; + FREE = "free"; + 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"; + 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"; + SELECTION_IS_EMPTY = "Selection is empty!"; + + //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; + } + + + static 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}, + {"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}, + {"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}, + {"MODES", &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}, + + {"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}, + {"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}, + {"SELECTION_IS_EMPTY", &SELECTION_IS_EMPTY}, + + //{"PACKAGE_VERSIONS", &PACKAGE_VERSIONS}, + //{"PROGRESS_ANIMATION", &PROGRESS_ANIMATION}, + + {"REBOOT_TO", &REBOOT_TO}, + {"REBOOT", &REBOOT}, + {"SHUTDOWN", &SHUTDOWN}, + {"BOOT_ENTRY", &BOOT_ENTRY}, + #endif + + {"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) { + // Static maps for replacements + #if IS_LAUNCHER_DIRECTIVE + const std::unordered_map launcherReplacements = { + {"Reboot To", &REBOOT_TO}, + {"Boot Entry", &BOOT_ENTRY}, + {"Reboot", &REBOOT}, + {"Shutdown", &SHUTDOWN} + }; + #endif + + const std::unordered_map valueReplacements = { + {"On", &ON}, + {"Off", &OFF} + }; + + // Determine which map to use + const std::unordered_map* replacements = nullptr; + + if (!isValue) { + #if IS_LAUNCHER_DIRECTIVE + replacements = &launcherReplacements; + #else + return; + #endif + } else { + replacements = &valueReplacements; + } + + // Perform the direct replacement + if (replacements) { + auto it = replacements->find(text); + if (it != replacements->end()) { + text = *(it->second); + } + } + } + + + + // 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}, + {"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", "AAAAAA"}, + {"overlay_version_text_color", "AAAAAA"}, + {"ult_overlay_version_text_color", "00FFDD"}, + {"package_version_text_color", "AAAAAA"}, + {"ult_package_version_text_color", "00FFDD"}, + {"on_text_color", "00FFDD"}, + {"off_text_color", "AAAAAA"}, + {"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"}, + {"trackbar_color", "555555"}, + {"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; + } + + + + float calculateAmplitude(float x, float peakDurationFactor) { + //const float phasePeriod = 360.0f * peakDurationFactor; // One full phase period + + // Convert x from radians to degrees and calculate phase within the period + const int phase = static_cast(x * RAD_TO_DEG) % static_cast(360.0f * peakDurationFactor); + + // Check if the phase is odd using bitwise operation + if (phase & 1) { + return 1.0f; // Flat amplitude (maximum positive) + } else { + // Calculate the sinusoidal amplitude for the remaining period + return (APPROXIMATE_cos(x) + 1.0f) / 2.0f; // Cosine function expects radians + } + } + + + + std::atomic refreshWallpaper(false); + std::vector wallpaperData; + std::atomic inPlot(false); + + std::mutex wallpaperMutex; + std::condition_variable cv; + + + // Function to load the RGBA file into memory and modify wallpaperData directly + void loadWallpaperFile(const std::string& filePath, s32 width, s32 height) { + const size_t originalDataSize = width * height * 4; // Original size in bytes (4 bytes per pixel) + const size_t compressedDataSize = originalDataSize / 2; // RGBA4444 uses half the space + + wallpaperData.resize(compressedDataSize); + + if (!isFileOrDirectory(filePath)) { + wallpaperData.clear(); + return; + } + + #if !USING_FSTREAM_DIRECTIVE + FILE* file = fopen(filePath.c_str(), "rb"); + if (!file) { + wallpaperData.clear(); + return; + } + + std::vector buffer(originalDataSize); + const size_t bytesRead = fread(buffer.data(), 1, originalDataSize, file); + fclose(file); + + if (bytesRead != originalDataSize) { + wallpaperData.clear(); + return; + } + + #else + std::ifstream file(filePath, std::ios::binary); + if (!file) { + wallpaperData.clear(); + return; + } + + std::vector buffer(originalDataSize); + file.read(reinterpret_cast(buffer.data()), originalDataSize); + if (!file) { + wallpaperData.clear(); + return; + } + #endif + + // Compress RGBA8888 to RGBA4444 + uint8_t* input = buffer.data(); + uint8_t* output = wallpaperData.data(); + uint8_t r1, g1, b1, a1; + uint8_t r2, g2, b2, a2; + + for (size_t i = 0, j = 0; i < originalDataSize; i += 8, j += 4) { + // Read 2 RGBA pixels (8 bytes) + r1 = input[i] >> 4; + g1 = input[i + 1] >> 4; + b1 = input[i + 2] >> 4; + a1 = input[i + 3] >> 4; + + r2 = input[i + 4] >> 4; + g2 = input[i + 5] >> 4; + b2 = input[i + 6] >> 4; + a2 = input[i + 7] >> 4; + + // Pack them into 4 bytes (2 bytes per pixel) + output[j] = (r1 << 4) | g1; + output[j + 1] = (b1 << 4) | a1; + output[j + 2] = (r2 << 4) | g2; + output[j + 3] = (b2 << 4) | a2; + } + } + + + 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 = "%a %T"; + + + // 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; + + const std::string loaderInfo = envGetLoaderInfo(); + const std::string loaderTitle = extractTitle(loaderInfo); + const bool expandedMemory = (loaderTitle == "nx-ovlloader+"); + + 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 = expandedMemory ? 4 : 0; + std::vector renderThreads(numThreads); + const s32 bmpChunkSize = (numThreads > 0) ? ((720 + numThreads - 1) / numThreads) : 0; + 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 new file mode 100644 index 00000000..4e0cc197 --- /dev/null +++ b/Source/sys-clk/overlay/lib/libultrahand/ultrahand.mk @@ -0,0 +1,30 @@ +#--------------------------------------------------------------------------------- +# 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 diff --git a/Source/sys-clk/overlay/scripts/make_logo.sh b/Source/sys-clk/overlay/scripts/make_logo.sh new file mode 100644 index 00000000..bbd01a7f --- /dev/null +++ b/Source/sys-clk/overlay/scripts/make_logo.sh @@ -0,0 +1,16 @@ +#!/bin/bash +set -e + +CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" + +DEST="$CURRENT_DIR/../data/logo_rgba.bin" +FONT="$CURRENT_DIR/../../manager/resources/fira/FiraSans-Medium-rnx.ttf" +FONT_SIZE="30.5" +TEXT="sys-clk" + +function render() { + convert -background transparent -colorspace RGB -depth 8 -fill white -font "$1" -pointsize "$2" "label:$3" "$4" +} + +render "$FONT" "$FONT_SIZE" "$TEXT" info: +render "$FONT" "$FONT_SIZE" "$TEXT" "RGBA:$DEST" \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ipc.h b/Source/sys-clk/overlay/src/ipc.h new file mode 100644 index 00000000..56c9bcdf --- /dev/null +++ b/Source/sys-clk/overlay/src/ipc.h @@ -0,0 +1,23 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#if defined(__cplusplus) +extern "C" +{ +#endif + +#include +#include + +#if defined(__cplusplus) +} +#endif diff --git a/Source/sys-clk/overlay/src/main.cpp b/Source/sys-clk/overlay/src/main.cpp new file mode 100644 index 00000000..03c69f35 --- /dev/null +++ b/Source/sys-clk/overlay/src/main.cpp @@ -0,0 +1,81 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#define TESLA_INIT_IMPL +#include + +#include "ui/gui/fatal_gui.h" +#include "ui/gui/main_gui.h" +#include "rgltr_services.h" // for extern Service g_rgltrSrv, etc. + +class AppOverlay : public tsl::Overlay +{ + public: + AppOverlay() {} + ~AppOverlay() {} + + //virtual void initServices() override { + // rgltrInitialize(); + //} + + virtual void exitServices() override { + rgltrExit(); + sysclkIpcExit(); + } + + virtual std::unique_ptr loadInitialGui() override + { + uint32_t apiVersion; + smInitialize(); + + tsl::hlp::ScopeGuard smGuard([] { smExit(); }); + + if(!sysclkIpcRunning()) + { + return initially( + "sys-clk is not running.\n\n" + "\n" + "Please make sure it is correctly\n\n" + "installed and enabled.", + "" + ); + } + + if(R_FAILED(sysclkIpcInitialize()) || R_FAILED(sysclkIpcGetAPIVersion(&apiVersion))) + { + return initially( + "Could not connect to sys-clk.\n\n" + "\n" + "Please make sure it is correctly\n\n" + "installed and enabled.", + "" + ); + } + + if(SYSCLK_IPC_API_VERSION != apiVersion) + { + return initially( + "Overlay not compatible with\n\n" + "the running sys-clk version.\n\n" + "\n" + "Please make sure everything is\n\n" + "installed and up to date.", + "" + ); + } + + return initially(); + } +}; + +int main(int argc, char **argv) +{ + return tsl::loop(argc, argv); +} diff --git a/Source/sys-clk/overlay/src/pcv_types.h b/Source/sys-clk/overlay/src/pcv_types.h new file mode 100644 index 00000000..50d3e3ea --- /dev/null +++ b/Source/sys-clk/overlay/src/pcv_types.h @@ -0,0 +1,41 @@ +typedef enum { + PcvPowerDomain_Max77620_Sd0 = 0, + PcvPowerDomain_Max77620_Sd1 = 1, + PcvPowerDomain_Max77620_Sd2 = 2, + PcvPowerDomain_Max77620_Sd3 = 3, + PcvPowerDomain_Max77620_Ldo0 = 4, + PcvPowerDomain_Max77620_Ldo1 = 5, + PcvPowerDomain_Max77620_Ldo2 = 6, + PcvPowerDomain_Max77620_Ldo3 = 7, + PcvPowerDomain_Max77620_Ldo4 = 8, + PcvPowerDomain_Max77620_Ldo5 = 9, + PcvPowerDomain_Max77620_Ldo6 = 10, + PcvPowerDomain_Max77620_Ldo7 = 11, + PcvPowerDomain_Max77620_Ldo8 = 12, + PcvPowerDomain_Max77621_Cpu = 13, + PcvPowerDomain_Max77621_Gpu = 14, + PcvPowerDomain_Max77812_Cpu = 15, + PcvPowerDomain_Max77812_Gpu = 16, + PcvPowerDomain_Max77812_Dram = 17, +} PowerDomain; + +typedef enum { + PcvPowerDomainId_Max77620_Sd0 = 0x3A000080, + PcvPowerDomainId_Max77620_Sd1 = 0x3A000081, + PcvPowerDomainId_Max77620_Sd2 = 0x3A000082, + PcvPowerDomainId_Max77620_Sd3 = 0x3A000083, + PcvPowerDomainId_Max77620_Ldo0 = 0x3A0000A0, + PcvPowerDomainId_Max77620_Ldo1 = 0x3A0000A1, + PcvPowerDomainId_Max77620_Ldo2 = 0x3A0000A2, + PcvPowerDomainId_Max77620_Ldo3 = 0x3A0000A3, + PcvPowerDomainId_Max77620_Ldo4 = 0x3A0000A4, + PcvPowerDomainId_Max77620_Ldo5 = 0x3A0000A5, + PcvPowerDomainId_Max77620_Ldo6 = 0x3A0000A6, + PcvPowerDomainId_Max77620_Ldo7 = 0x3A0000A7, + PcvPowerDomainId_Max77620_Ldo8 = 0x3A0000A8, + PcvPowerDomainId_Max77621_Cpu = 0x3A000003, + PcvPowerDomainId_Max77621_Gpu = 0x3A000004, + PcvPowerDomainId_Max77812_Cpu = 0x3A000003, + PcvPowerDomainId_Max77812_Gpu = 0x3A000004, + PcvPowerDomainId_Max77812_Dram = 0x3A000005, +} PowerDomainId; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/rgltr.h b/Source/sys-clk/overlay/src/rgltr.h new file mode 100644 index 00000000..dd57f4c5 --- /dev/null +++ b/Source/sys-clk/overlay/src/rgltr.h @@ -0,0 +1,19 @@ +#pragma once +#include +#include "pcv_types.h" + +typedef struct { + Service s; +} RgltrSession; + +Result rgltrInitialize(void); + +void rgltrExit(void); + +Service* rgltrGetServiceSession(void); + +Result rgltrOpenSession(RgltrSession* session_out, PowerDomainId module_id); +void rgltrCloseSession(RgltrSession* session); +Result rgltrGetVoltage(RgltrSession* session, u32 *out_volt); +Result rgltrGetPowerModuleNumLimit(u32 *out); +Result rgltrGetVoltageEnabled(RgltrSession* session, u32 *out); diff --git a/Source/sys-clk/overlay/src/rgltr_services.cpp b/Source/sys-clk/overlay/src/rgltr_services.cpp new file mode 100644 index 00000000..5f2160db --- /dev/null +++ b/Source/sys-clk/overlay/src/rgltr_services.cpp @@ -0,0 +1,43 @@ +// rgltr_services.cpp (no changes needed here—just compile it once) +#include +#include "rgltr.h" +#include "rgltr_services.h" // for extern Service g_rgltrSrv, etc. + +// Global service handle +Service g_rgltrSrv; + +Result rgltrInitialize(void) { + if (hosversionBefore(8, 0, 0)) { + return MAKERESULT(Module_Libnx, LibnxError_IncompatSysVer); + } + return smGetService(&g_rgltrSrv, "rgltr"); +} + +void rgltrExit(void) { + serviceClose(&g_rgltrSrv); +} + +Result rgltrOpenSession(RgltrSession* session_out, PowerDomainId module_id) { + const u32 in = (u32)module_id; + return serviceDispatchIn( + &g_rgltrSrv, + 0, + in, + .out_num_objects = 1, + .out_objects = &session_out->s + ); +} + +Result rgltrGetVoltage(RgltrSession* session, u32* out_volt) { + // Service returns µV (microvolts) in a local u32: + u32 temp = 0; + Result rc = serviceDispatchOut(&session->s, 4, temp); + if (R_SUCCEEDED(rc)) { + *out_volt = temp; + } + return rc; +} + +void rgltrCloseSession(RgltrSession* session) { + serviceClose(&session->s); +} diff --git a/Source/sys-clk/overlay/src/rgltr_services.h b/Source/sys-clk/overlay/src/rgltr_services.h new file mode 100644 index 00000000..32becbf8 --- /dev/null +++ b/Source/sys-clk/overlay/src/rgltr_services.h @@ -0,0 +1,29 @@ +// rgltr_services.h +// ======== +// Minimal header declarations for rgltr‐related functionality. +// Any file that wants to call rgltrOpenSession(), rgltrGetVoltage(), etc. should +// simply do `#include "infonx.h"` (NOT infonx.cpp). + +#pragma once + +#include // for Service, Result, hosversionBefore(), smGetService(), serviceClose(), etc. +#include "rgltr.h" // for RgltrSession, PowerDomainId, etc. + +// Global service handle for "rgltr". Defined in infonx.cpp. +extern Service g_rgltrSrv; + +// Open/close the "rgltr" service. You must call rgltrInitialize() (once) before using +// rgltrOpenSession() & friends. Call rgltrExit() when your app is shutting down. +Result rgltrInitialize(void); +void rgltrExit(void); + +// Open a regulator session for the given PowerDomainId (e.g. CPU, GPU, DRAM). +// On success, (*session_out).s will contain a valid Service handle. +Result rgltrOpenSession(RgltrSession* session_out, PowerDomainId module_id); + +// Query the current voltage (in microvolts, µV) from a previously opened session. +// Writes the result into *out_volt. +Result rgltrGetVoltage(RgltrSession* session, u32* out_volt); + +// Close a previously opened regulator session. +void rgltrCloseSession(RgltrSession* session); diff --git a/Source/sys-clk/overlay/src/ui/elements/base_frame.h b/Source/sys-clk/overlay/src/ui/elements/base_frame.h new file mode 100644 index 00000000..053ef26a --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/elements/base_frame.h @@ -0,0 +1,31 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include "../gui/base_gui.h" + +class BaseFrame : public tsl::elm::HeaderOverlayFrame +{ + public: + BaseFrame(BaseGui* gui) : tsl::elm::HeaderOverlayFrame(234) { + this->gui = gui; + } + + void draw(tsl::gfx::Renderer* renderer) override + { + tsl::elm::HeaderOverlayFrame::draw(renderer); + this->gui->preDraw(renderer); + } + + protected: + BaseGui* gui; +}; diff --git a/Source/sys-clk/overlay/src/ui/format.h b/Source/sys-clk/overlay/src/ui/format.h new file mode 100644 index 00000000..e20c5b5b --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/format.h @@ -0,0 +1,28 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include + +#define FREQ_DEFAULT_TEXT "Do not override" + +static inline std::string formatListFreqMHz(std::uint32_t mhz) +{ + if(mhz == 0) + { + return FREQ_DEFAULT_TEXT; + } + + char buf[10]; + return std::string(buf, snprintf(buf, sizeof(buf), "%u MHz", mhz)); +} + +static inline std::string formatListFreqHz(std::uint32_t hz) { return formatListFreqMHz(hz / 1000000); } diff --git a/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.cpp new file mode 100644 index 00000000..cac497f9 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.cpp @@ -0,0 +1,127 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "app_profile_gui.h" + +#include "../format.h" +#include "fatal_gui.h" + +AppProfileGui::AppProfileGui(std::uint64_t applicationId, SysClkTitleProfileList* profileList) +{ + this->applicationId = applicationId; + this->profileList = profileList; +} + +AppProfileGui::~AppProfileGui() +{ + delete this->profileList; +} + +void AppProfileGui::openFreqChoiceGui(tsl::elm::ListItem* listItem, SysClkProfile profile, SysClkModule module) +{ + std::uint32_t hzList[SYSCLK_FREQ_LIST_MAX]; + std::uint32_t hzCount; + Result rc = sysclkIpcGetFreqList(module, &hzList[0], SYSCLK_FREQ_LIST_MAX, &hzCount); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcGetFreqList", rc); + return; + } + + tsl::changeTo(this->profileList->mhzMap[profile][module] * 1000000, hzList, hzCount, module, [this, listItem, profile, module](std::uint32_t hz) { + this->profileList->mhzMap[profile][module] = hz / 1000000; + listItem->setValue(formatListFreqMHz(this->profileList->mhzMap[profile][module])); + Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); + return false; + } + + return true; + }); +} + +void AppProfileGui::addModuleListItem(SysClkProfile profile, SysClkModule module) +{ + tsl::elm::ListItem* listItem = new tsl::elm::ListItem(sysclkFormatModule(module, true)); + listItem->setValue(formatListFreqMHz(this->profileList->mhzMap[profile][module])); + listItem->setClickListener([this, listItem, profile, module](u64 keys) { + if((keys & HidNpadButton_A) == HidNpadButton_A) + { + this->openFreqChoiceGui(listItem, profile, module); + return true; + } + else if((keys & HidNpadButton_Y) == HidNpadButton_Y) + { + // Reset to "Do not override" (0 MHz) + this->profileList->mhzMap[profile][module] = 0; + listItem->setValue(formatListFreqMHz(0)); + + // Save the updated profile + Result rc = sysclkIpcSetProfiles(this->applicationId, this->profileList); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcSetProfiles", rc); + return false; + } + return true; + } + return false; + }); + this->listElement->addItem(listItem); +} + +void AppProfileGui::addProfileUI(SysClkProfile profile) +{ + this->listElement->addItem(new tsl::elm::CategoryHeader(sysclkFormatProfile(profile, true) + std::string(" ") + ult::DIVIDER_SYMBOL + "  Reset")); + this->addModuleListItem(profile, SysClkModule_CPU); + this->addModuleListItem(profile, SysClkModule_GPU); + this->addModuleListItem(profile, SysClkModule_MEM); +} + +void AppProfileGui::listUI() +{ + this->addProfileUI(SysClkProfile_Docked); + this->addProfileUI(SysClkProfile_Handheld); + this->addProfileUI(SysClkProfile_HandheldCharging); + this->addProfileUI(SysClkProfile_HandheldChargingOfficial); + this->addProfileUI(SysClkProfile_HandheldChargingUSB); +} + +void AppProfileGui::changeTo(std::uint64_t applicationId) +{ + SysClkTitleProfileList* profileList = new SysClkTitleProfileList; + Result rc = sysclkIpcGetProfiles(applicationId, profileList); + if(R_FAILED(rc)) + { + delete profileList; + FatalGui::openWithResultCode("sysclkIpcGetProfiles", rc); + return; + } + + tsl::changeTo(applicationId, profileList); +} + +void AppProfileGui::update() +{ + BaseMenuGui::update(); + + if((this->context && this->applicationId != this->context->applicationId) && this->applicationId != SYSCLK_GLOBAL_PROFILE_TID) + { + tsl::changeTo( + "Application changed\n\n" + "\n" + "The running application changed\n\n" + "while editing was going on.", + "" + ); + } +} diff --git a/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.h b/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.h new file mode 100644 index 00000000..5e1ecc6d --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/app_profile_gui.h @@ -0,0 +1,34 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include "../../ipc.h" +#include "base_menu_gui.h" +#include "freq_choice_gui.h" +#define SYSCLK_GLOBAL_PROFILE_TID 0xA111111111111111 + +class AppProfileGui : public BaseMenuGui +{ + protected: + std::uint64_t applicationId; + SysClkTitleProfileList* profileList; + + void openFreqChoiceGui(tsl::elm::ListItem* listItem, SysClkProfile profile, SysClkModule module); + void addModuleListItem(SysClkProfile profile, SysClkModule module); + void addProfileUI(SysClkProfile profile); + + public: + AppProfileGui(std::uint64_t applicationId, SysClkTitleProfileList* profileList); + ~AppProfileGui(); + void listUI() override; + static void changeTo(std::uint64_t applicationId); + void update() override; +}; diff --git a/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp new file mode 100644 index 00000000..1ec877cb --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/base_gui.cpp @@ -0,0 +1,56 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "base_gui.h" + +#include "../elements/base_frame.h" +#include "logo_rgba_bin.h" + + +#define LOGO_WIDTH 110 +#define LOGO_HEIGHT 39 +#define LOGO_X 18 +#define LOGO_Y 21 + +#define LOGO_LABEL_X (LOGO_X + LOGO_WIDTH + 6) +#define LOGO_LABEL_Y 50 +#define LOGO_LABEL_FONT_SIZE 28 + +#define VERSION_X (LOGO_LABEL_X + 110+8) +#define VERSION_Y LOGO_LABEL_Y-4 +#define VERSION_FONT_SIZE 15 + +std::string getVersionString() { + char buf[0x100] = ""; // 256 bytes — safe for any expected version string + Result rc = sysclkIpcGetVersionString(buf, sizeof(buf)); + if (R_FAILED(rc) || buf[0] == '\0') { + return "unknown"; + } + return std::string(buf); +} + +void BaseGui::preDraw(tsl::gfx::Renderer* renderer) +{ + renderer->drawBitmap(LOGO_X, LOGO_Y, LOGO_WIDTH, LOGO_HEIGHT, logo_rgba_bin); + renderer->drawString("overlay", false, LOGO_LABEL_X, LOGO_LABEL_Y, LOGO_LABEL_FONT_SIZE, renderer->a(TEXT_COLOR)); + renderer->drawString(TARGET_VERSION, false, VERSION_X, VERSION_Y, VERSION_FONT_SIZE, tsl::bannerVersionTextColor); +} + +tsl::elm::Element* BaseGui::createUI() +{ + BaseFrame* rootFrame = new BaseFrame(this); + rootFrame->setContent(this->baseUI()); + return rootFrame; +} + +void BaseGui::update() +{ + this->refresh(); +} diff --git a/Source/sys-clk/overlay/src/ui/gui/base_gui.h b/Source/sys-clk/overlay/src/ui/gui/base_gui.h new file mode 100644 index 00000000..a3a7f8cc --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/base_gui.h @@ -0,0 +1,36 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include +#include +#include +#include + +#include "../style.h" +#include "../../ipc.h" + +class BaseGui : public tsl::Gui +{ + public: + BaseGui() {} + ~BaseGui() {} + virtual void preDraw(tsl::gfx::Renderer* renderer); + void update() override; + tsl::elm::Element* createUI() override; + virtual tsl::elm::Element* baseUI() = 0; + virtual void refresh() {} + private: +}; + + +extern std::string getVersionString(); diff --git a/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.cpp new file mode 100644 index 00000000..c3053d07 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.cpp @@ -0,0 +1,291 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "base_menu_gui.h" +#include "fatal_gui.h" + +// Cache hardware model to avoid repeated syscalls + +BaseMenuGui::BaseMenuGui() : tempColors{tsl::Color(0), tsl::Color(0), tsl::Color(0)} +{ + tsl::initializeThemeVars(); + this->context = nullptr; + this->lastContextUpdate = 0; + this->listElement = nullptr; + + // Initialize all voltages to zero once + memset(&cpuVoltageUv, 0, sizeof(u32) * 5); // Zero all 5 voltage values at once + + // Pre-cache hardware model during initialization + IsMariko(); + + // Initialize display strings + memset(displayStrings, 0, sizeof(displayStrings)); +} + +BaseMenuGui::~BaseMenuGui() { + delete this->context; // delete handles nullptr automatically +} + +// Fast preDraw - just renders pre-computed strings +void BaseMenuGui::preDraw(tsl::gfx::Renderer* renderer) { + BaseGui::preDraw(renderer); + if(!this->context) [[unlikely]] return; + + // All constants pre-calculated and cached + static constexpr const char* const labels[10] = { + "App ID", "Profile", "CPU", "GPU", "MEM", "SOC", "PCB", "Skin", "Now", "Avg" + }; + + static constexpr u32 dataPositions[6] = {63-3+3, 200-1, 344-1-3, 200-1, 342-1, 321-1}; + + static u32 labelWidths[10]; + static bool positionsInitialized = false; + + if (!positionsInitialized) { + for (int i = 0; i < 10; i++) { + labelWidths[i] = renderer->getTextDimensions(labels[i], false, SMALL_TEXT_SIZE).first; + } + positionsInitialized = true; + } + static u32 positions[10] = {24-1, 310-labelWidths[1], 24-1, 192-labelWidths[3], 332-labelWidths[4], 24-1, 192 - labelWidths[6], 332-labelWidths[7], 192 - labelWidths[8], 332-labelWidths[9]}; + + static u32 maxProfileValueWidth = renderer->getTextDimensions("Official Charger", false, SMALL_TEXT_SIZE).first; // longest word + + u32 y = 91; + + // === TOP SECTION === + renderer->drawRoundedRect(14, 70-1, 420, 30+2, 10.0f, renderer->aWithOpacity(tsl::tableBGColor)); + + // App ID - use pre-formatted string + renderer->drawString(labels[0], false, positions[0], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + renderer->drawString(displayStrings[0], false, positions[0] + labelWidths[0] + 9, y, SMALL_TEXT_SIZE, tsl::infoTextColor); + + // Profile - use pre-formatted string + renderer->drawString(labels[1], false, 423 - maxProfileValueWidth - labelWidths[1] - 9, y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + renderer->drawString(displayStrings[1], false, 423 - maxProfileValueWidth, y, SMALL_TEXT_SIZE, tsl::infoTextColor); + + y = 129; // Direct assignment instead of += 38 + + // === MAIN DATA SECTION === + renderer->drawRoundedRect(14, 106, 420, 116, 10.0f, renderer->aWithOpacity(tsl::tableBGColor)); + + // === FREQUENCY SECTION === + // Labels first (better cache locality) + renderer->drawString(labels[2], false, positions[2], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + renderer->drawString(labels[3], false, positions[3], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + renderer->drawString(labels[4], false, positions[4], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + + // Current frequencies - use pre-formatted strings + renderer->drawString(displayStrings[2], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // CPU + renderer->drawString(displayStrings[3], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // GPU + renderer->drawString(displayStrings[4], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // MEM + + y = 149; // Direct assignment (129 + 20) + + // === REAL FREQUENCIES === + renderer->drawString(displayStrings[5], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // CPU real + renderer->drawString(displayStrings[6], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // GPU real + renderer->drawString(displayStrings[7], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // MEM real + + y = 169; // Direct assignment (149 + 20) + + // === VOLTAGES === + renderer->drawString(displayStrings[8], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // CPU voltage + renderer->drawString(displayStrings[9], false, dataPositions[1], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // GPU voltage + + // Memory voltage - check if VDD is present + if (emcVoltageUv && vddVoltageUv) { + renderer->drawStringWithColoredSections(displayStrings[10], false, {""}, dataPositions[5]-16, y, SMALL_TEXT_SIZE, tsl::infoTextColor, tsl::separatorColor); + } else if (vddVoltageUv) { + renderer->drawString(displayStrings[10], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); + } else if (emcVoltageUv) { + renderer->drawString(displayStrings[10], false, dataPositions[2], y, SMALL_TEXT_SIZE, tsl::infoTextColor); + } + + y = 191; // Direct assignment (169 + 22) + + // === TEMPERATURE SECTION === + // Labels + renderer->drawString(labels[5], false, positions[5], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + renderer->drawString(labels[6], false, positions[6]-1, y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + renderer->drawString(labels[7], false, positions[7], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + + // Temperatures with color - use pre-computed colors + renderer->drawString(displayStrings[11], false, dataPositions[0], y, SMALL_TEXT_SIZE, tempColors[0]); // SOC + renderer->drawString(displayStrings[12], false, dataPositions[1], y, SMALL_TEXT_SIZE, tempColors[1]); // PCB + renderer->drawString(displayStrings[13], false, dataPositions[2], y, SMALL_TEXT_SIZE, tempColors[2]); // Skin + + y = 211; // Direct assignment (191 + 20) + + // === SOC VOLTAGE & POWER === + // SOC voltage (if available) + if (socVoltageUv) [[likely]] { + renderer->drawString(displayStrings[14], false, dataPositions[0], y, SMALL_TEXT_SIZE, tsl::infoTextColor); + } + + // Power labels and values + renderer->drawString(labels[8], false, positions[8]-1, y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + renderer->drawString(labels[9], false, positions[9], y, SMALL_TEXT_SIZE, tsl::sectionTextColor); + + renderer->drawString(displayStrings[15], false, dataPositions[3], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // Power now + renderer->drawString(displayStrings[16], false, dataPositions[4], y, SMALL_TEXT_SIZE, tsl::infoTextColor); // Power avg +} + +// Optimized refresh - now does all the string formatting once per second +void BaseMenuGui::refresh() +{ + const u64 ticks = armGetSystemTick(); + // Use cached comparison - 1 billion nanoseconds + if (armTicksToNs(ticks - this->lastContextUpdate) <= 1000000000UL) [[likely]] { + return; // Early exit for most calls + } + + this->lastContextUpdate = ticks; + + // Lazy context allocation + if (!this->context) [[unlikely]] { + this->context = new SysClkContext; + } + + // === ULTRA-FAST VOLTAGE READING === + // Pre-computed domain configuration based on hardware + static const PowerDomainId domains[] = { + PcvPowerDomainId_Max77621_Cpu, // [0] CPU + PcvPowerDomainId_Max77621_Gpu, // [1] GPU + PcvPowerDomainId_Max77812_Dram, // [2] EMC/DRAM - Mariko only + PcvPowerDomainId_Max77620_Sd0, // [3] SOC - EOS only + PcvPowerDomainId_Max77620_Sd1 // [4] VDD2 - EOS only + }; + + // Voltage array for direct indexing + u32* voltages[] = {&cpuVoltageUv, &gpuVoltageUv, &emcVoltageUv, &socVoltageUv, &vddVoltageUv}; + + // Single regulator init/exit cycle + if (R_SUCCEEDED(rgltrInitialize())) [[likely]] { + if (IsMariko()) { + // Mariko with EOS: all 5 domains + for (int i = 0; i < 5; ++i) { + RgltrSession session; + if (R_SUCCEEDED(rgltrOpenSession(&session, domains[i]))) [[likely]] { + if (R_FAILED(rgltrGetVoltage(&session, voltages[i]))) { + *voltages[i] = 0; + } + rgltrCloseSession(&session); + } else { + *voltages[i] = 0; + } + } + } else { + // Erista + // Erista with EOS: CPU, GPU, SOC, VDD (no DRAM) + for (int i = 0; i < 5; ++i) { + if (i == 2) continue; // Skip DRAM domain + + RgltrSession session; + if (R_SUCCEEDED(rgltrOpenSession(&session, domains[i]))) [[likely]] { + if (R_FAILED(rgltrGetVoltage(&session, voltages[i]))) { + *voltages[i] = 0; + } + rgltrCloseSession(&session); + } else { + *voltages[i] = 0; + } + emcVoltageUv = 0; // Erista never supports DRAM + } + } + + rgltrExit(); + } else { + // Zero all voltages on regulator failure + memset(&cpuVoltageUv, 0, sizeof(u32) * 5); + } + + // === SYSCLK CONTEXT UPDATE === + const Result rc = sysclkIpcGetCurrentContext(this->context); + if (R_FAILED(rc)) [[unlikely]] { + FatalGui::openWithResultCode("sysclkIpcGetCurrentContext", rc); + return; + } + + // === FORMAT ALL DISPLAY STRINGS (once per second) === + // App ID (hex conversion) + sprintf(displayStrings[0], "%016lX", context->applicationId); + + // Profile + strcpy(displayStrings[1], sysclkFormatProfile(context->profile, true)); + + // Current frequencies + u32 hz = context->freqs[0]; // CPU + sprintf(displayStrings[2], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); + + hz = context->freqs[1]; // GPU + sprintf(displayStrings[3], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); + + hz = context->freqs[2]; // MEM + sprintf(displayStrings[4], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); + + // Real frequencies + hz = context->realFreqs[0]; // CPU + sprintf(displayStrings[5], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); + + hz = context->realFreqs[1]; // GPU + sprintf(displayStrings[6], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); + + hz = context->realFreqs[2]; // MEM + sprintf(displayStrings[7], "%u.%u MHz", hz / 1000000U, (hz / 100000U) % 10U); + + // Voltages + sprintf(displayStrings[8], "%u mV", cpuVoltageUv / 1000U); + sprintf(displayStrings[9], "%u mV", gpuVoltageUv / 1000U); + + // Memory voltage (handle VDD case) + if (emcVoltageUv && vddVoltageUv) { + //sprintf(displayStrings[10], "%u%u mV", vddVoltageUv / 1000U, emcVoltageUv / 1000U); + //sprintf(displayStrings[10], "%u%.1f mV", vddVoltageUv / 1000U, emcVoltageUv / 1000.0f); + sprintf(displayStrings[10], "%u.%u%u mV", vddVoltageUv / 1000U, (vddVoltageUv % 1000U) / 100U, emcVoltageUv / 1000U); + } else if (vddVoltageUv) { + //sprintf(displayStrings[10], "%u mV", vddVoltageUv / 1000U); + sprintf(displayStrings[10], "%u.%u mV", vddVoltageUv / 1000U, (vddVoltageUv % 1000U) / 100U); + } else if (emcVoltageUv) { + sprintf(displayStrings[10], "%u mV", emcVoltageUv / 1000U); + } + + // Temperatures and pre-compute colors + u32 millis = context->temps[0]; // SOC + sprintf(displayStrings[11], "%u.%u °C", millis / 1000U, (millis % 1000U) / 100U); + tempColors[0] = tsl::GradientColor(millis * 0.001f); + + millis = context->temps[1]; // PCB + sprintf(displayStrings[12], "%u.%u °C", millis / 1000U, (millis % 1000U) / 100U); + tempColors[1] = tsl::GradientColor(millis * 0.001f); + + millis = context->temps[2]; // Skin + sprintf(displayStrings[13], "%u.%u °C", millis / 1000U, (millis % 1000U) / 100U); + tempColors[2] = tsl::GradientColor(millis * 0.001f); + + // SOC voltage (if available) + if (socVoltageUv) { + sprintf(displayStrings[14], "%u mV", socVoltageUv / 1000U); + } + + // Power + sprintf(displayStrings[15], "%d mW", context->power[0]); // Now + sprintf(displayStrings[16], "%d mW", context->power[1]); // Avg +} + +tsl::elm::Element* BaseMenuGui::baseUI() +{ + auto* list = new tsl::elm::List(); + this->listElement = list; + this->listUI(); + + return list; +} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.h b/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.h new file mode 100644 index 00000000..d9c061ea --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/base_menu_gui.h @@ -0,0 +1,59 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include "../../rgltr_services.h" +#include "../../ipc.h" +#include "base_gui.h" + +class BaseMenuGui : public BaseGui +{ + protected: + SysClkContext* context; + std::uint64_t lastContextUpdate; + std::uint32_t cpuVoltageUv; + std::uint32_t gpuVoltageUv; + std::uint32_t emcVoltageUv; + std::uint32_t socVoltageUv; //add soc voltage + std::uint32_t vddVoltageUv;//add vdd2 voltage + + public: + bool g_hardwareModelCached = false; + bool g_isMariko = false; + + bool IsMariko() { + if (!g_hardwareModelCached) { + SetSysProductModel model = SetSysProductModel_Invalid; + setsysGetProductModel(&model); + g_isMariko = (model == SetSysProductModel_Iowa || + model == SetSysProductModel_Hoag || + model == SetSysProductModel_Calcio || + model == SetSysProductModel_Aula); + g_hardwareModelCached = true; + } + return g_isMariko; + } + + bool IsErista() { + return !IsMariko(); + } + BaseMenuGui(); + ~BaseMenuGui(); + void preDraw(tsl::gfx::Renderer* renderer) override; + tsl::elm::List* listElement; + tsl::elm::Element* baseUI() override; + void refresh() override; + virtual void listUI() = 0; + + private: + char displayStrings[17][32]; // Pre-formatted display strings + tsl::Color tempColors[3]; // Pre-computed temperature colors +}; diff --git a/Source/sys-clk/overlay/src/ui/gui/fatal_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/fatal_gui.cpp new file mode 100644 index 00000000..264668c7 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/fatal_gui.cpp @@ -0,0 +1,67 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "fatal_gui.h" + +FatalGui::FatalGui(const std::string message, const std::string info) +{ + this->message = message; + this->info = info; +} + +void FatalGui::openWithResultCode(std::string tag, Result rc) +{ + char rcStr[32]; + std::string info = tag; + info.append(rcStr, snprintf(rcStr, sizeof(rcStr), "\n\n[0x%x] %04d-%04d", rc, R_MODULE(rc), R_DESCRIPTION(rc))); + + tsl::changeTo( + "Could not connect to sys-clk.\n\n" + "\n" + "Please make sure everything is\n\n" + "correctly installed and enabled.", + info + ); +} + +tsl::elm::Element* FatalGui::baseUI() +{ + tsl::elm::CustomDrawer* drawer = new tsl::elm::CustomDrawer([this](tsl::gfx::Renderer* renderer, u16 x, u16 y, u16 w, u16 h) { + renderer->drawString("\uE150", false, 40, 210, 40, TEXT_COLOR); + renderer->drawString("Fatal error", false, 100, 210, 30, TEXT_COLOR); + + std::uint32_t txtY = 255; + if(!this->message.empty()) + { + txtY += renderer->drawString(this->message.c_str(), false, 40, txtY, 23, TEXT_COLOR).second; + txtY += 55; + } + + if(!this->info.empty()) + { + renderer->drawString(this->info.c_str(), false, 40, txtY, 18, DESC_COLOR); + } + }); + + return drawer; +} + +bool FatalGui::handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight) +{ + if((keysDown & HidNpadButton_A) == HidNpadButton_A || (keysDown & HidNpadButton_B) == HidNpadButton_B) + { + while(tsl::Overlay::get()->getCurrentGui() != nullptr) { + tsl::goBack(); + } + return true; + } + + return false; +} diff --git a/Source/sys-clk/overlay/src/ui/gui/fatal_gui.h b/Source/sys-clk/overlay/src/ui/gui/fatal_gui.h new file mode 100644 index 00000000..e20b6cc9 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/fatal_gui.h @@ -0,0 +1,29 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include + +#include "base_gui.h" + +class FatalGui : public BaseGui +{ + protected: + std::string message; + std::string info; + + public: + FatalGui(const std::string message, const std::string info); + ~FatalGui() {} + tsl::elm::Element* baseUI() override; + bool handleInput(u64 keysDown, u64 keysHeld, const HidTouchState &touchPos, HidAnalogStickState joyStickPosLeft, HidAnalogStickState joyStickPosRight); + static void openWithResultCode(std::string tag, Result rc); +}; diff --git a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp new file mode 100644 index 00000000..7b3c3e55 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.cpp @@ -0,0 +1,67 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "freq_choice_gui.h" + +#include "../format.h" +#include "fatal_gui.h" + +FreqChoiceGui::FreqChoiceGui(std::uint32_t selectedHz, std::uint32_t* hzList, std::uint32_t hzCount, SysClkModule module, FreqChoiceListener listener) +{ + this->selectedHz = selectedHz; + this->hzList = hzList; + this->hzCount = hzCount; + this->module = module; // Add this + this->listener = listener; +} + +tsl::elm::ListItem* FreqChoiceGui::createFreqListItem(std::uint32_t hz, bool selected) +{ + tsl::elm::ListItem* listItem = new tsl::elm::ListItem(formatListFreqHz(hz), "", true); + listItem->setValue(selected ? "\uE14B" : ""); + + listItem->setClickListener([this, hz](u64 keys) { + if((keys & HidNpadButton_A) == HidNpadButton_A && this->listener) + { + if(this->listener(hz)) + { + tsl::goBack(); + } + return true; + } + + return false; + }); + + return listItem; +} + +void FreqChoiceGui::listUI() +{ + // Add CategoryHeader based on module + std::string moduleName = sysclkFormatModule(this->module, true); + this->listElement->addItem(new tsl::elm::CategoryHeader(moduleName)); + + this->listElement->addItem(this->createFreqListItem(0, this->selectedHz == 0)); + std::uint32_t hz; + for(std::uint32_t i = 0; i < this->hzCount; i++) { + hz = this->hzList[i]; + // Skip 204 MHz exactly + if(moduleName == "Memory" && hz == 204000000) { + continue; + } + // if(moduleName == "GPU") { + // if(BaseGui::isMariko() && is) + // continue; + // } + this->listElement->addItem(this->createFreqListItem(hz, (hz / 1000000) == (this->selectedHz / 1000000))); + } + this->listElement->jumpToItem("", ""); +} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h new file mode 100644 index 00000000..d71cf418 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/freq_choice_gui.h @@ -0,0 +1,35 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include + +#include "base_menu_gui.h" + +using FreqChoiceListener = std::function; + +#define FREQ_DEFAULT_TEXT "Do not override" + +class FreqChoiceGui : public BaseMenuGui +{ + protected: + std::uint32_t selectedHz; + std::uint32_t* hzList; + std::uint32_t hzCount; + SysClkModule module; // Added + FreqChoiceListener listener; + tsl::elm::ListItem* createFreqListItem(std::uint32_t hz, bool selected); + + public: + FreqChoiceGui(std::uint32_t selectedHz, std::uint32_t* hzList, std::uint32_t hzCount, SysClkModule module, FreqChoiceListener listener); + ~FreqChoiceGui() {} + void listUI() override; +}; diff --git a/Source/sys-clk/overlay/src/ui/gui/global_override_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/global_override_gui.cpp new file mode 100644 index 00000000..97104411 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/global_override_gui.cpp @@ -0,0 +1,108 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "global_override_gui.h" + +#include "fatal_gui.h" +#include "../format.h" + +GlobalOverrideGui::GlobalOverrideGui() +{ + for(std::uint16_t m = 0; m < SysClkModule_EnumMax; m++) + { + this->listItems[m] = nullptr; + this->listHz[m] = 0; + } +} + +void GlobalOverrideGui::openFreqChoiceGui(SysClkModule module) +{ + std::uint32_t hzList[SYSCLK_FREQ_LIST_MAX]; + std::uint32_t hzCount; + Result rc = sysclkIpcGetFreqList(module, &hzList[0], SYSCLK_FREQ_LIST_MAX, &hzCount); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcGetFreqList", rc); + return; + } + tsl::changeTo(this->context->overrideFreqs[module], hzList, hzCount, module, [this, module](std::uint32_t hz) { + Result rc = sysclkIpcSetOverride(module, hz); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcSetOverride", rc); + return false; + } + + this->lastContextUpdate = armGetSystemTick(); + this->context->overrideFreqs[module] = hz; + + return true; + }); +} + +void GlobalOverrideGui::addModuleListItem(SysClkModule module) +{ + tsl::elm::ListItem* listItem = new tsl::elm::ListItem(sysclkFormatModule(module, true)); + listItem->setValue(formatListFreqMHz(0)); + listItem->setClickListener([this, module](u64 keys) { + if((keys & HidNpadButton_A) == HidNpadButton_A) + { + this->openFreqChoiceGui(module); + return true; + } + else if((keys & HidNpadButton_Y) == HidNpadButton_Y) + { + // Reset override to "Do not override" (0 Hz) + Result rc = sysclkIpcSetOverride(module, 0); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcSetOverride", rc); + return false; + } + + // Update context and tracking variables + this->lastContextUpdate = armGetSystemTick(); + this->context->overrideFreqs[module] = 0; + this->listHz[module] = 0; + + // Update display + this->listItems[module]->setValue(formatListFreqHz(0)); + + return true; + } + return false; + }); + this->listElement->addItem(listItem); + this->listItems[module] = listItem; +} + +void GlobalOverrideGui::listUI() +{ + this->listElement->addItem(new tsl::elm::CategoryHeader("Temporary Overrides " + ult::DIVIDER_SYMBOL + "  Reset")); + this->addModuleListItem(SysClkModule_CPU); + this->addModuleListItem(SysClkModule_GPU); + this->addModuleListItem(SysClkModule_MEM); +} + +void GlobalOverrideGui::refresh() +{ + BaseMenuGui::refresh(); + if(this->context) + { + for(std::uint16_t m = 0; m < SysClkModule_EnumMax; m++) + { + if(this->listItems[m] != nullptr && this->listHz[m] != this->context->overrideFreqs[m]) + { + this->listItems[m]->setValue(formatListFreqHz(this->context->overrideFreqs[m])); + this->listHz[m] = this->context->overrideFreqs[m]; + } + } + } +} diff --git a/Source/sys-clk/overlay/src/ui/gui/global_override_gui.h b/Source/sys-clk/overlay/src/ui/gui/global_override_gui.h new file mode 100644 index 00000000..3dc9caf5 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/global_override_gui.h @@ -0,0 +1,31 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include "../../ipc.h" +#include "base_menu_gui.h" +#include "freq_choice_gui.h" + +class GlobalOverrideGui : public BaseMenuGui +{ + protected: + tsl::elm::ListItem* listItems[SysClkModule_EnumMax]; + std::uint32_t listHz[SysClkModule_EnumMax]; + + void openFreqChoiceGui(SysClkModule module); + void addModuleListItem(SysClkModule module); + + public: + GlobalOverrideGui(); + ~GlobalOverrideGui() {} + void listUI() override; + void refresh() override; +}; diff --git a/Source/sys-clk/overlay/src/ui/gui/main_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/main_gui.cpp new file mode 100644 index 00000000..4e73f351 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/main_gui.cpp @@ -0,0 +1,93 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "main_gui.h" + +#include "fatal_gui.h" +#include "app_profile_gui.h" +#include "global_override_gui.h" +#include "misc_gui.h" + +void MainGui::listUI() +{ + this->enabledToggle = new tsl::elm::ToggleListItem("Enable", false); + enabledToggle->setStateChangedListener([this](bool state) { + Result rc = sysclkIpcSetEnabled(state); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcSetEnabled", rc); + } + + this->lastContextUpdate = armGetSystemTick(); + this->context->enabled = state; + }); + this->listElement->addItem(this->enabledToggle); + + tsl::elm::ListItem* appProfileItem = new tsl::elm::ListItem("Edit App Profile"); + appProfileItem->setClickListener([this](u64 keys) { + if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) + { + AppProfileGui::changeTo(this->context->applicationId); + return true; + } + + return false; + }); + this->listElement->addItem(appProfileItem); + + this->listElement->addItem(new tsl::elm::CategoryHeader("Advanced")); + + tsl::elm::ListItem* globalProfileItem = new tsl::elm::ListItem("Edit Global Profile"); + globalProfileItem->setClickListener([this](u64 keys) { + if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) + { + AppProfileGui::changeTo(SYSCLK_GLOBAL_PROFILE_TID); + return true; + } + + return false; + }); + this->listElement->addItem(globalProfileItem); + + tsl::elm::ListItem* globalOverrideItem = new tsl::elm::ListItem("Temporary Overrides"); + globalOverrideItem->setClickListener([this](u64 keys) { + if((keys & HidNpadButton_A) == HidNpadButton_A) + { + tsl::changeTo(); + return true; + } + + return false; + }); + this->listElement->addItem(globalOverrideItem); + + //this->listElement->addItem(new tsl::elm::CategoryHeader("Misc")); + + tsl::elm::ListItem* miscItem = new tsl::elm::ListItem("Settings"); + miscItem->setClickListener([this](u64 keys) { + if((keys & HidNpadButton_A) == HidNpadButton_A && this->context) + { + tsl::changeTo(); + return true; + } + + return false; + }); + this->listElement->addItem(miscItem); + } + +void MainGui::refresh() +{ + BaseMenuGui::refresh(); + //if(this->context) + //{ + // this->enabledToggle->setState(this->context->enabled); + //} +} diff --git a/Source/sys-clk/overlay/src/ui/gui/main_gui.h b/Source/sys-clk/overlay/src/ui/gui/main_gui.h new file mode 100644 index 00000000..ea54ef53 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/main_gui.h @@ -0,0 +1,25 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include "base_menu_gui.h" + +class MainGui : public BaseMenuGui +{ + protected: + tsl::elm::ToggleListItem* enabledToggle; + + public: + MainGui() {} + ~MainGui() {} + void listUI() override; + void refresh() override; +}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp b/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp new file mode 100644 index 00000000..20f20db4 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/misc_gui.cpp @@ -0,0 +1,444 @@ +#include "misc_gui.h" +#include "fatal_gui.h" +#include "../format.h" +#include +#include +//#include + +MiscGui::MiscGui() +{ + + // Load current config values + configValues["uncapped_clocks"] = getConfigValue("uncapped_clocks"); + configValues["override_boost_mode"] = getConfigValue("override_boost_mode"); + configValues["auto_cpu_boost"] = getConfigValue("auto_cpu_boost"); + configValues["sync_reversenx"] = getConfigValue("sync_reversenx"); + // gpu_dvfs is handled separately as it's now a trackbar with integer values +} + +MiscGui::~MiscGui() +{ + this->configToggles.clear(); +} + +bool MiscGui::getConfigValue(const std::string& iniKey) +{ + FILE* file = fopen("/config/sys-clk/config.ini", "r"); + if (!file) { + // Return default values if file doesn't exist + return (iniKey == "gpu_dvfs"); // gpu_dvfs defaults to true, others default to false + } + + char line[512]; + bool inValuesSection = false; + + size_t len; + while (fgets(line, sizeof(line), file)) { + // Remove newline if present + len = strlen(line); + if (len > 0 && line[len - 1] == '\n') { + line[len - 1] = '\0'; + } + + // Trim whitespace + char* start = line; + while (*start == ' ' || *start == '\t') start++; + char* end = start + strlen(start) - 1; + while (end > start && (*end == ' ' || *end == '\t')) { + *end = '\0'; + end--; + } + + // Check for [values] section + if (strcmp(start, "[values]") == 0) { + inValuesSection = true; + continue; + } + + // Check for new section + if (strlen(start) > 0 && start[0] == '[') { + inValuesSection = false; + continue; + } + + // Parse key=value in values section + if (inValuesSection) { + char* equalPos = strchr(start, '='); + if (equalPos != nullptr) { + *equalPos = '\0'; // Split the string + char* key = start; + char* value = equalPos + 1; + + if(iniKey == "uncapped_clocks") { + Result rc = sysclkIpcSetEnabled(value); + } + + // Trim key + char* keyEnd = key + strlen(key) - 1; + while (keyEnd > key && (*keyEnd == ' ' || *keyEnd == '\t')) { + *keyEnd = '\0'; + keyEnd--; + } + + // Trim value + while (*value == ' ' || *value == '\t') value++; + char* valueEnd = value + strlen(value) - 1; + while (valueEnd > value && (*valueEnd == ' ' || *valueEnd == '\t')) { + *valueEnd = '\0'; + valueEnd--; + } + + if (iniKey == key) { + bool result = (strcmp(value, "1") == 0); + fclose(file); + return result; + } + } + } + } + + fclose(file); + + // Return default values if key not found + return (iniKey == "gpu_dvfs"); // gpu_dvfs defaults to true, others default to false +} + +int MiscGui::getConfigIntValue(const std::string& iniKey, int defaultValue) +{ + FILE* file = fopen("/config/sys-clk/config.ini", "r"); + if (!file) { + return defaultValue; + } + + char line[512]; + bool inValuesSection = false; + + size_t len; + + while (fgets(line, sizeof(line), file)) { + // Remove newline if present + len = strlen(line); + if (len > 0 && line[len - 1] == '\n') { + line[len - 1] = '\0'; + } + + // Trim whitespace + char* start = line; + while (*start == ' ' || *start == '\t') start++; + char* end = start + strlen(start) - 1; + while (end > start && (*end == ' ' || *end == '\t')) { + *end = '\0'; + end--; + } + + // Check for [values] section + if (strcmp(start, "[values]") == 0) { + inValuesSection = true; + continue; + } + + // Check for new section + if (strlen(start) > 0 && start[0] == '[') { + inValuesSection = false; + continue; + } + + // Parse key=value in values section + if (inValuesSection) { + char* equalPos = strchr(start, '='); + if (equalPos != nullptr) { + *equalPos = '\0'; // Split the string + char* key = start; + char* value = equalPos + 1; + + // Trim key + char* keyEnd = key + strlen(key) - 1; + while (keyEnd > key && (*keyEnd == ' ' || *keyEnd == '\t')) { + *keyEnd = '\0'; + keyEnd--; + } + + // Trim value + while (*value == ' ' || *value == '\t') value++; + char* valueEnd = value + strlen(value) - 1; + while (valueEnd > value && (*valueEnd == ' ' || *valueEnd == '\t')) { + *valueEnd = '\0'; + valueEnd--; + } + + if (iniKey == key) { + int result = atoi(value); + fclose(file); + return result; + } + } + } + } + + fclose(file); + return defaultValue; +} + +SysClkIpcToggleUncappedClocks(SysClkModule_CPU, g_freq_table_hz[SysClkModule_CPU][result]) + +void MiscGui::setConfigValue(const std::string& iniKey, bool value) +{ + if(iniKey == "uncapped_clocks") { + Result rc = sysclkIpcSetEnabled(value); + } + // Read the entire file + FILE* file = fopen("/config/sys-clk/config.ini", "r"); + std::vector lines; + + if (file) { + char line[512]; + size_t len; + while (fgets(line, sizeof(line), file)) { + // Remove newline if present + len = strlen(line); + if (len > 0 && line[len - 1] == '\n') { + line[len - 1] = '\0'; + } + lines.push_back(std::string(line)); + } + fclose(file); + } + + // Find and update the value + bool inValuesSection = false; + bool keyFound = false; + int valuesSectionIndex = -1; + + std::string trimmedLine; + size_t equalPos; + std::string key; + for (size_t i = 0; i < lines.size(); i++) { + trimmedLine = lines[i]; + trimmedLine.erase(0, trimmedLine.find_first_not_of(" \t")); + trimmedLine.erase(trimmedLine.find_last_not_of(" \t") + 1); + + if (trimmedLine == "[values]") { + inValuesSection = true; + valuesSectionIndex = i; + continue; + } + + if (trimmedLine.length() > 0 && trimmedLine[0] == '[') { + inValuesSection = false; + continue; + } + + if (inValuesSection) { + equalPos = trimmedLine.find('='); + if (equalPos != std::string::npos) { + key = trimmedLine.substr(0, equalPos); + key.erase(0, key.find_first_not_of(" \t")); + key.erase(key.find_last_not_of(" \t") + 1); + + if (key == iniKey) { + lines[i] = iniKey + "=" + (value ? "1" : "0"); + keyFound = true; + break; + } + } + } + } + + // If key wasn't found, add it to the values section + if (!keyFound) { + if (valuesSectionIndex == -1) { + // Add [values] section if it doesn't exist + lines.push_back("[values]"); + lines.push_back(iniKey + "=" + (value ? "1" : "0")); + } else { + // Add to existing values section + lines.insert(lines.begin() + valuesSectionIndex + 1, iniKey + "=" + (value ? "1" : "0")); + } + } + + // Write the file back + FILE* outFile = fopen("/config/sys-clk/config.ini", "w"); + if (outFile) { + for (const auto& fileLine : lines) { + fprintf(outFile, "%s\n", fileLine.c_str()); + } + fclose(outFile); + } +} + +void MiscGui::setConfigIntValue(const std::string& iniKey, int value) +{ + // Read the entire file + FILE* file = fopen("/config/sys-clk/config.ini", "r"); + std::vector lines; + + if (file) { + char line[512]; + size_t len; + while (fgets(line, sizeof(line), file)) { + // Remove newline if present + len = strlen(line); + if (len > 0 && line[len - 1] == '\n') { + line[len - 1] = '\0'; + } + lines.push_back(std::string(line)); + } + fclose(file); + } + + // Find and update the value + bool inValuesSection = false; + bool keyFound = false; + int valuesSectionIndex = -1; + + std::string trimmedLine; + size_t equalPos; + std::string key; + + for (size_t i = 0; i < lines.size(); i++) { + trimmedLine = lines[i]; + trimmedLine.erase(0, trimmedLine.find_first_not_of(" \t")); + trimmedLine.erase(trimmedLine.find_last_not_of(" \t") + 1); + + if (trimmedLine == "[values]") { + inValuesSection = true; + valuesSectionIndex = i; + continue; + } + + if (trimmedLine.length() > 0 && trimmedLine[0] == '[') { + inValuesSection = false; + continue; + } + + if (inValuesSection) { + equalPos = trimmedLine.find('='); + if (equalPos != std::string::npos) { + key = trimmedLine.substr(0, equalPos); + key.erase(0, key.find_first_not_of(" \t")); + key.erase(key.find_last_not_of(" \t") + 1); + + if (key == iniKey) { + lines[i] = iniKey + "=" + std::to_string(value); + keyFound = true; + break; + } + } + } + } + + // If key wasn't found, add it to the values section + if (!keyFound) { + if (valuesSectionIndex == -1) { + // Add [values] section if it doesn't exist + lines.push_back("[values]"); + lines.push_back(iniKey + "=" + std::to_string(value)); + } else { + // Add to existing values section + lines.insert(lines.begin() + valuesSectionIndex + 1, iniKey + "=" + std::to_string(value)); + } + } + + // Write the file back + FILE* outFile = fopen("/config/sys-clk/config.ini", "w"); + if (outFile) { + for (const auto& fileLine : lines) { + fprintf(outFile, "%s\n", fileLine.c_str()); + } + fclose(outFile); + } +} + +void MiscGui::addConfigToggle(const std::string& iniKey, const char* displayName) { + tsl::elm::ToggleListItem* toggle = new tsl::elm::ToggleListItem(displayName, configValues[iniKey]); + toggle->setStateChangedListener([this, iniKey](bool state) { + configValues[iniKey] = state; + setConfigValue(iniKey, state); + this->lastContextUpdate = armGetSystemTick(); + }); + this->listElement->addItem(toggle); + this->configToggles[iniKey] = toggle; +} + +void MiscGui::updateConfigToggles() { + for (const auto& [key, toggle] : this->configToggles) { + if (toggle != nullptr) { + bool currentValue = getConfigValue(key); + configValues[key] = currentValue; + toggle->setState(currentValue); + } + } +} + +void MiscGui::listUI() +{ + + this->listElement->addItem(new tsl::elm::CategoryHeader("Settings")); + + this->enabledToggle = new tsl::elm::ToggleListItem("Enable", false); + enabledToggle->setStateChangedListener([this](bool state) { + Result rc = sysclkIpcSetEnabled(state); + if(R_FAILED(rc)) + { + FatalGui::openWithResultCode("sysclkIpcSetEnabled", rc); + } + + this->lastContextUpdate = armGetSystemTick(); + this->context->enabled = state; + }); + this->listElement->addItem(this->enabledToggle); + + // Add the 4 boolean config toggles using INI keys + addConfigToggle("uncapped_clocks", "Uncapped Clocks"); + addConfigToggle("override_boost_mode", "Override Boost Mode"); + addConfigToggle("auto_cpu_boost", "Auto CPU Boost"); + addConfigToggle("reversenx_sync", "Sync ReverseNX"); + + // Add GPU DVFS as a NamedStepTrackBar with V2 style + this->gpuDvfsTrackbar = new tsl::elm::NamedStepTrackBar("", { + "Off", + "Official Service Method", + "Hijack Method" + }, true, "GPU DVFS"); + + // Set initial value (default is 0 if not set) + int currentDvfsValue = getConfigIntValue("gpu_dvfs", 1); + // Ensure the value is within valid range (0-2) + currentDvfsValue = std::max(0, std::min(2, currentDvfsValue)); + this->gpuDvfsTrackbar->setProgress(static_cast(currentDvfsValue)); + + // Set up the value change listener to update the INI file + this->gpuDvfsTrackbar->setValueChangedListener([this](u8 value) { + // Ensure value is within expected range + const int intValue = static_cast(std::min(static_cast(2), value)); + setConfigIntValue("gpu_dvfs", intValue); + this->lastContextUpdate = armGetSystemTick(); + }); + + this->listElement->addItem(this->gpuDvfsTrackbar); +} + +void MiscGui::refresh() { + BaseMenuGui::refresh(); + + // Update the enabled toggle state + if(this->context) + { + this->enabledToggle->setState(this->context->enabled); + } + + // Update config values and toggle states every 60 frames (once per second at 60fps) + if (this->context && ++frameCounter >= 60) + { + frameCounter = 0; + updateConfigToggles(); + + // Update GPU DVFS trackbar + if (this->gpuDvfsTrackbar != nullptr) { + int currentDvfsValue = getConfigIntValue("gpu_dvfs", 1); + // Ensure the value is within valid range (0-2) + currentDvfsValue = std::max(0, std::min(2, currentDvfsValue)); + this->gpuDvfsTrackbar->setProgress(static_cast(currentDvfsValue)); + } + } +} \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/gui/misc_gui.h b/Source/sys-clk/overlay/src/ui/gui/misc_gui.h new file mode 100644 index 00000000..8f7be10f --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/gui/misc_gui.h @@ -0,0 +1,30 @@ +#pragma once +#include "../../ipc.h" +#include "base_menu_gui.h" +#include +#include + +class MiscGui : public BaseMenuGui +{ + public: + MiscGui(); + ~MiscGui(); + void listUI() override; + void refresh() override; + protected: + + std::unordered_map configToggles; + std::unordered_map configValues; + + void addConfigToggle(const std::string& iniKey, const char* displayName); + void updateConfigToggles(); + bool getConfigValue(const std::string& iniKey); + void setConfigValue(const std::string& iniKey, bool value); + int getConfigIntValue(const std::string& iniKey, int defaultValue); + void setConfigIntValue(const std::string& iniKey, int value); + + tsl::elm::ToggleListItem* enabledToggle; + tsl::elm::NamedStepTrackBar* gpuDvfsTrackbar; // Add this line + + u8 frameCounter = 60; +}; \ No newline at end of file diff --git a/Source/sys-clk/overlay/src/ui/style.h b/Source/sys-clk/overlay/src/ui/style.h new file mode 100644 index 00000000..86b56d89 --- /dev/null +++ b/Source/sys-clk/overlay/src/ui/style.h @@ -0,0 +1,20 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include + +#define TEXT_COLOR tsl::gfx::Renderer::a(0xFFFF) +#define DESC_COLOR tsl::gfx::Renderer::a({ 0xC, 0xC, 0xC, 0xF }) +#define VALUE_COLOR tsl::gfx::Renderer::a({ 0x5, 0xC, 0xA, 0xF }) +#define SMALL_TEXT_SIZE 15 +#define LABEL_SPACING 7 +#define LABEL_FONT_SIZE 15 diff --git a/Source/sys-clk/sysmodule/.gitignore b/Source/sys-clk/sysmodule/.gitignore new file mode 100644 index 00000000..36a52c92 --- /dev/null +++ b/Source/sys-clk/sysmodule/.gitignore @@ -0,0 +1,2 @@ +/out +/build diff --git a/Source/sys-clk/sysmodule/Makefile b/Source/sys-clk/sysmodule/Makefile new file mode 100644 index 00000000..cc97fab7 --- /dev/null +++ b/Source/sys-clk/sysmodule/Makefile @@ -0,0 +1,164 @@ +#--------------------------------------------------------------------------------- +.SUFFIXES: +#--------------------------------------------------------------------------------- + +ifeq ($(strip $(DEVKITPRO)),) +$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") +endif + +TOPDIR ?= $(CURDIR) +include $(DEVKITPRO)/libnx/switch_rules + +#--------------------------------------------------------------------------------- +# TARGET is the name of the output +# BUILD is the directory where object files & intermediate files will be placed +# SOURCES is a list of directories containing source code +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +# EXEFS_SRC is the optional input directory containing data copied into exefs, if anything this normally should only contain "main.npdm". +#--------------------------------------------------------------------------------- +TARGET := sys-clk +BUILD := build +OUTDIR := out +RESOURCES := res +SOURCES := src src/nx/ipc ../common/src +DATA := data +INCLUDES := ../common/include +EXEFS_SRC := exefs_src +LIBNAMES := minIni nxExt + +#--------------------------------------------------------------------------------- +# version control constants +#--------------------------------------------------------------------------------- +TARGET_VERSION := $(shell git describe --dirty --always --tags) + +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- +DEFINES := -DDISABLE_IPC -DTARGET="\"$(TARGET)\"" -DTARGET_VERSION="\"$(TARGET_VERSION)\"" + +ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIE + +CFLAGS := -g -Wall -O2 -ffunction-sections \ + $(ARCH) $(DEFINES) + +CFLAGS += $(INCLUDE) -D__SWITCH__ + +CXXFLAGS := $(CFLAGS) -fno-rtti -std=gnu++17 + +ASFLAGS := -g $(ARCH) +LDFLAGS = -specs=$(DEVKITPRO)/libnx/switch.specs -g $(ARCH) -Wl,-Map,$(notdir $*.map) + +LIBS := $(foreach lib,$(LIBNAMES),-l$(lib)) -lnx + +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS := $(PORTLIBS) $(LIBNX) $(foreach lib,$(LIBNAMES),$(TOPDIR)/lib/$(lib)) + +#--------------------------------------------------------------------------------- +# no real need to edit anything past this point unless you need to add additional +# rules for different file extensions +#--------------------------------------------------------------------------------- +ifneq ($(BUILD),$(notdir $(CURDIR))) +#--------------------------------------------------------------------------------- + +export OUTPUT := $(CURDIR)/$(OUTDIR)/$(TARGET) +export TOPDIR := $(CURDIR) + +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + +export DEPSDIR := $(CURDIR)/$(BUILD) + +CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) +CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) +#--------------------------------------------------------------------------------- + export LD := $(CC) +#--------------------------------------------------------------------------------- +else +#--------------------------------------------------------------------------------- + export LD := $(CXX) +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- + +export OFILES := $(addsuffix .o,$(BINFILES)) \ + $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) + +export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) + +export LIBPATHS := $(foreach dir,$(LIBDIRS),-L$(dir)/lib) + +export BUILD_EXEFS_SRC := $(TOPDIR)/$(EXEFS_SRC) + +export APP_JSON := $(TOPDIR)/perms.json + +.PHONY: $(BUILD) clean clean-libs clean-build all libs + +#--------------------------------------------------------------------------------- +all: $(BUILD) + +libs: + @$(foreach lib,$(LIBNAMES),$(MAKE) --no-print-directory -C $(TOPDIR)/lib/$(lib) && ) true + +$(LIBNAMES): + @echo $@ + +$(BUILD): libs + @[ -d $@ ] || mkdir -p $@ + @[ -d $(OUTDIR) ] || mkdir -p $(OUTDIR) + @$(MAKE) --no-print-directory -C $(BUILD) -f $(CURDIR)/Makefile + +#--------------------------------------------------------------------------------- +clean-libs: + @echo clean libs $(LIBNAMES) ... + @$(foreach lib,$(LIBNAMES),$(MAKE) -C $(TOPDIR)/lib/$(lib) clean && ) true + +clean-build: + @echo clean build ... + @rm -fr $(BUILD) $(TARGET).kip $(TARGET).nsp $(TARGET).npdm $(TARGET).nso $(TARGET).elf $(OUTDIR) + +clean: clean-libs clean-build + + +#--------------------------------------------------------------------------------- +else +.PHONY: all $(LIBFILES) + +LIBFILES := $(foreach lib,$(LIBNAMES),$(TOPDIR)/lib/$(lib)/lib/lib$(lib).a) +DEPENDS := $(OFILES:.o=.d) + +#--------------------------------------------------------------------------------- +# main targets +#--------------------------------------------------------------------------------- + +all: $(OUTPUT).nsp + +$(OUTPUT).nsp: $(OUTPUT).nso $(OUTPUT).npdm + +$(OUTPUT).elf: $(OFILES) $(LIBFILES) + +#--------------------------------------------------------------------------------- +# you need a rule like this for each extension you use as binary data +#--------------------------------------------------------------------------------- +%.bin.o : %.bin +#--------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + +-include $(DEPENDS) + +#--------------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/sysmodule/lib/minIni/.gitignore b/Source/sys-clk/sysmodule/lib/minIni/.gitignore new file mode 100644 index 00000000..0806f7bf --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/.gitignore @@ -0,0 +1,13 @@ +# Editor files +*.swp +*~ + +# Objects +*.o +*.a +*.so + +# Lib +lib +release +debug \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/minIni/.gitrepo b/Source/sys-clk/sysmodule/lib/minIni/.gitrepo new file mode 100644 index 00000000..44cc0b36 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/.gitrepo @@ -0,0 +1,12 @@ +; DO NOT EDIT (unless you know what you are doing) +; +; This subdirectory is a git "subrepo", and this file is maintained by the +; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme +; +[subrepo] + remote = https://github.com/compuphase/minIni + branch = master + commit = 8ce144c3c287fa4e59f8ed4c405cd8b7e29f189b + parent = f32c0b1bca87a6d7e55fb341f8db9ef33b13819f + method = merge + cmdver = 0.4.0 diff --git a/Source/sys-clk/sysmodule/lib/minIni/LICENSE b/Source/sys-clk/sysmodule/lib/minIni/LICENSE new file mode 100644 index 00000000..cbf8eb4c --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/LICENSE @@ -0,0 +1,189 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + + EXCEPTION TO THE APACHE 2.0 LICENSE + + As a special exception to the Apache License 2.0 (and referring to the + definitions in Section 1 of this license), you may link, statically or + dynamically, the "Work" to other modules to produce an executable file + containing portions of the "Work", and distribute that executable file + in "Object" form under the terms of your choice, without any of the + additional requirements listed in Section 4 of the Apache License 2.0. + This exception applies only to redistributions in "Object" form (not + "Source" form) and only if no modifications have been made to the "Work". + + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + diff --git a/Source/sys-clk/sysmodule/lib/minIni/Makefile b/Source/sys-clk/sysmodule/lib/minIni/Makefile new file mode 100644 index 00000000..b9565d07 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/Makefile @@ -0,0 +1,133 @@ +#--------------------------------------------------------------------------------- +.SUFFIXES: +#--------------------------------------------------------------------------------- + +ifeq ($(strip $(DEVKITPRO)),) +$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") +endif + +include $(DEVKITPRO)/libnx/switch_rules + +#--------------------------------------------------------------------------------- +# TARGET is the name of the output +# SOURCES is a list of directories containing source code +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +#--------------------------------------------------------------------------------- +TARGET := $(notdir $(CURDIR)) +SOURCES := dev +DATA := data +INCLUDES := dev +SRC_H_FILES := + +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- +ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIC -ftls-model=local-exec + +CFLAGS := -g -Wall -Werror \ + -ffunction-sections \ + -fdata-sections \ + $(ARCH) \ + $(BUILD_CFLAGS) + +CFLAGS += $(INCLUDE) + +CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions + +ASFLAGS := -g $(ARCH) + +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS := $(PORTLIBS) $(LIBNX) + +#--------------------------------------------------------------------------------- +# no real need to edit anything past this point unless you need to add additional +# rules for different file extensions +#--------------------------------------------------------------------------------- +ifneq ($(BUILD),$(notdir $(CURDIR))) +#--------------------------------------------------------------------------------- + +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + +CFILES := minIni.c +CPPFILES := +SFILES := +BINFILES := + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) +#--------------------------------------------------------------------------------- + export LD := $(CC) +#--------------------------------------------------------------------------------- +else +#--------------------------------------------------------------------------------- + export LD := $(CXX) +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- + +export OFILES_BIN := $(addsuffix .o,$(BINFILES)) +export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) +export OFILES := $(OFILES_BIN) $(OFILES_SRC) +export HFILES := $(addsuffix .h,$(subst .,_,$(BINFILES))) + +export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) + +.PHONY: clean all lib/lib$(TARGET).a + +#--------------------------------------------------------------------------------- +all: lib/lib$(TARGET).a + +lib: + @[ -d $@ ] || mkdir -p $@ + +release: + @[ -d $@ ] || mkdir -p $@ + +debug: + @[ -d $@ ] || mkdir -p $@ + +lib/lib$(TARGET).a : lib release $(SOURCES) $(INCLUDES) + @$(MAKE) BUILD=release OUTPUT=$(CURDIR)/$@ \ + BUILD_CFLAGS="-DNDEBUG=1 -O2" \ + DEPSDIR=$(CURDIR)/release \ + --no-print-directory -C release \ + -f $(CURDIR)/Makefile + +#--------------------------------------------------------------------------------- +clean: + @echo clean ... + @rm -fr release debug lib + +#--------------------------------------------------------------------------------- +else + +DEPENDS := $(OFILES:.o=.d) + +#--------------------------------------------------------------------------------- +# main targets +#--------------------------------------------------------------------------------- +$(OUTPUT) : $(OFILES) + +$(OFILES_SRC) : $(HFILES) + +#--------------------------------------------------------------------------------- +%_bin.h %.bin.o : %.bin +#--------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + + +-include $(DEPENDS) + +#--------------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/sysmodule/lib/minIni/NOTICE b/Source/sys-clk/sysmodule/lib/minIni/NOTICE new file mode 100644 index 00000000..dbd0bba0 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/NOTICE @@ -0,0 +1,12 @@ +minIni is a programmer's library to read and write "INI" files in embedded +systems. The library takes little resources and can be configured for various +kinds of file I/O libraries. + +The method for portable INI file management in minIni is, in part based, on the +article "Multiplatform .INI Files" by Joseph J. Graf in the March 1994 issue of +Dr. Dobb's Journal. + +The C++ class in minIni.h was contributed by Steven Van Ingelgem. + +The option to compile minIni as a read-only library was contributed by Luca +Bassanello. diff --git a/Source/sys-clk/sysmodule/lib/minIni/README.md b/Source/sys-clk/sysmodule/lib/minIni/README.md new file mode 100644 index 00000000..9f30a019 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/README.md @@ -0,0 +1,170 @@ +# minIni +minIni is a portable and configurable library for reading and writing ".INI" files. At 830 lines of commented source +code +(version 1.2), minIni truly is a "mini" INI file parser, especially considering its features. + +The library does not require the file I/O functions from the standard C/C++ library, but instead lets you configure +the file I/O interface to use via macros. minIni uses limited stack space and does not use dynamic memory (malloc and +friends) at all. + +Some minor variations on standard INI files are supported too, notably minIni supports INI files that lack sections. + + +# Acknowledgement + +minIni is derived from an earlier INI file parser (which I wrote) for desktop systems. + +In turn, that earlier parser was a re-write of the code from the article "Multiplatform .INI Files" by Joseph J. Graf +in the March 1994 issue of Dr. Dobb's Journal. In other words, minIni has its roots in the work of Joseph Graf (even +though the code has been almost completely re-written). + + +# Features + +minIni is a programmer's library to read and write "INI" files in embedded systems. minIni takes little resources, +can be configured for various kinds of file I/O libraries and provides functionality for reading, writing and +deleting keys from an INI file. + +Although the main feature of minIni is that it is small and minimal, it has a few other features: + + * minIni supports reading keys that are outside a section, and it thereby supports configuration files that do not use sections (but that are otherwise compatible with INI files). + * You may use a colon to separate key and value; the colon is equivalent to the equal sign. That is, the strings "Name: Value" and "Name=Value" have the same meaning. + * The hash character ("#") is an alternative for the semicolon to start a comment. Trailing comments (i.e. behind a key/value pair on a line) are allowed. + * Leading and trailing white space around key names and values is ignored. + * When writing a value that contains a comment character (";" or "#"), that value will automatically be put between double quotes; when reading the value, these quotes are removed. When a double-quote itself appears in the setting, these characters are escaped. + * Section and key enumeration are supported. + * You can optionally set the line termination (for text files) that minIni will use. (This is a compile-time setting, not a run-time setting.) + * Since writing speed is much lower than reading speed in Flash memory (SD/MMC cards, USB memory sticks), minIni minimizes "file writes" at the expense of double "file reads". + * The memory footprint is deterministic. There is no dynamic memory allocation. + +## INI file reading paradigms + +There are two approaches to reading settings from an INI file. One way is to call a function, such as +GetProfileString() for every section and key that you need. This is especially convenient if there is a large +INI file, but you only need a few settings from that file at any time —especially if the INI file can also +change while your program runs. This is the approach that the Microsoft Windows API uses. + +The above procedure is quite inefficient, however, when you need to retrieve quite a few settings in a row from +the INI file —especially if the INI file is not cached in memory (which it isn't, in minIni). A different approach +to getting settings from an INI file is to call a "parsing" function and let that function call the application +back with the section and key names plus the associated data. XML parsing libraries often use this approach; see +for example the Expat library. + +minIni supports both approaches. For reading a single setting, use functions like ini_gets(). For the callback +approach, implement a callback and call ini_browse(). See the minIni manual for details. + + +# INI file syntax + +INI files are best known from Microsoft Windows, but they are also used with applications that run on other +platforms (although their file extension is sometimes ".cfg" instead of ".ini"). + +INI files have a simple syntax with name/value pairs in a plain text file. The name must be unique (per section) +and the value must fit on a single line. INI files are commonly separated into sections —in minIni, this is +optional. A section is a name between square brackets, like "[Network]" in the example below. + +``` +[Network] +hostname=My Computer +address=dhcp +dns = 192.168.1.1 +``` + +In the API and in this documentation, the "name" for a setting is denoted as the key for the setting. The key +and the value are separated by an equal sign ("="). minIni supports the colon (":") as an alternative to the +equal sign for the key/value delimiter. + +Leading a trailing spaces around values or key names are removed. If you need to include leading and/or trailing +spaces in a value, put the value between double quotes. The ini_gets() function (from the minIni library, see the +minIni manual) strips off the double quotes from the returned value. Function ini_puts() adds double quotes if +the value to write contains trailing white space (or special characters). + +minIni ignores spaces around the "=" or ":" delimiters, but it does not ignore spaces between the brackets in a +section name. In other words, it is best not to put spaces behind the opening bracket "[" or before the closing +bracket "]" of a section name. + +Comments in the INI must start with a semicolon (";") or a hash character ("#"), and run to the end of the line. +A comment can be a line of its own, or it may follow a key/value pair (the "#" character and trailing comments +are extensions of minIni). + +For more details on the format, please see http://en.wikipedia.org/wiki/INI_file. + + +# Adapting minIni to a file system + +The minIni library must be configured for a platform with the help of a so- called "glue file". This glue file +contains macros (and possibly functions) that map file reading and writing functions used by the minIni library +to those provided by the operating system. The glue file must be called "minGlue.h". + +To get you started, the minIni distribution comes with the following example glue files: + + * a glue file that maps to the standard C/C++ library (specifically the file I/O functions from the "stdio" package), + * a glue file for Microchip's "Memory Disk Drive File System Library" (see http://www.microchip.com/), + * a glue file for the FAT library provided with the CCS PIC compiler (see http://www.ccsinfo.com/) + * a glue file for the EFS Library (EFSL, http://www.efsl.be/), + * and a glue file for the FatFs and Petit-FatFs libraries (http://elm-chan.org/fsw/ff/00index_e.html). + +The minIni library does not rely on the availability of a standard C library, because embedded operating systems +may have limited support for file I/O. Even on full operating systems, separating the file I/O from the INI format +parsing carries advantages, because it allows you to cache the INI file and thereby enhance performance. + +The glue file must specify the type that identifies a file, whether it is a handle or a pointer. For the standard +C/C++ file I/O library, this would be: + +```C +#define INI_FILETYPE FILE* +``` + +If you are not using the standard C/C++ file I/O library, chances are that you need a different handle or +"structure" to identify the storage than the ubiquitous "FILE*" type. For example, the glue file for the FatFs +library uses the following declaration: + +```C +#define INI_FILETYPE FIL +``` + +The minIni functions declare variables of this INI_FILETYPE type and pass these variables to sub-functions +(including the glue interface functions) by reference. + +For "write support", another type that must be defined is for variables that hold the "current position" in a +file. For the standard C/C++ I/O library, this is "fpos_t". + +Another item that needs to be configured is the buffer size. The functions in the minIni library allocate this +buffer on the stack, so the buffer size is directly related to the stack usage. In addition, the buffer size +determines the maximum line length that is supported in the INI file and the maximum path name length for the +temporary file. For example, minGlue.h could contain the definition: + +```C +#define INI_BUFFERSIZE 512 +``` + +The above macro limits the line length of the INI files supported by minIni to 512 characters. + +The temporary file is only used when writing to INI files. The minIni routines copy/change the INI file to a +temporary file and then rename that temporary file to the original file. This approach uses the least amount of +memory. The path name of the temporary file is the same as the input file, but with the last character set to a +tilde ("~"). + +Below is an example of a glue file (this is the one that maps to the C/C++ "stdio" library). + +```C +#include + +#define INI_FILETYPE FILE* +#define ini_openread(filename,file) ((*(file) = fopen((filename),"r")) != NULL) +#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"w")) != NULL) +#define ini_close(file) (fclose(*(file)) == 0) +#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL) +#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0) +#define ini_rename(source,dest) (rename((source), (dest)) == 0) +#define ini_remove(filename) (remove(filename) == 0) + +#define INI_FILEPOS fpos_t +#define ini_tell(file,pos) (fgetpos(*(file), (pos)) == 0) +#define ini_seek(file,pos) (fsetpos(*(file), (pos)) == 0) +``` + +As you can see, a glue file is mostly a set of macros that wraps one function definition around another. + +The glue file may contain more settings, for support of rational numbers, to explicitly set the line termination +character(s), or to disable write support (for example). See the manual that comes with the archive for the details. diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-FatFs.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-FatFs.h new file mode 100644 index 00000000..51593a26 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-FatFs.h @@ -0,0 +1,37 @@ +/* Glue functions for the minIni library, based on the FatFs and Petit-FatFs + * libraries, see http://elm-chan.org/fsw/ff/00index_e.html + * + * By CompuPhase, 2008-2012 + * This "glue file" is in the public domain. It is distributed without + * warranties or conditions of any kind, either express or implied. + * + * (The FatFs and Petit-FatFs libraries are copyright by ChaN and licensed at + * its own terms.) + */ + +#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ + +/* You must set _USE_STRFUNC to 1 or 2 in the include file ff.h (or tff.h) + * to enable the "string functions" fgets() and fputs(). + */ +#include "ff.h" /* include tff.h for Tiny-FatFs */ + +#define INI_FILETYPE FIL +#define ini_openread(filename,file) (f_open((file), (filename), FA_READ+FA_OPEN_EXISTING) == FR_OK) +#define ini_openwrite(filename,file) (f_open((file), (filename), FA_WRITE+FA_CREATE_ALWAYS) == FR_OK) +#define ini_close(file) (f_close(file) == FR_OK) +#define ini_read(buffer,size,file) f_gets((buffer), (size),(file)) +#define ini_write(buffer,file) f_puts((buffer), (file)) +#define ini_remove(filename) (f_unlink(filename) == FR_OK) + +#define INI_FILEPOS DWORD +#define ini_tell(file,pos) (*(pos) = f_tell((file))) +#define ini_seek(file,pos) (f_lseek((file), *(pos)) == FR_OK) + +static int ini_rename(TCHAR *source, const TCHAR *dest) +{ + /* Function f_rename() does not allow drive letters in the destination file */ + char *drive = strchr(dest, ':'); + drive = (drive == NULL) ? dest : drive + 1; + return (f_rename(source, drive) == FR_OK); +} diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ccs.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ccs.h new file mode 100644 index 00000000..22a8c92b --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ccs.h @@ -0,0 +1,64 @@ +/* minIni glue functions for FAT library by CCS, Inc. (as provided with their + * PIC MCU compiler) + * + * By CompuPhase, 2011-2012 + * This "glue file" is in the public domain. It is distributed without + * warranties or conditions of any kind, either express or implied. + * + * (The FAT library is copyright (c) 2007 Custom Computer Services, and + * licensed at its own terms.) + */ + +#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ + +#ifndef FAT_PIC_C + #error FAT library must be included before this module +#endif +#define const /* keyword not supported by CCS */ + +#define INI_FILETYPE FILE +#define ini_openread(filename,file) (fatopen((filename), "r", (file)) == GOODEC) +#define ini_openwrite(filename,file) (fatopen((filename), "w", (file)) == GOODEC) +#define ini_close(file) (fatclose((file)) == 0) +#define ini_read(buffer,size,file) (fatgets((buffer), (size), (file)) != NULL) +#define ini_write(buffer,file) (fatputs((buffer), (file)) == GOODEC) +#define ini_remove(filename) (rm_file((filename)) == 0) + +#define INI_FILEPOS fatpos_t +#define ini_tell(file,pos) (fatgetpos((file), (pos)) == 0) +#define ini_seek(file,pos) (fatsetpos((file), (pos)) == 0) + +#ifndef INI_READONLY +/* CCS FAT library lacks a rename function, so instead we copy the file to the + * new name and delete the old file + */ +static int ini_rename(char *source, char *dest) +{ + FILE fr, fw; + int n; + + if (fatopen(source, "r", &fr) != GOODEC) + return 0; + if (rm_file(dest) != 0) + return 0; + if (fatopen(dest, "w", &fw) != GOODEC) + return 0; + + /* With some "insider knowledge", we can save some memory: the "source" + * parameter holds a filename that was built from the "dest" parameter. It + * was built in a local buffer with the size INI_BUFFERSIZE. We can reuse + * this buffer for copying the file. + */ + while (n=fatread(source, 1, INI_BUFFERSIZE, &fr)) + fatwrite(source, 1, n, &fw); + + fatclose(&fr); + fatclose(&fw); + + /* Now we need to delete the source file. However, we have garbled the buffer + * that held the filename of the source. So we need to build it again. + */ + ini_tempname(source, dest, INI_BUFFERSIZE); + return rm_file(source) == 0; +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-efsl.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-efsl.h new file mode 100644 index 00000000..5fe0fcf8 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-efsl.h @@ -0,0 +1,63 @@ +/* Glue functions for the minIni library, based on the EFS Library, see + * http://www.efsl.be/ + * + * By CompuPhase, 2008-2012 + * This "glue file" is in the public domain. It is distributed without + * warranties or conditions of any kind, either express or implied. + * + * (EFSL is copyright 2005-2006 Lennart Ysboodt and Michael De Nil, and + * licensed under the GPL with an exception clause for static linking.) + */ + +#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ +#define INI_LINETERM "\r\n" /* set line termination explicitly */ + +#include "efs.h" +extern EmbeddedFileSystem g_efs; + +#define INI_FILETYPE EmbeddedFile +#define ini_openread(filename,file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'r') == 0) +#define ini_openwrite(filename,file) (file_fopen((file), &g_efs.myFs, (char*)(filename), 'w') == 0) +#define ini_close(file) file_fclose(file) +#define ini_read(buffer,size,file) (file_read((file), (size), (buffer)) > 0) +#define ini_write(buffer,file) (file_write((file), strlen(buffer), (char*)(buffer)) > 0) +#define ini_remove(filename) rmfile(&g_efs.myFs, (char*)(filename)) + +#define INI_FILEPOS euint32 +#define ini_tell(file,pos) (*(pos) = (file)->FilePtr)) +#define ini_seek(file,pos) file_setpos((file), (*pos)) + +#if ! defined INI_READONLY +/* EFSL lacks a rename function, so instead we copy the file to the new name + * and delete the old file + */ +static int ini_rename(char *source, const char *dest) +{ + EmbeddedFile fr, fw; + int n; + + if (file_fopen(&fr, &g_efs.myFs, source, 'r') != 0) + return 0; + if (rmfile(&g_efs.myFs, (char*)dest) != 0) + return 0; + if (file_fopen(&fw, &g_efs.myFs, (char*)dest, 'w') != 0) + return 0; + + /* With some "insider knowledge", we can save some memory: the "source" + * parameter holds a filename that was built from the "dest" parameter. It + * was built in buffer and this buffer has the size INI_BUFFERSIZE. We can + * reuse this buffer for copying the file. + */ + while (n=file_read(&fr, INI_BUFFERSIZE, source)) + file_write(&fw, n, source); + + file_fclose(&fr); + file_fclose(&fw); + + /* Now we need to delete the source file. However, we have garbled the buffer + * that held the filename of the source. So we need to build it again. + */ + ini_tempname(source, dest, INI_BUFFERSIZE); + return rmfile(&g_efs.myFs, source) == 0; +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ffs.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ffs.h new file mode 100644 index 00000000..bf874e41 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-ffs.h @@ -0,0 +1,26 @@ +/* Glue functions for the minIni library, based on the "FAT Filing System" + * library by embedded-code.com + * + * By CompuPhase, 2008-2012 + * This "glue file" is in the public domain. It is distributed without + * warranties or conditions of any kind, either express or implied. + * + * (The "FAT Filing System" library itself is copyright embedded-code.com, and + * licensed at its own terms.) + */ + +#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ +#include + +#define INI_FILETYPE FFS_FILE* +#define ini_openread(filename,file) ((*(file) = ffs_fopen((filename),"r")) != NULL) +#define ini_openwrite(filename,file) ((*(file) = ffs_fopen((filename),"w")) != NULL) +#define ini_close(file) (ffs_fclose(*(file)) == 0) +#define ini_read(buffer,size,file) (ffs_fgets((buffer),(size),*(file)) != NULL) +#define ini_write(buffer,file) (ffs_fputs((buffer),*(file)) >= 0) +#define ini_rename(source,dest) (ffs_rename((source), (dest)) == 0) +#define ini_remove(filename) (ffs_remove(filename) == 0) + +#define INI_FILEPOS long +#define ini_tell(file,pos) (ffs_fgetpos(*(file), (pos)) == 0) +#define ini_seek(file,pos) (ffs_fsetpos(*(file), (pos)) == 0) diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-mdd.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-mdd.h new file mode 100644 index 00000000..ec5e0be1 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-mdd.h @@ -0,0 +1,58 @@ +/* minIni glue functions for Microchip's "Memory Disk Drive" file system + * library, as presented in Microchip application note AN1045. + * + * By CompuPhase, 2011-2014 + * This "glue file" is in the public domain. It is distributed without + * warranties or conditions of any kind, either express or implied. + * + * (The "Microchip Memory Disk Drive File System" is copyright (c) Microchip + * Technology Incorporated, and licensed at its own terms.) + */ + +#define INI_BUFFERSIZE 256 /* maximum line length, maximum path length */ + +#include "MDD File System\fsio.h" +#include + +#define INI_FILETYPE FSFILE* +#define ini_openread(filename,file) ((*(file) = FSfopen((filename),FS_READ)) != NULL) +#define ini_openwrite(filename,file) ((*(file) = FSfopen((filename),FS_WRITE)) != NULL) +#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),FS_READPLUS)) != NULL) +#define ini_close(file) (FSfclose(*(file)) == 0) +#define ini_write(buffer,file) (FSfwrite((buffer), 1, strlen(buffer), (*file)) > 0) +#define ini_remove(filename) (FSremove((filename)) == 0) + +#define INI_FILEPOS long int +#define ini_tell(file,pos) (*(pos) = FSftell(*(file))) +#define ini_seek(file,pos) (FSfseek(*(file), *(pos), SEEK_SET) == 0) + +/* Since the Memory Disk Drive file system library reads only blocks of files, + * the function to read a text line does so by "over-reading" a block of the + * of the maximum size and truncating it behind the end-of-line. + */ +static int ini_read(char *buffer, int size, INI_FILETYPE *file) +{ + size_t numread = size; + char *eol; + + if ((numread = FSfread(buffer, 1, size, *file)) == 0) + return 0; /* at EOF */ + if ((eol = strchr(buffer, '\n')) == NULL) + eol = strchr(buffer, '\r'); + if (eol != NULL) { + /* terminate the buffer */ + *++eol = '\0'; + /* "unread" the data that was read too much */ + FSfseek(*file, - (int)(numread - (size_t)(eol - buffer)), SEEK_CUR); + } /* if */ + return 1; +} + +#ifndef INI_READONLY +static int ini_rename(const char *source, const char *dest) +{ + FSFILE* ftmp = FSfopen((source), FS_READ); + FSrename((dest), ftmp); + return FSfclose(ftmp) == 0; +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-stdio.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-stdio.h new file mode 100644 index 00000000..67d24334 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue-stdio.h @@ -0,0 +1,31 @@ +/* Glue functions for the minIni library, based on the C/C++ stdio library + * + * Or better said: this file contains macros that maps the function interface + * used by minIni to the standard C/C++ file I/O functions. + * + * By CompuPhase, 2008-2014 + * This "glue file" is in the public domain. It is distributed without + * warranties or conditions of any kind, either express or implied. + */ + +/* map required file I/O types and functions to the standard C library */ +#include + +#define INI_FILETYPE FILE* +#define ini_openread(filename,file) ((*(file) = fopen((filename),"rb")) != NULL) +#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"wb")) != NULL) +#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),"r+b")) != NULL) +#define ini_close(file) (fclose(*(file)) == 0) +#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL) +#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0) +#define ini_rename(source,dest) (rename((source), (dest)) == 0) +#define ini_remove(filename) (remove(filename) == 0) + +#define INI_FILEPOS long int +#define ini_tell(file,pos) (*(pos) = ftell(*(file))) +#define ini_seek(file,pos) (fseek(*(file), *(pos), SEEK_SET) == 0) + +/* for floating-point support, define additional types and functions */ +#define INI_REAL float +#define ini_ftoa(string,value) sprintf((string),"%f",(value)) +#define ini_atof(string) (INI_REAL)strtod((string),NULL) diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue.h new file mode 100644 index 00000000..c3149627 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minGlue.h @@ -0,0 +1,35 @@ +/* Glue functions for the minIni library, based on the C/C++ stdio library + * + * Or better said: this file contains macros that maps the function interface + * used by minIni to the standard C/C++ file I/O functions. + * + * By CompuPhase, 2008-2014 + * This "glue file" is in the public domain. It is distributed without + * warranties or conditions of any kind, either express or implied. + */ + +/* map required file I/O types and functions to the standard C library */ +#include + +#define INI_FILETYPE FILE* +#define ini_openread(filename,file) ((*(file) = fopen((filename),"rb")) != NULL) +#define ini_openwrite(filename,file) ((*(file) = fopen((filename),"wb")) != NULL) +#define ini_openrewrite(filename,file) ((*(file) = fopen((filename),"r+b")) != NULL) +#define ini_close(file) (fclose(*(file)) == 0) +#define ini_read(buffer,size,file) (fgets((buffer),(size),*(file)) != NULL) +#define ini_write(buffer,file) (fputs((buffer),*(file)) >= 0) +#define ini_rename(source,dest) (rename((source), (dest)) == 0) +#define ini_remove(filename) (remove(filename) == 0) + +#define INI_FILEPOS long int +#define ini_tell(file,pos) (*(pos) = ftell(*(file))) +#define ini_seek(file,pos) (fseek(*(file), *(pos), SEEK_SET) == 0) + +/* for floating-point support, define additional types and functions */ +//#define INI_REAL float +//#define ini_ftoa(string,value) sprintf((string),"%f",(value)) +//#define ini_atof(string) (INI_REAL)strtod((string),NULL) + +#define INI_ANSIONLY +#define INI_LINETERM "\n" +#define PORTABLE_STRNICMP \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.c b/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.c new file mode 100644 index 00000000..a0f75a27 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.c @@ -0,0 +1,1009 @@ +/* minIni - Multi-Platform INI file parser, suitable for embedded systems + * + * These routines are in part based on the article "Multiplatform .INI Files" + * by Joseph J. Graf in the March 1994 issue of Dr. Dobb's Journal. + * + * Copyright (c) CompuPhase, 2008-2017 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * Version: $Id: minIni.c 53 2015-01-18 13:35:11Z thiadmer.riemersma@gmail.com $ + */ + +#if (defined _UNICODE || defined __UNICODE__ || defined UNICODE) && !defined INI_ANSIONLY +# if !defined UNICODE /* for Windows */ +# define UNICODE +# endif +# if !defined _UNICODE /* for C library */ +# define _UNICODE +# endif +#endif + +#define MININI_IMPLEMENTATION +#include "minIni.h" +#if defined NDEBUG + #define assert(e) +#else + #include +#endif + +#if !defined __T || defined INI_ANSIONLY + #include + #include + #include + #define TCHAR char + #define __T(s) s + #define _tcscat strcat + #define _tcschr strchr + #define _tcscmp strcmp + #define _tcscpy strcpy + #define _tcsicmp stricmp + #define _tcslen strlen + #define _tcsncmp strncmp + #define _tcsnicmp strnicmp + #define _tcsrchr strrchr + #define _tcstol strtol + #define _tcstod strtod + #define _totupper toupper + #define _stprintf sprintf + #define _tfgets fgets + #define _tfputs fputs + #define _tfopen fopen + #define _tremove remove + #define _trename rename +#endif + +#if defined __linux || defined __linux__ + #define __LINUX__ +#elif defined FREEBSD && !defined __FreeBSD__ + #define __FreeBSD__ +#elif defined(_MSC_VER) + #pragma warning(disable: 4996) /* for Microsoft Visual C/C++ */ +#endif +#if !defined strnicmp && !defined PORTABLE_STRNICMP + #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__ + #define strnicmp strncasecmp + #endif +#endif +#if !defined _totupper + #define _totupper toupper +#endif + +#if !defined INI_LINETERM + #if defined __LINUX__ || defined __FreeBSD__ || defined __OpenBSD__ || defined __APPLE__ + #define INI_LINETERM __T("\n") + #else + #define INI_LINETERM __T("\r\n") + #endif +#endif +#if !defined INI_FILETYPE + #error Missing definition for INI_FILETYPE. +#endif + +#if !defined sizearray + #define sizearray(a) (sizeof(a) / sizeof((a)[0])) +#endif + +enum quote_option { + QUOTE_NONE, + QUOTE_ENQUOTE, + QUOTE_DEQUOTE, +}; + +#if defined PORTABLE_STRNICMP +int strnicmp(const TCHAR *s1, const TCHAR *s2, size_t n) +{ + while (n-- != 0 && (*s1 || *s2)) { + register int c1, c2; + c1 = *s1++; + if ('a' <= c1 && c1 <= 'z') + c1 += ('A' - 'a'); + c2 = *s2++; + if ('a' <= c2 && c2 <= 'z') + c2 += ('A' - 'a'); + if (c1 != c2) + return c1 - c2; + } /* while */ + return 0; +} +#endif /* PORTABLE_STRNICMP */ + +static TCHAR *skipleading(const TCHAR *str) +{ + assert(str != NULL); + while ('\0' < *str && *str <= ' ') + str++; + return (TCHAR *)str; +} + +static TCHAR *skiptrailing(const TCHAR *str, const TCHAR *base) +{ + assert(str != NULL); + assert(base != NULL); + while (str > base && '\0' < *(str-1) && *(str-1) <= ' ') + str--; + return (TCHAR *)str; +} + +static TCHAR *striptrailing(TCHAR *str) +{ + TCHAR *ptr = skiptrailing(_tcschr(str, '\0'), str); + assert(ptr != NULL); + *ptr = '\0'; + return str; +} + +static TCHAR *ini_strncpy(TCHAR *dest, const TCHAR *source, size_t maxlen, enum quote_option option) +{ + size_t d, s; + + assert(maxlen>0); + assert(source != NULL && dest != NULL); + assert((dest < source || (dest == source && option != QUOTE_ENQUOTE)) || dest > source + strlen(source)); + if (option == QUOTE_ENQUOTE && maxlen < 3) + option = QUOTE_NONE; /* cannot store two quotes and a terminating zero in less than 3 characters */ + + switch (option) { + case QUOTE_NONE: + for (d = 0; d < maxlen - 1 && source[d] != '\0'; d++) + dest[d] = source[d]; + assert(d < maxlen); + dest[d] = '\0'; + break; + case QUOTE_ENQUOTE: + d = 0; + dest[d++] = '"'; + for (s = 0; source[s] != '\0' && d < maxlen - 2; s++, d++) { + if (source[s] == '"') { + if (d >= maxlen - 3) + break; /* no space to store the escape character plus the one that follows it */ + dest[d++] = '\\'; + } /* if */ + dest[d] = source[s]; + } /* for */ + dest[d++] = '"'; + dest[d] = '\0'; + break; + case QUOTE_DEQUOTE: + for (d = s = 0; source[s] != '\0' && d < maxlen - 1; s++, d++) { + if ((source[s] == '"' || source[s] == '\\') && source[s + 1] == '"') + s++; + dest[d] = source[s]; + } /* for */ + dest[d] = '\0'; + break; + default: + assert(0); + } /* switch */ + + return dest; +} + +static TCHAR *cleanstring(TCHAR *string, enum quote_option *quotes) +{ + int isstring; + TCHAR *ep; + + assert(string != NULL); + assert(quotes != NULL); + + /* Remove a trailing comment */ + isstring = 0; + for (ep = string; *ep != '\0' && ((*ep != ';' && *ep != '#') || isstring); ep++) { + if (*ep == '"') { + if (*(ep + 1) == '"') + ep++; /* skip "" (both quotes) */ + else + isstring = !isstring; /* single quote, toggle isstring */ + } else if (*ep == '\\' && *(ep + 1) == '"') { + ep++; /* skip \" (both quotes */ + } /* if */ + } /* for */ + assert(ep != NULL && (*ep == '\0' || *ep == ';' || *ep == '#')); + *ep = '\0'; /* terminate at a comment */ + striptrailing(string); + /* Remove double quotes surrounding a value */ + *quotes = QUOTE_NONE; + if (*string == '"' && (ep = _tcschr(string, '\0')) != NULL && *(ep - 1) == '"') { + string++; + *--ep = '\0'; + *quotes = QUOTE_DEQUOTE; /* this is a string, so remove escaped characters */ + } /* if */ + return string; +} + +static int getkeystring(INI_FILETYPE *fp, const TCHAR *Section, const TCHAR *Key, + int idxSection, int idxKey, TCHAR *Buffer, int BufferSize, + INI_FILEPOS *mark) +{ + TCHAR *sp, *ep; + int len, idx; + enum quote_option quotes; + TCHAR LocalBuffer[INI_BUFFERSIZE]; + + assert(fp != NULL); + /* Move through file 1 line at a time until a section is matched or EOF. If + * parameter Section is NULL, only look at keys above the first section. If + * idxSection is positive, copy the relevant section name. + */ + len = (Section != NULL) ? (int)_tcslen(Section) : 0; + if (len > 0 || idxSection >= 0) { + assert(idxSection >= 0 || Section != NULL); + idx = -1; + do { + if (!ini_read(LocalBuffer, INI_BUFFERSIZE, fp)) + return 0; + sp = skipleading(LocalBuffer); + ep = _tcsrchr(sp, ']'); + } while (*sp != '[' || ep == NULL || + (((int)(ep-sp-1) != len || Section == NULL || _tcsnicmp(sp+1,Section,len) != 0) && ++idx != idxSection)); + if (idxSection >= 0) { + if (idx == idxSection) { + assert(ep != NULL); + assert(*ep == ']'); + *ep = '\0'; + ini_strncpy(Buffer, sp + 1, BufferSize, QUOTE_NONE); + return 1; + } /* if */ + return 0; /* no more section found */ + } /* if */ + } /* if */ + + /* Now that the section has been found, find the entry. + * Stop searching upon leaving the section's area. + */ + assert(Key != NULL || idxKey >= 0); + len = (Key != NULL) ? (int)_tcslen(Key) : 0; + idx = -1; + do { + if (mark != NULL) + ini_tell(fp, mark); /* optionally keep the mark to the start of the line */ + if (!ini_read(LocalBuffer,INI_BUFFERSIZE,fp) || *(sp = skipleading(LocalBuffer)) == '[') + return 0; + sp = skipleading(LocalBuffer); + ep = _tcschr(sp, '='); /* Parse out the equal sign */ + if (ep == NULL) + ep = _tcschr(sp, ':'); + } while (*sp == ';' || *sp == '#' || ep == NULL + || ((len == 0 || (int)(skiptrailing(ep,sp)-sp) != len || _tcsnicmp(sp,Key,len) != 0) && ++idx != idxKey)); + if (idxKey >= 0) { + if (idx == idxKey) { + assert(ep != NULL); + assert(*ep == '=' || *ep == ':'); + *ep = '\0'; + striptrailing(sp); + ini_strncpy(Buffer, sp, BufferSize, QUOTE_NONE); + return 1; + } /* if */ + return 0; /* no more key found (in this section) */ + } /* if */ + + /* Copy up to BufferSize chars to buffer */ + assert(ep != NULL); + assert(*ep == '=' || *ep == ':'); + sp = skipleading(ep + 1); + sp = cleanstring(sp, "es); /* Remove a trailing comment */ + ini_strncpy(Buffer, sp, BufferSize, quotes); + return 1; +} + +/** ini_gets() + * \param Section the name of the section to search for + * \param Key the name of the entry to find the value of + * \param DefValue default string in the event of a failed read + * \param Buffer a pointer to the buffer to copy into + * \param BufferSize the maximum number of characters to copy + * \param Filename the name and full path of the .ini file to read from + * + * \return the number of characters copied into the supplied buffer + */ +int ini_gets(const TCHAR *Section, const TCHAR *Key, const TCHAR *DefValue, + TCHAR *Buffer, int BufferSize, const TCHAR *Filename) +{ + INI_FILETYPE fp; + int ok = 0; + + if (Buffer == NULL || BufferSize <= 0 || Key == NULL) + return 0; + if (ini_openread(Filename, &fp)) { + ok = getkeystring(&fp, Section, Key, -1, -1, Buffer, BufferSize, NULL); + (void)ini_close(&fp); + } /* if */ + if (!ok) + ini_strncpy(Buffer, (DefValue != NULL) ? DefValue : __T(""), BufferSize, QUOTE_NONE); + return (int)_tcslen(Buffer); +} + +/** ini_getl() + * \param Section the name of the section to search for + * \param Key the name of the entry to find the value of + * \param DefValue the default value in the event of a failed read + * \param Filename the name of the .ini file to read from + * + * \return the value located at Key + */ +long ini_getl(const TCHAR *Section, const TCHAR *Key, long DefValue, const TCHAR *Filename) +{ + TCHAR LocalBuffer[64]; + int len = ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename); + return (len == 0) ? DefValue + : ((len >= 2 && _totupper((int)LocalBuffer[1]) == 'X') ? _tcstol(LocalBuffer, NULL, 16) + : _tcstol(LocalBuffer, NULL, 10)); +} + +#if defined INI_REAL +/** ini_getf() + * \param Section the name of the section to search for + * \param Key the name of the entry to find the value of + * \param DefValue the default value in the event of a failed read + * \param Filename the name of the .ini file to read from + * + * \return the value located at Key + */ +INI_REAL ini_getf(const TCHAR *Section, const TCHAR *Key, INI_REAL DefValue, const TCHAR *Filename) +{ + TCHAR LocalBuffer[64]; + int len = ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename); + return (len == 0) ? DefValue : ini_atof(LocalBuffer); +} +#endif + +/** ini_getbool() + * \param Section the name of the section to search for + * \param Key the name of the entry to find the value of + * \param DefValue default value in the event of a failed read; it should + * zero (0) or one (1). + * \param Filename the name and full path of the .ini file to read from + * + * A true boolean is found if one of the following is matched: + * - A string starting with 'y' or 'Y' + * - A string starting with 't' or 'T' + * - A string starting with '1' + * + * A false boolean is found if one of the following is matched: + * - A string starting with 'n' or 'N' + * - A string starting with 'f' or 'F' + * - A string starting with '0' + * + * \return the true/false flag as interpreted at Key + */ +int ini_getbool(const TCHAR *Section, const TCHAR *Key, int DefValue, const TCHAR *Filename) +{ + TCHAR LocalBuffer[2] = __T(""); + int ret; + + ini_gets(Section, Key, __T(""), LocalBuffer, sizearray(LocalBuffer), Filename); + LocalBuffer[0] = (TCHAR)_totupper((int)LocalBuffer[0]); + if (LocalBuffer[0] == 'Y' || LocalBuffer[0] == '1' || LocalBuffer[0] == 'T') + ret = 1; + else if (LocalBuffer[0] == 'N' || LocalBuffer[0] == '0' || LocalBuffer[0] == 'F') + ret = 0; + else + ret = DefValue; + + return(ret); +} + +/** ini_getsection() + * \param idx the zero-based sequence number of the section to return + * \param Buffer a pointer to the buffer to copy into + * \param BufferSize the maximum number of characters to copy + * \param Filename the name and full path of the .ini file to read from + * + * \return the number of characters copied into the supplied buffer + */ +int ini_getsection(int idx, TCHAR *Buffer, int BufferSize, const TCHAR *Filename) +{ + INI_FILETYPE fp; + int ok = 0; + + if (Buffer == NULL || BufferSize <= 0 || idx < 0) + return 0; + if (ini_openread(Filename, &fp)) { + ok = getkeystring(&fp, NULL, NULL, idx, -1, Buffer, BufferSize, NULL); + (void)ini_close(&fp); + } /* if */ + if (!ok) + *Buffer = '\0'; + return (int)_tcslen(Buffer); +} + +/** ini_getkey() + * \param Section the name of the section to browse through, or NULL to + * browse through the keys outside any section + * \param idx the zero-based sequence number of the key to return + * \param Buffer a pointer to the buffer to copy into + * \param BufferSize the maximum number of characters to copy + * \param Filename the name and full path of the .ini file to read from + * + * \return the number of characters copied into the supplied buffer + */ +int ini_getkey(const TCHAR *Section, int idx, TCHAR *Buffer, int BufferSize, const TCHAR *Filename) +{ + INI_FILETYPE fp; + int ok = 0; + + if (Buffer == NULL || BufferSize <= 0 || idx < 0) + return 0; + if (ini_openread(Filename, &fp)) { + ok = getkeystring(&fp, Section, NULL, -1, idx, Buffer, BufferSize, NULL); + (void)ini_close(&fp); + } /* if */ + if (!ok) + *Buffer = '\0'; + return (int)_tcslen(Buffer); +} + + +#if !defined INI_NOBROWSE +/** ini_browse() + * \param Callback a pointer to a function that will be called for every + * setting in the INI file. + * \param UserData arbitrary data, which the function passes on the + * \c Callback function + * \param Filename the name and full path of the .ini file to read from + * + * \return 1 on success, 0 on failure (INI file not found) + * + * \note The \c Callback function must return 1 to continue + * browsing through the INI file, or 0 to stop. Even when the + * callback stops the browsing, this function will return 1 + * (for success). + */ +int ini_browse(INI_CALLBACK Callback, void *UserData, const TCHAR *Filename) +{ + TCHAR LocalBuffer[INI_BUFFERSIZE]; + int lenSec, lenKey; + enum quote_option quotes; + INI_FILETYPE fp; + + if (Callback == NULL) + return 0; + if (!ini_openread(Filename, &fp)) + return 0; + + LocalBuffer[0] = '\0'; /* copy an empty section in the buffer */ + lenSec = (int)_tcslen(LocalBuffer) + 1; + for ( ;; ) { + TCHAR *sp, *ep; + if (!ini_read(LocalBuffer + lenSec, INI_BUFFERSIZE - lenSec, &fp)) + break; + sp = skipleading(LocalBuffer + lenSec); + /* ignore empty strings and comments */ + if (*sp == '\0' || *sp == ';' || *sp == '#') + continue; + /* see whether we reached a new section */ + ep = _tcsrchr(sp, ']'); + if (*sp == '[' && ep != NULL) { + *ep = '\0'; + ini_strncpy(LocalBuffer, sp + 1, INI_BUFFERSIZE, QUOTE_NONE); + lenSec = (int)_tcslen(LocalBuffer) + 1; + continue; + } /* if */ + /* not a new section, test for a key/value pair */ + ep = _tcschr(sp, '='); /* test for the equal sign or colon */ + if (ep == NULL) + ep = _tcschr(sp, ':'); + if (ep == NULL) + continue; /* invalid line, ignore */ + *ep++ = '\0'; /* split the key from the value */ + striptrailing(sp); + ini_strncpy(LocalBuffer + lenSec, sp, INI_BUFFERSIZE - lenSec, QUOTE_NONE); + lenKey = (int)_tcslen(LocalBuffer + lenSec) + 1; + /* clean up the value */ + sp = skipleading(ep); + sp = cleanstring(sp, "es); /* Remove a trailing comment */ + ini_strncpy(LocalBuffer + lenSec + lenKey, sp, INI_BUFFERSIZE - lenSec - lenKey, quotes); + /* call the callback */ + if (!Callback(LocalBuffer, LocalBuffer + lenSec, LocalBuffer + lenSec + lenKey, UserData)) + break; + } /* for */ + + (void)ini_close(&fp); + return 1; +} +#endif /* INI_NOBROWSE */ + +#if ! defined INI_READONLY +static void ini_tempname(TCHAR *dest, const TCHAR *source, int maxlength) +{ + TCHAR *p; + + ini_strncpy(dest, source, maxlength, QUOTE_NONE); + p = _tcsrchr(dest, '\0'); + assert(p != NULL); + *(p - 1) = '~'; +} + +static enum quote_option check_enquote(const TCHAR *Value) +{ + const TCHAR *p; + + /* run through the value, if it has trailing spaces, or '"', ';' or '#' + * characters, enquote it + */ + assert(Value != NULL); + for (p = Value; *p != '\0' && *p != '"' && *p != ';' && *p != '#'; p++) + /* nothing */; + return (*p != '\0' || (p > Value && *(p - 1) == ' ')) ? QUOTE_ENQUOTE : QUOTE_NONE; +} + +static void writesection(TCHAR *LocalBuffer, const TCHAR *Section, INI_FILETYPE *fp) +{ + if (Section != NULL && _tcslen(Section) > 0) { + TCHAR *p; + LocalBuffer[0] = '['; + ini_strncpy(LocalBuffer + 1, Section, INI_BUFFERSIZE - 4, QUOTE_NONE); /* -1 for '[', -1 for ']', -2 for '\r\n' */ + p = _tcsrchr(LocalBuffer, '\0'); + assert(p != NULL); + *p++ = ']'; + _tcscpy(p, INI_LINETERM); /* copy line terminator (typically "\n") */ + if (fp != NULL) + (void)ini_write(LocalBuffer, fp); + } /* if */ +} + +static void writekey(TCHAR *LocalBuffer, const TCHAR *Key, const TCHAR *Value, INI_FILETYPE *fp) +{ + TCHAR *p; + enum quote_option option = check_enquote(Value); + ini_strncpy(LocalBuffer, Key, INI_BUFFERSIZE - 3, QUOTE_NONE); /* -1 for '=', -2 for '\r\n' */ + p = _tcsrchr(LocalBuffer, '\0'); + assert(p != NULL); + *p++ = '='; + ini_strncpy(p, Value, INI_BUFFERSIZE - (p - LocalBuffer) - 2, option); /* -2 for '\r\n' */ + p = _tcsrchr(LocalBuffer, '\0'); + assert(p != NULL); + _tcscpy(p, INI_LINETERM); /* copy line terminator (typically "\n") */ + if (fp != NULL) + (void)ini_write(LocalBuffer, fp); +} + +static int cache_accum(const TCHAR *string, int *size, int max) +{ + int len = (int)_tcslen(string); + if (*size + len >= max) + return 0; + *size += len; + return 1; +} + +static int cache_flush(TCHAR *buffer, int *size, + INI_FILETYPE *rfp, INI_FILETYPE *wfp, INI_FILEPOS *mark) +{ + int terminator_len = (int)_tcslen(INI_LINETERM); + int pos = 0; + + (void)ini_seek(rfp, mark); + assert(buffer != NULL); + buffer[0] = '\0'; + assert(size != NULL); + assert(*size <= INI_BUFFERSIZE); + while (pos < *size) { + (void)ini_read(buffer + pos, INI_BUFFERSIZE - pos, rfp); + while (pos < *size && buffer[pos] != '\0') + pos++; /* cannot use _tcslen() because buffer may not be zero-terminated */ + } /* while */ + if (buffer[0] != '\0') { + assert(pos > 0 && pos <= INI_BUFFERSIZE); + if (pos == INI_BUFFERSIZE) + pos--; + buffer[pos] = '\0'; /* force zero-termination (may be left unterminated in the above while loop) */ + (void)ini_write(buffer, wfp); + } + ini_tell(rfp, mark); /* update mark */ + *size = 0; + /* return whether the buffer ended with a line termination */ + return (pos > terminator_len) && (_tcscmp(buffer + pos - terminator_len, INI_LINETERM) == 0); +} + +static int close_rename(INI_FILETYPE *rfp, INI_FILETYPE *wfp, const TCHAR *filename, TCHAR *buffer) +{ + (void)ini_close(rfp); + (void)ini_close(wfp); + (void)ini_remove(filename); + (void)ini_tempname(buffer, filename, INI_BUFFERSIZE); + (void)ini_rename(buffer, filename); + return 1; +} + +/** ini_puts() + * \param Section the name of the section to write the string in + * \param Key the name of the entry to write, or NULL to erase all keys in the section + * \param Value a pointer to the buffer the string, or NULL to erase the key + * \param Filename the name and full path of the .ini file to write to + * + * \return 1 if successful, otherwise 0 + */ +int ini_puts(const TCHAR *Section, const TCHAR *Key, const TCHAR *Value, const TCHAR *Filename) +{ + INI_FILETYPE rfp; + INI_FILETYPE wfp; + INI_FILEPOS mark; + INI_FILEPOS head, tail; + TCHAR *sp, *ep; + TCHAR LocalBuffer[INI_BUFFERSIZE]; + int len, match, flag, cachelen; + + assert(Filename != NULL); + if (!ini_openread(Filename, &rfp)) { + /* If the .ini file doesn't exist, make a new file */ + if (Key != NULL && Value != NULL) { + if (!ini_openwrite(Filename, &wfp)) + return 0; + writesection(LocalBuffer, Section, &wfp); + writekey(LocalBuffer, Key, Value, &wfp); + (void)ini_close(&wfp); + } /* if */ + return 1; + } /* if */ + + /* If parameters Key and Value are valid (so this is not an "erase" request) + * and the setting already exists, there are two short-cuts to avoid rewriting + * the INI file. + */ + if (Key != NULL && Value != NULL) { + ini_tell(&rfp, &mark); + match = getkeystring(&rfp, Section, Key, -1, -1, LocalBuffer, sizearray(LocalBuffer), &head); + if (match) { + /* if the current setting is identical to the one to write, there is + * nothing to do. + */ + if (_tcscmp(LocalBuffer,Value) == 0) { + (void)ini_close(&rfp); + return 1; + } /* if */ + /* if the new setting has the same length as the current setting, and the + * glue file permits file read/write access, we can modify in place. + */ + #if defined ini_openrewrite + /* we already have the start of the (raw) line, get the end too */ + ini_tell(&rfp, &tail); + /* create new buffer (without writing it to file) */ + writekey(LocalBuffer, Key, Value, NULL); + if (_tcslen(LocalBuffer) == (size_t)(tail - head)) { + /* length matches, close the file & re-open for read/write, then + * write at the correct position + */ + (void)ini_close(&rfp); + if (!ini_openrewrite(Filename, &wfp)) + return 0; + (void)ini_seek(&wfp, &head); + (void)ini_write(LocalBuffer, &wfp); + (void)ini_close(&wfp); + return 1; + } /* if */ + #endif + } /* if */ + /* key not found, or different value & length -> proceed (but rewind the + * input file first) + */ + (void)ini_seek(&rfp, &mark); + } /* if */ + + /* Get a temporary file name to copy to. Use the existing name, but with + * the last character set to a '~'. + */ + ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE); + if (!ini_openwrite(LocalBuffer, &wfp)) { + (void)ini_close(&rfp); + return 0; + } /* if */ + (void)ini_tell(&rfp, &mark); + cachelen = 0; + + /* Move through the file one line at a time until a section is + * matched or until EOF. Copy to temp file as it is read. + */ + len = (Section != NULL) ? (int)_tcslen(Section) : 0; + if (len > 0) { + do { + if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { + /* Failed to find section, so add one to the end */ + flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + if (Key!=NULL && Value!=NULL) { + if (!flag) + (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */ + writesection(LocalBuffer, Section, &wfp); + writekey(LocalBuffer, Key, Value, &wfp); + } /* if */ + return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ + } /* if */ + /* Copy the line from source to dest, but not if this is the section that + * we are looking for and this section must be removed + */ + sp = skipleading(LocalBuffer); + ep = _tcsrchr(sp, ']'); + match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0); + if (!match || Key != NULL) { + if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); + } /* if */ + } /* if */ + } while (!match); + } /* if */ + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + /* when deleting a section, the section head that was just found has not been + * copied to the output file, but because this line was not "accumulated" in + * the cache, the position in the input file was reset to the point just + * before the section; this must now be skipped (again) + */ + if (Key == NULL) { + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + (void)ini_tell(&rfp, &mark); + } /* if */ + + /* Now that the section has been found, find the entry. Stop searching + * upon leaving the section's area. Copy the file as it is read + * and create an entry if one is not found. + */ + len = (Key != NULL) ? (int)_tcslen(Key) : 0; + for( ;; ) { + if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { + /* EOF without an entry so make one */ + flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + if (Key!=NULL && Value!=NULL) { + if (!flag) + (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */ + writekey(LocalBuffer, Key, Value, &wfp); + } /* if */ + return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ + } /* if */ + sp = skipleading(LocalBuffer); + ep = _tcschr(sp, '='); /* Parse out the equal sign */ + if (ep == NULL) + ep = _tcschr(sp, ':'); + match = (ep != NULL && len > 0 && (int)(skiptrailing(ep,sp)-sp) == len && _tcsnicmp(sp,Key,len) == 0); + if ((Key != NULL && match) || *sp == '[') + break; /* found the key, or found a new section */ + /* copy other keys in the section */ + if (Key == NULL) { + (void)ini_tell(&rfp, &mark); /* we are deleting the entire section, so update the read position */ + } else { + if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); + } /* if */ + } /* if */ + } /* for */ + /* the key was found, or we just dropped on the next section (meaning that it + * wasn't found); in both cases we need to write the key, but in the latter + * case, we also need to write the line starting the new section after writing + * the key + */ + flag = (*sp == '['); + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + if (Key != NULL && Value != NULL) + writekey(LocalBuffer, Key, Value, &wfp); + /* cache_flush() reset the "read pointer" to the start of the line with the + * previous key or the new section; read it again (because writekey() destroyed + * the buffer) + */ + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + if (flag) { + /* the new section heading needs to be copied to the output file */ + cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); + } else { + /* forget the old key line */ + (void)ini_tell(&rfp, &mark); + } /* if */ + /* Copy the rest of the INI file */ + while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { + if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); + } /* if */ + } /* while */ + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ +} + +/* Ansi C "itoa" based on Kernighan & Ritchie's "Ansi C" book. */ +#define ABS(v) ((v) < 0 ? -(v) : (v)) + +static void strreverse(TCHAR *str) +{ + int i, j; + for (i = 0, j = (int)_tcslen(str) - 1; i < j; i++, j--) { + TCHAR t = str[i]; + str[i] = str[j]; + str[j] = t; + } /* for */ +} + +static void long2str(long value, TCHAR *str) +{ + int i = 0; + long sign = value; + + /* generate digits in reverse order */ + do { + int n = (int)(value % 10); /* get next lowest digit */ + str[i++] = (TCHAR)(ABS(n) + '0'); /* handle case of negative digit */ + } while (value /= 10); /* delete the lowest digit */ + if (sign < 0) + str[i++] = '-'; + str[i] = '\0'; + + strreverse(str); +} + +/** ini_putl() + * \param Section the name of the section to write the value in + * \param Key the name of the entry to write + * \param Value the value to write + * \param Filename the name and full path of the .ini file to write to + * + * \return 1 if successful, otherwise 0 + */ +int ini_putl(const TCHAR *Section, const TCHAR *Key, long Value, const TCHAR *Filename) +{ + TCHAR LocalBuffer[32]; + long2str(Value, LocalBuffer); + return ini_puts(Section, Key, LocalBuffer, Filename); +} + +#if defined INI_REAL +/** ini_putf() + * \param Section the name of the section to write the value in + * \param Key the name of the entry to write + * \param Value the value to write + * \param Filename the name and full path of the .ini file to write to + * + * \return 1 if successful, otherwise 0 + */ +int ini_putf(const TCHAR *Section, const TCHAR *Key, INI_REAL Value, const TCHAR *Filename) +{ + TCHAR LocalBuffer[64]; + ini_ftoa(LocalBuffer, Value); + return ini_puts(Section, Key, LocalBuffer, Filename); +} +#endif /* INI_REAL */ + +static void putsection(TCHAR *LocalBuffer, const TCHAR *Section, const TCHAR **Keys, const TCHAR **Values, INI_FILETYPE *fp) { + if(Keys && Values && *Keys && *Values) { + writesection(LocalBuffer, Section, fp); + while(*Keys && *Values) { + writekey(LocalBuffer, *Keys, *Values, fp); + Keys++; + Values++; + } + (void)ini_write(INI_LINETERM, fp); /* force a new line behind the last line of the section */ + } +} + +int ini_putsection(const TCHAR *Section, const TCHAR **Keys, const TCHAR **Values, const TCHAR *Filename) +{ + INI_FILETYPE rfp; + INI_FILETYPE wfp; + INI_FILEPOS mark; + TCHAR *sp = NULL; + TCHAR *ep; + TCHAR LocalBuffer[INI_BUFFERSIZE]; + int len, match, flag, cachelen; + + assert(Filename != NULL); + if (!ini_openread(Filename, &rfp)) { + /* If the .ini file doesn't exist, make a new file */ + if (!ini_openwrite(Filename, &wfp)) + return 0; + putsection(LocalBuffer, Section, Keys, Values, &wfp); + (void)ini_close(&wfp); + return 1; + } /* if */ + + /* Get a temporary file name to copy to. Use the existing name, but with + * the last character set to a '~'. + */ + ini_tempname(LocalBuffer, Filename, INI_BUFFERSIZE); + if (!ini_openwrite(LocalBuffer, &wfp)) { + (void)ini_close(&rfp); + return 0; + } /* if */ + (void)ini_tell(&rfp, &mark); + cachelen = 0; + + /* Move through the file one line at a time until a section is + * matched or until EOF. Copy to temp file as it is read. + */ + len = (Section != NULL) ? (int)_tcslen(Section) : 0; + if (len > 0) { + do { + if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { + /* Failed to find section, so add one to the end */ + flag = cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + if (!flag) + (void)ini_write(INI_LINETERM, &wfp); /* force a new line behind the last line of the INI file */ + + putsection(LocalBuffer, Section, Keys, Values, &wfp); + + return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ + } /* if */ + /* Copy the line from source to dest, but not if this is the section that + * we are looking for + */ + sp = skipleading(LocalBuffer); + ep = _tcsrchr(sp, ']'); + match = (*sp == '[' && ep != NULL && (int)(ep-sp-1) == len && _tcsnicmp(sp + 1,Section,len) == 0); + if (!match) { + if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); + } /* if */ + } /* if */ + } while (!match); + } /* if */ + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + /* when deleting a section, the section head that was just found has not been + * copied to the output file, but because this line was not "accumulated" in + * the cache, the position in the input file was reset to the point just + * before the section; this must now be skipped (again) + */ + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + (void)ini_tell(&rfp, &mark); + + /* Now that the section has been found, find the entry. Stop searching + * upon leaving the section's area. Copy the file as it is read + * and create an entry if one is not found. + */ + len = 0; + for( ;; ) { + if (!ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { + /* EOF without an entry */ + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + (void)ini_tell(&rfp, &mark); /* we are deleting the entire section, so update the read position */ + break; + } /* if */ + sp = skipleading(LocalBuffer); + if (*sp == '[') + break; /* found a new section */ + /* copy other keys in the section */ + (void)ini_tell(&rfp, &mark); /* we are deleting the entire section, so update the read position */ + } /* for */ + /* we just dropped on the next section + * we also need to write the line starting the new section after writing + */ + flag = (sp && *sp == '['); + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + putsection(LocalBuffer, Section, Keys, Values, &wfp); + + /* cache_flush() reset the "read pointer" to the start of the line with the + * previous key or the new section; read it again (because writekey() destroyed + * the buffer) + */ + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + if (flag) { + /* the new section heading needs to be copied to the output file */ + cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); + } else { + /* forget the old key line */ + (void)ini_tell(&rfp, &mark); + } /* if */ + /* Copy the rest of the INI file */ + while (ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp)) { + if (!cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE)) { + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + (void)ini_read(LocalBuffer, INI_BUFFERSIZE, &rfp); + cache_accum(LocalBuffer, &cachelen, INI_BUFFERSIZE); + } /* if */ + } /* while */ + cache_flush(LocalBuffer, &cachelen, &rfp, &wfp, &mark); + return close_rename(&rfp, &wfp, Filename, LocalBuffer); /* clean up and rename */ +} + +#endif /* !INI_READONLY */ diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.h b/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.h new file mode 100644 index 00000000..73e33c01 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/minIni.h @@ -0,0 +1,68 @@ +/* minIni - Multi-Platform INI file parser, suitable for embedded systems + * + * Copyright (c) CompuPhase, 2008-2017 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * Version: $Id: minIni.h 53 2015-01-18 13:35:11Z thiadmer.riemersma@gmail.com $ + */ +#ifndef MININI_H +#define MININI_H + +#include "minGlue.h" + +#if (defined _UNICODE || defined __UNICODE__ || defined UNICODE) && !defined INI_ANSIONLY + #include + #define mTCHAR TCHAR +#else + /* force TCHAR to be "char", but only for minIni */ + #define mTCHAR char +#endif + +#if !defined INI_BUFFERSIZE + #define INI_BUFFERSIZE 512 +#endif + +#if defined __cplusplus + extern "C" { +#endif + +int ini_getbool(const mTCHAR *Section, const mTCHAR *Key, int DefValue, const mTCHAR *Filename); +long ini_getl(const mTCHAR *Section, const mTCHAR *Key, long DefValue, const mTCHAR *Filename); +int ini_gets(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *DefValue, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename); +int ini_getsection(int idx, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename); +int ini_getkey(const mTCHAR *Section, int idx, mTCHAR *Buffer, int BufferSize, const mTCHAR *Filename); + +#if defined INI_REAL +INI_REAL ini_getf(const mTCHAR *Section, const mTCHAR *Key, INI_REAL DefValue, const mTCHAR *Filename); +#endif + +#if !defined INI_READONLY +int ini_putl(const mTCHAR *Section, const mTCHAR *Key, long Value, const mTCHAR *Filename); +int ini_puts(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *Value, const mTCHAR *Filename); +int ini_putsection(const mTCHAR *Section, const mTCHAR **Keys, const mTCHAR **Values, const mTCHAR *Filename); +#if defined INI_REAL +int ini_putf(const mTCHAR *Section, const mTCHAR *Key, INI_REAL Value, const mTCHAR *Filename); +#endif +#endif /* INI_READONLY */ + +#if !defined INI_NOBROWSE +typedef int (*INI_CALLBACK)(const mTCHAR *Section, const mTCHAR *Key, const mTCHAR *Value, void *UserData); +int ini_browse(INI_CALLBACK Callback, void *UserData, const mTCHAR *Filename); +#endif /* INI_NOBROWSE */ + +#if defined __cplusplus + } +#endif + +#endif /* MININI_H */ diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/test.c b/Source/sys-clk/sysmodule/lib/minIni/dev/test.c new file mode 100644 index 00000000..80508cd7 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/test.c @@ -0,0 +1,117 @@ +/* Simple test program + * + * gcc -o test test.c minIni.c + */ +#include +#include +#include +#include "minIni.h" + +#define sizearray(a) (sizeof(a) / sizeof((a)[0])) + +const char inifile[] = "test.ini"; +const char inifile2[] = "testplain.ini"; + +int Callback(const char *section, const char *key, const char *value, void *userdata) +{ + (void)userdata; /* this parameter is not used in this example */ + printf(" [%s]\t%s=%s\n", section, key, value); + return 1; +} + +int main(void) +{ + char str[100]; + long n; + int s, k; + char section[50]; + + /* string reading */ + n = ini_gets("first", "string", "dummy", str, sizearray(str), inifile); + assert(n==4 && strcmp(str,"noot")==0); + n = ini_gets("second", "string", "dummy", str, sizearray(str), inifile); + assert(n==4 && strcmp(str,"mies")==0); + n = ini_gets("first", "undefined", "dummy", str, sizearray(str), inifile); + assert(n==5 && strcmp(str,"dummy")==0); + /* ----- */ + n = ini_gets("", "string", "dummy", str, sizearray(str), inifile2); + assert(n==4 && strcmp(str,"noot")==0); + n = ini_gets(NULL, "string", "dummy", str, sizearray(str), inifile2); + assert(n==4 && strcmp(str,"noot")==0); + /* ----- */ + printf("1. String reading tests passed\n"); + + /* value reading */ + n = ini_getl("first", "val", -1, inifile); + assert(n==1); + n = ini_getl("second", "val", -1, inifile); + assert(n==2); + n = ini_getl("first", "undefined", -1, inifile); + assert(n==-1); + /* ----- */ + n = ini_getl(NULL, "val", -1, inifile2); + assert(n==1); + /* ----- */ + printf("2. Value reading tests passed\n"); + + /* string writing */ + n = ini_puts("first", "alt", "flagged as \"correct\"", inifile); + assert(n==1); + n = ini_gets("first", "alt", "dummy", str, sizearray(str), inifile); + assert(n==20 && strcmp(str,"flagged as \"correct\"")==0); + /* ----- */ + n = ini_puts("second", "alt", "correct", inifile); + assert(n==1); + n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile); + assert(n==7 && strcmp(str,"correct")==0); + /* ----- */ + n = ini_puts("third", "test", "correct", inifile); + assert(n==1); + n = ini_gets("third", "test", "dummy", str, sizearray(str), inifile); + assert(n==7 && strcmp(str,"correct")==0); + /* ----- */ + n = ini_puts("second", "alt", "overwrite", inifile); + assert(n==1); + n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile); + assert(n==9 && strcmp(str,"overwrite")==0); + /* ----- */ + n = ini_puts("second", "alt", "123456789", inifile); + assert(n==1); + n = ini_gets("second", "alt", "dummy", str, sizearray(str), inifile); + assert(n==9 && strcmp(str,"123456789")==0); + /* ----- */ + n = ini_puts(NULL, "alt", "correct", inifile2); + assert(n==1); + n = ini_gets(NULL, "alt", "dummy", str, sizearray(str), inifile2); + assert(n==7 && strcmp(str,"correct")==0); + /* ----- */ + printf("3. String writing tests passed\n"); + + /* section/key enumeration */ + printf("4. Section/key enumeration, file structure follows\n"); + for (s = 0; ini_getsection(s, section, sizearray(section), inifile) > 0; s++) { + printf(" [%s]\n", section); + for (k = 0; ini_getkey(section, k, str, sizearray(str), inifile) > 0; k++) { + printf("\t%s\n", str); + } /* for */ + } /* for */ + + /* browsing through the file */ + printf("5. browse through all settings, file field list follows\n"); + ini_browse(Callback, NULL, inifile); + + /* string deletion */ + n = ini_puts("first", "alt", NULL, inifile); + assert(n==1); + n = ini_puts("second", "alt", NULL, inifile); + assert(n==1); + n = ini_puts("third", NULL, NULL, inifile); + assert(n==1); + /* ----- */ + n = ini_puts(NULL, "alt", NULL, inifile2); + assert(n==1); + printf("6. String deletion tests passed\n"); + + return 0; +} + diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/test.ini b/Source/sys-clk/sysmodule/lib/minIni/dev/test.ini new file mode 100644 index 00000000..565aef78 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/test.ini @@ -0,0 +1,8 @@ +[First] +String=noot # trailing commment +Val=1 + +[Second] +Val = 2 +#comment=3 +String = mies diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/test2.cc b/Source/sys-clk/sysmodule/lib/minIni/dev/test2.cc new file mode 100644 index 00000000..4e19b319 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/test2.cc @@ -0,0 +1,80 @@ +/* + gcc -o minIni.o -c minIni.c + g++ -o test2.o -c test2.cc + g++ -o test2 test2.o minIni.o + ./test2 +*/ + + +#include +#include +#include +using namespace std ; + +#include "minIni.h" + +int main(void) +{ + minIni ini("test.ini"); + string s; + + /* string reading */ + s = ini.gets( "first", "string" , "aap" ); + assert(s == "noot"); + s = ini.gets( "second", "string" , "aap" ); + assert(s == "mies"); + s = ini.gets( "first", "dummy" , "aap" ); + assert(s == "aap"); + cout << "1. String reading tests passed" << endl ; + + + /* value reading */ + long n; + n = ini.getl("first", "val", -1 ); + assert(n==1); + n = ini.getl("second", "val", -1); + assert(n==2); + n = ini.getl("first", "dummy", -1); + assert(n==-1); + cout << "2. Value reading tests passed" << endl ; + + + /* string writing */ + bool b; + b = ini.put("first", "alt", "flagged as \"correct\""); + assert(b); + s = ini.gets("first", "alt", "aap"); + assert(s=="flagged as \"correct\""); + + b = ini.put("second", "alt", "correct"); + assert(b); + s = ini.gets("second", "alt", "aap"); + assert(s=="correct"); + + b = ini.put("third", "alt", "correct"); + assert(b); + s = ini.gets("third", "alt", "aap" ); + assert(s=="correct"); + cout << "3. String writing tests passed" << endl; + + /* section/key enumeration */ + cout << "4. section/key enumeration; file contents follows" << endl; + string section; + for (int is = 0; section = ini.getsection(is), section.length() > 0; is++) { + cout << " [" << section.c_str() << "]" << endl; + for (int ik = 0; s = ini.getkey(section, ik), s.length() > 0; ik++) { + cout << "\t" << s.c_str() << endl; + } + } + + /* string deletion */ + b = ini.del("first", "alt"); + assert(b); + b = ini.del("second", "alt"); + assert(b); + b = ini.del("third"); + assert(b); + cout << "5. string deletion passed " << endl; + + return 0; +} diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/testplain.ini b/Source/sys-clk/sysmodule/lib/minIni/dev/testplain.ini new file mode 100644 index 00000000..2a5ce4b6 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/testplain.ini @@ -0,0 +1,3 @@ +String=noot # trailing commment +#comment=3 +Val=1 diff --git a/Source/sys-clk/sysmodule/lib/minIni/dev/wxMinIni.h b/Source/sys-clk/sysmodule/lib/minIni/dev/wxMinIni.h new file mode 100644 index 00000000..f932bb63 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/minIni/dev/wxMinIni.h @@ -0,0 +1,101 @@ +/* minIni - Multi-Platform INI file parser, wxWidgets interface + * + * Copyright (c) CompuPhase, 2008-2012 + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy + * of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + * + * Version: $Id: wxMinIni.h 44 2012-01-04 15:52:56Z thiadmer.riemersma@gmail.com $ + */ +#ifndef WXMININI_H +#define WXMININI_H + +#include +#include "minIni.h" + +class minIni +{ +public: + minIni(const wxString& filename) : iniFilename(filename) + { } + + bool getbool(const wxString& Section, const wxString& Key, bool DefValue=false) const + { return ini_getbool(Section.utf8_str(), Key.utf8_str(), int(DefValue), iniFilename.utf8_str()) != 0; } + + long getl(const wxString& Section, const wxString& Key, long DefValue=0) const + { return ini_getl(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str()); } + + int geti(const wxString& Section, const wxString& Key, int DefValue=0) const + { return static_cast(ini_getl(Section.utf8_str(), Key.utf8_str(), (long)DefValue, iniFilename.utf8_str())); } + + wxString gets(const wxString& Section, const wxString& Key, const wxString& DefValue=wxT("")) const + { + char buffer[INI_BUFFERSIZE]; + ini_gets(Section.utf8_str(), Key.utf8_str(), DefValue.utf8_str(), buffer, INI_BUFFERSIZE, iniFilename.utf8_str()); + wxString result = wxString::FromUTF8(buffer); + return result; + } + + wxString getsection(int idx) const + { + char buffer[INI_BUFFERSIZE]; + ini_getsection(idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str()); + wxString result = wxString::FromUTF8(buffer); + return result; + } + + wxString getkey(const wxString& Section, int idx) const + { + char buffer[INI_BUFFERSIZE]; + ini_getkey(Section.utf8_str(), idx, buffer, INI_BUFFERSIZE, iniFilename.utf8_str()); + wxString result = wxString::FromUTF8(buffer); + return result; + } + +#if defined INI_REAL + INI_REAL getf(const wxString& Section, wxString& Key, INI_REAL DefValue=0) const + { return ini_getf(Section.utf8_str(), Key.utf8_str(), DefValue, iniFilename.utf8_str()); } +#endif + +#if ! defined INI_READONLY + bool put(const wxString& Section, const wxString& Key, long Value) const + { return ini_putl(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; } + + bool put(const wxString& Section, const wxString& Key, int Value) const + { return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0; } + + bool put(const wxString& Section, const wxString& Key, bool Value) const + { return ini_putl(Section.utf8_str(), Key.utf8_str(), (long)Value, iniFilename.utf8_str()) != 0; } + + bool put(const wxString& Section, const wxString& Key, const wxString& Value) const + { return ini_puts(Section.utf8_str(), Key.utf8_str(), Value.utf8_str(), iniFilename.utf8_str()) != 0; } + + bool put(const wxString& Section, const wxString& Key, const char* Value) const + { return ini_puts(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; } + +#if defined INI_REAL + bool put(const wxString& Section, const wxString& Key, INI_REAL Value) const + { return ini_putf(Section.utf8_str(), Key.utf8_str(), Value, iniFilename.utf8_str()) != 0; } +#endif + + bool del(const wxString& Section, const wxString& Key) const + { return ini_puts(Section.utf8_str(), Key.utf8_str(), 0, iniFilename.utf8_str()) != 0; } + + bool del(const wxString& Section) const + { return ini_puts(Section.utf8_str(), 0, 0, iniFilename.utf8_str()) != 0; } +#endif + +private: + wxString iniFilename; +}; + +#endif /* WXMININI_H */ diff --git a/Source/sys-clk/sysmodule/lib/minIni/doc/minIni.pdf b/Source/sys-clk/sysmodule/lib/minIni/doc/minIni.pdf new file mode 100644 index 0000000000000000000000000000000000000000..603d13eaa0294d7dc3f125060667e842d147349f GIT binary patch literal 153827 zcma&MQ+F=Vx~!WK+Z?fN+qRvI*tTukwr$(V7u&Y2Gf!*hV(qi`#k}i(;H`RkRgo%) zh|x0Au|ks`-Ce&yGqDgb5ZD=7Li6y@i&f;oSsOT;h?p4J8Jp0{nAn;*n-egy zv2pP6K|47+ni$wXyKh`;$=VUK!}h$YPdi}1Sdl8_iS7vp*aqyh&eWU@X52W$P0G2RTEH< z+&CB17BJ@(CZV0l$(0{B!V+g^R+4b@EWOmQfDQOP&zwgQWc2jTLhVft@*5&5-NJTa z!^BQ@iIV^Ia`tzG;gT3Q$eN3y?f<)P@nB}YLM1QwmI4mt;;E3Ozwu1@>S~g?M*QiW zV4GEJI&VwG{t%f`N;Ceb3qczV0|T#Vd!V+*m@klCVWTPhVCYH|jmkifT*?(Q%|=F; z>kz%@xk_VzsS9C{vPL3WkzqwkN6TEntR`&gbJ|od5if84L$;!{*U3w7&eVY*l;&ap zudI#ZU)iL})X6mj{$i498`H<#R%w$R6H%G`;K?ERTu|jYo)(Hd4EgvP2m1T0l*ohUs=~8Rm9i9%#W4a zy8x8v*GJ{DpQEu-{H7!X)!$hiN={J@({wa_z%o)MiT!B4yFw7QG>GS#jIBuN{CyVP zd}2kB1GaZTL zP6^%)5vxKVP1;Edh8wFFN1aI4%=b^eiwk;ChojPY^w|g6EuhCS`AA{|%b&9S^9(SV zNG|MsmOwUPK{2-`S$p2}e@s^krUr&1M_fIs^0-d%foguC+661})}HTAe1}}DSNtN% zr{7_z=|m3y>Unkh#49idXWo3)P#{)MvB2;KQ%Q9?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_VIUyU^zagQC;CyEt|-WuEucdFtKxN_H8nomwts4eajVJ0TCN3Tl`uv1siVF3EKy5 zbQnCIA-T0;!LhD~E3ZF9t5ih;aOV;>2kkbo>A*9o#3O_1g}F)_sYb3w3TRx-H)$+# zjBOIB$f7Va-BaJjTO7OuV)h^O(6EI3lJYpSB87ZYQ13L>6!qhf(aWdAKSr9&Cbl15 zEPP0~urI`$iF)h{UHWYl&hn?8Y*Sy=#5*R`(U9O4Z-uf>jnm}cS0^<#I3|`BLk, , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include "../dev/minIni.h" + +#ifdef __cplusplus +} +#endif \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/nxExt/.gitignore b/Source/sys-clk/sysmodule/lib/nxExt/.gitignore new file mode 100644 index 00000000..0806f7bf --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/.gitignore @@ -0,0 +1,13 @@ +# Editor files +*.swp +*~ + +# Objects +*.o +*.a +*.so + +# Lib +lib +release +debug \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/lib/nxExt/Makefile b/Source/sys-clk/sysmodule/lib/nxExt/Makefile new file mode 100644 index 00000000..34be0db8 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/Makefile @@ -0,0 +1,132 @@ +#--------------------------------------------------------------------------------- +.SUFFIXES: +#--------------------------------------------------------------------------------- + +ifeq ($(strip $(DEVKITPRO)),) +$(error "Please set DEVKITPRO in your environment. export DEVKITPRO=/devkitpro") +endif + +include $(DEVKITPRO)/libnx/switch_rules + +#--------------------------------------------------------------------------------- +# TARGET is the name of the output +# SOURCES is a list of directories containing source code +# DATA is a list of directories containing data files +# INCLUDES is a list of directories containing header files +#--------------------------------------------------------------------------------- +TARGET := $(notdir $(CURDIR)) +SOURCES := src +DATA := data +INCLUDES := include + +#--------------------------------------------------------------------------------- +# options for code generation +#--------------------------------------------------------------------------------- +ARCH := -march=armv8-a+crc+crypto -mtune=cortex-a57 -mtp=soft -fPIC -ftls-model=local-exec + +CFLAGS := -g -Wall -Werror \ + -ffunction-sections \ + -fdata-sections \ + $(ARCH) \ + $(BUILD_CFLAGS) + +CFLAGS += $(INCLUDE) -std=gnu11 + +CXXFLAGS := $(CFLAGS) -fno-rtti -fno-exceptions + +ASFLAGS := -g $(ARCH) + +#--------------------------------------------------------------------------------- +# list of directories containing libraries, this must be the top level containing +# include and lib +#--------------------------------------------------------------------------------- +LIBDIRS := $(PORTLIBS) $(LIBNX) + +#--------------------------------------------------------------------------------- +# no real need to edit anything past this point unless you need to add additional +# rules for different file extensions +#--------------------------------------------------------------------------------- +ifneq ($(BUILD),$(notdir $(CURDIR))) +#--------------------------------------------------------------------------------- + +export VPATH := $(foreach dir,$(SOURCES),$(CURDIR)/$(dir)) \ + $(foreach dir,$(DATA),$(CURDIR)/$(dir)) + +CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) +CPPFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.cpp))) +SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) +BINFILES := $(foreach dir,$(DATA),$(notdir $(wildcard $(dir)/*.*))) + +#--------------------------------------------------------------------------------- +# use CXX for linking C++ projects, CC for standard C +#--------------------------------------------------------------------------------- +ifeq ($(strip $(CPPFILES)),) +#--------------------------------------------------------------------------------- + export LD := $(CC) +#--------------------------------------------------------------------------------- +else +#--------------------------------------------------------------------------------- + export LD := $(CXX) +#--------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------- + +export OFILES_BIN := $(addsuffix .o,$(BINFILES)) +export OFILES_SRC := $(CPPFILES:.cpp=.o) $(CFILES:.c=.o) $(SFILES:.s=.o) +export OFILES := $(OFILES_BIN) $(OFILES_SRC) +export HFILES := $(addsuffix .h,$(subst .,_,$(BINFILES))) + +export INCLUDE := $(foreach dir,$(INCLUDES),-I$(CURDIR)/$(dir)) \ + $(foreach dir,$(LIBDIRS),-I$(dir)/include) \ + -I$(CURDIR)/$(BUILD) + +.PHONY: clean all lib/lib$(TARGET).a lib/lib$(TARGET)d.a + +#--------------------------------------------------------------------------------- +all: lib/lib$(TARGET).a lib/lib$(TARGET)d.a + +lib: + @[ -d $@ ] || mkdir -p $@ + +release: + @[ -d $@ ] || mkdir -p $@ + +debug: + @[ -d $@ ] || mkdir -p $@ + +lib/lib$(TARGET).a : lib release $(SOURCES) $(INCLUDES) + @$(MAKE) BUILD=release OUTPUT=$(CURDIR)/$@ \ + BUILD_CFLAGS="-DNDEBUG=1 -O2" \ + DEPSDIR=$(CURDIR)/release \ + --no-print-directory -C release \ + -f $(CURDIR)/Makefile + +#--------------------------------------------------------------------------------- +clean: + @echo clean ... + @rm -fr release debug lib + +#--------------------------------------------------------------------------------- +else + +DEPENDS := $(OFILES:.o=.d) + +#--------------------------------------------------------------------------------- +# main targets +#--------------------------------------------------------------------------------- +$(OUTPUT) : $(OFILES) + +$(OFILES_SRC) : $(HFILES) + +#--------------------------------------------------------------------------------- +%_bin.h %.bin.o : %.bin +#--------------------------------------------------------------------------------- + @echo $(notdir $<) + @$(bin2o) + + +-include $(DEPENDS) + +#--------------------------------------------------------------------------------------- +endif +#--------------------------------------------------------------------------------------- diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt.h new file mode 100644 index 00000000..6361703d --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt.h @@ -0,0 +1,19 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include "nxExt/apm_ext.h" +#include "nxExt/i2c.h" +#include "nxExt/t210.h" +#include "nxExt/max17050.h" +#include "nxExt/tmp451.h" +#include "nxExt/ipc_server.h" +#include "nxExt/cpp/lockable_mutex.h" diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/apm_ext.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/apm_ext.h new file mode 100644 index 00000000..b491a5ee --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/apm_ext.h @@ -0,0 +1,29 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +Result apmExtInitialize(void); +void apmExtExit(void); + +Result apmExtGetPerformanceMode(u32* out_mode); +Result apmExtSysRequestPerformanceMode(u32 mode); +Result apmExtGetCurrentPerformanceConfiguration(u32* out_conf); + +#ifdef __cplusplus +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/cpp/lockable_mutex.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/cpp/lockable_mutex.h new file mode 100644 index 00000000..44f19f2d --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/cpp/lockable_mutex.h @@ -0,0 +1,64 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus + +#include +#include + +class LockableMutex +{ +public: + LockableMutex() + { + mutexInit(&this->m); + } + + virtual ~LockableMutex() {} + + void Lock() + { + mutexLock(&this->m); + } + + bool TryLock() + { + return mutexTryLock(&this->m); + } + + void Unlock() + { + mutexUnlock(&this->m); + } + + // snake_case aliases in order to implement Lockable + + void lock() + { + this->Lock(); + } + + bool try_lock() + { + return this->TryLock(); + } + + void unlock() + { + this->Unlock(); + } + +private: + Mutex m; +}; + +#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/i2c.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/i2c.h new file mode 100644 index 00000000..48656424 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/i2c.h @@ -0,0 +1,24 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +Result i2csessionExtRegReceive(I2cSession* s, u8 in, void* out, u8 out_size); + +#ifdef __cplusplus +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/ipc_server.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/ipc_server.h new file mode 100644 index 00000000..4dd8f88f --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/ipc_server.h @@ -0,0 +1,62 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +#define IPC_SERVER_EXT_RESPONSE_MAX_DATA_SIZE (0x100 - 0x10 - sizeof(IpcServerRawHeader)) + +typedef struct +{ + u64 magic; + union + { + u64 cmdId; + u64 result; + }; +} IpcServerRawHeader; + +typedef struct +{ + SmServiceName srvName; + Handle handles[MAX_WAIT_OBJECTS]; + u32 max; + u32 count; +} IpcServer; + +typedef struct +{ + u64 cmdId; + void* ptr; + size_t size; +} IpcServerRequestData; + +typedef struct +{ + HipcParsedRequest hipc; + IpcServerRequestData data; +} IpcServerRequest; + +typedef Result (*IpcServerRequestHandler)(void* userdata, const IpcServerRequest* r, u8* out_data, size_t* out_dataSize); + +Result ipcServerInit(IpcServer* server, const char* name, u32 max_sessions); +Result ipcServerExit(IpcServer* server); +Result ipcServerProcess(IpcServer* server, IpcServerRequestHandler handler, void* userdata); +Result ipcServerParseCommand(const IpcServerRequest* r, size_t* out_datasize, void** out_data, u64* out_cmd); + +#ifdef __cplusplus +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/max17050.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/max17050.h new file mode 100644 index 00000000..05924dd7 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/max17050.h @@ -0,0 +1,27 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +Result max17050Initialize(void); +void max17050Exit(void); +s32 max17050PowerNow(void); +s32 max17050PowerAvg(void); + +#ifdef __cplusplus +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/t210.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/t210.h new file mode 100644 index 00000000..334691e9 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/t210.h @@ -0,0 +1,28 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +u32 t210ClkCpuFreq(void); +u32 t210ClkMemFreq(void); +u32 t210ClkGpuFreq(void); +u32 t210EmcLoadAll(void); +u32 t210EmcLoadCpu(void); + +#ifdef __cplusplus +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/tmp451.h b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/tmp451.h new file mode 100644 index 00000000..587596b6 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/include/nxExt/tmp451.h @@ -0,0 +1,27 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#ifdef __cplusplus +extern "C" +{ +#endif + +#include + +Result tmp451Initialize(void); +void tmp451Exit(void); +s32 tmp451TempPcb(void); +s32 tmp451TempSoc(void); + +#ifdef __cplusplus +} +#endif diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/apm_ext.c b/Source/sys-clk/sysmodule/lib/nxExt/src/apm_ext.c new file mode 100644 index 00000000..7815e0a1 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/src/apm_ext.c @@ -0,0 +1,66 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "nxExt/apm_ext.h" + +#include + +static Service g_apmSrv; +static Service g_apmSysSrv; +static atomic_size_t g_refCnt; + +Result apmExtInitialize(void) +{ + g_refCnt++; + + if (serviceIsActive(&g_apmSrv)) + { + return 0; + } + + Result rc = 0; + + rc = smGetService(&g_apmSrv, "apm"); + if(R_SUCCEEDED(rc)) + { + rc = smGetService(&g_apmSysSrv, "apm:sys"); + } + + if (R_FAILED(rc)) + { + apmExtExit(); + } + + return rc; +} + +void apmExtExit(void) +{ + if (--g_refCnt == 0) + { + serviceClose(&g_apmSrv); + serviceClose(&g_apmSysSrv); + } +} + +Result apmExtGetPerformanceMode(u32* out_mode) +{ + return serviceDispatchOut(&g_apmSrv, 1, *out_mode); +} + +Result apmExtSysRequestPerformanceMode(u32 mode) +{ + return serviceDispatchIn(&g_apmSysSrv, 0, mode); +} + +Result apmExtGetCurrentPerformanceConfiguration(u32* out_conf) +{ + return serviceDispatchOut(&g_apmSysSrv, 7, *out_conf); +} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c b/Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c new file mode 100644 index 00000000..9a82cc1d --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/src/i2c.c @@ -0,0 +1,28 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "nxExt/i2c.h" + +#define I2C_CMD_SND 0 +#define I2C_CMD_RCV 1 + +Result i2csessionExtRegReceive(I2cSession* s, u8 in, void* out, u8 out_size) +{ + u8 cmdlist[5] = { + I2C_CMD_SND | (I2cTransactionOption_Start << 6), + sizeof(in), + in, + + I2C_CMD_RCV | (I2cTransactionOption_All << 6), + out_size + }; + + return i2csessionExecuteCommandList(s, out, out_size, cmdlist, sizeof(cmdlist)); +} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/ipc_server.c b/Source/sys-clk/sysmodule/lib/nxExt/src/ipc_server.c new file mode 100644 index 00000000..1953c707 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/src/ipc_server.c @@ -0,0 +1,204 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "nxExt/ipc_server.h" +#include + +Result ipcServerInit(IpcServer* server, const char* name, u32 max_sessions) +{ + if(max_sessions < 1 || max_sessions > (MAX_WAIT_OBJECTS - 1)) + { + return MAKERESULT(Module_Libnx, LibnxError_BadInput); + } + + server->srvName = smEncodeName(name); + server->max = max_sessions + 1; + server->count = 0; + + Result rc = smRegisterService(&server->handles[0], server->srvName, false, max_sessions); + if(R_SUCCEEDED(rc)) + { + server->count = 1; + } + return rc; +} + +Result ipcServerExit(IpcServer* server) +{ + for(u32 i = 0; i < server->count; i++) + { + svcCloseHandle(server->handles[i]); + } + server->count = 0; + return smUnregisterService(server->srvName); +} + +static Result _ipcServerAddSession(IpcServer* server, Handle session) +{ + if(server->count >= server->max) + { + return MAKERESULT(Module_Libnx, LibnxError_OutOfMemory); + } + + server->handles[server->count] = session; + server->count++; + return 0; +} + +static Result _ipcServerDeleteSession(IpcServer* server, u32 index) +{ + if(!index || index >= server->count) + { + return MAKERESULT(Module_Libnx, LibnxError_BadInput); + } + + svcCloseHandle(server->handles[index]); + + for(u32 j = index; j < (server->count - 1); j++) + { + server->handles[j] = server->handles[j + 1]; + } + server->count--; + return 0; +} + +static Result _ipcServerParseRequest(IpcServerRequest* r) +{ + u8* base = armGetTls(); + + r->hipc = hipcParseRequest(base); + r->data.cmdId = 0; + r->data.size = 0; + r->data.ptr = NULL; + + if(r->hipc.meta.type == CmifCommandType_Request) + { + IpcServerRawHeader* header = cmifGetAlignedDataStart(r->hipc.data.data_words, base); + size_t dataSize = r->hipc.meta.num_data_words * 4; + + if(!header || dataSize < sizeof(IpcServerRawHeader) || header->magic != CMIF_IN_HEADER_MAGIC) + { + return MAKERESULT(Module_Libnx, LibnxError_BadInput); + } + + r->data.cmdId = header->cmdId; + if(dataSize > sizeof(IpcServerRawHeader)) + { + r->data.size = dataSize - sizeof(IpcServerRawHeader); + r->data.ptr = ((u8*)header) + sizeof(IpcServerRawHeader); + } + } + + return 0; +} + +static void _ipcServerPrepareResponse(Result rc, void* data, size_t dataSize) +{ + u8* base = armGetTls(); + HipcRequest hipc = hipcMakeRequestInline(base, + .type = CmifCommandType_Request, + .num_data_words = (sizeof(IpcServerRawHeader) + dataSize + 0x10) / 4, + ); + + IpcServerRawHeader* rawHeader = cmifGetAlignedDataStart(hipc.data_words, base); + rawHeader->magic = CMIF_OUT_HEADER_MAGIC; + rawHeader->result = rc; + + if(R_SUCCEEDED(rc)) + { + memcpy(((u8*)rawHeader) + sizeof(IpcServerRawHeader), data, dataSize); + } +} + +static Result _ipcServerProcessNewSession(IpcServer* server) +{ + Handle session; + Result rc = svcAcceptSession(&session, server->handles[0]); + if(R_SUCCEEDED(rc) && R_FAILED(rc = _ipcServerAddSession(server, session))) + { + svcCloseHandle(session); + } + return rc; +} + +static Result _ipcServerProcessSession(IpcServer* server, IpcServerRequestHandler handler, void* userdata, u32 handleIndex) +{ + s32 unusedIndex; + IpcServerRequest r; + size_t dataSize = 0; + u8 data[IPC_SERVER_EXT_RESPONSE_MAX_DATA_SIZE]; + bool close = false; + + Result rc = svcReplyAndReceive(&unusedIndex, &server->handles[handleIndex], 1, 0, UINT64_MAX); + if(R_SUCCEEDED(rc)) + { + rc = _ipcServerParseRequest(&r); + } + + if(R_SUCCEEDED(rc)) + { + switch(r.hipc.meta.type) + { + case CmifCommandType_Request: + _ipcServerPrepareResponse( + handler(userdata, &r, data, &dataSize), + data, + dataSize + ); + break; + case CmifCommandType_Close: + _ipcServerPrepareResponse(0, NULL, 0); + close = true; + break; + default: + _ipcServerPrepareResponse(MAKERESULT(11, 403), NULL, 0); + break; + } + + rc = svcReplyAndReceive(&unusedIndex, &server->handles[handleIndex], 0, server->handles[handleIndex], 0); + if(rc == KERNELRESULT(TimedOut)) + { + rc = 0; + } + } + + if(R_FAILED(rc) || close) + { + _ipcServerDeleteSession(server, handleIndex); + } + + return rc; +} + +Result ipcServerProcess(IpcServer* server, IpcServerRequestHandler handler, void* userdata) +{ + s32 handleIndex = -1; + Result rc = svcWaitSynchronization(&handleIndex, server->handles, server->count, UINT64_MAX); + + if(R_SUCCEEDED(rc) && (handleIndex < 0 || handleIndex >= server->count)) + { + rc = MAKERESULT(Module_Libnx, LibnxError_NotFound); + } + + if(R_SUCCEEDED(rc)) + { + if(handleIndex) + { + rc = _ipcServerProcessSession(server, handler, userdata, handleIndex); + } + else + { + rc = _ipcServerProcessNewSession(server); + } + } + + return rc; +} + diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/max17050.c b/Source/sys-clk/sysmodule/lib/nxExt/src/max17050.c new file mode 100644 index 00000000..fe6d00bc --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/src/max17050.c @@ -0,0 +1,124 @@ +/* + * Fuel gauge driver for Nintendo Switch's Maxim 17050 + * + * Copyright (c) 2011 Samsung Electronics + * MyungJoo Ham + * Copyright (c) 2018 CTCaer + * Copyright (c) 2022 p-sam + * + * This program is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +#include "nxExt/max17050.h" +#include "nxExt/i2c.h" + +#define MAX17050_WAIT_NS 1000000000UL + +#define MAX17050_VCELL 0x09 +#define MAX17050_Current 0x0A +#define MAX17050_AvgCurrent 0x0B +#define MAX17050_AvgVCELL 0x19 + +#define MAX17050_BOARD_CGAIN 2 +#define MAX17050_BOARD_SNS_RESISTOR_UOHM 5000 + +static I2cSession g_i2c_session; +static u64 g_update_ticks = 0; +static s32 g_power_now = 0; +static s32 g_power_avg = 0; + +static Result _max17050_get_power(s32 *out_mw_now, s32 *out_mw_avg) +{ + s64 ma, mv; + u16 values[3] = {0}; + + Result rc = i2csessionExtRegReceive(&g_i2c_session, MAX17050_VCELL, values, sizeof(values)); + + if (R_SUCCEEDED(rc)) + { + ma = (s16)values[1]; + ma = ma * 1562500 / (MAX17050_BOARD_SNS_RESISTOR_UOHM * MAX17050_BOARD_CGAIN); + + mv = (int)(values[0] >> 3) * 625 / 1000; + + *out_mw_now = ma * mv / 1000000; + } + + if (R_SUCCEEDED(rc)) + { + rc = i2csessionExtRegReceive(&g_i2c_session, MAX17050_AvgVCELL, values, sizeof(u16)); + } + + if (R_SUCCEEDED(rc)) + { + ma = (s16)values[2]; + ma = ma * 1562500 / (MAX17050_BOARD_SNS_RESISTOR_UOHM * MAX17050_BOARD_CGAIN); + + mv = (int)(values[0] >> 3) * 625 / 1000; + + *out_mw_avg = ma * mv / 1000000; + } + + return rc; +} + +static void _max17050_update() +{ + u64 ticks = armGetSystemTick(); + if(armTicksToNs(ticks - g_update_ticks) <= MAX17050_WAIT_NS) + { + return; + } + + g_update_ticks = ticks; + + if(!serviceIsActive(&g_i2c_session.s)) + { + return; + } + + _max17050_get_power(&g_power_now, &g_power_avg); +} + +Result max17050Initialize(void) +{ + Result rc = i2cInitialize(); + + if(R_SUCCEEDED(rc)) + { + rc = i2cOpenSession(&g_i2c_session, I2cDevice_Max17050); + } + + return rc; +} + +void max17050Exit(void) +{ + i2csessionClose(&g_i2c_session); + i2cExit(); +} + +s32 max17050PowerNow(void) +{ + _max17050_update(); + return g_power_now; +} + +s32 max17050PowerAvg(void) +{ + _max17050_update(); + return g_power_avg; +} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/t210.c b/Source/sys-clk/sysmodule/lib/nxExt/src/t210.c new file mode 100644 index 00000000..fca19668 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/src/t210.c @@ -0,0 +1,289 @@ +/* + * Copyright (c) 2020-2023 CTCaer + * Copyright (c) 2023 p-sam + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "nxExt/t210.h" + +#define WAIT_NS 1000000000UL + +#define usleep(x) svcSleepThread(1000UL * x) + +#define GPU_TRIM_SYS_GPCPLL_COEFF 0x4 +#define GPU_TRIM_SYS_GPCPLL(x) (*(volatile u32 *)(g_gpu_base + 0x137000ul + (x))) + +#define CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL 0x60 +#define CLK_RST_CONTROLLER_PTO_CLK_CNT_STATUS 0x64 +#define CLK_RST_CONTROLLER_CLK_OUT_ENB_X 0x280 +#define CLK_RST_CONTROLLER_RST_DEVICES_X 0x28C + +/*! PTO_CLK_CNT */ +#define PTO_REF_CLK_WIN_CFG_MASK 0xF +#define PTO_REF_CLK_WIN_CFG_16P 0xF +#define PTO_CNT_EN BIT(9) +#define PTO_CNT_RST BIT(10) +#define PTO_CLK_ENABLE BIT(13) +#define PTO_SRC_SEL_SHIFT 14 +#define PTO_SRC_SEL_MASK 0x1FF +#define PTO_DIV_SEL_MASK (3 << 23) +#define PTO_DIV_SEL_GATED (0 << 23) +#define PTO_DIV_SEL_DIV1 (1 << 23) +#define PTO_DIV_SEL_DIV2_RISING (2 << 23) +#define PTO_DIV_SEL_DIV2_FALLING (3 << 23) +#define PTO_DIV_SEL_CPU_EARLY (0 << 23) +#define PTO_DIV_SEL_CPU_LATE (1 << 23) + +#define PTO_CLK_CNT_BUSY BIT(31) +#define PTO_CLK_CNT 0xFFFFFF +#define CLK_PTO_CCLK_G 0x12 +#define CLK_PTO_EMC 0x24 + +#define CLOCK(x) (*(volatile u32 *)(g_clk_base + (x))) + +/* Actmon Global registers */ +#define ACTMON_GLB_STATUS 0x0 +#define ACTMON_MCCPU_MON_ACT BIT(8) +#define ACTMON_MCALL_MON_ACT BIT(9) +#define ACTMON_CPU_FREQ_MON_ACT BIT(10) +#define ACTMON_BPMP_MON_ACT BIT(14) +#define ACTMON_CPU_MON_ACT BIT(15) + +#define ACTMON_GLB_PERIOD_CTRL 0x4 +#define ACTMON_GLB_PERIOD_USEC BIT(8) +#define ACTMON_GLB_PERIOD_SAMPLE(n) (((n) - 1) & 0xFF) + +/* Actmon Device Registers */ +#define ACTMON_DEV_SIZE 0x40 +/* Actmon CTRL */ +#define ACTMON_DEV_CTRL_K_VAL(k) (((k) & 7) << 10) +#define ACTMON_DEV_CTRL_ENB_PERIODIC BIT(18) +#define ACTMON_DEV_CTRL_ENB BIT(31) + +#define ACTMON_PERIOD_MS 20 +#define DEV_COUNT_WEIGHT 1024 + +#define ACTMON_BASE (g_act_base + 0x800) +#define ACTMON_DEV_BASE (ACTMON_BASE + 0x80) +#define ACTMON(x) (*(volatile u32 *)(ACTMON_BASE + (x))) + +typedef enum _actmon_dev_t +{ + ACTMON_DEV_CPU, + ACTMON_DEV_BPMP, + ACTMON_DEV_AHB, + ACTMON_DEV_APB, + ACTMON_DEV_CPU_FREQ, + ACTMON_DEV_MC_ALL, + ACTMON_DEV_MC_CPU, + + ACTMON_DEV_NUM, +} actmon_dev_t; + +typedef struct _actmon_dev_reg_t +{ + vu32 ctrl; + vu32 upper_wnark; + vu32 lower_wmark; + vu32 init_avg; + vu32 avg_upper_wmark; + vu32 avg_lower_wmark; + vu32 count_weight; + vu32 count; + vu32 avg_count; + vu32 intr_status; + vu32 ctrl2; + vu32 rsvd[5]; +} actmon_dev_reg_t; + +static uintptr_t g_clk_base = 0; +static uintptr_t g_gpu_base = 0; +static uintptr_t g_act_base = 0; +static u64 g_update_ticks = 0; +static u32 g_cpu_freq = 0; +static u32 g_gpu_freq = 0; +static u32 g_mem_freq = 0; +static u32 g_emc_lall = 0; +static u32 g_emc_lcpu = 0; + +static u32 _clock_get_dev_freq(u32 id) +{ + const u32 pto_win = 16; + const u32 pto_osc = 32768; + + u32 val = ((id & PTO_SRC_SEL_MASK) << PTO_SRC_SEL_SHIFT) | PTO_DIV_SEL_DIV1 | PTO_CLK_ENABLE | (pto_win - 1); + CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val; + (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); + usleep(2); + + CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val | PTO_CNT_RST; + (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); + usleep(2); + + CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val; + (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); + usleep(2); + + CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = val | PTO_CNT_EN; + (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); + usleep((1000000ULL * pto_win / pto_osc) + 12 + 2); // 502 us. + + while (CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_STATUS) & PTO_CLK_CNT_BUSY) + ; + + u32 cnt = CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_STATUS) & PTO_CLK_CNT; + + CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL) = 0; + (void)CLOCK(CLK_RST_CONTROLLER_PTO_CLK_CNT_CNTL); + usleep(2); + + u32 freq_khz = (u64)cnt * pto_osc / pto_win / 1000; + + return freq_khz; +} + +static void _actmon_dev_enable(actmon_dev_t dev, u32 freq, u32 weight) +{ + actmon_dev_reg_t *regs = (actmon_dev_reg_t *)(ACTMON_DEV_BASE + (dev * ACTMON_DEV_SIZE)); + + regs->init_avg = (u32)freq * ACTMON_PERIOD_MS / 2; + regs->count_weight = weight; + + regs->ctrl = ACTMON_DEV_CTRL_ENB | ACTMON_DEV_CTRL_ENB_PERIODIC | ACTMON_DEV_CTRL_K_VAL(3); // 8 samples average. +} + +static u32 _actmon_dev_get_count_avg(actmon_dev_t dev) +{ + actmon_dev_reg_t *regs = (actmon_dev_reg_t *)(ACTMON_DEV_BASE + (dev * ACTMON_DEV_SIZE)); + + return regs->avg_count; +} + +static inline Result _svcQueryMemoryMappingFallback(u64* virtaddr, u64 physaddr, u64 size) +{ + if(hosversionAtLeast(10,0,0)) + { + u64 out_size; + return svcQueryMemoryMapping(virtaddr, &out_size, physaddr, size); + } + else + { + return svcLegacyQueryIoMapping(virtaddr, physaddr, size); + } +} + +static void _clock_update_freqs(void) +{ + u64 ticks = armGetSystemTick(); + if(armTicksToNs(ticks - g_update_ticks) <= WAIT_NS) + { + return; + } + + g_update_ticks = ticks; + + if (!g_clk_base) + { + _svcQueryMemoryMappingFallback(&g_clk_base, 0x60006000ul, 0x1000); + } + + if(!g_clk_base) + { + return; + } + + g_mem_freq = _clock_get_dev_freq(CLK_PTO_EMC) * 1000; + g_cpu_freq = _clock_get_dev_freq(CLK_PTO_CCLK_G) * 1000; + + if (!g_gpu_base) + { + _svcQueryMemoryMappingFallback(&g_gpu_base, 0x57000000ul, 0x1000000); + } + + if (!g_gpu_base) + { + return; + } + + bool gpu_enabled = (CLOCK(CLK_RST_CONTROLLER_CLK_OUT_ENB_X) & BIT(24)) && !(CLOCK(CLK_RST_CONTROLLER_RST_DEVICES_X) & BIT(24)); + if(!gpu_enabled) + { + return; + } + + if (!g_act_base) + { + _svcQueryMemoryMappingFallback(&g_act_base, 0x6000C000ul, 0x1000); + } + + if(!g_act_base) + { + return; + } + + const u32 osc = 38400000; + u32 coeff = GPU_TRIM_SYS_GPCPLL(GPU_TRIM_SYS_GPCPLL_COEFF); + u32 divm = coeff & 0xFF; + u32 divn = (coeff >> 8) & 0xFF; + u32 divp = (coeff >> 16) & 0x3F; + g_gpu_freq = osc * divn / (divm * divp) / 2; + + u32 emc_freq = g_mem_freq / 1000; + + // Check if actmon is disabled + if (!(ACTMON(ACTMON_GLB_STATUS) & ACTMON_MCALL_MON_ACT)) + { + ACTMON(ACTMON_GLB_PERIOD_CTRL) = ACTMON_GLB_PERIOD_SAMPLE(ACTMON_PERIOD_MS); + _actmon_dev_enable(ACTMON_DEV_MC_ALL, emc_freq, 256 * 4); + } + + // Check if actmon is disabled + if (!(ACTMON(ACTMON_GLB_STATUS) & ACTMON_MCCPU_MON_ACT)) + _actmon_dev_enable(ACTMON_DEV_MC_CPU, emc_freq, 256 * 4); + + // Get 1000 -> 100.0. + g_emc_lall = (u64)_actmon_dev_get_count_avg(ACTMON_DEV_MC_ALL) * 10 * 100 / (emc_freq * ACTMON_PERIOD_MS); + g_emc_lcpu = (u64)_actmon_dev_get_count_avg(ACTMON_DEV_MC_CPU) * 10 * 100 / (emc_freq * ACTMON_PERIOD_MS); +} + + +u32 t210ClkCpuFreq(void) +{ + _clock_update_freqs(); + return g_cpu_freq; +} + +u32 t210ClkMemFreq(void) +{ + _clock_update_freqs(); + return g_mem_freq; +} + +u32 t210ClkGpuFreq(void) +{ + _clock_update_freqs(); + return g_gpu_freq; +} + +u32 t210EmcLoadAll() +{ + _clock_update_freqs(); + return g_emc_lall; +} + +u32 t210EmcLoadCpu() +{ + _clock_update_freqs(); + return g_emc_lcpu; +} diff --git a/Source/sys-clk/sysmodule/lib/nxExt/src/tmp451.c b/Source/sys-clk/sysmodule/lib/nxExt/src/tmp451.c new file mode 100644 index 00000000..90c8d1c2 --- /dev/null +++ b/Source/sys-clk/sysmodule/lib/nxExt/src/tmp451.c @@ -0,0 +1,102 @@ +/* + * SOC/PCB Temperature driver for Nintendo Switch's TI TMP451 + * + * Copyright (c) 2018-2024 CTCaer + * Copyright (c) 2024 p-sam + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include "nxExt/tmp451.h" +#include "nxExt/i2c.h" + +#define TMP451_WAIT_NS 1000000000UL + +#define TMP451_PCB_TEMP_REG 0x00 +#define TMP451_SOC_TEMP_REG 0x01 + +#define TMP451_SOC_TMP_DEC_REG 0x10 +#define TMP451_PCB_TMP_DEC_REG 0x15 + +static I2cSession g_i2c_session; +static u64 g_update_ticks = 0; +static s32 g_temp_pcb = 0; +static s32 g_temp_soc = 0; + +static Result _tmp451_get_temp(u8 reg, u8 dec_reg, s32* out) +{ + u8 val = 0; + Result rc = i2csessionExtRegReceive(&g_i2c_session, reg, &val, sizeof(val)); + + if(R_SUCCEEDED(rc)) + { + *out = (s32)val * 1000; + rc = i2csessionExtRegReceive(&g_i2c_session, dec_reg, &val, sizeof(val)); + } + + if(R_SUCCEEDED(rc)) + { + *out += ((s32)(val >> 4) * 625) / 10; + } + + return rc; +} + +static void _tmp451_update() +{ + u64 ticks = armGetSystemTick(); + if(armTicksToNs(ticks - g_update_ticks) <= TMP451_WAIT_NS) + { + return; + } + + g_update_ticks = ticks; + + if(!serviceIsActive(&g_i2c_session.s)) + { + return; + } + + _tmp451_get_temp(TMP451_PCB_TEMP_REG, TMP451_PCB_TMP_DEC_REG, &g_temp_pcb); + _tmp451_get_temp(TMP451_SOC_TEMP_REG, TMP451_SOC_TMP_DEC_REG, &g_temp_soc); +} + +Result tmp451Initialize(void) +{ + Result rc = i2cInitialize(); + + if(R_SUCCEEDED(rc)) + { + rc = i2cOpenSession(&g_i2c_session, I2cDevice_Tmp451); + } + + return rc; +} + +void tmp451Exit(void) +{ + i2csessionClose(&g_i2c_session); + i2cExit(); +} + +s32 tmp451TempPcb(void) +{ + _tmp451_update(); + return g_temp_pcb; +} + +s32 tmp451TempSoc(void) +{ + _tmp451_update(); + return g_temp_soc; +} diff --git a/Source/sys-clk/sysmodule/perms.json b/Source/sys-clk/sysmodule/perms.json new file mode 100644 index 00000000..e3417e2b --- /dev/null +++ b/Source/sys-clk/sysmodule/perms.json @@ -0,0 +1,129 @@ +{ + "name": "sys:clk", + "title_id": "0x00FF0000636C6BFF", + "title_id_range_min": "0x00FF0000636C6BFF", + "title_id_range_max": "0x00FF0000636C6BFF", + "main_thread_stack_size": "0x00004000", + "main_thread_priority": 49, + "default_cpu_id": 3, + "process_category": 0, + "is_retail": true, + "pool_partition": 2, + "is_64_bit": true, + "address_space_type": 3, + "filesystem_access": { + "permissions": "0xFFFFFFFFFFFFFFFF" + }, + "service_access": [ + "*" + ], + "service_host": [ + "sys:clk" + ], + "kernel_capabilities": [ + { + "type": "kernel_flags", + "value": { + "highest_thread_priority": 63, + "lowest_thread_priority": 24, + "lowest_cpu_id": 3, + "highest_cpu_id": 3 + } + }, + { + "type": "map", + "value": { + "address": "0x60006000", + "size": "0x1000", + "is_ro": false, + "is_io": true + } + }, + { + "type": "map", + "value": { + "address": "0x57000000", + "size": "0x1000000", + "is_ro": false, + "is_io": true + } + }, + { + "type": "map", + "value": { + "address": "0x6000C000", + "size": "0x1000", + "is_ro": false, + "is_io": true + } + }, + { + "type": "syscalls", + "value": { + "svcSetHeapSize": "0x01", + "svcSetMemoryPermission": "0x02", + "svcSetMemoryAttribute": "0x03", + "svcMapMemory": "0x04", + "svcUnmapMemory": "0x05", + "svcQueryMemory": "0x06", + "svcExitProcess": "0x07", + "svcCreateThread": "0x08", + "svcStartThread": "0x09", + "svcExitThread": "0x0a", + "svcSleepThread": "0x0b", + "svcGetThreadPriority": "0x0c", + "svcSetThreadPriority": "0x0d", + "svcGetThreadCoreMask": "0x0e", + "svcSetThreadCoreMask": "0x0f", + "svcGetCurrentProcessorNumber": "0x10", + "svcSignalEvent": "0x11", + "svcClearEvent": "0x12", + "svcMapSharedMemory": "0x13", + "svcUnmapSharedMemory": "0x14", + "svcCreateTransferMemory": "0x15", + "svcCloseHandle": "0x16", + "svcResetSignal": "0x17", + "svcWaitSynchronization": "0x18", + "svcCancelSynchronization": "0x19", + "svcArbitrateLock": "0x1a", + "svcArbitrateUnlock": "0x1b", + "svcWaitProcessWideKeyAtomic": "0x1c", + "svcSignalProcessWideKey": "0x1d", + "svcGetSystemTick": "0x1e", + "svcConnectToNamedPort": "0x1f", + "svcSendSyncRequestLight": "0x20", + "svcSendSyncRequest": "0x21", + "svcSendSyncRequestWithUserBuffer": "0x22", + "svcSendAsyncRequestWithUserBuffer": "0x23", + "svcGetProcessId": "0x24", + "svcGetThreadId": "0x25", + "svcBreak": "0x26", + "svcOutputDebugString": "0x27", + "svcReturnFromException": "0x28", + "svcGetInfo": "0x29", + "svcWaitForAddress": "0x34", + "svcSignalToAddress": "0x35", + "svcCreateSession": "0x40", + "svcAcceptSession": "0x41", + "svcReplyAndReceiveLight": "0x42", + "svcReplyAndReceive": "0x43", + "svcReplyAndReceiveWithUserBuffer": "0x44", + "svcCreateEvent": "0x45", + "svcCreateInterruptEvent": "0x53", + "svcReadWriteRegister": "0x4E", + "svcQueryMemoryMapping": "0x55", + "svcCreateDeviceAddressSpace": "0x56", + "svcAttachDeviceAddressSpace": "0x57", + "svcDetachDeviceAddressSpace": "0x58", + "svcMapDeviceAddressSpaceAligned": "0x5a", + "svcUnmapDeviceAddressSpace": "0x5c", + "svcGetSystemInfo": "0x6f", + "svcCallSecureMonitor": "0x7f" + } + }, + { + "type": "min_kernel_version", + "value": "0x0060" + } + ] +} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/board.cpp b/Source/sys-clk/sysmodule/src/board.cpp new file mode 100644 index 00000000..84e9c67a --- /dev/null +++ b/Source/sys-clk/sysmodule/src/board.cpp @@ -0,0 +1,377 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include +#include "board.h" +#include "errors.h" + +#define HOSSVC_HAS_CLKRST (hosversionAtLeast(8,0,0)) +#define HOSSVC_HAS_TC (hosversionAtLeast(5,0,0)) + +static SysClkSocType g_socType = SysClkSocType_Erista; + +const char* Board::GetModuleName(SysClkModule module, bool pretty) +{ + ASSERT_ENUM_VALID(SysClkModule, module); + return sysclkFormatModule(module, pretty); +} + +const char* Board::GetProfileName(SysClkProfile profile, bool pretty) +{ + ASSERT_ENUM_VALID(SysClkProfile, profile); + return sysclkFormatProfile(profile, pretty); +} + +const char* Board::GetThermalSensorName(SysClkThermalSensor sensor, bool pretty) +{ + ASSERT_ENUM_VALID(SysClkThermalSensor, sensor); + return sysclkFormatThermalSensor(sensor, pretty); +} + +const char* Board::GetPowerSensorName(SysClkPowerSensor sensor, bool pretty) +{ + ASSERT_ENUM_VALID(SysClkPowerSensor, sensor); + return sysclkFormatPowerSensor(sensor, pretty); +} + +PcvModule Board::GetPcvModule(SysClkModule sysclkModule) +{ + switch(sysclkModule) + { + case SysClkModule_CPU: + return PcvModule_CpuBus; + case SysClkModule_GPU: + return PcvModule_GPU; + case SysClkModule_MEM: + return PcvModule_EMC; + default: + ASSERT_ENUM_VALID(SysClkModule, sysclkModule); + } + + return (PcvModule)0; +} + +PcvModuleId Board::GetPcvModuleId(SysClkModule sysclkModule) +{ + PcvModuleId pcvModuleId; + Result rc = pcvGetModuleId(&pcvModuleId, GetPcvModule(sysclkModule)); + ASSERT_RESULT_OK(rc, "pcvGetModuleId"); + + return pcvModuleId; +} + +void Board::Initialize() +{ + Result rc = 0; + + if(HOSSVC_HAS_CLKRST) + { + rc = clkrstInitialize(); + ASSERT_RESULT_OK(rc, "clkrstInitialize"); + } + else + { + rc = pcvInitialize(); + ASSERT_RESULT_OK(rc, "pcvInitialize"); + } + + rc = apmExtInitialize(); + ASSERT_RESULT_OK(rc, "apmExtInitialize"); + + rc = psmInitialize(); + ASSERT_RESULT_OK(rc, "psmInitialize"); + + if(HOSSVC_HAS_TC) + { + rc = tcInitialize(); + ASSERT_RESULT_OK(rc, "tcInitialize"); + } + + rc = max17050Initialize(); + ASSERT_RESULT_OK(rc, "max17050Initialize"); + + rc = tmp451Initialize(); + ASSERT_RESULT_OK(rc, "tmp451Initialize"); + + FetchHardwareInfos(); +} + +void Board::Exit() +{ + if(HOSSVC_HAS_CLKRST) + { + clkrstExit(); + } + else + { + pcvExit(); + } + + apmExtExit(); + psmExit(); + + if(HOSSVC_HAS_TC) + { + tcExit(); + } + + max17050Exit(); + tmp451Exit(); +} + +SysClkProfile Board::GetProfile() +{ + std::uint32_t mode = 0; + Result rc = apmExtGetPerformanceMode(&mode); + ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); + + if(mode) + { + return SysClkProfile_Docked; + } + + PsmChargerType chargerType; + + rc = psmGetChargerType(&chargerType); + ASSERT_RESULT_OK(rc, "psmGetChargerType"); + + if(chargerType == PsmChargerType_EnoughPower) + { + return SysClkProfile_HandheldChargingOfficial; + } + else if(chargerType == PsmChargerType_LowPower) + { + return SysClkProfile_HandheldChargingUSB; + } + + return SysClkProfile_Handheld; +} + +void Board::SetHz(SysClkModule module, std::uint32_t hz) +{ + Result rc = 0; + + if(HOSSVC_HAS_CLKRST) + { + ClkrstSession session = {0}; + + rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); + ASSERT_RESULT_OK(rc, "clkrstOpenSession"); + + rc = clkrstSetClockRate(&session, hz); + ASSERT_RESULT_OK(rc, "clkrstSetClockRate"); + + clkrstCloseSession(&session); + } + else + { + rc = pcvSetClockRate(Board::GetPcvModule(module), hz); + ASSERT_RESULT_OK(rc, "pcvSetClockRate"); + } +} + +std::uint32_t Board::GetHz(SysClkModule module) +{ + Result rc = 0; + std::uint32_t hz = 0; + + if(HOSSVC_HAS_CLKRST) + { + ClkrstSession session = {0}; + + rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); + ASSERT_RESULT_OK(rc, "clkrstOpenSession"); + + rc = clkrstGetClockRate(&session, &hz); + ASSERT_RESULT_OK(rc, "clkrstSetClockRate"); + + clkrstCloseSession(&session); + } + else + { + rc = pcvGetClockRate(Board::GetPcvModule(module), &hz); + ASSERT_RESULT_OK(rc, "pcvGetClockRate"); + } + + return hz; +} + +std::uint32_t Board::GetRealHz(SysClkModule module) +{ + switch(module) + { + case SysClkModule_CPU: + return t210ClkCpuFreq(); + case SysClkModule_GPU: + return t210ClkGpuFreq(); + case SysClkModule_MEM: + return t210ClkMemFreq(); + default: + ASSERT_ENUM_VALID(SysClkModule, module); + } + + return 0; +} + +void Board::GetFreqList(SysClkModule module, std::uint32_t* outList, std::uint32_t maxCount, std::uint32_t* outCount) +{ + Result rc = 0; + PcvClockRatesListType type; + s32 tmpInMaxCount = maxCount; + s32 tmpOutCount = 0; + + if(HOSSVC_HAS_CLKRST) + { + ClkrstSession session = {0}; + + rc = clkrstOpenSession(&session, Board::GetPcvModuleId(module), 3); + ASSERT_RESULT_OK(rc, "clkrstOpenSession"); + + rc = clkrstGetPossibleClockRates(&session, outList, tmpInMaxCount, &type, &tmpOutCount); + ASSERT_RESULT_OK(rc, "clkrstGetPossibleClockRates"); + + clkrstCloseSession(&session); + } + else + { + rc = pcvGetPossibleClockRates(Board::GetPcvModule(module), outList, tmpInMaxCount, &type, &tmpOutCount); + ASSERT_RESULT_OK(rc, "pcvGetPossibleClockRates"); + } + + if(type != PcvClockRatesListType_Discrete) + { + ERROR_THROW("Unexpected PcvClockRatesListType: %u (module = %s)", type, Board::GetModuleName(module, false)); + } + + *outCount = tmpOutCount; +} + +void Board::ResetToStock() +{ + Result rc = 0; + if(hosversionAtLeast(9,0,0)) + { + std::uint32_t confId = 0; + rc = apmExtGetCurrentPerformanceConfiguration(&confId); + ASSERT_RESULT_OK(rc, "apmExtGetCurrentPerformanceConfiguration"); + + SysClkApmConfiguration* apmConfiguration = NULL; + for(size_t i = 0; sysclk_g_apm_configurations[i].id; i++) + { + if(sysclk_g_apm_configurations[i].id == confId) + { + apmConfiguration = &sysclk_g_apm_configurations[i]; + break; + } + } + + if(!apmConfiguration) + { + ERROR_THROW("Unknown apm configuration: %x", confId); + } + + Board::SetHz(SysClkModule_CPU, apmConfiguration->cpu_hz); + Board::SetHz(SysClkModule_GPU, apmConfiguration->gpu_hz); + Board::SetHz(SysClkModule_MEM, apmConfiguration->mem_hz); + } + else + { + std::uint32_t mode = 0; + rc = apmExtGetPerformanceMode(&mode); + ASSERT_RESULT_OK(rc, "apmExtGetPerformanceMode"); + + rc = apmExtSysRequestPerformanceMode(mode); + ASSERT_RESULT_OK(rc, "apmExtSysRequestPerformanceMode"); + } +} + +std::uint32_t Board::GetTemperatureMilli(SysClkThermalSensor sensor) +{ + std::int32_t millis = 0; + + if(sensor == SysClkThermalSensor_SOC) + { + millis = tmp451TempSoc(); + } + else if(sensor == SysClkThermalSensor_PCB) + { + millis = tmp451TempPcb(); + } + else if(sensor == SysClkThermalSensor_Skin) + { + if(HOSSVC_HAS_TC) + { + Result rc; + rc = tcGetSkinTemperatureMilliC(&millis); + ASSERT_RESULT_OK(rc, "tcGetSkinTemperatureMilliC"); + } + } + else + { + ASSERT_ENUM_VALID(SysClkThermalSensor, sensor); + } + + return std::max(0, millis); +} + +std::int32_t Board::GetPowerMw(SysClkPowerSensor sensor) +{ + switch(sensor) + { + case SysClkPowerSensor_Now: + return max17050PowerNow(); + case SysClkPowerSensor_Avg: + return max17050PowerAvg(); + default: + ASSERT_ENUM_VALID(SysClkPowerSensor, sensor); + } + + return 0; +} + +std::uint32_t Board::GetRamLoad(SysClkRamLoad loadSource) +{ + switch(loadSource) + { + case SysClkRamLoad_All: + return t210EmcLoadAll(); + case SysClkRamLoad_Cpu: + return t210EmcLoadCpu(); + default: + ASSERT_ENUM_VALID(SysClkRamLoad, loadSource); + } + + return 0; +} + +SysClkSocType Board::GetSocType() { + return g_socType; +} + +void Board::FetchHardwareInfos() +{ + u64 sku = 0; + Result rc = splInitialize(); + ASSERT_RESULT_OK(rc, "splInitialize"); + + rc = splGetConfig(SplConfigItem_HardwareType, &sku); + ASSERT_RESULT_OK(rc, "splGetConfig"); + + splExit(); + + switch(sku) + { + case 2 ... 5: + g_socType = SysClkSocType_Mariko; + break; + default: + g_socType = SysClkSocType_Erista; + } +} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/board.h b/Source/sys-clk/sysmodule/src/board.h new file mode 100644 index 00000000..7ed04ab6 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/board.h @@ -0,0 +1,40 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once +#include +#include +#include + +class Board +{ + public: + static const char* GetProfileName(SysClkProfile profile, bool pretty); + static const char* GetModuleName(SysClkModule module, bool pretty); + static const char* GetThermalSensorName(SysClkThermalSensor sensor, bool pretty); + static const char* GetPowerSensorName(SysClkPowerSensor sensor, bool pretty); + static void Initialize(); + static void Exit(); + static void ResetToStock(); + static SysClkProfile GetProfile(); + static void SetHz(SysClkModule module, std::uint32_t hz); + static std::uint32_t GetHz(SysClkModule module); + static std::uint32_t GetRealHz(SysClkModule module); + static void GetFreqList(SysClkModule module, std::uint32_t* outList, std::uint32_t maxCount, std::uint32_t* outCount); + static std::uint32_t GetTemperatureMilli(SysClkThermalSensor sensor); + static std::int32_t GetPowerMw(SysClkPowerSensor sensor); + static std::uint32_t GetRamLoad(SysClkRamLoad load); + static SysClkSocType GetSocType(); + + protected: + static void FetchHardwareInfos(); + static PcvModule GetPcvModule(SysClkModule sysclkModule); + static PcvModuleId GetPcvModuleId(SysClkModule sysclkModule); +}; diff --git a/Source/sys-clk/sysmodule/src/clock_manager.cpp b/Source/sys-clk/sysmodule/src/clock_manager.cpp new file mode 100644 index 00000000..a5907542 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/clock_manager.cpp @@ -0,0 +1,316 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "clock_manager.h" +#include +#include "file_utils.h" +#include "board.h" +#include "process_management.h" +#include "errors.h" +#include "ipc_service.h" +ClockManager::ClockManager() +{ + this->config = Config::CreateDefault(); + + this->context = new SysClkContext; + this->context->applicationId = 0; + this->context->profile = SysClkProfile_Handheld; + this->context->enabled = false; + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + this->context->freqs[module] = 0; + this->context->realFreqs[module] = 0; + this->context->overrideFreqs[module] = 0; + this->RefreshFreqTableRow((SysClkModule)module); + } + + this->running = false; + this->lastTempLogNs = 0; + this->lastCsvWriteNs = 0; +} + +ClockManager::~ClockManager() +{ + delete this->config; + delete this->context; +} + +SysClkContext ClockManager::GetCurrentContext() +{ + std::scoped_lock lock{this->contextMutex}; + return *this->context; +} + +Config *ClockManager::GetConfig() +{ + return this->config; +} + +void ClockManager::SetRunning(bool running) +{ + this->running = running; +} + +bool ClockManager::Running() +{ + return this->running; +} + +void ClockManager::GetFreqList(SysClkModule module, std::uint32_t *list, std::uint32_t maxCount, std::uint32_t *outCount) +{ + ASSERT_ENUM_VALID(SysClkModule, module); + + *outCount = std::min(maxCount, this->freqTable[module].count); + memcpy(list, &this->freqTable[module].list[0], *outCount * sizeof(this->freqTable[0].list[0])); +} + +bool ClockManager::IsAssignableHz(SysClkModule module, std::uint32_t hz) +{ + switch (module) + { + case SysClkModule_CPU: + return hz >= 400000000; + case SysClkModule_MEM: + return hz == 204000000 || hz >= 665600000; + default: + return true; + } +} + +std::uint32_t ClockManager::GetMaxAllowedHz(SysClkModule module, SysClkProfile profile) +{ + return 4294967294; // Integer limit, uncapped clocks ON +} + +std::uint32_t ClockManager::GetNearestHz(SysClkModule module, std::uint32_t inHz, std::uint32_t maxHz) +{ + std::uint32_t *freqs = &this->freqTable[module].list[0]; + size_t count = this->freqTable[module].count - 1; + + size_t i = 0; + while (i < count) + { + if (maxHz > 0 && freqs[i] >= maxHz) + { + break; + } + + if (inHz <= ((std::uint64_t)freqs[i] + freqs[i + 1]) / 2) + { + break; + } + + i++; + } + + return freqs[i]; +} + +bool ClockManager::ConfigIntervalTimeout(SysClkConfigValue intervalMsConfigValue, std::uint64_t ns, std::uint64_t *lastLogNs) +{ + std::uint64_t logInterval = this->GetConfig()->GetConfigValue(intervalMsConfigValue) * 1000000ULL; + bool shouldLog = logInterval && ((ns - *lastLogNs) > logInterval); + + if (shouldLog) + { + *lastLogNs = ns; + } + + return shouldLog; +} + +void ClockManager::RefreshFreqTableRow(SysClkModule module) +{ + std::scoped_lock lock{this->contextMutex}; + + std::uint32_t freqs[SYSCLK_FREQ_LIST_MAX]; + std::uint32_t count; + + FileUtils::LogLine("[mgr] %s freq list refresh", Board::GetModuleName(module, true)); + Board::GetFreqList(module, &freqs[0], SYSCLK_FREQ_LIST_MAX, &count); + + std::uint32_t *hz = &this->freqTable[module].list[0]; + this->freqTable[module].count = 0; + for (std::uint32_t i = 0; i < count; i++) + { + if (!this->IsAssignableHz(module, freqs[i])) + { + continue; + } + + *hz = freqs[i]; + FileUtils::LogLine("[mgr] %02u - %u - %u.%u MHz", this->freqTable[module].count, *hz, *hz / 1000000, *hz / 100000 - *hz / 1000000 * 10); + + this->freqTable[module].count++; + hz++; + } + + FileUtils::LogLine("[mgr] count = %u", this->freqTable[module].count); +} + +void ClockManager::Tick() +{ + std::scoped_lock lock{this->contextMutex}; + if (this->RefreshContext() || this->config->Refresh()) + { + std::uint32_t targetHz = 0; + std::uint32_t maxHz = 0; + std::uint32_t nearestHz = 0; + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + targetHz = this->context->overrideFreqs[module]; + + if (!targetHz) + { + targetHz = this->config->GetAutoClockHz(this->context->applicationId, (SysClkModule)module, this->context->profile); + } + + if (targetHz) + { + maxHz = this->GetMaxAllowedHz((SysClkModule)module, this->context->profile); + nearestHz = this->GetNearestHz((SysClkModule)module, targetHz, maxHz); + + if (nearestHz != this->context->freqs[module] && this->context->enabled) + { + FileUtils::LogLine( + "[mgr] %s clock set : %u.%u MHz (target = %u.%u MHz)", + Board::GetModuleName((SysClkModule)module, true), + nearestHz / 1000000, nearestHz / 100000 - nearestHz / 1000000 * 10, + targetHz / 1000000, targetHz / 100000 - targetHz / 1000000 * 10); + + Board::SetHz((SysClkModule)module, nearestHz); + this->context->freqs[module] = nearestHz; + } + } + } + } +} + +void ClockManager::WaitForNextTick() +{ + svcSleepThread(this->GetConfig()->GetConfigValue(SysClkConfigValue_PollingIntervalMs) * 1000000ULL); +} + +bool ClockManager::RefreshContext() +{ + bool hasChanged = false; + + bool enabled = this->GetConfig()->Enabled(); + if (enabled != this->context->enabled) + { + this->context->enabled = enabled; + FileUtils::LogLine("[mgr] " TARGET " status: %s", enabled ? "enabled" : "disabled"); + hasChanged = true; + } + + std::uint64_t applicationId = ProcessManagement::GetCurrentApplicationId(); + if (applicationId != this->context->applicationId) + { + FileUtils::LogLine("[mgr] TitleID change: %016lX", applicationId); + this->context->applicationId = applicationId; + hasChanged = true; + } + + SysClkProfile profile = Board::GetProfile(); + if (profile != this->context->profile) + { + FileUtils::LogLine("[mgr] Profile change: %s", Board::GetProfileName(profile, true)); + this->context->profile = profile; + hasChanged = true; + } + + // restore clocks to stock values on app or profile change + if (hasChanged) + { + Board::ResetToStock(); + this->WaitForNextTick(); + } + + std::uint32_t hz = 0; + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + hz = Board::GetHz((SysClkModule)module); + if (hz != 0 && hz != this->context->freqs[module]) + { + FileUtils::LogLine("[mgr] %s clock change: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); + this->context->freqs[module] = hz; + hasChanged = true; + } + + hz = this->GetConfig()->GetOverrideHz((SysClkModule)module); + if (hz != this->context->overrideFreqs[module]) + { + if (hz) + { + FileUtils::LogLine("[mgr] %s override change: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), hz / 1000000, hz / 100000 - hz / 1000000 * 10); + } + else + { + FileUtils::LogLine("[mgr] %s override disabled", Board::GetModuleName((SysClkModule)module, true)); + } + this->context->overrideFreqs[module] = hz; + hasChanged = true; + } + } + + std::uint64_t ns = armTicksToNs(armGetSystemTick()); + + // temperatures do not and should not force a refresh, hasChanged untouched + std::uint32_t millis = 0; + bool shouldLogTemp = this->ConfigIntervalTimeout(SysClkConfigValue_TempLogIntervalMs, ns, &this->lastTempLogNs); + for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++) + { + millis = Board::GetTemperatureMilli((SysClkThermalSensor)sensor); + if (shouldLogTemp) + { + FileUtils::LogLine("[mgr] %s temp: %u.%u °C", Board::GetThermalSensorName((SysClkThermalSensor)sensor, true), millis / 1000, (millis - millis / 1000 * 1000) / 100); + } + this->context->temps[sensor] = millis; + } + + // power stats do not and should not force a refresh, hasChanged untouched + std::int32_t mw = 0; + bool shouldLogPower = this->ConfigIntervalTimeout(SysClkConfigValue_PowerLogIntervalMs, ns, &this->lastPowerLogNs); + for (unsigned int sensor = 0; sensor < SysClkPowerSensor_EnumMax; sensor++) + { + mw = Board::GetPowerMw((SysClkPowerSensor)sensor); + if (shouldLogPower) + { + FileUtils::LogLine("[mgr] Power %s: %d mW", Board::GetPowerSensorName((SysClkPowerSensor)sensor, false), mw); + } + this->context->power[sensor] = mw; + } + + // real freqs do not and should not force a refresh, hasChanged untouched + std::uint32_t realHz = 0; + bool shouldLogFreq = this->ConfigIntervalTimeout(SysClkConfigValue_FreqLogIntervalMs, ns, &this->lastFreqLogNs); + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + realHz = Board::GetRealHz((SysClkModule)module); + if (shouldLogFreq) + { + FileUtils::LogLine("[mgr] %s real freq: %u.%u MHz", Board::GetModuleName((SysClkModule)module, true), realHz / 1000000, realHz / 100000 - realHz / 1000000 * 10); + } + this->context->realFreqs[module] = realHz; + } + + // ram load do not and should not force a refresh, hasChanged untouched + for (unsigned int loadSource = 0; loadSource < SysClkRamLoad_EnumMax; loadSource++) + { + this->context->ramLoad[loadSource] = Board::GetRamLoad((SysClkRamLoad)loadSource); + } + + if (this->ConfigIntervalTimeout(SysClkConfigValue_CsvWriteIntervalMs, ns, &this->lastCsvWriteNs)) + { + FileUtils::WriteContextToCsv(this->context); + } + + return hasChanged; +} diff --git a/Source/sys-clk/sysmodule/src/clock_manager.h b/Source/sys-clk/sysmodule/src/clock_manager.h new file mode 100644 index 00000000..5fa12afd --- /dev/null +++ b/Source/sys-clk/sysmodule/src/clock_manager.h @@ -0,0 +1,54 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include + +#include "config.h" +#include "board.h" +#include + +class ClockManager +{ + public: + ClockManager(); + virtual ~ClockManager(); + + SysClkContext GetCurrentContext(); + Config* GetConfig(); + void SetRunning(bool running); + bool Running(); + void GetFreqList(SysClkModule module, std::uint32_t* list, std::uint32_t maxCount, std::uint32_t* outCount); + void Tick(); + void WaitForNextTick(); + + protected: + bool IsAssignableHz(SysClkModule module, std::uint32_t hz); + std::uint32_t GetMaxAllowedHz(SysClkModule module, SysClkProfile profile); + std::uint32_t GetNearestHz(SysClkModule module, std::uint32_t inHz, std::uint32_t maxHz); + bool ConfigIntervalTimeout(SysClkConfigValue intervalMsConfigValue, std::uint64_t ns, std::uint64_t* lastLogNs); + void RefreshFreqTableRow(SysClkModule module); + bool RefreshContext(); + + std::atomic_bool running; + LockableMutex contextMutex; + struct { + std::uint32_t count; + std::uint32_t list[SYSCLK_FREQ_LIST_MAX]; + } freqTable[SysClkModule_EnumMax]; + Config* config; + SysClkContext* context; + std::uint64_t lastTempLogNs; + std::uint64_t lastFreqLogNs; + std::uint64_t lastPowerLogNs; + std::uint64_t lastCsvWriteNs; +}; diff --git a/Source/sys-clk/sysmodule/src/config.cpp b/Source/sys-clk/sysmodule/src/config.cpp new file mode 100644 index 00000000..e8c40f5e --- /dev/null +++ b/Source/sys-clk/sysmodule/src/config.cpp @@ -0,0 +1,473 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "config.h" +#include +#include +#include +#include +#include +#include +#include "errors.h" +#include "file_utils.h" + +Config::Config(std::string path) +{ + this->path = path; + this->loaded = false; + this->profileMHzMap = std::map, std::uint32_t>(); + this->profileCountMap = std::map(); + this->mtime = 0; + this->enabled = false; + for(unsigned int i = 0; i < SysClkModule_EnumMax; i++) + { + this->overrideFreqs[i] = 0; + } + + for(unsigned int i = 0; i < SysClkConfigValue_EnumMax; i++) + { + this->configValues[i] = sysclkDefaultConfigValue((SysClkConfigValue)i); + } +} + +Config::~Config() +{ + std::scoped_lock lock{this->configMutex}; + this->Close(); +} + +Config* Config::CreateDefault() +{ + return new Config(FILE_CONFIG_DIR "/config.ini"); +} + +void Config::Load() +{ + FileUtils::LogLine("[cfg] Reading %s", this->path.c_str()); + + this->Close(); + this->mtime = this->CheckModificationTime(); + if(!this->mtime) + { + FileUtils::LogLine("[cfg] Error finding file"); + } + else if (!ini_browse(&BrowseIniFunc, this, this->path.c_str())) + { + FileUtils::LogLine("[cfg] Error loading file"); + } + + this->loaded = true; +} + +void Config::Close() +{ + this->loaded = false; + this->profileMHzMap.clear(); + this->profileCountMap.clear(); + + for(unsigned int i = 0; i < SysClkConfigValue_EnumMax; i++) + { + this->configValues[i] = sysclkDefaultConfigValue((SysClkConfigValue)i); + } +} + +bool Config::Refresh() +{ + std::scoped_lock lock{this->configMutex}; + if (!this->loaded || this->mtime != this->CheckModificationTime()) + { + this->Load(); + return true; + } + return false; +} + +bool Config::HasProfilesLoaded() +{ + std::scoped_lock lock{this->configMutex}; + return this->loaded; +} + +time_t Config::CheckModificationTime() +{ + time_t mtime = 0; + struct stat st; + if (stat(this->path.c_str(), &st) == 0) + { + mtime = st.st_mtime; + } + + return mtime; +} + +std::uint32_t Config::FindClockMHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile) +{ + if (this->loaded) + { + std::map, std::uint32_t>::const_iterator it = this->profileMHzMap.find(std::make_tuple(tid, profile, module)); + if (it != this->profileMHzMap.end()) + { + return it->second; + } + } + + return 0; +} + +std::uint32_t Config::FindClockHzFromProfiles(std::uint64_t tid, SysClkModule module, std::initializer_list profiles) +{ + std::uint32_t mhz = 0; + + if (this->loaded) + { + for(auto profile: profiles) + { + mhz = FindClockMHz(tid, module, profile); + + if(mhz) + { + break; + } + } + } + + return std::max((std::uint32_t)0, mhz * 1000000); +} + +std::uint32_t Config::GetAutoClockHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile) +{ + std::scoped_lock lock{this->configMutex}; + switch(profile) + { + case SysClkProfile_Handheld: + return FindClockHzFromProfiles(tid, module, {SysClkProfile_Handheld}); + case SysClkProfile_HandheldCharging: + case SysClkProfile_HandheldChargingUSB: + return FindClockHzFromProfiles(tid, module, {SysClkProfile_HandheldChargingUSB, SysClkProfile_HandheldCharging, SysClkProfile_Handheld}); + case SysClkProfile_HandheldChargingOfficial: + return FindClockHzFromProfiles(tid, module, {SysClkProfile_HandheldChargingOfficial, SysClkProfile_HandheldCharging, SysClkProfile_Handheld}); + case SysClkProfile_Docked: + return FindClockHzFromProfiles(tid, module, {SysClkProfile_Docked}); + default: + ERROR_THROW("Unhandled SysClkProfile: %u", profile); + } + + return 0; +} + +void Config::GetProfiles(std::uint64_t tid, SysClkTitleProfileList* out_profiles) +{ + std::scoped_lock lock{this->configMutex}; + + for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) + { + for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + out_profiles->mhzMap[profile][module] = FindClockMHz(tid, (SysClkModule)module, (SysClkProfile)profile); + } + } +} + +bool Config::SetProfiles(std::uint64_t tid, SysClkTitleProfileList* profiles, bool immediate) +{ + std::scoped_lock lock{this->configMutex}; + uint8_t numProfiles = 0; + + // String pointer array passed to ini + char* iniKeys[SysClkProfile_EnumMax * SysClkModule_EnumMax + 1]; + char* iniValues[SysClkProfile_EnumMax * SysClkModule_EnumMax + 1]; + + // Char arrays to build strings + char keysStr[SysClkProfile_EnumMax * SysClkModule_EnumMax * 0x40]; + char valuesStr[SysClkProfile_EnumMax * SysClkModule_EnumMax * 0x10]; + char section[17] = {0}; + + // Iteration pointers + char** ik = &iniKeys[0]; + char** iv = &iniValues[0]; + char* sk = &keysStr[0]; + char* sv = &valuesStr[0]; + std::uint32_t* mhz = &profiles->mhz[0]; + + snprintf(section, sizeof(section), "%016lX", tid); + + for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) + { + for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + if(*mhz) + { + numProfiles++; + + // Put key and value as string + snprintf(sk, 0x40, "%s_%s", Board::GetProfileName((SysClkProfile)profile, false), Board::GetModuleName((SysClkModule)module, false)); + snprintf(sv, 0x10, "%d", *mhz); + + // Add them to the ini key/value str arrays + *ik = sk; + *iv = sv; + ik++; + iv++; + + // We used those chars, get to the next ones + sk += 0x40; + sv += 0x10; + } + + mhz++; + } + } + + *ik = NULL; + *iv = NULL; + + if(!ini_putsection(section, (const char**)iniKeys, (const char**)iniValues, this->path.c_str())) + { + return false; + } + + // Only actually apply changes in memory after a succesful save + if(immediate) + { + mhz = &profiles->mhz[0]; + this->profileCountMap[tid] = numProfiles; + for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) + { + for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + if(*mhz) + { + this->profileMHzMap[std::make_tuple(tid, (SysClkProfile)profile, (SysClkModule)module)] = *mhz; + } + else + { + this->profileMHzMap.erase(std::make_tuple(tid, (SysClkProfile)profile, (SysClkModule)module)); + } + mhz++; + } + } + } + + return true; +} + +std::uint8_t Config::GetProfileCount(std::uint64_t tid) +{ + std::map::iterator it = this->profileCountMap.find(tid); + if (it == this->profileCountMap.end()) + { + return 0; + } + + return it->second; +} + +int Config::BrowseIniFunc(const char* section, const char* key, const char* value, void* userdata) +{ + Config* config = (Config*)userdata; + std::uint64_t input; + if(!strcmp(section, CONFIG_VAL_SECTION)) + { + for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) + { + if(!strcmp(key, sysclkFormatConfigValue((SysClkConfigValue)kval, false))) + { + input = strtoul(value, NULL, 0); + if(!sysclkValidConfigValue((SysClkConfigValue)kval, input)) + { + input = sysclkDefaultConfigValue((SysClkConfigValue)kval); + FileUtils::LogLine("[cfg] Invalid value for key '%s' in section '%s': using default %d", key, section, input); + } + config->configValues[kval] = input; + return 1; + } + } + + FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Unrecognized config value", key, section); + return 1; + } + + std::uint64_t tid = strtoul(section, NULL, 16); + + if(!tid || strlen(section) != 16) + { + FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Invalid TitleID", key, section); + return 1; + } + + SysClkProfile parsedProfile = SysClkProfile_EnumMax; + SysClkModule parsedModule = SysClkModule_EnumMax; + + for(unsigned int profile = 0; profile < SysClkProfile_EnumMax; profile++) + { + const char* profileCode = Board::GetProfileName((SysClkProfile)profile, false); + size_t profileCodeLen = strlen(profileCode); + + if(!strncmp(key, profileCode, profileCodeLen) && key[profileCodeLen] == '_') + { + const char* subkey = key + profileCodeLen + 1; + + for(unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + const char* moduleCode = Board::GetModuleName((SysClkModule)module, false); + size_t moduleCodeLen = strlen(moduleCode); + if(!strncmp(subkey, moduleCode, moduleCodeLen) && subkey[moduleCodeLen] == '\0') + { + parsedProfile = (SysClkProfile)profile; + parsedModule = (SysClkModule)module; + } + } + } + } + + if(parsedModule == SysClkModule_EnumMax || parsedProfile == SysClkProfile_EnumMax) + { + FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Unrecognized key", key, section); + return 1; + } + + std::uint32_t mhz = strtoul(value, NULL, 10); + if(!mhz) + { + FileUtils::LogLine("[cfg] Skipping key '%s' in section '%s': Invalid value", key, section); + return 1; + } + + config->profileMHzMap[std::make_tuple(tid, parsedProfile, parsedModule)] = mhz; + std::map::iterator it = config->profileCountMap.find(tid); + if (it == config->profileCountMap.end()) + { + config->profileCountMap[tid] = 1; + } + else + { + it->second++; + } + + return 1; +} + +void Config::SetEnabled(bool enabled) +{ + this->enabled = enabled; +} + +bool Config::Enabled() +{ + return this->enabled; +} + +void Config::SetOverrideHz(SysClkModule module, std::uint32_t hz) +{ + ASSERT_ENUM_VALID(SysClkModule, module); + + std::scoped_lock lock{this->overrideMutex}; + + this->overrideFreqs[module] = hz; +} + +std::uint32_t Config::GetOverrideHz(SysClkModule module) +{ + ASSERT_ENUM_VALID(SysClkModule, module); + + std::scoped_lock lock{this->overrideMutex}; + + return this->overrideFreqs[module]; +} + +std::uint64_t Config::GetConfigValue(SysClkConfigValue kval) +{ + ASSERT_ENUM_VALID(SysClkConfigValue, kval); + + std::scoped_lock lock{this->configMutex}; + + return this->configValues[kval]; +} + +const char* Config::GetConfigValueName(SysClkConfigValue kval, bool pretty) +{ + ASSERT_ENUM_VALID(SysClkConfigValue, kval); + + const char* result = sysclkFormatConfigValue(kval, pretty); + + return result; +} + +void Config::GetConfigValues(SysClkConfigValueList* out_configValues) +{ + std::scoped_lock lock{this->configMutex}; + + for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) + { + out_configValues->values[kval] = this->configValues[kval]; + } +} + +bool Config::SetConfigValues(SysClkConfigValueList* configValues, bool immediate) +{ + std::scoped_lock lock{this->configMutex}; + + // String pointer array passed to ini + const char* iniKeys[SysClkConfigValue_EnumMax + 1]; + char* iniValues[SysClkConfigValue_EnumMax + 1]; + + // char arrays to build strings + char valuesStr[SysClkConfigValue_EnumMax * 0x20]; + + // Iteration pointers + char* sv = &valuesStr[0]; + const char** ik = &iniKeys[0]; + char** iv = &iniValues[0]; + + for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) + { + if(!sysclkValidConfigValue((SysClkConfigValue)kval, configValues->values[kval]) || configValues->values[kval] == sysclkDefaultConfigValue((SysClkConfigValue)kval)) + { + continue; + } + + // Put key and value as string + // And add them to the ini key/value str arrays + snprintf(sv, 0x20, "%ld", configValues->values[kval]); + *ik = sysclkFormatConfigValue((SysClkConfigValue)kval, false); + *iv = sv; + + // We used those chars, get to the next ones + sv += 0x20; + ik++; + iv++; + } + + *ik = NULL; + *iv = NULL; + + if(!ini_putsection(CONFIG_VAL_SECTION, (const char**)iniKeys, (const char**)iniValues, this->path.c_str())) + { + return false; + } + + // Only actually apply changes in memory after a succesful save + if(immediate) + { + for(unsigned int kval = 0; kval < SysClkConfigValue_EnumMax; kval++) + { + if(sysclkValidConfigValue((SysClkConfigValue)kval, configValues->values[kval])) + { + this->configValues[kval] = configValues->values[kval]; + } + else + { + this->configValues[kval] = sysclkDefaultConfigValue((SysClkConfigValue)kval); + } + } + } + + return true; +} diff --git a/Source/sys-clk/sysmodule/src/config.h b/Source/sys-clk/sysmodule/src/config.h new file mode 100644 index 00000000..8893fd62 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/config.h @@ -0,0 +1,70 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "board.h" + +#define CONFIG_VAL_SECTION "values" + +class Config +{ + public: + Config(std::string path); + virtual ~Config(); + + static Config* CreateDefault(); + + bool Refresh(); + + bool HasProfilesLoaded(); + + std::uint8_t GetProfileCount(std::uint64_t tid); + void GetProfiles(std::uint64_t tid, SysClkTitleProfileList* out_profiles); + bool SetProfiles(std::uint64_t tid, SysClkTitleProfileList* profiles, bool immediate); + std::uint32_t GetAutoClockHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile); + + void SetEnabled(bool enabled); + bool Enabled(); + void SetOverrideHz(SysClkModule module, std::uint32_t hz); + std::uint32_t GetOverrideHz(SysClkModule module); + + std::uint64_t GetConfigValue(SysClkConfigValue val); + const char* GetConfigValueName(SysClkConfigValue val, bool pretty); + void GetConfigValues(SysClkConfigValueList* out_configValues); + bool SetConfigValues(SysClkConfigValueList* configValues, bool immediate); + protected: + void Load(); + void Close(); + + time_t CheckModificationTime(); + std::uint32_t FindClockMHz(std::uint64_t tid, SysClkModule module, SysClkProfile profile); + std::uint32_t FindClockHzFromProfiles(std::uint64_t tid, SysClkModule module, std::initializer_list profiles); + static int BrowseIniFunc(const char* section, const char* key, const char* value, void* userdata); + + std::map, std::uint32_t> profileMHzMap; + std::map profileCountMap; + bool loaded; + std::string path; + time_t mtime; + LockableMutex configMutex; + LockableMutex overrideMutex; + std::atomic_bool enabled; + std::uint32_t overrideFreqs[SysClkModule_EnumMax]; + std::uint64_t configValues[SysClkConfigValue_EnumMax]; +}; diff --git a/Source/sys-clk/sysmodule/src/errors.cpp b/Source/sys-clk/sysmodule/src/errors.cpp new file mode 100644 index 00000000..c4913050 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/errors.cpp @@ -0,0 +1,37 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "errors.h" +#include +#include + +void Errors::ThrowException(const char* format, ...) +{ + va_list args; + va_start(args, format); + const char* msg = Errors::FormatMessage(format, args); + va_end(args); + + throw std::runtime_error(msg); +} + +const char* Errors::FormatMessage(const char* format, va_list args) +{ + size_t len = vsnprintf(NULL, 0, format, args) * sizeof(char); + char* buf = (char*)malloc(len + 1); + if (buf == NULL) + { + return format; + } + + vsnprintf(buf, len + 1, format, args); + + return buf; +} diff --git a/Source/sys-clk/sysmodule/src/errors.h b/Source/sys-clk/sysmodule/src/errors.h new file mode 100644 index 00000000..d626d920 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/errors.h @@ -0,0 +1,35 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include + +#define ERROR_THROW(format, ...) Errors::ThrowException(format "\n in %s:%u", ##__VA_ARGS__, __FILE__, __LINE__) +#define ERROR_RESULT_THROW(rc, format, ...) ERROR_THROW(format "\n RC: [0x%x] %04d-%04d", ##__VA_ARGS__, rc, R_MODULE(rc), R_DESCRIPTION(rc)) +#define ASSERT_RESULT_OK(rc, format, ...) \ + if (R_FAILED(rc)) \ + { \ + ERROR_RESULT_THROW(rc, "ASSERT_RESULT_OK: " format, ##__VA_ARGS__); \ + } +#define ASSERT_ENUM_VALID(n, v) \ + if(!SYSCLK_ENUM_VALID(n, v)) { \ + ERROR_THROW("No such %s: %u", #n, v); \ + } + +class Errors +{ + public: + static void ThrowException(const char* format, ...); + + protected: + static const char* FormatMessage(const char* format, va_list args); +}; diff --git a/Source/sys-clk/sysmodule/src/file_utils.cpp b/Source/sys-clk/sysmodule/src/file_utils.cpp new file mode 100644 index 00000000..ceed6a50 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/file_utils.cpp @@ -0,0 +1,199 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "file_utils.h" +#include + +static LockableMutex g_log_mutex; +static LockableMutex g_csv_mutex; +static std::atomic_bool g_has_initialized = false; +static bool g_log_enabled = false; +static std::uint64_t g_last_flag_check = 0; + +extern "C" void __libnx_init_time(void); + +static void _FileUtils_InitializeThreadFunc(void* args) +{ + FileUtils::Initialize(); +} + +bool FileUtils::IsInitialized() +{ + return g_has_initialized; +} + +void FileUtils::LogLine(const char* format, ...) +{ + std::scoped_lock lock{g_log_mutex}; + + va_list args; + va_start(args, format); + if (g_has_initialized) + { + FileUtils::RefreshFlags(false); + + if(g_log_enabled) + { + FILE* file = fopen(FILE_LOG_FILE_PATH, "a"); + + if (file) + { + struct timespec now; + clock_gettime(CLOCK_REALTIME, &now); + struct tm* nowTm = localtime(&now.tv_sec); + + fprintf(file, "[%04d-%02d-%02d %02d:%02d:%02d.%03ld] ", nowTm->tm_year+1900, nowTm->tm_mon+1, nowTm->tm_mday, nowTm->tm_hour, nowTm->tm_min, nowTm->tm_sec, now.tv_nsec / 1000000UL); + vfprintf(file, format, args); + fprintf(file, "\n"); + fclose(file); + } + } + } + va_end(args); +} + +void FileUtils::WriteContextToCsv(const SysClkContext* context) +{ + std::scoped_lock lock{g_csv_mutex}; + + FILE* file = fopen(FILE_CONTEXT_CSV_PATH, "a"); + + if (file) + { + // Print header + if(!ftell(file)) + { + fprintf(file, "timestamp,profile,app_tid"); + + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + fprintf(file, ",%s_hz", sysclkFormatModule((SysClkModule)module, false)); + } + + for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++) + { + fprintf(file, ",%s_milliC", sysclkFormatThermalSensor((SysClkThermalSensor)sensor, false)); + } + + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + fprintf(file, ",%s_real_hz", sysclkFormatModule((SysClkModule)module, false)); + } + + for (unsigned int sensor = 0; sensor < SysClkPowerSensor_EnumMax; sensor++) + { + fprintf(file, ",%s_mw", sysclkFormatPowerSensor((SysClkPowerSensor)sensor, false)); + } + + fprintf(file, "\n"); + } + + struct timespec now; + clock_gettime(CLOCK_REALTIME, &now); + + fprintf(file, "%ld%03ld,%s,%016lx", now.tv_sec, now.tv_nsec / 1000000UL, sysclkFormatProfile(context->profile, false), context->applicationId); + + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + fprintf(file, ",%d", context->freqs[module]); + } + + for (unsigned int sensor = 0; sensor < SysClkThermalSensor_EnumMax; sensor++) + { + fprintf(file, ",%d", context->temps[sensor]); + } + + for (unsigned int module = 0; module < SysClkModule_EnumMax; module++) + { + fprintf(file, ",%d", context->realFreqs[module]); + } + + for (unsigned int sensor = 0; sensor < SysClkPowerSensor_EnumMax; sensor++) + { + fprintf(file, ",%d", context->power[sensor]); + } + + fprintf(file, "\n"); + fclose(file); + } +} + +void FileUtils::RefreshFlags(bool force) +{ + std::uint64_t now = armTicksToNs(armGetSystemTick()); + if(!force && (now - g_last_flag_check) < FILE_FLAG_CHECK_INTERVAL_NS) + { + return; + } + + FILE* file = fopen(FILE_LOG_FLAG_PATH, "r"); + if (file) + { + g_log_enabled = true; + fclose(file); + } else { + g_log_enabled = false; + } + + g_last_flag_check = now; +} + +void FileUtils::InitializeAsync() +{ + Thread initThread = {0}; + threadCreate(&initThread, _FileUtils_InitializeThreadFunc, NULL, NULL, 0x4000, 0x15, 0); + threadStart(&initThread); +} + +Result FileUtils::Initialize() +{ + Result rc = 0; + + if (R_SUCCEEDED(rc)) + { + rc = timeInitialize(); + } + + __libnx_init_time(); + timeExit(); + + if (R_SUCCEEDED(rc)) + { + rc = fsInitialize(); + } + + if (R_SUCCEEDED(rc)) + { + rc = fsdevMountSdmc(); + } + + if (R_SUCCEEDED(rc)) + { + FileUtils::RefreshFlags(true); + g_has_initialized = true; + FileUtils::LogLine("=== " TARGET " " TARGET_VERSION " ==="); + } + + return rc; +} + +void FileUtils::Exit() +{ + if (!g_has_initialized) + { + return; + } + + g_has_initialized = false; + g_log_enabled = false; + + fsdevUnmountAll(); + fsExit(); +} diff --git a/Source/sys-clk/sysmodule/src/file_utils.h b/Source/sys-clk/sysmodule/src/file_utils.h new file mode 100644 index 00000000..681fd9ed --- /dev/null +++ b/Source/sys-clk/sysmodule/src/file_utils.h @@ -0,0 +1,38 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once +#include +#include +#include +#include +#include +#include +#include + +#define FILE_CONFIG_DIR "/config/" TARGET +#define FILE_FLAG_CHECK_INTERVAL_NS 5000000000ULL +#define FILE_CONTEXT_CSV_PATH FILE_CONFIG_DIR "/context.csv" +#define FILE_LOG_FLAG_PATH FILE_CONFIG_DIR "/log.flag" +#define FILE_LOG_FILE_PATH FILE_CONFIG_DIR "/log.txt" + +class FileUtils +{ + public: + static void Exit(); + static Result Initialize(); + static bool IsInitialized(); + static bool IsLogEnabled(); + static void InitializeAsync(); + static void LogLine(const char* format, ...); + static void WriteContextToCsv(const SysClkContext* context); + protected: + static void RefreshFlags(bool force); +}; diff --git a/Source/sys-clk/sysmodule/src/ipc_service.cpp b/Source/sys-clk/sysmodule/src/ipc_service.cpp new file mode 100644 index 00000000..83d5e08d --- /dev/null +++ b/Source/sys-clk/sysmodule/src/ipc_service.cpp @@ -0,0 +1,326 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "ipc_service.h" +#include +#include +#include "file_utils.h" +#include "errors.h" + +IpcService::IpcService(ClockManager* clockMgr) +{ + std::int32_t priority; + Result rc = svcGetThreadPriority(&priority, CUR_THREAD_HANDLE); + ASSERT_RESULT_OK(rc, "svcGetThreadPriority"); + rc = ipcServerInit(&this->server, SYSCLK_IPC_SERVICE_NAME, 42); + ASSERT_RESULT_OK(rc, "ipcServerInit"); + rc = threadCreate(&this->thread, &IpcService::ProcessThreadFunc, this, NULL, 0x2000, priority, -2); + ASSERT_RESULT_OK(rc, "threadCreate"); + + this->running = false; + this->clockMgr = clockMgr; +} + +void IpcService::SetRunning(bool running) +{ + std::scoped_lock lock{this->threadMutex}; + if(this->running == running) + { + return; + } + + this->running = running; + + if(running) + { + Result rc = threadStart(&this->thread); + ASSERT_RESULT_OK(rc, "threadStart"); + } + else + { + svcCancelSynchronization(this->thread.handle); + threadWaitForExit(&this->thread); + } +} + +IpcService::~IpcService() +{ + this->SetRunning(false); + Result rc = threadClose(&this->thread); + ASSERT_RESULT_OK(rc, "threadClose"); + rc = ipcServerExit(&this->server); + ASSERT_RESULT_OK(rc, "ipcServerExit"); +} + +void IpcService::ProcessThreadFunc(void* arg) +{ + Result rc; + IpcService* ipcSrv = (IpcService*)arg; + while(true) + { + rc = ipcServerProcess(&ipcSrv->server, &IpcService::ServiceHandlerFunc, arg); + if(R_FAILED(rc)) + { + if(rc == KERNELRESULT(Cancelled)) + { + return; + } + if(rc != KERNELRESULT(ConnectionClosed)) + { + FileUtils::LogLine("[ipc] ipcServerProcess: [0x%x] %04d-%04d", rc, R_MODULE(rc), R_DESCRIPTION(rc)); + } + } + } +} + +Result IpcService::ServiceHandlerFunc(void* arg, const IpcServerRequest* r, u8* out_data, size_t* out_dataSize) +{ + IpcService* ipcSrv = (IpcService*)arg; + + switch(r->data.cmdId) + { + case SysClkIpcCmd_GetApiVersion: + *out_dataSize = sizeof(u32); + return ipcSrv->GetApiVersion((u32*)out_data); + + case SysClkIpcCmd_GetVersionString: + if(r->hipc.meta.num_recv_buffers >= 1) + { + return ipcSrv->GetVersionString( + (char*)hipcGetBufferAddress(r->hipc.data.recv_buffers), + hipcGetBufferSize(r->hipc.data.recv_buffers) + ); + } + break; + + case SysClkIpcCmd_GetCurrentContext: + *out_dataSize = sizeof(SysClkContext); + return ipcSrv->GetCurrentContext((SysClkContext*)out_data); + + case SysClkIpcCmd_Exit: + return ipcSrv->Exit(); + + case SysClkIpcCmd_GetProfileCount: + if(r->data.size >= sizeof(std::uint64_t)) + { + *out_dataSize = sizeof(std::uint8_t); + return ipcSrv->GetProfileCount((std::uint64_t*)r->data.ptr, (std::uint8_t*)out_data); + } + break; + + case SysClkIpcCmd_GetProfiles: + if(r->data.size >= sizeof(std::uint64_t)) + { + *out_dataSize = sizeof(SysClkTitleProfileList); + return ipcSrv->GetProfiles((std::uint64_t*)r->data.ptr, (SysClkTitleProfileList*)out_data); + } + break; + + case SysClkIpcCmd_SetProfiles: + if(r->data.size >= sizeof(SysClkIpc_SetProfiles_Args)) + { + return ipcSrv->SetProfiles((SysClkIpc_SetProfiles_Args*)r->data.ptr); + } + break; + + case SysClkIpcCmd_SetEnabled: + if(r->data.size >= sizeof(std::uint8_t)) + { + return ipcSrv->SetEnabled((std::uint8_t*)r->data.ptr); + } + break; + + case SysClkIpcCmd_SetOverride: + if(r->data.size >= sizeof(SysClkIpc_SetOverride_Args)) + { + return ipcSrv->SetOverride((SysClkIpc_SetOverride_Args*)r->data.ptr); + } + break; + + case SysClkIpcCmd_GetConfigValues: + *out_dataSize = sizeof(SysClkTitleProfileList); + return ipcSrv->GetConfigValues((SysClkConfigValueList*)out_data); + + case SysClkIpcCmd_SetConfigValues: + if(r->data.size >= sizeof(SysClkConfigValueList)) + { + return ipcSrv->SetConfigValues((SysClkConfigValueList*)r->data.ptr); + } + break; + case SysClkIpcCmd_ToggleUncappedClocks: + if(r->data.size >= sizeof(SysClkConfigValueList)) + { + return ipcSrv->SetConfigValues((SysClkConfigValueList*)r->data.ptr); + } + break; + case SysClkIpcCmd_GetFreqList: + if(r->data.size >= sizeof(SysClkIpc_GetFreqList_Args) && r->hipc.meta.num_recv_buffers >= 1) + { + *out_dataSize = sizeof(std::uint32_t); + return ipcSrv->GetFreqList( + (SysClkIpc_GetFreqList_Args*)r->data.ptr, + (std::uint32_t*)hipcGetBufferAddress(r->hipc.data.recv_buffers), + hipcGetBufferSize(r->hipc.data.recv_buffers), + (std::uint32_t*)out_data + ); + } + break; + + } + + return SYSCLK_ERROR(Generic); +} + +Result IpcService::GetApiVersion(u32* out_version) +{ + *out_version = SYSCLK_IPC_API_VERSION; + + return 0; +} + +Result IpcService::GetVersionString(char* out_buf, size_t bufSize) +{ + if(bufSize) + { + strncpy(out_buf, TARGET_VERSION, bufSize-1); + } + + return 0; +} + +Result IpcService::GetCurrentContext(SysClkContext* out_ctx) +{ + *out_ctx = this->clockMgr->GetCurrentContext(); + + return 0; +} + +Result IpcService::Exit() +{ + this->clockMgr->SetRunning(false); + + return 0; +} + +Result IpcService::GetProfileCount(std::uint64_t* tid, std::uint8_t* out_count) +{ + Config* config = this->clockMgr->GetConfig(); + if(!config->HasProfilesLoaded()) + { + return SYSCLK_ERROR(ConfigNotLoaded); + } + + *out_count = config->GetProfileCount(*tid); + + return 0; +} + +Result IpcService::GetProfiles(std::uint64_t* tid, SysClkTitleProfileList* out_profiles) +{ + Config* config = this->clockMgr->GetConfig(); + if(!config->HasProfilesLoaded()) + { + return SYSCLK_ERROR(ConfigNotLoaded); + } + + config->GetProfiles(*tid, out_profiles); + + return 0; +} + +Result IpcService::SetProfiles(SysClkIpc_SetProfiles_Args* args) +{ + Config* config = this->clockMgr->GetConfig(); + if(!config->HasProfilesLoaded()) + { + return SYSCLK_ERROR(ConfigNotLoaded); + } + + SysClkTitleProfileList profiles = args->profiles; + + if(!config->SetProfiles(args->tid, &profiles, true)) + { + return SYSCLK_ERROR(ConfigSaveFailed); + } + + return 0; +} + +Result IpcService::SetEnabled(std::uint8_t* enabled) +{ + Config* config = this->clockMgr->GetConfig(); + config->SetEnabled(*enabled); + + return 0; +} + +Result IpcService::SetOverride(SysClkIpc_SetOverride_Args* args) +{ + SysClkModule module = args->module; + std::uint32_t hz = args->hz; + + if(!SYSCLK_ENUM_VALID(SysClkModule, args->module)) + { + return SYSCLK_ERROR(Generic); + } + + Config* config = this->clockMgr->GetConfig(); + config->SetOverrideHz(module, hz); + + return 0; +} + +Result IpcService::GetConfigValues(SysClkConfigValueList* out_configValues) +{ + Config* config = this->clockMgr->GetConfig(); + if(!config->HasProfilesLoaded()) + { + return SYSCLK_ERROR(ConfigNotLoaded); + } + + config->GetConfigValues(out_configValues); + + return 0; +} + +Result IpcService::SetConfigValues(SysClkConfigValueList* configValues) +{ + Config* config = this->clockMgr->GetConfig(); + if(!config->HasProfilesLoaded()) + { + return SYSCLK_ERROR(ConfigNotLoaded); + } + + SysClkConfigValueList configValuesCopy = *configValues; + + if(!config->SetConfigValues(&configValuesCopy, true)) + { + return SYSCLK_ERROR(ConfigSaveFailed); + } + + return 0; +} + +Result IpcService::GetFreqList(SysClkIpc_GetFreqList_Args* args, std::uint32_t* out_list, std::size_t size, std::uint32_t* out_count) +{ + if(!SYSCLK_ENUM_VALID(SysClkModule, args->module)) + { + return SYSCLK_ERROR(Generic); + } + + if(args->maxCount != size/sizeof(*out_list)) + { + return SYSCLK_ERROR(Generic); + } + + this->clockMgr->GetFreqList(args->module, out_list, args->maxCount, out_count); + + return 0; +} \ No newline at end of file diff --git a/Source/sys-clk/sysmodule/src/ipc_service.h b/Source/sys-clk/sysmodule/src/ipc_service.h new file mode 100644 index 00000000..da030be3 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/ipc_service.h @@ -0,0 +1,47 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once + +#include +#include +#include +#include "clock_manager.h" + +class IpcService +{ + public: + IpcService(ClockManager* clockMgr); + virtual ~IpcService(); + void SetRunning(bool running); + static void ProcessThreadFunc(void* arg); + static Result ServiceHandlerFunc(void* arg, const IpcServerRequest* r, std::uint8_t* out_data, size_t* out_dataSize); + + Result GetApiVersion(u32* out_version); + Result GetVersionString(char* out_buf, size_t bufSize); + Result GetCurrentContext(SysClkContext* out_ctx); + Result Exit(); + Result GetProfileCount(std::uint64_t* tid, std::uint8_t* out_count); + Result GetProfiles(std::uint64_t* tid, SysClkTitleProfileList* out_profiles); + Result SetProfiles(SysClkIpc_SetProfiles_Args* args); + Result SetEnabled(std::uint8_t* enabled); + Result SetOverride(SysClkIpc_SetOverride_Args* args); + Result GetConfigValues(SysClkConfigValueList* out_configValues); + Result SetConfigValues(SysClkConfigValueList* configValues); + Result GetFreqList(SysClkIpc_GetFreqList_Args* args, std::uint32_t* out_list, std::size_t size, std::uint32_t* out_count); + + bool running; + Thread thread; + LockableMutex threadMutex; + IpcServer server; + ClockManager* clockMgr; + bool uncappedClocks = 0; + protected: +}; diff --git a/Source/sys-clk/sysmodule/src/main.cpp b/Source/sys-clk/sysmodule/src/main.cpp new file mode 100644 index 00000000..96a026a0 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/main.cpp @@ -0,0 +1,125 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include +#include +#include + +#include + +#include "errors.h" +#include "file_utils.h" +#include "board.h" +#include "process_management.h" +#include "clock_manager.h" +#include "ipc_service.h" + +#define INNER_HEAP_SIZE 0x30000 + +extern "C" +{ + extern std::uint32_t __start__; + + std::uint32_t __nx_applet_type = AppletType_None; + TimeServiceType __nx_time_service_type = TimeServiceType_System; + std::uint32_t __nx_fs_num_sessions = 1; + + size_t nx_inner_heap_size = INNER_HEAP_SIZE; + char nx_inner_heap[INNER_HEAP_SIZE]; + + void __libnx_initheap(void) + { + void* addr = nx_inner_heap; + size_t size = nx_inner_heap_size; + + /* Newlib Heap Management */ + extern char* fake_heap_start; + extern char* fake_heap_end; + + fake_heap_start = (char*)addr; + fake_heap_end = (char*)addr + size; + } + + void __appInit(void) + { + if (R_FAILED(smInitialize())) + { + fatalThrow(MAKERESULT(Module_Libnx, LibnxError_InitFail_SM)); + } + + Result rc = setsysInitialize(); + if (R_SUCCEEDED(rc)) + { + SetSysFirmwareVersion fw; + rc = setsysGetFirmwareVersion(&fw); + if (R_SUCCEEDED(rc)) + hosversionSet(MAKEHOSVERSION(fw.major, fw.minor, fw.micro)); + setsysExit(); + } + } + + void __appExit(void) + { + smExit(); + } +} + +int main(int argc, char** argv) +{ + Result rc = FileUtils::Initialize(); + if (R_FAILED(rc)) + { + fatalThrow(rc); + return 1; + } + + try + { + Board::Initialize(); + ProcessManagement::Initialize(); + + ProcessManagement::WaitForQLaunch(); + + ClockManager* clockMgr = new ClockManager(); + IpcService* ipcSrv = new IpcService(clockMgr); + + FileUtils::LogLine("Ready"); + + clockMgr->SetRunning(true); + clockMgr->GetConfig()->SetEnabled(true); + ipcSrv->SetRunning(true); + + while (clockMgr->Running()) + { + clockMgr->Tick(); + clockMgr->WaitForNextTick(); + } + + ipcSrv->SetRunning(false); + delete ipcSrv; + delete clockMgr; + ProcessManagement::Exit(); + Board::Exit(); + } + catch (const std::exception &ex) + { + FileUtils::LogLine("[!] %s", ex.what()); + } + catch (...) + { + std::exception_ptr p = std::current_exception(); + FileUtils::LogLine("[!?] %s", p ? p.__cxa_exception_type()->name() : "..."); + } + + FileUtils::LogLine("Exit"); + svcSleepThread(1000000ULL); + FileUtils::Exit(); + return 0; +} diff --git a/Source/sys-clk/sysmodule/src/process_management.cpp b/Source/sys-clk/sysmodule/src/process_management.cpp new file mode 100644 index 00000000..8cb369cc --- /dev/null +++ b/Source/sys-clk/sysmodule/src/process_management.cpp @@ -0,0 +1,67 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#include "process_management.h" +#include "file_utils.h" +#include "errors.h" + +void ProcessManagement::Initialize() +{ + Result rc = 0; + + rc = pmdmntInitialize(); + ASSERT_RESULT_OK(rc, "pmdmntInitialize"); + + rc = pminfoInitialize(); + ASSERT_RESULT_OK(rc, "pminfoInitialize"); +} + +void ProcessManagement::WaitForQLaunch() +{ + Result rc = 0; + std::uint64_t pid = 0; + do + { + rc = pmdmntGetProcessId(&pid, PROCESS_MANAGEMENT_QLAUNCH_TID); + svcSleepThread(500000000ULL); + } while (R_FAILED(rc)); +} + +std::uint64_t ProcessManagement::GetCurrentApplicationId() +{ + Result rc = 0; + std::uint64_t pid = 0; + std::uint64_t tid = 0; + rc = pmdmntGetApplicationProcessId(&pid); + + if (rc == 0x20f) + { + return PROCESS_MANAGEMENT_QLAUNCH_TID; + } + + ASSERT_RESULT_OK(rc, "pmdmntGetApplicationProcessId"); + + rc = pminfoGetProgramId(&tid, pid); + + if (rc == 0x20f) + { + return PROCESS_MANAGEMENT_QLAUNCH_TID; + } + + ASSERT_RESULT_OK(rc, "pminfoGetProgramId"); + + return tid; +} + +void ProcessManagement::Exit() +{ + pmdmntExit(); + pminfoExit(); +} diff --git a/Source/sys-clk/sysmodule/src/process_management.h b/Source/sys-clk/sysmodule/src/process_management.h new file mode 100644 index 00000000..0727c276 --- /dev/null +++ b/Source/sys-clk/sysmodule/src/process_management.h @@ -0,0 +1,24 @@ +/* + * -------------------------------------------------------------------------- + * "THE BEER-WARE LICENSE" (Revision 42): + * , , + * wrote this file. As long as you retain this notice you can do whatever you + * want with this stuff. If you meet any of us some day, and you think this + * stuff is worth it, you can buy us a beer in return. - The sys-clk authors + * -------------------------------------------------------------------------- + */ + +#pragma once +#include +#include + +#define PROCESS_MANAGEMENT_QLAUNCH_TID 0x0100000000001000ULL + +class ProcessManagement +{ + public: + static void Initialize(); + static void WaitForQLaunch(); + static std::uint64_t GetCurrentApplicationId(); + static void Exit(); +}; diff --git a/build.sh b/build.sh new file mode 100644 index 00000000..9b97824a --- /dev/null +++ b/build.sh @@ -0,0 +1,21 @@ +#!/bin/sh + +# Define source and destination paths +SRC="Source/Atmosphere/stratosphere/loader/source/oc" +DEST="build/stratosphere/loader/source/oc" + +# Create destination directory if it doesn't exist +mkdir -p "$DEST" + +# Copy contents of oc into destination oc (safe, includes hidden files) +cp -r "$SRC"/. "$DEST"/ + +# Enter build directory and compile using all available cores +cd build/stratosphere/loader || exit 1 +rm out/nintendo_nx_arm64_armv8a/release/loader.kip +rm -rf build/ +make -j"$(nproc)" +hactool -t kip1 out/nintendo_nx_arm64_armv8a/release/loader.kip --uncompress=ocs2.kip +rm out/nintendo_nx_arm64_armv8a/release/loader.kip +rm -rf build/ +